instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setM_Product_Category_ID (final int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_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 setName (final @Nullable java.lang.String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPlannedAmt (final BigDecimal PlannedAmt) { set_ValueNoCheck (COLUMNNAME_PlannedAmt, PlannedAmt); } @Override public BigDecimal getPlannedAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedMarginAmt (final BigDecimal PlannedMarginAmt) { set_ValueNoCheck (COLUMNNAME_PlannedMarginAmt, PlannedMarginAmt); } @Override public BigDecimal getPlannedMarginAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedMarginAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedPrice (final BigDecimal PlannedPrice) { set_ValueNoCheck (COLUMNNAME_PlannedPrice, PlannedPrice); } @Override public BigDecimal getPlannedPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedPrice); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedQty (final BigDecimal PlannedQty) { set_ValueNoCheck (COLUMNNAME_PlannedQty, PlannedQty); }
@Override public BigDecimal getPlannedQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setProductValue (final @Nullable java.lang.String ProductValue) { set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setSKU (final @Nullable java.lang.String SKU) { set_ValueNoCheck (COLUMNNAME_SKU, SKU); } @Override public java.lang.String getSKU() { return get_ValueAsString(COLUMNNAME_SKU); } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_ValueNoCheck (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Details_v.java
1
请在Spring Boot框架中完成以下Java代码
public void setObservationRegistry(ObservationRegistry observationRegistry) { this.observationRegistry = observationRegistry; } } static class ObservationRegistryFactory implements FactoryBean<ObservationRegistry> { @Override public ObservationRegistry getObject() throws Exception { return ObservationRegistry.NOOP; } @Override public Class<?> getObjectType() { return ObservationRegistry.class; } } public static final class FilterChainDecoratorFactory implements FactoryBean<FilterChainProxy.FilterChainDecorator> {
private ObservationRegistry observationRegistry = ObservationRegistry.NOOP; @Override public FilterChainProxy.FilterChainDecorator getObject() throws Exception { if (this.observationRegistry.isNoop()) { return new FilterChainProxy.VirtualFilterChainDecorator(); } return new ObservationFilterChainDecorator(this.observationRegistry); } @Override public Class<?> getObjectType() { return FilterChainProxy.FilterChainDecorator.class; } public void setObservationRegistry(ObservationRegistry registry) { this.observationRegistry = registry; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\HttpSecurityBeanDefinitionParser.java
2
请完成以下Java代码
public class DefaultJaxBContextProvider implements JaxBContextProvider { private static final DomXmlLogger LOG = DomXmlLogger.XML_DOM_LOGGER; public JAXBContext getContext(Class<?>... types) { try { return JAXBContext.newInstance(types); } catch (JAXBException e) { throw LOG.unableToCreateContext(e); } } @Override public Marshaller createMarshaller(Class<?>... types) { try { return getContext(types).createMarshaller();
} catch (JAXBException e) { throw LOG.unableToCreateMarshaller(e); } } @Override public Unmarshaller createUnmarshaller(Class<?>... types) { try { return getContext(types).createUnmarshaller(); } catch (JAXBException e) { throw LOG.unableToCreateUnmarshaller(e); } } }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\format\spi\DefaultJaxBContextProvider.java
1
请完成以下Java代码
public class MonthInterval { public int monthsBetween(Date startDate, Date endDate) { if (startDate == null || endDate == null) { throw new IllegalArgumentException("Both startDate and endDate must be provided"); } Calendar startCalendar = Calendar.getInstance(); startCalendar.setTime(startDate); int startDateTotalMonths = 12 * startCalendar.get(Calendar.YEAR) + startCalendar.get(Calendar.MONTH); Calendar endCalendar = Calendar.getInstance(); endCalendar.setTime(endDate); int endDateTotalMonths = 12 * endCalendar.get(Calendar.YEAR) + endCalendar.get(Calendar.MONTH); return endDateTotalMonths - startDateTotalMonths; } public int monthsBetweenWithDayValue(Date startDate, Date endDate) { if (startDate == null || endDate == null) { throw new IllegalArgumentException("Both startDate and endDate must be provided"); } Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startDate); int startDateDayOfMonth = startCalendar.get(Calendar.DAY_OF_MONTH); int startDateTotalMonths = 12 * startCalendar.get(Calendar.YEAR) + startCalendar.get(Calendar.MONTH); Calendar endCalendar = Calendar.getInstance(); endCalendar.setTime(endDate); int endDateDayOfMonth = endCalendar.get(Calendar.DAY_OF_MONTH); int endDateTotalMonths = 12 * endCalendar.get(Calendar.YEAR) + endCalendar.get(Calendar.MONTH); return (startDateDayOfMonth > endDateDayOfMonth) ? (endDateTotalMonths - startDateTotalMonths) - 1 : (endDateTotalMonths - startDateTotalMonths); } }
repos\tutorials-master\core-java-modules\core-java-8-datetime-3\src\main\java\com\baeldung\monthintervalbetweentwodates\MonthInterval.java
1
请完成以下Java代码
final class OAuth2EndpointUtils { private OAuth2EndpointUtils() { } static MultiValueMap<String, String> getFormParameters(HttpServletRequest request) { Map<String, String[]> parameterMap = request.getParameterMap(); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameterMap.forEach((key, values) -> { String queryString = StringUtils.hasText(request.getQueryString()) ? request.getQueryString() : ""; // If not query parameter then it's a form parameter if (!queryString.contains(key) && values.length > 0) { for (String value : values) { parameters.add(key, value); } } });
return parameters; } static MultiValueMap<String, String> getQueryParameters(HttpServletRequest request) { Map<String, String[]> parameterMap = request.getParameterMap(); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameterMap.forEach((key, values) -> { String queryString = StringUtils.hasText(request.getQueryString()) ? request.getQueryString() : ""; if (queryString.contains(key) && values.length > 0) { for (String value : values) { parameters.add(key, value); } } }); return parameters; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\web\authentication\OAuth2EndpointUtils.java
1
请完成以下Java代码
public String getParentProcessDefinitionId() { return parentProcessDefinitionId; } @CamundaQueryParam(value="parentProcessDefinitionId") public void setParentProcessDefinitionId(String parentProcessDefinitionId) { this.parentProcessDefinitionId = parentProcessDefinitionId; } public String getSuperProcessDefinitionId() { return superProcessDefinitionId; } @CamundaQueryParam(value="superProcessDefinitionId") public void setSuperProcessDefinitionId(String superProcessDefinitionId) { this.superProcessDefinitionId = superProcessDefinitionId; } public String[] getActivityIdIn() { return activityIdIn; } @CamundaQueryParam(value="activityIdIn", converter = StringArrayConverter.class) public void setActivityIdIn(String[] activityIdIn) { this.activityIdIn = activityIdIn; } public String getBusinessKey() { return businessKey; } @CamundaQueryParam(value="businessKey") public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } @CamundaQueryParam(value = "variables", converter = VariableListConverter.class) public void setVariables(List<VariableQueryParameterDto> variables) { this.variables = variables; } public List<QueryVariableValue> getQueryVariableValues() { return queryVariableValues; } public void initQueryVariableValues(VariableSerializers variableTypes, String dbType) {
queryVariableValues = createQueryVariableValues(variableTypes, variables, dbType); } @Override protected String getOrderByValue(String sortBy) { return super.getOrderBy(); } @Override protected boolean isValidSortByValue(String value) { return false; } private List<QueryVariableValue> createQueryVariableValues(VariableSerializers variableTypes, List<VariableQueryParameterDto> variables, String dbType) { List<QueryVariableValue> values = new ArrayList<QueryVariableValue>(); if (variables == null) { return values; } for (VariableQueryParameterDto variable : variables) { QueryVariableValue value = new QueryVariableValue( variable.getName(), resolveVariableValue(variable.getValue()), ConditionQueryParameterDto.getQueryOperator(variable.getOperator()), false); value.initialize(variableTypes, dbType); values.add(value); } return values; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\query\ProcessDefinitionQueryDto.java
1
请完成以下Java代码
public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getProcessInstanceId() { return this.processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; }
public static CommentDto fromComment(Comment comment) { CommentDto dto = new CommentDto(); dto.id = comment.getId(); dto.userId = comment.getUserId(); dto.time = comment.getTime(); dto.taskId = comment.getTaskId(); dto.message = comment.getFullMessage(); dto.removalTime = comment.getRemovalTime(); dto.rootProcessInstanceId = comment.getRootProcessInstanceId(); dto.processInstanceId = comment.getProcessInstanceId(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\CommentDto.java
1
请完成以下Java代码
private void updateUI() { assertEventDispatchThread(); final boolean visibleNew = !notification2panel.isEmpty(); if (visibleNew) { revalidate(); pack(); final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();// size of the screen final Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(getGraphicsConfiguration());// height of the task bar this.setLocation( screenSize.width - getWidth(), screenSize.height - screenInsets.bottom - getHeight() - (Math.max(frameBottomGap, 0))); } setVisible(visibleNew); if (visibleNew) { repaint(); } } /** * Called when a new event is received from bus */ private void onEvent(final Event event) { if (!isEligibleToBeDisplayed(event)) { return; } final NotificationItem notificationItem = toNotificationItem(event); // Add the notification item component (in EDT) executeInEDTAfter(0, () -> addNotificationItemNow(notificationItem)); } private boolean isEligibleToBeDisplayed(final Event event) { final int loginUserId = Env.getAD_User_ID(getCtx()); return event.hasRecipient(loginUserId); }
private NotificationItem toNotificationItem(final Event event) { // // Build summary text final String summaryTrl = msgBL.getMsg(getCtx(), MSG_Notification_Summary_Default, new Object[] { Adempiere.getName() }); final UserNotification notification = UserNotificationUtils.toUserNotification(event); // // Build detail message final StringBuilder detailBuf = new StringBuilder(); { // Add plain detail if any final String detailPlain = notification.getDetailPlain(); if (!Check.isEmpty(detailPlain, true)) { detailBuf.append(detailPlain.trim()); } // Translate, parse and add detail (AD_Message). final String detailADMessage = notification.getDetailADMessage(); if (!Check.isEmpty(detailADMessage, true)) { final String detailTrl = msgBL.getMsg(getCtx(), detailADMessage); final String detailTrlParsed = EventHtmlMessageFormat.newInstance() .setArguments(notification.getDetailADMessageParams()) .format(detailTrl); if (!Check.isEmpty(detailTrlParsed, true)) { if (detailBuf.length() > 0) { detailBuf.append("<br>"); } detailBuf.append(detailTrlParsed); } } } return NotificationItem.builder() .setSummary(summaryTrl) .setDetail(detailBuf.toString()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\notifications\SwingEventNotifierFrame.java
1
请完成以下Java代码
public void putContextInfos(final Map<StockAvailabilityQueryItem, MSV3ArtikelContextInfo> contextInfos) { contextInfosByQueryItem.putAll(contextInfos); } public void putContextInfo( @NonNull final StockAvailabilityQueryItem queryItem, @NonNull final MSV3ArtikelContextInfo contextInfo) { contextInfosByQueryItem.put(queryItem, contextInfo); } public void putContextInfo( @NonNull final StockAvailabilityResponseItem responseItem, @NonNull final MSV3ArtikelContextInfo contextInfo) { contextInfosByResponse.put(responseItem, contextInfo); } public I_MSV3_Verfuegbarkeit_Transaction store() { final I_MSV3_Verfuegbarkeit_Transaction transactionRecord = newInstance(I_MSV3_Verfuegbarkeit_Transaction.class); transactionRecord.setAD_Org_ID(orgId.getRepoId()); final I_MSV3_VerfuegbarkeitsanfrageEinzelne verfuegbarkeitsanfrageEinzelneRecord = // availabilityDataPersister.storeAvailabilityRequest( query, ImmutableMap.copyOf(contextInfosByQueryItem)); transactionRecord.setMSV3_VerfuegbarkeitsanfrageEinzelne(verfuegbarkeitsanfrageEinzelneRecord); if (response != null) { final I_MSV3_VerfuegbarkeitsanfrageEinzelneAntwort verfuegbarkeitsanfrageEinzelneAntwortRecord = // availabilityDataPersister.storeAvailabilityResponse( response, ImmutableMap.copyOf(contextInfosByResponse)); transactionRecord.setMSV3_VerfuegbarkeitsanfrageEinzelneAntwort(verfuegbarkeitsanfrageEinzelneAntwortRecord); } if (faultInfo != null) { final I_MSV3_FaultInfo faultInfoRecord = Msv3FaultInfoDataPersister .newInstanceWithOrgId(orgId) .storeMsv3FaultInfoOrNull(faultInfo); transactionRecord.setMSV3_FaultInfo(faultInfoRecord); }
if (otherException != null) { final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(otherException); transactionRecord.setAD_Issue_ID(issueId.getRepoId()); } save(transactionRecord); return transactionRecord; } public RuntimeException getExceptionOrNull() { if (faultInfo == null && otherException == null) { return null; } return Msv3ClientException.builder().msv3FaultInfo(faultInfo) .cause(otherException).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\availability\MSV3AvailabilityTransaction.java
1
请完成以下Java代码
public <T> T call(final Callable<T> callable) { return call(null, callable); } /** * Execute a {@link Callable} binding the given {@link ConnectionFactory} and finally unbinding it. * @param contextName the name of the context. In null, empty or blank, default context is bound. * @param callable the {@link Callable} object to be executed. * @param <T> the return type. * @return the result of the {@link Callable}. */ public <T> T call(@Nullable String contextName, Callable<T> callable) { try { bind(contextName); return callable.call(); } catch (Exception ex) { throw new IllegalStateException(ex); } finally { unbind(contextName); } } /** * Execute a {@link Runnable} binding to the default {@link ConnectionFactory} and finally unbinding it. * @param runnable the {@link Runnable} object to be executed. * @throws RuntimeException when a RuntimeException is thrown by the {@link Runnable}. */ public void run(Runnable runnable) { run(null, runnable); } /** * Execute a {@link Runnable} binding the given {@link ConnectionFactory} and finally unbinding it. * @param contextName the name of the context. In null, empty or blank, default context is bound. * @param runnable the {@link Runnable} object to be executed. * @throws RuntimeException when a RuntimeException is thrown by the {@link Runnable}. */ public void run(@Nullable String contextName, Runnable runnable) { try { bind(contextName); runnable.run();
} finally { unbind(contextName); } } /** * Bind the context. * @param contextName the name of the context for the connection factory. */ private void bind(@Nullable String contextName) { if (StringUtils.hasText(contextName)) { SimpleResourceHolder.bind(this.connectionFactory, contextName); } } /** * Unbind the context. * @param contextName the name of the context for the connection factory. */ private void unbind(@Nullable String contextName) { if (StringUtils.hasText(contextName)) { SimpleResourceHolder.unbind(this.connectionFactory); } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\ConnectionFactoryContextWrapper.java
1
请完成以下Java代码
public class AddProductCommand { @TargetAggregateIdentifier private final String orderId; private final String productId; public AddProductCommand(String orderId, String productId) { this.orderId = orderId; this.productId = productId; } public String getOrderId() { return orderId; } public String getProductId() { return productId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false;
} AddProductCommand that = (AddProductCommand) o; return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId); } @Override public int hashCode() { return Objects.hash(orderId, productId); } @Override public String toString() { return "AddProductCommand{" + "orderId='" + orderId + '\'' + ", productId='" + productId + '\'' + '}'; } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\coreapi\commands\AddProductCommand.java
1
请完成以下Java代码
public class AtomNode { public String sWord; public int nPOS; public AtomNode(String sWord, int nPOS) { this.sWord = sWord; this.nPOS = nPOS; } public AtomNode(char c, int nPOS) { this.sWord = String.valueOf(c); this.nPOS = nPOS; } /** * 原子的词性 * @return */ public Nature getNature() { Nature nature = Nature.nz; switch (nPOS) { case CharType.CT_CHINESE: break; case CharType.CT_NUM: case CharType.CT_INDEX: case CharType.CT_CNUM: nature = Nature.m; sWord = Predefine.TAG_NUMBER; break; case CharType.CT_DELIMITER: nature = Nature.w; break; case CharType.CT_LETTER: nature = Nature.nx; sWord = Predefine.TAG_CLUSTER; break; case CharType.CT_SINGLE://12021-2129-3121 if (Predefine.PATTERN_FLOAT_NUMBER.matcher(sWord).matches())//匹配浮点数 { nature = Nature.m; sWord = Predefine.TAG_NUMBER; } else { nature = Nature.nx; sWord = Predefine.TAG_CLUSTER; } break; default: break; } return nature; } @Override public String toString() { return "AtomNode{" +
"word='" + sWord + '\'' + ", nature=" + nPOS + '}'; } public static Vertex convert(String word, int type) { String name = word; Nature nature = Nature.n; int dValue = 1; switch (type) { case CharType.CT_CHINESE: break; case CharType.CT_NUM: case CharType.CT_INDEX: case CharType.CT_CNUM: nature = Nature.m; word = Predefine.TAG_NUMBER; break; case CharType.CT_DELIMITER: nature = Nature.w; break; case CharType.CT_LETTER: nature = Nature.nx; word = Predefine.TAG_CLUSTER; break; case CharType.CT_SINGLE://12021-2129-3121 // if (Pattern.compile("^(-?\\d+)(\\.\\d+)?$").matcher(word).matches())//匹配浮点数 // { // nature = Nature.m; // word = Predefine.TAG_NUMBER; // } else // { nature = Nature.nx; word = Predefine.TAG_CLUSTER; // } break; default: break; } return new Vertex(word, name, new CoreDictionary.Attribute(nature, dValue)); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\NShort\Path\AtomNode.java
1
请完成以下Java代码
public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getOperationLogManager() .findOperationLogEntryCountByQueryCriteria(this); } public List<UserOperationLogEntry> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getOperationLogManager() .findOperationLogEntriesByQueryCriteria(this, page); } public boolean isTenantIdSet() { return isTenantIdSet; } public UserOperationLogQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds;
this.isTenantIdSet = true; return this; } public UserOperationLogQuery withoutTenantId() { this.tenantIds = null; this.isTenantIdSet = true; return this; } @Override protected boolean hasExcludingConditions() { return super.hasExcludingConditions() || CompareUtil.areNotInAscendingOrder(timestampAfter, timestampBefore); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserOperationLogQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public ODataServiceFactory getServiceFactory() { return this.serviceFactory; } } @Provider public static class EntityManagerFilter implements ContainerRequestFilter, ContainerResponseFilter { public static final String EM_REQUEST_ATTRIBUTE = EntityManagerFilter.class.getName() + "_ENTITY_MANAGER"; private final EntityManagerFactory entityManagerFactory; @Context private HttpServletRequest httpRequest; public EntityManagerFilter(EntityManagerFactory entityManagerFactory) { this.entityManagerFactory = entityManagerFactory; } @Override public void filter(ContainerRequestContext containerRequestContext) throws IOException { EntityManager entityManager = this.entityManagerFactory.createEntityManager(); httpRequest.setAttribute(EM_REQUEST_ATTRIBUTE, entityManager);
if (!"GET".equalsIgnoreCase(containerRequestContext.getMethod())) { entityManager.getTransaction().begin(); } } @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { EntityManager entityManager = (EntityManager) httpRequest.getAttribute(EM_REQUEST_ATTRIBUTE); if (!"GET".equalsIgnoreCase(requestContext.getMethod())) { EntityTransaction entityTransaction = entityManager.getTransaction(); //we do not commit because it's just a READ if (entityTransaction.isActive() && !entityTransaction.getRollbackOnly()) { entityTransaction.commit(); } } entityManager.close(); } } }
repos\springboot-demo-master\olingo\src\main\java\com\et\olingo\config\JerseyConfig.java
2
请完成以下Java代码
public String toString() { return "basic public fields"; } @Override public boolean test(final IDocumentFieldView field) { return field.isPublicField() && !field.isAdvancedField(); } }; private static final Predicate<DocumentFieldChange> FILTER_DocumentFieldChange_BASIC_PUBLIC_FIELDS = new Predicate<DocumentFieldChange>() { @Override public String toString() { return "basic public fields"; } @Override public boolean test(final DocumentFieldChange field) { return field.isPublicField() && !field.isAdvancedField(); } }; private static final Predicate<IDocumentFieldView> FILTER_DocumentFieldView_ALL_PUBLIC_FIELDS = new Predicate<IDocumentFieldView>() { @Override public String toString() { return "all public fields"; } @Override public boolean test(final IDocumentFieldView field) { return field.isPublicField(); } }; private static final Predicate<DocumentFieldChange> FILTER_DocumentFieldChange_ALL_PUBLIC_FIELDS = new Predicate<DocumentFieldChange>() { @Override public String toString() { return "all public fields"; } @Override public boolean test(final DocumentFieldChange field) { return field.isPublicField(); } }; private static final class FILTER_DocumentFieldView_ByFieldNamesSet implements Predicate<IDocumentFieldView> { private final Set<String> fieldNamesSet; private final Predicate<IDocumentFieldView> parentFilter; private FILTER_DocumentFieldView_ByFieldNamesSet(final Set<String> fieldNamesSet, final Predicate<IDocumentFieldView> parentFilter)
{ super(); this.fieldNamesSet = fieldNamesSet; this.parentFilter = parentFilter; } @Override public String toString() { return "field name in " + fieldNamesSet + " and " + parentFilter; } @Override public boolean test(final IDocumentFieldView field) { if (!fieldNamesSet.contains(field.getFieldName())) { return false; } return parentFilter.test(field); } } private static final class FILTER_DocumentFieldChange_ByFieldNamesSet implements Predicate<DocumentFieldChange> { private final Set<String> fieldNamesSet; private final Predicate<DocumentFieldChange> parentFilter; private FILTER_DocumentFieldChange_ByFieldNamesSet(final Set<String> fieldNamesSet, final Predicate<DocumentFieldChange> parentFilter) { super(); this.fieldNamesSet = fieldNamesSet; this.parentFilter = parentFilter; } @Override public String toString() { return "field name in " + fieldNamesSet + " and " + parentFilter; } @Override public boolean test(final DocumentFieldChange field) { if (!fieldNamesSet.contains(field.getFieldName())) { return false; } return parentFilter.test(field); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentOptions.java
1
请在Spring Boot框架中完成以下Java代码
public String getAttachmentPrefix(final String defaultValue) { if (attachmentPrefix == null) { return defaultValue; } return attachmentPrefix; } @Override public I_AD_User getFrom() { return from; } @Override public String getMessage() { return ""; } @Override public String getSubject() { return subject; } @Override public String getTitle() { return Msg.getMsg(Env.getCtx(), MSG_SEND_MAIL);
} @Override public String getTo() { return to; } @Override public String getExportFilePrefix() { return EXPORT_FILE_PREFIX; } @Override public MADBoilerPlate getDefaultTextPreset() { if (defaultBoilerPlateId != null && defaultBoilerPlateId > 0) { return new MADBoilerPlate(Env.getCtx(), defaultBoilerPlateId, null); } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\report\email\service\impl\DocumentEmailParams.java
2
请完成以下Java代码
public ICompositeQueryUpdater<T> addQueryUpdater(@NonNull final IQueryUpdater<T> updater) { queryUpdaters.add(updater); sqlBuilt = false; return this; } @Override public ICompositeQueryUpdater<T> addSetColumnValue(final String columnName, @Nullable final Object value) { final IQueryUpdater<T> updater = new SetColumnNameQueryUpdater<>(columnName, value); return addQueryUpdater(updater); } @Override public ICompositeQueryUpdater<T> addSetColumnFromColumn(final String columnName, final ModelColumnNameValue<T> fromColumnName) { final IQueryUpdater<T> updater = new SetColumnNameQueryUpdater<>(columnName, fromColumnName); return addQueryUpdater(updater); } @Override public ICompositeQueryUpdater<T> addAddValueToColumn(final String columnName, final BigDecimal valueToAdd) { final IQueryFilter<T> onlyWhenFilter = null; final IQueryUpdater<T> updater = new AddToColumnQueryUpdater<>(columnName, valueToAdd, onlyWhenFilter); return addQueryUpdater(updater); } @Override public ICompositeQueryUpdater<T> addAddValueToColumn(final String columnName, final BigDecimal valueToAdd, final IQueryFilter<T> onlyWhenFilter) { final IQueryUpdater<T> updater = new AddToColumnQueryUpdater<>(columnName, valueToAdd, onlyWhenFilter); return addQueryUpdater(updater); } @Override public boolean update(final T model) { boolean updated = false; for (final IQueryUpdater<T> updater : queryUpdaters) { if (updater.update(model)) { updated = true; } } return updated; } @Override public String getSql(final Properties ctx, final List<Object> params) { buildSql(ctx); params.addAll(sqlParams); return sql; } private void buildSql(final Properties ctx) { if (sqlBuilt) { return;
} if (queryUpdaters.isEmpty()) { throw new AdempiereException("Cannot build sql update query for an empty " + CompositeQueryUpdater.class); } final StringBuilder sql = new StringBuilder(); final List<Object> params = new ArrayList<>(); for (final IQueryUpdater<T> updater : queryUpdaters) { final ISqlQueryUpdater<T> sqlUpdater = (ISqlQueryUpdater<T>)updater; final String sqlChunk = sqlUpdater.getSql(ctx, params); if (Check.isEmpty(sqlChunk)) { continue; } if (sql.length() > 0) { sql.append(", "); } sql.append(sqlChunk); } this.sql = sql.toString(); this.sqlParams = params; this.sqlBuilt = true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CompositeQueryUpdater.java
1
请完成以下Java代码
public Map<String, Object> getProcessVariables() { Map<String, Object> variables = new HashMap<String, Object>(); if (queryVariables != null) { for (VariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() == null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public List<VariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new VariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<VariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } public Date getClaimTime() { return claimTime; }
public void setClaimTime(Date claimTime) { this.claimTime = claimTime; } public Integer getAppVersion() { return this.appVersion; } public void setAppVersion(Integer appVersion) { this.appVersion = appVersion; } public String toString() { return "Task[id=" + id + ", name=" + name + "]"; } private String truncate(String string, int maxLength) { if (string != null) { return string.length() > maxLength ? string.substring(0, maxLength) : string; } return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntityImpl.java
1
请完成以下Java代码
public Money convertToRelativeValue(@NonNull final Money realValue) { final int toRelativeValueMultiplier = getToRelativeValueMultiplier(); return toRelativeValueMultiplier > 0 ? realValue : realValue.negate(); } public Amount convertToRelativeValue(@NonNull final Amount realValue) { final int toRelativeValueMultiplier = getToRelativeValueMultiplier(); return toRelativeValueMultiplier > 0 ? realValue : realValue.negate(); } public boolean isNegateToConvertToRealValue() { return getToRealValueMultiplier() < 0; } private int getToRealValueMultiplier() { int toRealValueMultiplier = this.toRealValueMultiplier; if (toRealValueMultiplier == 0) { toRealValueMultiplier = this.toRealValueMultiplier = computeToRealValueMultiplier(); } return toRealValueMultiplier; } private int computeToRealValueMultiplier() { int multiplier = 1; // Adjust by SOTrx if needed if (!isAPAdjusted) { final int multiplierAP = soTrx.isPurchase() ? -1 : +1; multiplier *= multiplierAP; } // Adjust by Credit Memo if needed if (!isCreditMemoAdjusted) { final int multiplierCM = isCreditMemo ? -1 : +1; multiplier *= multiplierCM; } return multiplier; } private int getToRelativeValueMultiplier() { // NOTE: the relative->real and real->relative value multipliers are the same return getToRealValueMultiplier(); } public Money fromNotAdjustedAmount(@NonNull final Money money) { final int multiplier = computeFromNotAdjustedAmountMultiplier(); return multiplier > 0 ? money : money.negate(); } private int computeFromNotAdjustedAmountMultiplier() { int multiplier = 1;
// Do we have to SO adjust? if (isAPAdjusted) { final int multiplierAP = soTrx.isPurchase() ? -1 : +1; multiplier *= multiplierAP; } // Do we have to adjust by Credit Memo? if (isCreditMemoAdjusted) { final int multiplierCM = isCreditMemo ? -1 : +1; multiplier *= multiplierCM; } return multiplier; } /** * @return {@code true} for purchase-invoice and sales-creditmemo. {@code false} otherwise. */ public boolean isOutgoingMoney() { return isCreditMemo ^ soTrx.isPurchase(); } public InvoiceAmtMultiplier withAPAdjusted(final boolean isAPAdjustedNew) { return isAPAdjusted == isAPAdjustedNew ? this : toBuilder().isAPAdjusted(isAPAdjustedNew).build().intern(); } public InvoiceAmtMultiplier withCMAdjusted(final boolean isCreditMemoAdjustedNew) { return isCreditMemoAdjusted == isCreditMemoAdjustedNew ? this : toBuilder().isCreditMemoAdjusted(isCreditMemoAdjustedNew).build().intern(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceAmtMultiplier.java
1
请完成以下Java代码
protected void addError( List<ValidationError> validationErrors, String problem, Process process, BaseElement baseElement, boolean isWarning, Map<String, String> params ) { ValidationError error = new ValidationError(); error.setWarning(isWarning); if (process != null) { error.setProcessDefinitionId(process.getId()); error.setProcessDefinitionName(process.getName()); } if (baseElement != null) { error.setXmlLineNumber(baseElement.getXmlRowNumber()); error.setXmlColumnNumber(baseElement.getXmlColumnNumber()); } error.setKey(problem); error.setProblem(problem); error.setDefaultDescription(problem); error.setParams(params); if (baseElement instanceof FlowElement) { FlowElement flowElement = (FlowElement) baseElement;
error.setActivityId(flowElement.getId()); error.setActivityName(flowElement.getName()); } addError(validationErrors, error); } protected void addError(List<ValidationError> validationErrors, String problem, Process process, String id) { ValidationError error = new ValidationError(); if (process != null) { error.setProcessDefinitionId(process.getId()); error.setProcessDefinitionName(process.getName()); } error.setKey(problem); error.setProblem(problem); error.setDefaultDescription(problem); error.setActivityId(id); addError(validationErrors, error); } }
repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\validator\ValidatorImpl.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isCachable() { return true; } @Override public boolean isAbleToStore(Object value) { if (value instanceof Collection) { return EMPTY_LIST_CLASS.isInstance(value) || EMPTY_SET_CLASS.isInstance(value); } return false; } @Override public void setValue(Object value, ValueFields valueFields) { if (EMPTY_LIST_CLASS.isInstance(value)) { valueFields.setTextValue("list"); } else { valueFields.setTextValue("set");
} } @Override public Object getValue(ValueFields valueFields) { String value = valueFields.getTextValue(); if (LIST.equals(value)) { return Collections.emptyList(); } else if (SET.equals(value)) { return Collections.emptySet(); } return null; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\EmptyCollectionType.java
2
请完成以下Java代码
public class HUTrxAttributeProcessor_HU implements IHUTrxAttributeProcessor { @Override public void processSave(final IHUContext huContext, final I_M_HU_Trx_Attribute trxAttribute, final Object referencedModel) { if (!HUConstants.DEBUG_07277_processHUTrxAttribute) { return; // FIXME debuging } final I_M_HU hu = InterfaceWrapperHelper.create(referencedModel, I_M_HU.class); final IHUAttributesDAO huAttributesDAO = huContext.getHUAttributeStorageFactory().getHUAttributesDAO(); final I_M_HU_Attribute huAttributeExisting = retrieveHUAttribute(huAttributesDAO, trxAttribute); final I_M_HU_Attribute huAttribute; if (huAttributeExisting == null) { // Create new attribute huAttribute = InterfaceWrapperHelper.newInstance(I_M_HU_Attribute.class, hu); huAttribute.setAD_Org_ID(hu.getAD_Org_ID()); huAttribute.setM_HU(hu); huAttribute.setM_Attribute_ID(trxAttribute.getM_Attribute_ID()); huAttribute.setM_HU_PI_Attribute_ID(trxAttribute.getM_HU_PI_Attribute_ID()); } else { huAttribute = huAttributeExisting; } // // Update values huAttribute.setValue(trxAttribute.getValue()); huAttribute.setValueNumber(trxAttribute.getValueNumber()); // TODO tsa: why following line was missing?!? // huAttribute.setValueDate(trxAttribute.getValueDate()); huAttributesDAO.save(huAttribute); } @Override public void processDrop(final IHUContext huContext, final I_M_HU_Trx_Attribute huTrxAttribute, final Object referencedModel) {
final IHUAttributesDAO huAttributesDAO = huContext.getHUAttributeStorageFactory().getHUAttributesDAO(); final I_M_HU_Attribute huAttributeExisting = retrieveHUAttribute(huAttributesDAO, huTrxAttribute); if (huAttributeExisting == null) { throw new InvalidAttributeValueException("Retrieved HUAttribute cannot be null (" + huTrxAttribute.getM_Attribute_ID() + "): " + huTrxAttribute); } huAttributesDAO.delete(huAttributeExisting); } private I_M_HU_Attribute retrieveHUAttribute(final IHUAttributesDAO huAttributesDAO, final I_M_HU_Trx_Attribute trx) { if (trx.getM_HU_Attribute_ID() > 0) { final I_M_HU_Attribute huAttributeExisting = trx.getM_HU_Attribute(); if (huAttributeExisting != null && huAttributeExisting.getM_HU_Attribute_ID() > 0) { return huAttributeExisting; } } final I_M_HU hu = trx.getM_HU(); final AttributeId attributeId = AttributeId.ofRepoId(trx.getM_Attribute_ID()); final I_M_HU_Attribute huAttribute = huAttributesDAO.retrieveAttribute(hu, attributeId); return huAttribute; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\spi\impl\HUTrxAttributeProcessor_HU.java
1
请完成以下Java代码
private List<RuleChain> findEdgeRuleChains(TenantId tenantId, EdgeId edgeId) { List<RuleChain> result = new ArrayList<>(); PageDataIterable<RuleChain> ruleChains = new PageDataIterable<>( link -> ruleChainService.findRuleChainsByTenantIdAndEdgeId(tenantId, edgeId, link), 1024); for (RuleChain ruleChain : ruleChains) { result.add(ruleChain); } return result; } @Override public long countByTenantId(TenantId tenantId) { return edgeDao.countByTenantId(tenantId); } @Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findEdgeById(tenantId, new EdgeId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(findEdgeByIdAsync(tenantId, new EdgeId(entityId.getId()))) .transform(Optional::ofNullable, directExecutor()); } @Override public EntityType getEntityType() { return EntityType.EDGE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\edge\EdgeServiceImpl.java
1
请完成以下Java代码
public int hashCode() { // name's hashCode is multiplied by an arbitrary prime number (13) // in order to make sure there is a difference in the hashCode between // these two parameters: // name: a value: aa // name: aa value: a return key.hashCode() * 13 + (value == null ? 0 : value.hashCode()); } /** * <p>Test this <code>Pair</code> for equality with another * <code>Object</code>.</p> * * <p>If the <code>Object</code> to be tested is not a * <code>Pair</code> or is <code>null</code>, then this method * returns <code>false</code>.</p> * * <p>Two <code>Pair</code>s are considered equal if and only if * both the names and values are equal.</p>
* * @param o the <code>Object</code> to test for * equality with this <code>Pair</code> * @return <code>true</code> if the given <code>Object</code> is * equal to this <code>Pair</code> else <code>false</code> */ @Override public boolean equals(Object o) { if (this == o) return true; if (o instanceof Pair) { Pair pair = (Pair) o; if (key != null ? !key.equals(pair.key) : pair.key != null) return false; if (value != null ? !value.equals(pair.value) : pair.value != null) return false; return true; } return false; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\Pair.java
1
请在Spring Boot框架中完成以下Java代码
public void setTopCategoryId(String topCategoryId) { this.topCategoryId = topCategoryId; } public String getSubCategoryId() { return subCategoryId; } public void setSubCategoryId(String subCategoryId) { this.subCategoryId = subCategoryId; } public String getBrandId() { return brandId; } public void setBrandId(String brandId) { this.brandId = brandId; } public Integer getProdStateCode() { return prodStateCode; } public void setProdStateCode(Integer prodStateCode) { this.prodStateCode = prodStateCode; } public String getCompanyId() { return companyId; } public void setCompanyId(String companyId) { this.companyId = companyId; } public Integer getOrderByPrice() {
return orderByPrice; } public void setOrderByPrice(Integer orderByPrice) { this.orderByPrice = orderByPrice; } public Integer getOrderBySales() { return orderBySales; } public void setOrderBySales(Integer orderBySales) { this.orderBySales = orderBySales; } @Override public String toString() { return "ProdQueryReq{" + "id='" + id + '\'' + ", prodName='" + prodName + '\'' + ", shopPriceStart='" + shopPriceStart + '\'' + ", shopPriceEnd='" + shopPriceEnd + '\'' + ", topCategoryId='" + topCategoryId + '\'' + ", subCategoryId='" + subCategoryId + '\'' + ", brandId='" + brandId + '\'' + ", prodStateCode=" + prodStateCode + ", companyId='" + companyId + '\'' + ", orderByPrice=" + orderByPrice + ", orderBySales=" + orderBySales + ", page=" + page + ", numPerPage=" + numPerPage + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\product\ProdQueryReq.java
2
请完成以下Java代码
public Optional<byte[]> getInvoicePDF(@NonNull final InvoiceId invoiceId) { return getLastArchive(invoiceId).map(archiveBL::getBinaryData); } public boolean hasArchive(@NonNull final InvoiceId invoiceId) { return getLastArchive(invoiceId).isPresent(); } private Optional<I_AD_Archive> getLastArchive(@NonNull final InvoiceId invoiceId) { return archiveBL.getLastArchiveRecord(TableRecordReference.of(I_C_Invoice.Table_Name, invoiceId)); } @NonNull public JSONInvoiceInfoResponse getInvoiceInfo(@NonNull final InvoiceId invoiceId, final String ad_language) { final JSONInvoiceInfoResponse.JSONInvoiceInfoResponseBuilder result = JSONInvoiceInfoResponse.builder(); final I_C_Invoice invoice = invoiceDAO.getByIdInTrx(invoiceId); final CurrencyCode currency = currencyDAO.getCurrencyCodeById(CurrencyId.ofRepoId(invoice.getC_Currency_ID())); final List<I_C_InvoiceLine> lines = invoiceDAO.retrieveLines(invoiceId); for (final I_C_InvoiceLine line : lines) { final String productName = productBL.getProductNameTrl(ProductId.ofRepoId(line.getM_Product_ID())).translate(ad_language); final Percent taxRate = taxDAO.getRateById(TaxId.ofRepoId(line.getC_Tax_ID())); result.lineInfo(JSONInvoiceLineInfo.builder() .lineNumber(line.getLine()) .productName(productName) .qtyInvoiced(line.getQtyEntered()) .price(line.getPriceEntered()) .taxRate(taxRate) .lineNetAmt(line.getLineNetAmt())
.currency(currency) .build()); } return result.build(); } @NonNull public Optional<JsonReverseInvoiceResponse> reverseInvoice(@NonNull final InvoiceId invoiceId) { final I_C_Invoice documentRecord = invoiceDAO.getByIdInTrx(invoiceId); if (documentRecord == null) { return Optional.empty(); } documentBL.processEx(documentRecord, IDocument.ACTION_Reverse_Correct, IDocument.STATUS_Reversed); final JsonReverseInvoiceResponse.JsonReverseInvoiceResponseBuilder responseBuilder = JsonReverseInvoiceResponse.builder(); invoiceCandDAO .retrieveInvoiceCandidates(invoiceId) .stream() .map(this::buildJSONItem) .forEach(responseBuilder::affectedInvoiceCandidate); return Optional.of(responseBuilder.build()); } private JsonInvoiceCandidatesResponseItem buildJSONItem(@NonNull final I_C_Invoice_Candidate invoiceCandidate) { return JsonInvoiceCandidatesResponseItem .builder() .externalHeaderId(JsonExternalId.ofOrNull(invoiceCandidate.getExternalHeaderId())) .externalLineId(JsonExternalId.ofOrNull(invoiceCandidate.getExternalLineId())) .metasfreshId(MetasfreshId.of(invoiceCandidate.getC_Invoice_Candidate_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\invoice\impl\InvoiceService.java
1
请完成以下Java代码
public boolean invalidateIt() { log.info(toString()); setDocAction(DOCACTION_Prepare); return true; } // invalidateIt /** * Prepare Document * * @return new status (In Progress or Invalid) */ @Override public String prepareIt() { log.info(toString()); m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_PREPARE); if (m_processMsg != null) return IDocument.STATUS_Invalid; m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_PREPARE); if (m_processMsg != null) return IDocument.STATUS_Invalid; // m_justPrepared = true; if (!DOCACTION_Complete.equals(getDocAction())) setDocAction(DOCACTION_Complete); return IDocument.STATUS_InProgress; } // prepareIt @Override public boolean processIt(final String processAction) { m_processMsg = null; return Services.get(IDocumentBL.class).processIt(this, processAction); } @Override public boolean reActivateIt() { log.info(toString()); // Before reActivate m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REACTIVATE); if (m_processMsg != null) return false; setProcessed(false); setDocAction(DOCACTION_Complete); // After reActivate m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REACTIVATE); if (m_processMsg != null) return false; return true; } // reActivateIt @Override public boolean rejectIt() { return true; }
@Override public boolean reverseAccrualIt() { log.info(toString()); // Before reverseAccrual m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSEACCRUAL); if (m_processMsg != null) return false; // After reverseAccrual m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSEACCRUAL); if (m_processMsg != null) return false; return true; } // reverseAccrualIt @Override public boolean reverseCorrectIt() { log.info(toString()); // Before reverseCorrect m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSECORRECT); if (m_processMsg != null) return false; // After reverseCorrect m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSECORRECT); if (m_processMsg != null) return false; return true; } /** * Unlock Document. * * @return true if success */ @Override public boolean unlockIt() { log.info(toString()); setProcessing(false); return true; } // unlockIt @Override public boolean voidIt() { return false; } @Override public int getC_Currency_ID() { return 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\model\MCFlatrateConditions.java
1
请完成以下Java代码
public int getC_BPartner_ID() { return delegate.getC_BPartner_ID(); } @Override public void setC_BPartner_ID(final int C_BPartner_ID) { delegate.setC_BPartner_ID(C_BPartner_ID); } @Override public int getC_BPartner_Location_ID() { return delegate.getC_BPartner_Location_ID(); } @Override public void setC_BPartner_Location_ID(final int C_BPartner_Location_ID) { delegate.setC_BPartner_Location_ID(C_BPartner_Location_ID); } @Override public int getC_BPartner_Location_Value_ID() { return delegate.getC_BPartner_Location_Value_ID(); } @Override public void setC_BPartner_Location_Value_ID(final int C_BPartner_Location_Value_ID) { delegate.setC_BPartner_Location_Value_ID(C_BPartner_Location_Value_ID); } @Override public int getAD_User_ID() { return delegate.getAD_User_ID(); } @Override public void setAD_User_ID(final int AD_User_ID) { delegate.setAD_User_ID(AD_User_ID); } @Override public String getBPartnerAddress() { return delegate.getBPartnerAddress(); } @Override public void setBPartnerAddress(String address) { delegate.setBPartnerAddress(address); } @Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) {
IDocumentLocationAdapter.super.setRenderedAddress(from); } public void setFrom(@NonNull final I_M_InOut from) { setFrom(new DocumentLocationAdapter(from).toDocumentLocation()); } public void setFrom(@NonNull final I_C_Order from) { setFrom(OrderDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation()); } public void setFrom(@NonNull final I_C_Invoice from) { setFrom(InvoiceDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation()); } @Override public I_M_InOut getWrappedRecord() { return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public DocumentLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new DocumentLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_M_InOut.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\location\adapter\DocumentLocationAdapter.java
1
请完成以下Java代码
public void setGO_RequestUsername (java.lang.String GO_RequestUsername) { set_Value (COLUMNNAME_GO_RequestUsername, GO_RequestUsername); } /** Get Request Username. @return Request Username */ @Override public java.lang.String getGO_RequestUsername () { return (java.lang.String)get_Value(COLUMNNAME_GO_RequestUsername); } /** Set GO Shipper Configuration. @param GO_Shipper_Config_ID GO Shipper Configuration */ @Override public void setGO_Shipper_Config_ID (int GO_Shipper_Config_ID) { if (GO_Shipper_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_GO_Shipper_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_GO_Shipper_Config_ID, Integer.valueOf(GO_Shipper_Config_ID)); } /** Get GO Shipper Configuration. @return GO Shipper Configuration */ @Override public int getGO_Shipper_Config_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GO_Shipper_Config_ID); if (ii == null) return 0; return ii.intValue(); } /** Set GO URL. @param GO_URL GO URL */ @Override public void setGO_URL (java.lang.String GO_URL) { set_Value (COLUMNNAME_GO_URL, GO_URL); } /** Get GO URL. @return GO URL */ @Override public java.lang.String getGO_URL () { return (java.lang.String)get_Value(COLUMNNAME_GO_URL); } @Override public org.compiere.model.I_M_Shipper getM_Shipper() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class);
} @Override public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper) { set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper); } /** Set Lieferweg. @param M_Shipper_ID Methode oder Art der Warenlieferung */ @Override public void setM_Shipper_ID (int M_Shipper_ID) { if (M_Shipper_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID)); } /** Get Lieferweg. @return Methode oder Art der Warenlieferung */ @Override public int getM_Shipper_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-gen\de\metas\shipper\gateway\go\model\X_GO_Shipper_Config.java
1
请在Spring Boot框架中完成以下Java代码
public ClientDetails loadClientByClientId(String id) throws ClientRegistrationException { return sysClientDetailsRepository.findFirstByClientId(id).orElseThrow(() -> new ClientRegistrationException("Loading client exception.")); } @Override public SysClientDetails findByClientId(String clientId) { return sysClientDetailsRepository.findFirstByClientId(clientId).orElseThrow(() -> new ClientRegistrationException("Loading client exception.")); } @Override public void addClientDetails(SysClientDetails clientDetails) throws ClientAlreadyExistsException { clientDetails.setId(null); if (sysClientDetailsRepository.findFirstByClientId(clientDetails.getClientId()).isPresent()) { throw new ClientAlreadyExistsException(String.format("Client id %s already exist.", clientDetails.getClientId())); } sysClientDetailsRepository.save(clientDetails); } @Override public void updateClientDetails(SysClientDetails clientDetails) throws NoSuchClientException { SysClientDetails exist = sysClientDetailsRepository.findFirstByClientId(clientDetails.getClientId()).orElseThrow(() -> new NoSuchClientException("No such client!"));
clientDetails.setClientSecret(exist.getClientSecret()); sysClientDetailsRepository.save(clientDetails); } @Override public void updateClientSecret(String clientId, String clientSecret) throws NoSuchClientException { SysClientDetails exist = sysClientDetailsRepository.findFirstByClientId(clientId).orElseThrow(() -> new NoSuchClientException("No such client!")); exist.setClientSecret(passwordEncoder.encode(clientSecret)); sysClientDetailsRepository.save(exist); } @Override public void removeClientDetails(String clientId) throws NoSuchClientException { sysClientDetailsRepository.deleteByClientId(clientId); } @Override public List<SysClientDetails> findAll() { return sysClientDetailsRepository.findAll(); } }
repos\spring-boot-demo-master\demo-oauth\oauth-authorization-server\src\main\java\com\xkcoding\oauth\service\impl\SysClientDetailsServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
protected void validateCreate(TenantId tenantId, Device device) { validateNumberOfEntitiesPerTenant(tenantId, EntityType.DEVICE); } @Override protected Device validateUpdate(TenantId tenantId, Device device) { Device old = deviceDao.findById(device.getTenantId(), device.getId().getId()); if (old == null) { throw new DataValidationException("Can't update non existing device!"); } return old; } @Override protected void validateDataImpl(TenantId tenantId, Device device) { validateString("Device name", device.getName()); if (device.getTenantId() == null) { throw new DataValidationException("Device should be assigned to tenant!"); } else { if (!tenantService.tenantExists(device.getTenantId())) { throw new DataValidationException("Device is referencing to non-existent tenant!"); } } if (device.getCustomerId() == null) { device.setCustomerId(new CustomerId(NULL_UUID));
} else if (!device.getCustomerId().getId().equals(NULL_UUID)) { Customer customer = customerDao.findById(device.getTenantId(), device.getCustomerId().getId()); if (customer == null) { throw new DataValidationException("Can't assign device to non-existent customer!"); } if (!customer.getTenantId().getId().equals(device.getTenantId().getId())) { throw new DataValidationException("Can't assign device to customer from different tenant!"); } } Optional.ofNullable(device.getDeviceData()) .flatMap(deviceData -> Optional.ofNullable(deviceData.getTransportConfiguration())) .ifPresent(DeviceTransportConfiguration::validate); validateOtaPackage(tenantId, device, device.getDeviceProfileId()); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\DeviceDataValidator.java
2
请在Spring Boot框架中完成以下Java代码
public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } @ApiModelProperty(example = "dmn-DecisionTableOne.dmn") public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } @ApiModelProperty(example = "46aa6b3a-c0a1-11e6-bc93-6ab56fad108a") public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; }
@ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "decision_table") public String getDecisionType() { return decisionType; } public void setDecisionType(String decisionType) { this.decisionType = decisionType; } }
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\repository\DecisionResponse.java
2
请完成以下Java代码
public void setDocumentNo (String DocumentNo) { set_ValueNoCheck (COLUMNNAME_DocumentNo, DocumentNo); } /** Get Document No. @return Document sequence number of the document */ public String getDocumentNo () { return (String)get_Value(COLUMNNAME_DocumentNo); } /** Set Record ID. @param Record_ID Direct internal record ID */ public void setRecord_ID (int Record_ID) {
if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Record ID. @return Direct internal record ID */ public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence_Audit.java
1
请在Spring Boot框架中完成以下Java代码
public class ColorId implements RepoIdAware { int repoId; @JsonCreator public static ColorId ofRepoId(final int repoId) { return new ColorId(repoId); } public static ColorId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new ColorId(repoId) : null; } public static int toRepoId(final ColorId id)
{ return id != null ? id.getRepoId() : -1; } private ColorId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "AD_Color_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\ColorId.java
2
请完成以下Spring Boot application配置
spring.datasource.initialization-mode=always spring.datasource.platform=mysql spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect logging.level.com.zaxxer.hikari.HikariConfig=DEBUG logging.leve
l.com.zaxxer.hikari=TRACE spring.jpa.open-in-view=false spring.jpa.hibernate.ddl-auto=create
repos\Hibernate-SpringBoot-master\HibernateSpringBootDataSourceBuilderProgHikariCPKickoff\src\main\resources\application.properties
2
请完成以下Java代码
public Builder<?> toBuilder() { return new Builder<>(this); } /** * A builder of {@link CasServiceTicketAuthenticationToken} instances * * @since 7.0 */ public static class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> { private String principal; private @Nullable Object credentials; protected Builder(CasServiceTicketAuthenticationToken token) { super(token); this.principal = token.identifier; this.credentials = token.credentials; } @Override public B principal(@Nullable Object principal) { Assert.isInstanceOf(String.class, principal, "principal must be of type String"); this.principal = (String) principal;
return (B) this; } @Override public B credentials(@Nullable Object credentials) { Assert.notNull(credentials, "credentials cannot be null"); this.credentials = credentials; return (B) this; } @Override public CasServiceTicketAuthenticationToken build() { return new CasServiceTicketAuthenticationToken(this); } } }
repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\authentication\CasServiceTicketAuthenticationToken.java
1
请完成以下Java代码
public String getBatchType() { return batchType; } public void setBatchType(String batchType) { this.batchType = batchType; } public Integer getHistoryTimeToLive() { return historyTimeToLive; } public void setHistoryTimeToLive(Integer historyTimeToLive) { this.historyTimeToLive = historyTimeToLive; } public long getFinishedBatchesCount() { return finishedBatchesCount; } public void setFinishedBatchesCount(long finishedBatchCount) { this.finishedBatchesCount = finishedBatchCount; } public long getCleanableBatchesCount() { return cleanableBatchesCount; } public void setCleanableBatchesCount(long cleanableBatchCount) { this.cleanableBatchesCount = cleanableBatchCount; }
protected CleanableHistoricBatchReport createNewReportQuery(ProcessEngine engine) { return engine.getHistoryService().createCleanableHistoricBatchReport(); } public static List<CleanableHistoricBatchReportResultDto> convert(List<CleanableHistoricBatchReportResult> reportResult) { List<CleanableHistoricBatchReportResultDto> dtos = new ArrayList<CleanableHistoricBatchReportResultDto>(); for (CleanableHistoricBatchReportResult current : reportResult) { CleanableHistoricBatchReportResultDto dto = new CleanableHistoricBatchReportResultDto(); dto.setBatchType(current.getBatchType()); dto.setHistoryTimeToLive(current.getHistoryTimeToLive()); dto.setFinishedBatchesCount(current.getFinishedBatchesCount()); dto.setCleanableBatchesCount(current.getCleanableBatchesCount()); dtos.add(dto); } return dtos; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\batch\CleanableHistoricBatchReportResultDto.java
1
请在Spring Boot框架中完成以下Java代码
public class LoggingAspect { private final Logger logger = LoggerFactory.getLogger(getClass()); //Pointcut - When? // execution(* PACKAGE.*.*(..)) @Before("com.in28minutes.learnspringaop.aopexample.aspects.CommonPointcutConfig.allPackageConfigUsingBean()")//WHEN public void logMethodCallBeforeExecution(JoinPoint joinPoint) { logger.info("Before Aspect - {} is called with arguments: {}" , joinPoint, joinPoint.getArgs());//WHAT } @After("com.in28minutes.learnspringaop.aopexample.aspects.CommonPointcutConfig.businessPackageConfig()") public void logMethodCallAfterExecution(JoinPoint joinPoint) { logger.info("After Aspect - {} has executed", joinPoint); } @AfterThrowing( pointcut = "com.in28minutes.learnspringaop.aopexample.aspects.CommonPointcutConfig.businessAndDataPackageConfig()", throwing = "exception"
) public void logMethodCallAfterException(JoinPoint joinPoint, Exception exception) { logger.info("AfterThrowing Aspect - {} has thrown an exception {}" , joinPoint, exception); } @AfterReturning( pointcut = "com.in28minutes.learnspringaop.aopexample.aspects.CommonPointcutConfig.dataPackageConfig()", returning = "resultValue" ) public void logMethodCallAfterSuccessfulExecution(JoinPoint joinPoint, Object resultValue) { logger.info("AfterReturning Aspect - {} has returned {}" , joinPoint, resultValue); } }
repos\master-spring-and-spring-boot-main\73-spring-aop\src\main\java\com\in28minutes\learnspringaop\aopexample\aspects\LoggingAspect.java
2
请完成以下Java代码
public void setIsShipmentsNotSent (final boolean IsShipmentsNotSent) { throw new IllegalArgumentException ("IsShipmentsNotSent is virtual column"); } @Override public boolean isShipmentsNotSent() { return get_ValueAsBoolean(COLUMNNAME_IsShipmentsNotSent); } @Override public void setMovementDate (final @Nullable java.sql.Timestamp MovementDate) { set_Value (COLUMNNAME_MovementDate, MovementDate); } @Override public java.sql.Timestamp getMovementDate() { return get_ValueAsTimestamp(COLUMNNAME_MovementDate); } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override
public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setShipment_DocumentNo (final @Nullable java.lang.String Shipment_DocumentNo) { throw new IllegalArgumentException ("Shipment_DocumentNo is virtual column"); } @Override public java.lang.String getShipment_DocumentNo() { return get_ValueAsString(COLUMNNAME_Shipment_DocumentNo); } @Override public void setSumDeliveredInStockingUOM (final BigDecimal SumDeliveredInStockingUOM) { set_Value (COLUMNNAME_SumDeliveredInStockingUOM, SumDeliveredInStockingUOM); } @Override public BigDecimal getSumDeliveredInStockingUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumDeliveredInStockingUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSumOrderedInStockingUOM (final BigDecimal SumOrderedInStockingUOM) { set_Value (COLUMNNAME_SumOrderedInStockingUOM, SumOrderedInStockingUOM); } @Override public BigDecimal getSumOrderedInStockingUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumOrderedInStockingUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUserFlag (final @Nullable java.lang.String UserFlag) { set_Value (COLUMNNAME_UserFlag, UserFlag); } @Override public java.lang.String getUserFlag() { return get_ValueAsString(COLUMNNAME_UserFlag); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv.java
1
请完成以下Java代码
public void exitMulDiv(LabeledExprParser.MulDivContext ctx) { int left = values.get(ctx.expr(0)); int right = values.get(ctx.expr(1)); if (ctx.op.getType() == LabeledExprParser.MUL) { values.put(ctx, left * right); } else { values.put(ctx, left / right); } } @Override public void exitAddSub(LabeledExprParser.AddSubContext ctx) { int left = values.get(ctx.expr(0)); int right = values.get(ctx.expr(1)); if (ctx.op.getType() == LabeledExprParser.ADD) { values.put(ctx, left + right); } else { values.put(ctx, left - right); } } @Override public void exitInt(LabeledExprParser.IntContext ctx) { int value = Integer.parseInt(ctx.INT().getText()); values.put(ctx, value);
} @Override public void exitId(LabeledExprParser.IdContext ctx) { String id = ctx.ID().getText(); if (memory.containsKey(id)) { values.put(ctx, memory.get(id)); } else { values.put(ctx, 0); // default value if the variable is not found } } @Override public void exitParens(LabeledExprParser.ParensContext ctx) { values.put(ctx, values.get(ctx.expr())); } }
repos\springboot-demo-master\ANTLR\src\main\java\com\et\antlr\EvalListener.java
1
请完成以下Java代码
protected void copyPostDeployers(ProcessEngineConfigurationImpl flowable6Configuration, org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl flowable5Configuration) { if (flowable6Configuration.getCustomPostDeployers() != null) { List<org.activiti.engine.impl.persistence.deploy.Deployer> activiti5Deployers = new ArrayList<>(); for (EngineDeployer deployer : flowable6Configuration.getCustomPostDeployers()) { if (deployer instanceof RulesDeployer) { activiti5Deployers.add(new org.activiti.engine.impl.rules.RulesDeployer()); break; } } if (activiti5Deployers.size() > 0) { if (flowable5Configuration.getCustomPostDeployers() != null) { flowable5Configuration.getCustomPostDeployers().addAll(activiti5Deployers); } else { flowable5Configuration.setCustomPostDeployers(activiti5Deployers); } } } } protected void copyCustomVariableTypes(ProcessEngineConfigurationImpl flowable6Configuration, org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl flowable5Configuration) { flowable5Configuration.setCustomPreVariableTypes(flowable6Configuration.getCustomPreVariableTypes()); flowable5Configuration.setCustomPostVariableTypes(flowable6Configuration.getCustomPostVariableTypes()); } protected void convertParseHandlers(ProcessEngineConfigurationImpl flowable6Configuration, org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl flowable5Configuration) { flowable5Configuration.setPreBpmnParseHandlers(convert(flowable6Configuration.getFlowable5PreBpmnParseHandlers())); flowable5Configuration.setPostBpmnParseHandlers(convert(flowable6Configuration.getFlowable5PostBpmnParseHandlers()));
flowable5Configuration.setCustomDefaultBpmnParseHandlers(convert(flowable6Configuration.getFlowable5CustomDefaultBpmnParseHandlers())); } protected List<BpmnParseHandler> convert(List<Object> activiti5BpmnParseHandlers) { if (activiti5BpmnParseHandlers == null) { return null; } List<BpmnParseHandler> parseHandlers = new ArrayList<>(activiti5BpmnParseHandlers.size()); for (Object activiti6BpmnParseHandler : activiti5BpmnParseHandlers) { parseHandlers.add((BpmnParseHandler) activiti6BpmnParseHandler); } return parseHandlers; } }
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\DefaultProcessEngineFactory.java
1
请完成以下Java代码
private static SortedSet<LocalDateTime> newReverseSortedSet(final Collection<LocalDateTime> values) { final TreeSet<LocalDateTime> sortedSet = new TreeSet<>(Comparator.<LocalDateTime> naturalOrder().reversed()); if (values != null && !values.isEmpty()) { sortedSet.addAll(values); } return sortedSet; } private static LocalDateTime max(final Collection<LocalDateTime> dates) { Check.assumeNotEmpty(dates, "dates is not empty"); return dates.stream().max(Comparator.naturalOrder()).get(); } // // // // // public static class DateSequenceGeneratorBuilder { public DateSequenceGeneratorBuilder byDay() { return incrementor(CalendarIncrementors.dayByDay()); } /** * Iterate each <code>day</code> days. * * @param day * @return this */ public DateSequenceGeneratorBuilder byNthDay(final int day) { return incrementor(CalendarIncrementors.eachNthDay(day)); } public DateSequenceGeneratorBuilder byWeeks(final int week, final DayOfWeek dayOfWeek) { return incrementor(CalendarIncrementors.eachNthWeek(week, dayOfWeek)); } public DateSequenceGeneratorBuilder byMonths(final int months, final int dayOfMonth) { return incrementor(CalendarIncrementors.eachNthMonth(months, dayOfMonth)); } public DateSequenceGeneratorBuilder frequency(@NonNull final Frequency frequency) { incrementor(createCalendarIncrementor(frequency)); exploder(createDateSequenceExploder(frequency)); return this; } private static ICalendarIncrementor createCalendarIncrementor(final Frequency frequency) { if (frequency.isWeekly()) { return CalendarIncrementors.eachNthWeek(frequency.getEveryNthWeek(), DayOfWeek.MONDAY); } else if (frequency.isMonthly()) { return CalendarIncrementors.eachNthMonth(frequency.getEveryNthMonth(), 1); // every given month, 1st day }
else { throw new IllegalArgumentException("Frequency type not supported for " + frequency); } } private static IDateSequenceExploder createDateSequenceExploder(final Frequency frequency) { if (frequency.isWeekly()) { if (frequency.isOnlySomeDaysOfTheWeek()) { return DaysOfWeekExploder.of(frequency.getOnlyDaysOfWeek()); } else { return DaysOfWeekExploder.ALL_DAYS_OF_WEEK; } } else if (frequency.isMonthly()) { return DaysOfMonthExploder.of(frequency.getOnlyDaysOfMonth()); } else { throw new IllegalArgumentException("Frequency type not supported for " + frequency); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\generator\DateSequenceGenerator.java
1
请在Spring Boot框架中完成以下Java代码
public String getPhone() { return phone; } 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 AuthStatusEnum getAuthStatusEnum() { return authStatusEnum; } public void setAuthStatusEnum(AuthStatusEnum authStatusEnum) { this.authStatusEnum = authStatusEnum; } public String getAuthMsg() { return authMsg; } public void setAuthMsg(String authMsg) { this.authMsg = authMsg; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\AuthResultVo.java
2
请完成以下Java代码
public void setQtyToProcess (final @Nullable BigDecimal QtyToProcess) { set_Value (COLUMNNAME_QtyToProcess, QtyToProcess); } @Override public BigDecimal getQtyToProcess() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToProcess); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public org.compiere.model.I_S_Resource getS_Resource() { return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class); } @Override public void setS_Resource(final org.compiere.model.I_S_Resource S_Resource) { set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource); } @Override public void setS_Resource_ID (final int S_Resource_ID) { if (S_Resource_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Resource_ID, S_Resource_ID);
} @Override public int getS_Resource_ID() { return get_ValueAsInt(COLUMNNAME_S_Resource_ID); } @Override public org.compiere.model.I_S_Resource getWorkStation() { return get_ValueAsPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class); } @Override public void setWorkStation(final org.compiere.model.I_S_Resource WorkStation) { set_ValueFromPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class, WorkStation); } @Override public void setWorkStation_ID (final int WorkStation_ID) { if (WorkStation_ID < 1) set_Value (COLUMNNAME_WorkStation_ID, null); else set_Value (COLUMNNAME_WorkStation_ID, WorkStation_ID); } @Override public int getWorkStation_ID() { return get_ValueAsInt(COLUMNNAME_WorkStation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Candidate.java
1
请完成以下Java代码
private Authentication getAuthentication() { Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication(); if (authentication == null) { throw new AuthenticationCredentialsNotFoundException( "An Authentication object was not found in the SecurityContext"); } return authentication; } /** * Use this {@link AuthorizationEventPublisher} to publish * {@link AuthorizationDeniedEvent}s and {@link AuthorizationGrantedEvent}s. * @param eventPublisher the {@link ApplicationEventPublisher} to use * @since 5.7 */ public void setAuthorizationEventPublisher(AuthorizationEventPublisher eventPublisher) { Assert.notNull(eventPublisher, "eventPublisher cannot be null"); this.eventPublisher = eventPublisher; } /** * Gets the {@link AuthorizationManager} used by this filter * @return the {@link AuthorizationManager} */ public AuthorizationManager<HttpServletRequest> getAuthorizationManager() { return this.authorizationManager; } public boolean isObserveOncePerRequest() { return this.observeOncePerRequest; } /** * Sets whether this filter apply only once per request. By default, this is * <code>false</code>, meaning the filter will execute on every request. Sometimes * users may wish it to execute more than once per request, such as when JSP forwards * are being used and filter security is desired on each included fragment of the HTTP * request.
* @param observeOncePerRequest whether the filter should only be applied once per * request */ public void setObserveOncePerRequest(boolean observeOncePerRequest) { this.observeOncePerRequest = observeOncePerRequest; } /** * If set to true, the filter will be applied to error dispatcher. Defaults to * {@code true}. * @param filterErrorDispatch whether the filter should be applied to error dispatcher */ public void setFilterErrorDispatch(boolean filterErrorDispatch) { this.filterErrorDispatch = filterErrorDispatch; } /** * If set to true, the filter will be applied to the async dispatcher. Defaults to * {@code true}. * @param filterAsyncDispatch whether the filter should be applied to async dispatch */ public void setFilterAsyncDispatch(boolean filterAsyncDispatch) { this.filterAsyncDispatch = filterAsyncDispatch; } private static class NoopAuthorizationEventPublisher implements AuthorizationEventPublisher { @Override public <T> void publishAuthorizationEvent(Supplier<Authentication> authentication, T object, @Nullable AuthorizationResult result) { } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\intercept\AuthorizationFilter.java
1
请完成以下Java代码
public void registerListener(@NonNull final IQueueProcessorListener listener, final int workpackageId) { Check.assume(workpackageId > 0, "workpackageId > 0"); // If it's null then don't register it if (listener == NullQueueProcessorListener.instance) { return; } final ListenerEntry entry = new ListenerEntry(listener, workpackageId); addListenerEntry(workpackageId, entry); } @Override public boolean unregisterListener(final IQueueProcessorListener callback, final int workpackageId)
{ // If it's null then don't unregister it because it was never registered if (callback == NullQueueProcessorListener.instance) { return false; } return removeListenerEntry(workpackageId, callback); } @Override public boolean unregisterListeners(final int workpackageId) { return removeListenerEntry(workpackageId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\DefaultQueueProcessorEventDispatcher.java
1
请在Spring Boot框架中完成以下Java代码
private static class JasperEntry { @NonNull File jrxmlFile; @NonNull File jasperFile; @NonNull File hashFile; public URL getJasperUrl() { try { return jasperFile.toURI().toURL(); } catch (final MalformedURLException e) { throw new AdempiereException("Cannot convert " + jasperFile + " to URL", e); } } } // // // // // @ToString(of = "compiledJaspersDir") private static class CompliedJaspersCacheFileSystem { @NonNull private final Path compiledJaspersDir; public CompliedJaspersCacheFileSystem() { try { final Path basePath = Paths.get(FileUtil.getTempDir(), "compiled_jaspers"); this.compiledJaspersDir = Files.createDirectories(basePath); logger.info("Using compiled reports cache directory: {}", this.compiledJaspersDir); } catch (IOException e) { throw new AdempiereException("Failed to create the base temporary directory for compiled reports.", e); } } public JasperEntry getByJrxmlFile(@NonNull final File jrxmlFile) { return JasperEntry.builder() .jrxmlFile(jrxmlFile) .jasperFile(getCompiledAssetFile(jrxmlFile, jasperExtension)) .hashFile(getCompiledAssetFile(jrxmlFile, ".hash")) .build();
} private File getCompiledAssetFile(@NonNull final File jrxmlFile, @NonNull final String extension) { final Path jrxmlPath = jrxmlFile.toPath().toAbsolutePath(); // 1. Get the path *relative* to the drive/volume root. // Example: For C:\workspaces\...\report.jrxml, this isolates: // "workspaces\dt204\metasfresh\backend\de.metas.fresh\...\report_lu.jrxml" // We use the full relative path to ensure no collisions. final Path relativePath = jrxmlPath.getRoot().relativize(jrxmlPath); // 2. Separate the directory structure (parent) from the file name. final Path relativeDirPath = relativePath.getParent(); // 3. Resolve the cache directory path: compiledJaspersDir + relativeDirPath final Path cacheDir = compiledJaspersDir.resolve(relativeDirPath); // 4. Create the final compiled file name (only changes extension). final String compiledFileName = FileUtil.changeFileExtension(jrxmlFile.getName(), extension); // 5. Resolve the final cached path. final Path cachedPath = cacheDir.resolve(compiledFileName); return cachedPath.toFile(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\class_loader\JasperCompileClassLoader.java
2
请在Spring Boot框架中完成以下Java代码
private <T extends Collection<AnnotationAttributes>> T toAnnotationAttributesFromMultiValueMap( MultiValueMap<String, Object> map) { List<AnnotationAttributes> annotationAttributesList = new ArrayList<>(); map.forEach((key, value) -> { for (int index = 0, size = value.size(); index < size; index++) { AnnotationAttributes annotationAttributes = resolveAnnotationAttributes(annotationAttributesList, index); annotationAttributes.put(key, value.get(index)); } }); return (T) annotationAttributesList; } private AnnotationAttributes resolveAnnotationAttributes(List<AnnotationAttributes> annotationAttributesList, int index) { if (index < annotationAttributesList.size()) { return annotationAttributesList.get(index); } else { AnnotationAttributes newAnnotationAttributes = new AnnotationAttributes(); annotationAttributesList.add(newAnnotationAttributes); return newAnnotationAttributes; } } private PropertyResolver getPropertyResolver(ConditionContext context) { return context.getEnvironment(); } private List<String> collectPropertyNames(AnnotationAttributes annotationAttributes) { String prefix = getPrefix(annotationAttributes); String[] names = getNames(annotationAttributes); return Arrays.stream(names).map(name -> prefix + name).collect(Collectors.toList()); }
private String[] getNames(AnnotationAttributes annotationAttributes) { String[] names = annotationAttributes.getStringArray("name"); String[] values = annotationAttributes.getStringArray("value"); Assert.isTrue(names.length > 0 || values.length > 0, String.format("The name or value attribute of @%s is required", ConditionalOnMissingProperty.class.getSimpleName())); // TODO remove; not needed when using @AliasFor. /* Assert.isTrue(names.length * values.length == 0, String.format("The name and value attributes of @%s are exclusive", ConditionalOnMissingProperty.class.getSimpleName())); */ return names.length > 0 ? names : values; } private String getPrefix(AnnotationAttributes annotationAttributes) { String prefix = annotationAttributes.getString("prefix"); return StringUtils.hasText(prefix) ? prefix.trim().endsWith(".") ? prefix.trim() : prefix.trim() + "." : ""; } private Collection<String> findMatchingProperties(PropertyResolver propertyResolver, List<String> propertyNames) { return propertyNames.stream().filter(propertyResolver::containsProperty).collect(Collectors.toSet()); } private ConditionOutcome determineConditionOutcome(Collection<String> matchingProperties) { if (!matchingProperties.isEmpty()) { return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingProperty.class) .found("property already defined", "properties already defined") .items(matchingProperties)); } return ConditionOutcome.match(); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\condition\OnMissingPropertyCondition.java
2
请在Spring Boot框架中完成以下Java代码
public String getPICaption(@NonNull final HuPackingInstructionsId piId) { return huService.getPI(piId).getName(); } @Override public String getLocatorName(@NonNull final LocatorId locatorId) { return locatorNamesCache.computeIfAbsent(locatorId, warehouseService::getLocatorNameById); } @Override public HUQRCode getQRCodeByHUId(final HuId huId) { return huService.getQRCodeByHuId(huId); }
@Override public ScheduledPackageableLocks getLocks(final ShipmentScheduleAndJobScheduleIdSet scheduleIds) { return pickingJobLockService.getLocks(scheduleIds); } @Override public int getSalesOrderLineSeqNo(@NonNull final OrderAndLineId orderAndLineId) { return orderService.getSalesOrderLineSeqNo(orderAndLineId); } // // // }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\repository\DefaultPickingJobLoaderSupportingServices.java
2
请完成以下Java代码
public VariableAggregationDefinitions getAggregations() { return aggregations; } public void setAggregations(VariableAggregationDefinitions aggregations) { this.aggregations = aggregations; } public void addAggregation(VariableAggregationDefinition aggregation) { if (this.aggregations == null) { this.aggregations = new VariableAggregationDefinitions(); } this.aggregations.getAggregations().add(aggregation); } @Override public MultiInstanceLoopCharacteristics clone() { MultiInstanceLoopCharacteristics clone = new MultiInstanceLoopCharacteristics(); clone.setValues(this); return clone; }
public void setValues(MultiInstanceLoopCharacteristics otherLoopCharacteristics) { super.setValues(otherLoopCharacteristics); setInputDataItem(otherLoopCharacteristics.getInputDataItem()); setCollectionString(otherLoopCharacteristics.getCollectionString()); if (otherLoopCharacteristics.getHandler() != null) { setHandler(otherLoopCharacteristics.getHandler().clone()); } setLoopCardinality(otherLoopCharacteristics.getLoopCardinality()); setCompletionCondition(otherLoopCharacteristics.getCompletionCondition()); setElementVariable(otherLoopCharacteristics.getElementVariable()); setElementIndexVariable(otherLoopCharacteristics.getElementIndexVariable()); setSequential(otherLoopCharacteristics.isSequential()); setNoWaitStatesAsyncLeave(otherLoopCharacteristics.isNoWaitStatesAsyncLeave()); if (otherLoopCharacteristics.getAggregations() != null) { setAggregations(otherLoopCharacteristics.getAggregations().clone()); } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\MultiInstanceLoopCharacteristics.java
1
请完成以下Java代码
public class User implements UserDetails { private @MongoId ObjectId id; private String username; private String password; private Set<UserRole> userRoles; public ObjectId getId() { return id; } @Override public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void setUserRoles(Set<UserRole> userRoles) { this.userRoles = userRoles; } @Override public Set<UserRole> getAuthorities() { return this.userRoles; } @Override public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; }
@Override public boolean isAccountNonExpired() { return false; } @Override public boolean isAccountNonLocked() { return false; } @Override public boolean isCredentialsNonExpired() { return false; } @Override public boolean isEnabled() { return false; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return Objects.equals(username, user.username); } @Override public int hashCode() { return Objects.hash(username); } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\mongoauth\domain\User.java
1
请完成以下Java代码
public static ShipmentScheduleAvailableStock of() { return EMPTY; } private static final ShipmentScheduleAvailableStock EMPTY = new ShipmentScheduleAvailableStock(); private final ImmutableList<ShipmentScheduleAvailableStockDetail> list; private ShipmentScheduleAvailableStock(@NonNull final Collection<ShipmentScheduleAvailableStockDetail> list) { this.list = ImmutableList.copyOf(list); } private ShipmentScheduleAvailableStock() { this.list = ImmutableList.of(); } public BigDecimal getTotalQtyAvailable() { return list.stream() .map(ShipmentScheduleAvailableStockDetail::getQtyAvailable) .reduce(BigDecimal.ZERO, BigDecimal::add); } public boolean isEmpty() { return list.isEmpty(); } public int size() { return list.size();
} public BigDecimal getQtyAvailable(final int storageIndex) { return getStorageDetail(storageIndex).getQtyAvailable(); } public void subtractQtyOnHand(final int storageIndex, @NonNull final BigDecimal qtyOnHandToRemove) { getStorageDetail(storageIndex).subtractQtyOnHand(qtyOnHandToRemove); } public ShipmentScheduleAvailableStockDetail getStorageDetail(final int storageIndex) { return list.get(storageIndex); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\util\ShipmentScheduleAvailableStock.java
1
请在Spring Boot框架中完成以下Java代码
private File createFile(String bill_date, String stringResult, String dir) throws IOException { // 创建本地文件,用于存储支付宝对账文件 // String dir = "/home/roncoo/app/accountcheck/billfile/alipay"; File file = new File(dir, bill_date + "_" + ".xml"); int index = 1; // 判断文件是否已经存在 while (file.exists()) { file = new File(dir, bill_date + "_" + index + ".xml"); index++; } // 判断父文件是否存在,不存在就创建 if (!file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { // 新建文件目录失败,抛异常 throw new IOException("创建文件(父层文件夹)失败, filepath: " + file.getAbsolutePath()); } } // 判断文件是否存在,不存在则创建 if (!file.exists()) { if (!file.createNewFile()) { // 新建文件失败,抛异常 throw new IOException("创建文件失败, filepath: " + file.getAbsolutePath()); } }
try { // 把支付宝返回数据写入文件 FileWriter fileWriter = new FileWriter(file); fileWriter.write(stringResult); fileWriter.close(); // 关闭数据流 } catch (IOException e) { LOG.info("把支付宝返回的对账数据写入文件异常:" + e); } return file; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\fileDown\impl\AlipayFileDown.java
2
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_C_TaxType[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Tax Type. @param C_TaxType_ID Tax Type */ public void setC_TaxType_ID (int C_TaxType_ID) { if (C_TaxType_ID < 1) set_ValueNoCheck (COLUMNNAME_C_TaxType_ID, null); else set_ValueNoCheck (COLUMNNAME_C_TaxType_ID, Integer.valueOf(C_TaxType_ID)); } /** Get Tax Type. @return Tax Type */ public int getC_TaxType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */
public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_C_TaxType.java
1
请完成以下Java代码
private ProjectId createNewSalesPurchaseOrderProject(final @NonNull I_C_Order purchaseOrder) { final BPartnerId bpartnerId = BPartnerId.ofRepoId(purchaseOrder.getC_BPartner_ID()); return projectService.createProject(CreateProjectRequest.builder() .projectCategory(ProjectCategory.SalesPurchaseOrder) .orgId(OrgId.ofRepoId(purchaseOrder.getAD_Org_ID())) .currencyId(CurrencyId.ofRepoId(purchaseOrder.getC_Currency_ID())) .warehouseId(WarehouseId.ofRepoId(purchaseOrder.getM_Warehouse_ID())) .bpartnerAndLocationId(BPartnerLocationId.ofRepoId(bpartnerId, purchaseOrder.getC_BPartner_Location_ID())) .contactId(BPartnerContactId.ofRepoIdOrNull(bpartnerId, purchaseOrder.getAD_User_ID())) .build()); } private void setProjectIdToOrderLines(@NonNull final ProjectId newProjectId, @NonNull final List<I_C_OrderLine> poLines) { final HashMap<OrderAndLineId, I_C_OrderLine> poLinesUpdated = new HashMap<>(); poLines.stream() .filter(ol -> ProjectId.ofRepoIdOrNull(ol.getC_Project_ID()) == null)
.forEach(ol -> { ol.setC_Project_ID(newProjectId.getRepoId()); poLinesUpdated.put(OrderAndLineId.ofRepoIds(ol.getC_Order_ID(), ol.getC_OrderLine_ID()), ol); }); if (poLinesUpdated.isEmpty()) { return; } InterfaceWrapperHelper.saveAll(poLinesUpdated.values()); eventDispatcher.fireProjectCreatedEvent(ProjectCreatedEvent.builder() .projectId(newProjectId) .purchaseOrderLineIds(ImmutableSet.copyOf(poLinesUpdated.keySet())) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\model\interceptor\C_Order_Project.java
1
请完成以下Java代码
public void onResponse(ResponseEvent event) { if (isActive) { snmpTransportContext.getSnmpTransportService().processResponseEvent(this, event); } } public void initializeTarget(SnmpDeviceProfileTransportConfiguration profileTransportConfig, SnmpDeviceTransportConfiguration deviceTransportConfig) throws Exception { log.trace("Initializing target for SNMP session of device {}", device); this.target = snmpTransportContext.getSnmpAuthService().setUpSnmpTarget(profileTransportConfig, deviceTransportConfig); log.debug("SNMP target initialized: {}", target); } public void close() { isActive = false; } public String getToken() { return token; } @Override public int nextMsgId() { return msgIdSeq.incrementAndGet(); } @Override public void onGetAttributesResponse(GetAttributeResponseMsg getAttributesResponse) { } @Override public void onAttributeUpdate(UUID sessionId, AttributeUpdateNotificationMsg attributeUpdateNotification) { log.trace("[{}] Received attributes update notification to device", sessionId); try { snmpTransportContext.getSnmpTransportService().onAttributeUpdate(this, attributeUpdateNotification); } catch (Exception e) { snmpTransportContext.getTransportService().errorEvent(getTenantId(), getDeviceId(), SnmpCommunicationSpec.SHARED_ATTRIBUTES_SETTING.getLabel(), e); } }
@Override public void onRemoteSessionCloseCommand(UUID sessionId, SessionCloseNotificationProto sessionCloseNotification) { log.trace("[{}] Received the remote command to close the session: {}", sessionId, sessionCloseNotification.getMessage()); if (sessionCloseNotification.getMessage().equals(DefaultTransportService.SESSION_EXPIRED_MESSAGE)) { if (sessionTimeoutHandler != null) { sessionTimeoutHandler.run(); } } } @Override public void onToDeviceRpcRequest(UUID sessionId, ToDeviceRpcRequestMsg toDeviceRequest) { log.trace("[{}] Received RPC command to device", sessionId); try { snmpTransportContext.getSnmpTransportService().onToDeviceRpcRequest(this, toDeviceRequest); snmpTransportContext.getTransportService().process(getSessionInfo(), toDeviceRequest, RpcStatus.DELIVERED, TransportServiceCallback.EMPTY); } catch (Exception e) { snmpTransportContext.getTransportService().errorEvent(getTenantId(), getDeviceId(), SnmpCommunicationSpec.TO_DEVICE_RPC_REQUEST.getLabel(), e); } } @Override public void onToServerRpcResponse(ToServerRpcResponseMsg toServerResponse) { } }
repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\session\DeviceSessionContext.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isAfter(@NonNull final DateAndSeqNo other) { // note that we avoid using equals here, a timestamp and a date that are both "Date" might not be equal even if they have the same time. if (date.isAfter(other.getDate())) { return true; } if (date.isBefore(other.getDate())) { return false; } return seqNo > other.getSeqNo(); } /** * Analog to {@link #isAfter(DateAndSeqNo)}. */ public boolean isBefore(@NonNull final DateAndSeqNo other) { // note that we avoid using equals here, a timestamp and a date that are both "Date" might not be equal even if they have the same time. if (date.isBefore(other.getDate())) { return true; } if (date.isAfter(other.getDate())) { return false; } return seqNo < other.getSeqNo(); } public DateAndSeqNo min(@Nullable final DateAndSeqNo other) {
if (other == null) { return this; } else { return this.isBefore(other) ? this : other; } } public DateAndSeqNo max(@Nullable final DateAndSeqNo other) { if (other == null) { return this; } return this.isAfter(other) ? this : other; } public DateAndSeqNo withOperator(@Nullable final Operator operator) { return this .toBuilder() .operator(operator) .build(); } public static boolean equals(@Nullable final DateAndSeqNo value1, @Nullable final DateAndSeqNo value2) {return Objects.equals(value1, value2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\DateAndSeqNo.java
2
请完成以下Java代码
public class CreateHumanTaskAfterContext { protected HumanTask humanTask; protected TaskEntity taskEntity; protected PlanItemInstanceEntity planItemInstanceEntity; public CreateHumanTaskAfterContext() { } public CreateHumanTaskAfterContext(HumanTask humanTask, TaskEntity taskEntity, PlanItemInstanceEntity planItemInstanceEntity) { this.humanTask = humanTask; this.taskEntity = taskEntity; this.planItemInstanceEntity = planItemInstanceEntity; } public HumanTask getHumanTask() { return humanTask; } public void setHumanTask(HumanTask humanTask) { this.humanTask = humanTask; }
public TaskEntity getTaskEntity() { return taskEntity; } public void setTaskEntity(TaskEntity taskEntity) { this.taskEntity = taskEntity; } public PlanItemInstanceEntity getPlanItemInstanceEntity() { return planItemInstanceEntity; } public void setPlanItemInstanceEntity(PlanItemInstanceEntity planItemInstanceEntity) { this.planItemInstanceEntity = planItemInstanceEntity; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\interceptor\CreateHumanTaskAfterContext.java
1
请完成以下Java代码
public void mouseReleased(final MouseEvent e) { // nothing to do } @Override public void mouseClicked(final MouseEvent e) { if (e == null || listBox.getSelectedValue().equals(ITEM_More)) { setUserObject(null); return; } popup.setVisible(false); // 02027: tsa: hide popup when an item is selected final Object selected = listBox.getSelectedValue(); setUserObject(selected); textBox.setText(convertUserObjectForTextField(selected)); } public void addPropertyChangeListener(final PropertyChangeListener listener) { listBox.addPropertyChangeListener(listener); } public void setMaxItems(final int maxItems) { m_maxItems = maxItems; listBox.setVisibleRowCount(m_maxItems + 1); } public int getMaxItems() { return m_maxItems; } public final String getText() {
return textBox.getText(); } protected final int getTextCaretPosition() { return textBox.getCaretPosition(); } protected final void setTextCaretPosition(final int caretPosition) { textBox.setCaretPosition(caretPosition); } protected final void setText(final String text) { textBox.setText(text); } public final boolean isEnabled() { final boolean textBoxHasFocus = textBox.isFocusOwner(); return textBoxHasFocus; } public void setPopupMinimumChars(final int popupMinimumChars) { m_popupMinimumChars = popupMinimumChars; } public int getPopupMinimumChars() { return m_popupMinimumChars; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\FieldAutoCompleter.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(length); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(width); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Rectangle other = (Rectangle) obj; if (Double.doubleToLongBits(length) != Double.doubleToLongBits(other.length))
return false; if (Double.doubleToLongBits(width) != Double.doubleToLongBits(other.width)) return false; return true; } protected double getWidth() { return width; } protected double getLength() { return length; } }
repos\tutorials-master\core-java-modules\core-java-lang-8\src\main\java\com\baeldung\equalshashcode\entities\Rectangle.java
1
请完成以下Java代码
public void setIsInboundEMail (boolean IsInboundEMail) { set_Value (COLUMNNAME_IsInboundEMail, Boolean.valueOf(IsInboundEMail)); } /** Get Inbound EMail. @return Inbound EMail */ @Override public boolean isInboundEMail () { Object oo = get_Value(COLUMNNAME_IsInboundEMail); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Message-ID. @param MessageID EMail Message-ID */ @Override public void setMessageID (java.lang.String MessageID) { set_Value (COLUMNNAME_MessageID, MessageID); } /** Get Message-ID. @return EMail Message-ID */ @Override public java.lang.String getMessageID () { return (java.lang.String)get_Value(COLUMNNAME_MessageID); } @Override public org.compiere.model.I_R_Request getR_Request() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_R_Request_ID, org.compiere.model.I_R_Request.class); } @Override public void setR_Request(org.compiere.model.I_R_Request R_Request) { set_ValueFromPO(COLUMNNAME_R_Request_ID, org.compiere.model.I_R_Request.class, R_Request); } /** Set Aufgabe. @param R_Request_ID Request from a Business Partner or Prospect */ @Override public void setR_Request_ID (int R_Request_ID) { if (R_Request_ID < 1) set_Value (COLUMNNAME_R_Request_ID, null); else set_Value (COLUMNNAME_R_Request_ID, Integer.valueOf(R_Request_ID)); } /** Get Aufgabe. @return Request from a Business Partner or Prospect */
@Override public int getR_Request_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Request_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Betreff. @param Subject Mail Betreff */ @Override public void setSubject (java.lang.String Subject) { set_Value (COLUMNNAME_Subject, Subject); } /** Get Betreff. @return Mail Betreff */ @Override public java.lang.String getSubject () { return (java.lang.String)get_Value(COLUMNNAME_Subject); } @Override public org.compiere.model.I_AD_User getTo_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setTo_User(org.compiere.model.I_AD_User To_User) { set_ValueFromPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class, To_User); } /** Set To User. @param To_User_ID To User */ @Override public void setTo_User_ID (int To_User_ID) { if (To_User_ID < 1) set_Value (COLUMNNAME_To_User_ID, null); else set_Value (COLUMNNAME_To_User_ID, Integer.valueOf(To_User_ID)); } /** Get To User. @return To User */ @Override public int getTo_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_To_User_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Mail.java
1
请完成以下Spring Boot application配置
spring: application: name: demo-consumer cloud: # Nacos 作为注册中心的配置项 nacos: discovery: server-addr: 127.0.0.1:8848 # Dubbo 配置项,对应 DubboConfigurationProperties 类 dubbo: # Dubbo 服务注册中心配置,对应 RegistryConfig 类 registry: address: spring-cloud://127.0.0.1:8848 # 指定 Dubbo 服务注册中心的地址
# Spring Cloud Alibaba Dubbo 专属配置项,对应 DubboCloudProperties 类 cloud: subscribed-services: demo-provider # 设置订阅的应用列表,默认为 * 订阅所有应用。
repos\SpringBoot-Labs-master\labx-07-spring-cloud-alibaba-dubbo\labx-07-sca-dubbo-demo01\labx-07-sca-dubbo-demo01-consumer\src\main\resources\application.yaml
2
请完成以下Java代码
public String getSummary() { final StringBuilder sb = new StringBuilder(); if (countImportRecordsConsidered.isPresent() && countImportRecordsConsidered.getAsInt() > 0) { if (sb.length() > 0) {sb.append("; ");} sb.append(countImportRecordsConsidered.getAsInt()).append(" record(s) processed"); } if (!errors.isEmpty()) { if (sb.length() > 0) {sb.append("; ");} sb.append(errors.size()).append(" import errors encountered"); } return sb.toString(); } public String getCountInsertsIntoTargetTableString() { return counterToString(getCountInsertsIntoTargetTable()); } public String getCountUpdatesIntoTargetTableString() { return counterToString(getCountUpdatesIntoTargetTable()); } private static String counterToString(final OptionalInt counter) { return counter.isPresent() ? String.valueOf(counter.getAsInt()) : "N/A"; }
public boolean hasErrors() { return !getErrors().isEmpty(); } public int getCountErrors() { return getErrors().size(); } @Value @Builder public static class Error { @NonNull String message; @NonNull AdIssueId adIssueId; @Nullable transient Throwable exception; int affectedImportRecordsCount; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\ActualImportRecordsResult.java
1
请完成以下Java代码
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
请完成以下Java代码
protected String doIt() { StreamUtils.dice(streamDocumentsToRepost(), 1000) .forEach(this::enqueueChunk); return MSG_OK; } private void enqueueChunk(final Collection<DocumentToRepost> documentsToRepost) { FactAcctRepostCommand.builder() .documentsToRepost(documentsToRepost) .forcePosting(forcePosting) .onErrorNotifyUserId(getUserId()) .build() .execute(); } private Stream<DocumentToRepost> streamDocumentsToRepost() { return getView().streamByIds(getSelectedRowIds(), QueryLimit.NO_LIMIT) .map(this::extractDocumentToRepost); } private DocumentToRepost extractDocumentToRepost(@NonNull final IViewRow row) { final String tableName = getTableName(); if (I_Fact_Acct.Table_Name.equals(tableName) || FactAcctFilterDescriptorsProviderFactory.FACT_ACCT_TRANSACTIONS_VIEW.equals(tableName) || TABLENAME_RV_UnPosted.equals(tableName)) { return extractDocumentToRepostFromTableAndRecordIdRow(row); } else { return extractDocumentToRepostFromRegularRow(row); } } private DocumentToRepost extractDocumentToRepostFromTableAndRecordIdRow(final IViewRow row) { final int adTableId = row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Table_ID, -1); final int recordId = row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_Record_ID, -1); final ClientId adClientId = ClientId.ofRepoId(row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Client_ID, -1)); return DocumentToRepost.builder() .adTableId(adTableId) .recordId(recordId) .clientId(adClientId) .build();
} private DocumentToRepost extractDocumentToRepostFromRegularRow(final IViewRow row) { final int adTableId = adTablesRepo.retrieveTableId(getTableName()); final int recordId = row.getId().toInt(); final ClientId adClientId = ClientId.ofRepoId(row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Client_ID, -1)); return DocumentToRepost.builder() .adTableId(adTableId) .recordId(recordId) .clientId(adClientId) .build(); } @Override protected void postProcess(final boolean success) { getView().invalidateSelection(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\accounting\process\WEBUI_Fact_Acct_Repost_ViewRows.java
1
请完成以下Java代码
public void setAD_User_SortPref_Line_ID (int AD_User_SortPref_Line_ID) { if (AD_User_SortPref_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_SortPref_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_SortPref_Line_ID, Integer.valueOf(AD_User_SortPref_Line_ID)); } /** Get Sortierbegriff pro Benutzer Position. @return Sortierbegriff pro Benutzer Position */ @Override public int getAD_User_SortPref_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_SortPref_Line_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Spaltenname. @param ColumnName Name der Spalte in der Datenbank */ @Override public void setColumnName (java.lang.String ColumnName) { set_Value (COLUMNNAME_ColumnName, ColumnName); } /** Get Spaltenname. @return Name der Spalte in der Datenbank */ @Override public java.lang.String getColumnName () { return (java.lang.String)get_Value(COLUMNNAME_ColumnName); } /** Set Aufsteigender. @param IsAscending Aufsteigender */ @Override public void setIsAscending (boolean IsAscending) { set_Value (COLUMNNAME_IsAscending, Boolean.valueOf(IsAscending)); } /** Get Aufsteigender. @return Aufsteigender */ @Override public boolean isAscending () { Object oo = get_Value(COLUMNNAME_IsAscending); if (oo != null)
{ if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_SortPref_Line.java
1
请在Spring Boot框架中完成以下Java代码
public class DbTemplate { /** * 模拟数据库存储 user_id <-> session_id 的关系 */ public static final ConcurrentHashMap<String, UUID> DB = new ConcurrentHashMap<>(); /** * 获取所有SessionId * * @return SessionId列表 */ public List<UUID> findAll() { return CollUtil.newArrayList(DB.values()); } /** * 根据UserId查询SessionId * * @param userId 用户id * @return SessionId */ public Optional<UUID> findByUserId(String userId) { return Optional.ofNullable(DB.get(userId)); } /** * 保存/更新 user_id <-> session_id 的关系
* * @param userId 用户id * @param sessionId SessionId */ public void save(String userId, UUID sessionId) { DB.put(userId, sessionId); } /** * 删除 user_id <-> session_id 的关系 * * @param userId 用户id */ public void deleteByUserId(String userId) { DB.remove(userId); } }
repos\spring-boot-demo-master\demo-websocket-socketio\src\main\java\com\xkcoding\websocket\socketio\config\DbTemplate.java
2
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Error. @param IsError An Error occured in the execution */ public void setIsError (boolean IsError) { set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError)); } /** Get Error. @return An Error occured in the execution */ public boolean isError () { Object oo = get_Value(COLUMNNAME_IsError); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Reference. @param Reference Reference for this record */ public void setReference (String Reference) { set_Value (COLUMNNAME_Reference, Reference); } /** Get Reference. @return Reference for this record */ public String getReference () { return (String)get_Value(COLUMNNAME_Reference);
} /** Set Summary. @param Summary Textual summary of this request */ public void setSummary (String Summary) { set_Value (COLUMNNAME_Summary, Summary); } /** Get Summary. @return Textual summary of this request */ public String getSummary () { return (String)get_Value(COLUMNNAME_Summary); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AlertProcessorLog.java
1
请完成以下Java代码
private PInstanceId getOrCreateRecordsToImportSelectionId() { if (_recordsToImportSelectionId == null) { final ImportTableDescriptor importTableDescriptor = importFormat.getImportTableDescriptor(); final DataImportRunId dataImportRunId = getOrCreateDataImportRunId(); final IQuery<Object> query = queryBL.createQueryBuilder(importTableDescriptor.getTableName()) .addEqualsFilter(ImportTableDescriptor.COLUMNNAME_C_DataImport_Run_ID, dataImportRunId) .addEqualsFilter(ImportTableDescriptor.COLUMNNAME_I_ErrorMsg, null) .create(); _recordsToImportSelectionId = query.createSelection(); if (_recordsToImportSelectionId == null) { throw new AdempiereException("No records to import for " + query); } } return _recordsToImportSelectionId; }
private DataImportResult createResult() { final Duration duration = Duration.between(startTime, SystemTime.asInstant()); return DataImportResult.builder() .dataImportConfigId(dataImportConfigId) .duration(duration) // .insertIntoImportTable(insertIntoImportTableResult) .importRecordsValidation(validationResult) .actualImport(actualImportResult) .asyncImportResult(asyncImportResult) // .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\DataImportCommand.java
1
请完成以下Java代码
public String toString() { return "AtomNode{" + "word='" + sWord + '\'' + ", nature=" + nPOS + '}'; } public static Vertex convert(String word, int type) { String name = word; Nature nature = Nature.n; int dValue = 1; switch (type) { case CharType.CT_CHINESE: break; case CharType.CT_NUM: case CharType.CT_INDEX: case CharType.CT_CNUM: nature = Nature.m; word = Predefine.TAG_NUMBER; break; case CharType.CT_DELIMITER: nature = Nature.w; break; case CharType.CT_LETTER: nature = Nature.nx; word = Predefine.TAG_CLUSTER; break; case CharType.CT_SINGLE://12021-2129-3121 // if (Pattern.compile("^(-?\\d+)(\\.\\d+)?$").matcher(word).matches())//匹配浮点数 // {
// nature = Nature.m; // word = Predefine.TAG_NUMBER; // } else // { nature = Nature.nx; word = Predefine.TAG_CLUSTER; // } break; default: break; } return new Vertex(word, name, new CoreDictionary.Attribute(nature, dValue)); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\NShort\Path\AtomNode.java
1
请完成以下Java代码
public class UOMConversionRate { UomId fromUomId; UomId toUomId; @Getter(AccessLevel.NONE) BigDecimal fromToMultiplier; @Getter(AccessLevel.NONE) BigDecimal toFromMultiplier; boolean catchUOMForProduct; @Builder private UOMConversionRate( @NonNull final UomId fromUomId, @NonNull final UomId toUomId, @Nullable final BigDecimal fromToMultiplier, @Nullable final BigDecimal toFromMultiplier, final boolean catchUOMForProduct) { Check.assume(fromToMultiplier != null || toFromMultiplier != null, "at least fromToMultiplier={} or toFromMultiplier={} shall be not null", fromToMultiplier, toFromMultiplier); Check.assume(fromToMultiplier == null || fromToMultiplier.signum() != 0, "invalid fromToMultiplier: {}", fromToMultiplier); Check.assume(toFromMultiplier == null || toFromMultiplier.signum() != 0, "invalid toFromMultiplier: {}", toFromMultiplier); this.fromUomId = fromUomId; this.toUomId = toUomId; this.fromToMultiplier = fromToMultiplier; this.toFromMultiplier = toFromMultiplier; this.catchUOMForProduct = catchUOMForProduct; } public static UOMConversionRate one(@NonNull final UomId uomId) { return builder() .fromUomId(uomId) .toUomId(uomId) .fromToMultiplier(BigDecimal.ONE) .toFromMultiplier(BigDecimal.ONE) .build(); } public UOMConversionRate invert() { if (fromUomId.equals(toUomId)) { return this; } return UOMConversionRate.builder() .fromUomId(toUomId) .toUomId(fromUomId) .fromToMultiplier(toFromMultiplier) .toFromMultiplier(fromToMultiplier) .build(); } public boolean isOne() { return (fromToMultiplier == null || fromToMultiplier.compareTo(BigDecimal.ONE) == 0) && (toFromMultiplier == null || toFromMultiplier.compareTo(BigDecimal.ONE) == 0); } public BigDecimal getFromToMultiplier() { if (fromToMultiplier != null) { return fromToMultiplier; } else
{ return computeInvertedMultiplier(toFromMultiplier); } } public static BigDecimal computeInvertedMultiplier(@NonNull final BigDecimal multiplier) { if (multiplier.signum() == 0) { throw new AdempiereException("Multiplier shall not be ZERO"); } return NumberUtils.stripTrailingDecimalZeros(BigDecimal.ONE.divide(multiplier, 12, RoundingMode.HALF_UP)); } public BigDecimal convert(@NonNull final BigDecimal qty, @NonNull final UOMPrecision precision) { if (qty.signum() == 0) { return qty; } if (fromToMultiplier != null) { return precision.round(qty.multiply(fromToMultiplier)); } else { return qty.divide(toFromMultiplier, precision.toInt(), precision.getRoundingMode()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UOMConversionRate.java
1
请完成以下Java代码
public boolean isIgnoreInvoiceSchedule() { if (ignoreInvoiceSchedule != null) { return ignoreInvoiceSchedule; } else if (defaults != null) { return defaults.isIgnoreInvoiceSchedule(); } else { return false; } } public void setIgnoreInvoiceSchedule(final boolean ignoreInvoiceSchedule) { this.ignoreInvoiceSchedule = ignoreInvoiceSchedule; } @Nullable @Override public LocalDate getDateInvoiced() { if (dateInvoicedSet) { return dateInvoiced; } else if (defaults != null) { return defaults.getDateInvoiced(); } else { return null; } } public void setDateInvoiced(final LocalDate dateInvoiced) { this.dateInvoiced = dateInvoiced; dateInvoicedSet = true; } @Nullable @Override public LocalDate getDateAcct() { if (dateAcctSet) { return dateAcct; } else if (defaults != null) { return defaults.getDateAcct(); } else { return null; } } public void setDateAcct(final LocalDate dateAcct) { this.dateAcct = dateAcct; dateAcctSet = true; } @Nullable @Override public String getPOReference() { if (poReferenceSet) { return poReference; } else if (defaults != null) { return defaults.getPOReference(); } else { return null; } } public void setPOReference(@Nullable final String poReference) { this.poReference = poReference; poReferenceSet = true; }
@Nullable @Override public BigDecimal getCheck_NetAmtToInvoice() { if (check_NetAmtToInvoice != null) { return check_NetAmtToInvoice; } else if (defaults != null) { return defaults.getCheck_NetAmtToInvoice(); } return null; } @Override public boolean isStoreInvoicesInResult() { if (storeInvoicesInResult != null) { return storeInvoicesInResult; } else if (defaults != null) { return defaults.isStoreInvoicesInResult(); } else { return false; } } public PlainInvoicingParams setStoreInvoicesInResult(final boolean storeInvoicesInResult) { this.storeInvoicesInResult = storeInvoicesInResult; return this; } @Override public boolean isAssumeOneInvoice() { if (assumeOneInvoice != null) { return assumeOneInvoice; } else if (defaults != null) { return defaults.isAssumeOneInvoice(); } else { return false; } } public PlainInvoicingParams setAssumeOneInvoice(final boolean assumeOneInvoice) { this.assumeOneInvoice = assumeOneInvoice; return this; } public boolean isUpdateLocationAndContactForInvoice() { return updateLocationAndContactForInvoice; } public void setUpdateLocationAndContactForInvoice(boolean updateLocationAndContactForInvoice) { this.updateLocationAndContactForInvoice = updateLocationAndContactForInvoice; } public PlainInvoicingParams setCompleteInvoices(final boolean completeInvoices) { this.completeInvoices = completeInvoices; return this; } @Override public boolean isCompleteInvoices() { return completeInvoices; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\PlainInvoicingParams.java
1
请完成以下Spring Boot application配置
spring.docker.compose.enabled=true spring.docker.compose.file=./connectiondetails/docker/docker-compose-rabbitmq.yml spring.docker.compose.skip.in-tests=false spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true spring.mustache.check-template-location=false spring.profiles.active=rabbitmq spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration, org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration, org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration, org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration, org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration, org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration, org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration, org.springframework.boot.autoconfigure.data.cassandra.Cas
sandraRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration, org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.neo4j.Neo4jAutoConfiguration, org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration, org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration, org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration, org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration
repos\tutorials-master\spring-boot-modules\spring-boot-3-2\src\main\resources\connectiondetails\application-rabbitmq.properties
2
请在Spring Boot框架中完成以下Java代码
public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } @ApiModelProperty(example = "The One Task Case") public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "2") public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @ApiModelProperty(example = "http://localhost:8081/cmmn-repository/deployments/2") public String getDeploymentUrl() { return deploymentUrl; } public void setDeploymentUrl(String deploymentUrl) { this.deploymentUrl = deploymentUrl; } @ApiModelProperty(example = "Examples") public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public void setResource(String resource) { this.resource = resource; } @ApiModelProperty(example = "http://localhost:8182/cmmn-repository/deployments/2/resources/testCase.cmmn", value = "Contains the actual deployed CMMN 1.1 xml.") public String getResource() { return resource;
} @ApiModelProperty(example = "This is a case for testing purposes") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setDiagramResource(String diagramResource) { this.diagramResource = diagramResource; } @ApiModelProperty(example = "http://localhost:8182/cmmn-repository/deployments/2/resources/testProcess.png", value = "Contains a graphical representation of the case, null when no diagram is available.") public String getDiagramResource() { return diagramResource; } public void setGraphicalNotationDefined(boolean graphicalNotationDefined) { this.graphicalNotationDefined = graphicalNotationDefined; } @ApiModelProperty(value = "Indicates the case definition contains graphical information (CMMN DI).") public boolean isGraphicalNotationDefined() { return graphicalNotationDefined; } public void setStartFormDefined(boolean startFormDefined) { this.startFormDefined = startFormDefined; } public boolean isStartFormDefined() { return startFormDefined; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\CaseDefinitionResponse.java
2
请完成以下Java代码
public int getAD_User_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_Attribute_ID); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } /** * Attribute AD_Reference_ID=541332 * Reference name: AD_User_Attribute
*/ public static final int ATTRIBUTE_AD_Reference_ID=541332; /** Delegate = D */ public static final String ATTRIBUTE_Delegate = "D"; /** Politician = P */ public static final String ATTRIBUTE_Politician = "P"; /** Rechtsberater = R */ public static final String ATTRIBUTE_Rechtsberater = "R"; /** Schätzer = S */ public static final String ATTRIBUTE_Schaetzer = "S"; /** Vorstand = V */ public static final String ATTRIBUTE_Vorstand = "V"; @Override public void setAttribute (final java.lang.String Attribute) { set_Value (COLUMNNAME_Attribute, Attribute); } @Override public java.lang.String getAttribute() { return get_ValueAsString(COLUMNNAME_Attribute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Attribute.java
1
请完成以下Java代码
public void start() { commandExecutor.execute(new StartPlanItemInstanceCmd(planItemInstanceId, variables, formVariables, formOutcome, formInfo, localVariables, transientVariables, childTaskVariables, childTaskFormVariables, childTaskFormOutcome, childTaskFormInfo)); } @Override public void terminate() { validateChildTaskVariablesNotSet(); commandExecutor.execute(new TerminatePlanItemInstanceCmd(planItemInstanceId, variables, formVariables, formOutcome, formInfo, localVariables, transientVariables)); } @Override public void completeStage() { validateChildTaskVariablesNotSet(); commandExecutor.execute(new CompleteStagePlanItemInstanceCmd(planItemInstanceId, variables, formVariables, formOutcome, formInfo, localVariables, transientVariables, false)); }
@Override public void forceCompleteStage() { validateChildTaskVariablesNotSet(); commandExecutor.execute(new CompleteStagePlanItemInstanceCmd(planItemInstanceId, variables, formVariables, formOutcome, formInfo, localVariables, transientVariables, true)); } protected void validateChildTaskVariablesNotSet() { if (childTaskVariables != null) { throw new FlowableIllegalArgumentException("Child task variables can only be set when starting a plan item instance"); } if (childTaskFormInfo != null) { throw new FlowableIllegalArgumentException("Child form variables can only be set when starting a plan item instance"); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\PlanItemInstanceTransitionBuilderImpl.java
1
请完成以下Spring Boot application配置
server: port: 8081 spring: application: name: publisher-demo # Bus 相关配置项,对应 BusProperties cloud: bus: enabled: true # 是否开启,默认为 true destination: springCloudBus # 目标消息队列,默认为 springCloudBus # r
ocketmq 配置项,对应 RocketMQProperties 配置类 rocketmq: name-server: 127.0.0.1:9876 # RocketMQ Namesrv
repos\SpringBoot-Labs-master\labx-20\labx-20-sca-bus-rocketmq-demo-publisher\src\main\resources\application.yml
2
请完成以下Java代码
private static LocatorId findDestinationLocatorOrNull(@NonNull final I_M_InOutLine receiptLine) { final IReceiptScheduleDAO receiptScheduleDAO = Services.get(IReceiptScheduleDAO.class); final List<I_M_ReceiptSchedule> receiptScheduleRecords = receiptScheduleDAO.retrieveRsForInOutLine(receiptLine); return findDestinationLocatorOrNullForReceiptSchedules(receiptScheduleRecords); } private static LocatorId findDestinationLocatorOrNullForReceiptSchedules( @NonNull final List<I_M_ReceiptSchedule> receiptScheduleRecords) { final Integer warehouseDestRepoId = CollectionUtils.extractSingleElementOrDefault(receiptScheduleRecords, I_M_ReceiptSchedule::getM_Warehouse_Dest_ID, -1); if (warehouseDestRepoId <= 0) {
return null; } final IWarehouseBL warehouseBL = Services.get(IWarehouseBL.class); final I_M_Warehouse targetWarehouse = loadOutOfTrx(warehouseDestRepoId, I_M_Warehouse.class); final I_M_Locator locatorTo = warehouseBL.getOrCreateDefaultLocator(targetWarehouse); // Skip if we don't have a target warehouse if (locatorTo == null) { return null; } return LocatorId.ofRecordOrNull(locatorTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\api\ReceiptLineFindForwardToLocatorTool.java
1
请完成以下Java代码
public void setQtyShipped_CatchWeight_UOM_ID (final int QtyShipped_CatchWeight_UOM_ID) { if (QtyShipped_CatchWeight_UOM_ID < 1) set_Value (COLUMNNAME_QtyShipped_CatchWeight_UOM_ID, null); else set_Value (COLUMNNAME_QtyShipped_CatchWeight_UOM_ID, QtyShipped_CatchWeight_UOM_ID); } @Override public int getQtyShipped_CatchWeight_UOM_ID() { return get_ValueAsInt(COLUMNNAME_QtyShipped_CatchWeight_UOM_ID); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override
public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setReplicationTrxErrorMsg (final @Nullable java.lang.String ReplicationTrxErrorMsg) { throw new IllegalArgumentException ("ReplicationTrxErrorMsg is virtual column"); } @Override public java.lang.String getReplicationTrxErrorMsg() { return get_ValueAsString(COLUMNNAME_ReplicationTrxErrorMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java-gen\de\metas\ordercandidate\model\X_C_OLCand.java
1
请完成以下Java代码
public JSONLookupValuesPage getAttributeTypeahead( @PathVariable("asiDocId") final String asiDocIdStr, @PathVariable("attributeName") final String attributeName, @RequestParam(name = "query") final String query) { userSession.assertLoggedIn(); final DocumentId asiDocId = DocumentId.of(asiDocIdStr); return forASIDocumentReadonly(asiDocId, asiDoc -> asiDoc.getFieldLookupValuesForQuery(attributeName, query)) .transform(page -> JSONLookupValuesPage.of(page, userSession.getAD_Language())); } private boolean isLookupsAppendDescriptionToName() { return sysConfigBL.getBooleanValue(SYSCONFIG_LookupAppendDescriptionToName, true); } private JSONLookupValuesList toJSONLookupValuesList(final LookupValuesList lookupValuesList) { return JSONLookupValuesList.ofLookupValuesList(lookupValuesList, userSession.getAD_Language(), isLookupsAppendDescriptionToName()); } private JSONLookupValue toJSONLookupValue(final LookupValue lookupValue) { return JSONLookupValue.ofLookupValue(lookupValue, userSession.getAD_Language(), isLookupsAppendDescriptionToName()); } @GetMapping("/{asiDocId}/field/{attributeName}/dropdown") public JSONLookupValuesList getAttributeDropdown( @PathVariable("asiDocId") final String asiDocIdStr, @PathVariable("attributeName") final String attributeName) { userSession.assertLoggedIn(); final DocumentId asiDocId = DocumentId.of(asiDocIdStr); return forASIDocumentReadonly(asiDocId, asiDoc -> asiDoc.getFieldLookupValues(attributeName)) .transform(this::toJSONLookupValuesList); } @PostMapping(value = "/{asiDocId}/complete")
public JSONLookupValue complete( @PathVariable("asiDocId") final String asiDocIdStr, @RequestBody final JSONCompleteASIRequest request) { userSession.assertLoggedIn(); final DocumentId asiDocId = DocumentId.of(asiDocIdStr); return Execution.callInNewExecution("complete", () -> completeInTrx(asiDocId, request)) .transform(this::toJSONLookupValue); } private LookupValue completeInTrx(final DocumentId asiDocId, final JSONCompleteASIRequest request) { return asiRepo.forASIDocumentWritable( asiDocId, NullDocumentChangesCollector.instance, documentsCollection, asiDoc -> { final List<JSONDocumentChangedEvent> events = request.getEvents(); if (events != null && !events.isEmpty()) { asiDoc.processValueChanges(events, REASON_ProcessASIDocumentChanges); } return asiDoc.complete(); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASIRestController.java
1
请完成以下Java代码
public String getType() { return type; } public void setType(String type) { this.type = type; } public String getOpenType() { return openType; } public void setOpenType(String openType) { this.openType = openType; } public String getOpenPage() { return openPage;
} public void setOpenPage(String openPage) { this.openPage = openPage; } public static SysAnnmentTypeEnum getByType(String type) { if (oConvertUtils.isEmpty(type)) { return null; } for (SysAnnmentTypeEnum val : values()) { if (val.getType().equals(type)) { return val; } } return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\SysAnnmentTypeEnum.java
1
请完成以下Java代码
public Object get(Object key) { return key instanceof String ? cachingResolver.resolveProperty((String) key) : delegate.get(key); } @Override public Object getOrDefault(Object key, Object defaultValue) { return key instanceof String ? cachingResolver.resolveProperty((String) key) : delegate.getOrDefault(key, defaultValue); } @Override @NonNull public Collection<Object> values() { return new AbstractCollection<>() { @Override @NonNull public Iterator<Object> iterator() { return new DecoratingEntryValueIterator(delegate.entrySet().iterator()); } @Override public int size() { return delegate.size(); } }; } @Override @NonNull public Set<Entry<String, Object>> entrySet() { return new AbstractSet<>() { @Override @NonNull public Iterator<Entry<String, Object>> iterator() { return new DecoratingEntryIterator(delegate.entrySet().iterator()); } @Override public int size() { return delegate.size(); } }; } private class DecoratingEntryIterator implements Iterator<Entry<String, Object>> { private final Iterator<Entry<String, Object>> delegate; DecoratingEntryIterator(Iterator<Entry<String, Object>> delegate) { this.delegate = delegate; }
@Override public boolean hasNext() { return delegate.hasNext(); } @Override public Entry<String, Object> next() { Entry<String, Object> entry = delegate.next(); return new AbstractMap.SimpleEntry<>(entry.getKey(), cachingResolver.resolveProperty(entry.getKey())); } } @Override public void forEach(BiConsumer<? super String, ? super Object> action) { delegate.forEach((k, v) -> action.accept(k, cachingResolver.resolveProperty(k))); } private class DecoratingEntryValueIterator implements Iterator<Object> { private final Iterator<Entry<String, Object>> entryIterator; DecoratingEntryValueIterator(Iterator<Entry<String, Object>> entryIterator) { this.entryIterator = entryIterator; } @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public Object next() { Entry<String, Object> entry = entryIterator.next(); return cachingResolver.resolveProperty(entry.getKey()); } } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\caching\EncryptableMapWrapper.java
1
请在Spring Boot框架中完成以下Java代码
public class AcctSchemaId implements RepoIdAware { @JsonCreator @NonNull public static AcctSchemaId ofRepoId(final int repoId) { return new AcctSchemaId(repoId); } @Nullable public static AcctSchemaId ofRepoIdOrNull(final int repoId) { if (repoId <= 0) { return null; } else { return ofRepoId(repoId); } } public static int toRepoId(@Nullable final AcctSchemaId id) {
return id != null ? id.getRepoId() : -1; } int repoId; private AcctSchemaId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_AcctSchema_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals( @Nullable final AcctSchemaId id1, @Nullable final AcctSchemaId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\AcctSchemaId.java
2
请在Spring Boot框架中完成以下Java代码
public class RecurrentNonBusinessDay implements NonBusinessDay { @NonNull RecurrentNonBusinessDayFrequency frequency; @NonNull LocalDate startDate; @Nullable LocalDate endDate; @Nullable String name; @Override public boolean isMatching(@NonNull final LocalDate date) { if (!isInRange(date)) { return false; } if (frequency == RecurrentNonBusinessDayFrequency.WEEKLY) { final DayOfWeek dayOfWeek = this.startDate.getDayOfWeek(); return date.getDayOfWeek().equals(dayOfWeek); } else if (frequency == RecurrentNonBusinessDayFrequency.YEARLY) { LocalDate currentDate = startDate; while (isInRange(currentDate) && currentDate.compareTo(date) <= 0) { if (currentDate.equals(date)) {
return true; } currentDate = currentDate.plusYears(1); } return false; } else { throw new AdempiereException("Unknown frequency type: " + frequency); } } private boolean isInRange(@NonNull final LocalDate date) { // Before start date if (date.compareTo(startDate) < 0) { return false; } // After end date if (endDate != null && date.compareTo(endDate) > 0) { return false; } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\calendar\RecurrentNonBusinessDay.java
2
请完成以下Java代码
public String getPriority() { return priority; } public void setPriority(String priority) { this.priority = priority; } public String getAdmin() { return admin; } public void setAdmin(String admin) { this.admin = admin; } public String getConcurrency() { return concurrency; } public void setConcurrency(String concurrency) { this.concurrency = concurrency; }
public String getExecutor() { return executor; } public void setExecutor(String executor) { this.executor = executor; } public String getAckMode() { return ackMode; } public void setAckMode(String ackMode) { this.ackMode = ackMode; } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\RabbitInboundChannelModel.java
1
请完成以下Java代码
private ImmutableMap<ProductId, Quantity> divideQuantities( @NonNull final ImmutableMap<ProductId, Quantity> productsAndQuantities, final int divisor) { final ImmutableSet<Entry<ProductId, Quantity>> entrySet = productsAndQuantities.entrySet(); final BigDecimal divisorBD = new BigDecimal(divisor); return entrySet .stream() .collect(ImmutableMap.toImmutableMap( Entry::getKey, e -> e.getValue().divide(divisorBD))); } @Nullable private PackagingCode extractPackagingCodeId(@NonNull final I_M_HU hu) { final I_M_HU_PI_Version piVersionrecord = loadOutOfTrx(hu.getM_HU_PI_Version_ID(), I_M_HU_PI_Version.class); final int packagingCodeRecordId = piVersionrecord.getM_HU_PackagingCode_ID(); if (packagingCodeRecordId <= 0) { return null; } final I_M_HU_PackagingCode packagingCodeRecord = loadOutOfTrx(packagingCodeRecordId, I_M_HU_PackagingCode.class); return PackagingCode.builder() .id(PackagingCodeId.ofRepoId(packagingCodeRecordId)) .onlyForType(Optional.ofNullable(HUType.ofCodeOrNull(packagingCodeRecord.getHU_UnitType()))) .value(packagingCodeRecord.getPackagingCode()) .build(); } public HU getResult() { assume(huStack.isEmpty(), "In the end, huStack needs to be empty"); final HU root = currentIdAndBuilder.getRight().build(); return root; } } @ToString private static class HUStack { private final ArrayList<HuId> huIds = new ArrayList<>(); private final HashMap<HuId, HUBuilder> hus = new HashMap<>(); void push(@NonNull final IPair<HuId, HUBuilder> idWithHuBuilder) { this.huIds.add(idWithHuBuilder.getLeft());
this.hus.put(idWithHuBuilder.getLeft(), idWithHuBuilder.getRight()); } public boolean isEmpty() { return huIds.isEmpty(); } public IPair<HuId, HUBuilder> peek() { final HuId huId = this.huIds.get(huIds.size() - 1); final HUBuilder huBuilder = this.hus.get(huId); return ImmutablePair.of(huId, huBuilder); } final IPair<HuId, HUBuilder> pop() { final HuId huId = this.huIds.remove(huIds.size() - 1); final HUBuilder huBuilder = this.hus.remove(huId); return ImmutablePair.of(huId, huBuilder); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\generichumodel\HURepository.java
1
请在Spring Boot框架中完成以下Java代码
public ResponseEntity<Order> create(@RequestBody OrderForm form) { List<OrderProductDto> formDtos = form.getProductOrders(); validateProductsExistence(formDtos); Order order = new Order(); order.setStatus(OrderStatus.PAID.name()); order = this.orderService.create(order); List<OrderProduct> orderProducts = new ArrayList<>(); for (OrderProductDto dto : formDtos) { orderProducts.add(orderProductService.create(new OrderProduct(order, productService.getProduct(dto .getProduct() .getId()), dto.getQuantity()))); } order.setOrderProducts(orderProducts); this.orderService.update(order); String uri = ServletUriComponentsBuilder .fromCurrentServletMapping() .path("/orders/{id}") .buildAndExpand(order.getId()) .toString(); HttpHeaders headers = new HttpHeaders(); headers.add("Location", uri); return new ResponseEntity<>(order, headers, HttpStatus.CREATED); } private void validateProductsExistence(List<OrderProductDto> orderProducts) { List<OrderProductDto> list = orderProducts .stream() .filter(op -> Objects.isNull(productService.getProduct(op .getProduct()
.getId()))) .collect(Collectors.toList()); if (!CollectionUtils.isEmpty(list)) { new ResourceNotFoundException("Product not found"); } } public static class OrderForm { private List<OrderProductDto> productOrders; public List<OrderProductDto> getProductOrders() { return productOrders; } public void setProductOrders(List<OrderProductDto> productOrders) { this.productOrders = productOrders; } } }
repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\controller\OrderController.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getApp() { return app; } public void setApp(String app) { this.app = app; } public Long getTimestamp() { return timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } public Long getGmtCreate() { return gmtCreate; } public void setGmtCreate(Long gmtCreate) { this.gmtCreate = gmtCreate; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } public Long getPassQps() { return passQps; } public void setPassQps(Long passQps) { this.passQps = passQps; }
public Long getBlockQps() { return blockQps; } public void setBlockQps(Long blockQps) { this.blockQps = blockQps; } public Long getSuccessQps() { return successQps; } public void setSuccessQps(Long successQps) { this.successQps = successQps; } public Long getExceptionQps() { return exceptionQps; } public void setExceptionQps(Long exceptionQps) { this.exceptionQps = exceptionQps; } public Double getRt() { return rt; } public void setRt(Double rt) { this.rt = rt; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } @Override public int compareTo(MetricVo o) { return Long.compare(this.timestamp, o.timestamp); } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\MetricVo.java
1
请完成以下Java代码
public Class<? extends BaseElement> getHandledType() { return IntermediateCatchEvent.class; } @Override protected void executeParse(BpmnParse bpmnParse, IntermediateCatchEvent intermediateCatchEvent) { EventDefinition eventDefinition = null; if (!intermediateCatchEvent.getEventDefinitions().isEmpty()) { eventDefinition = intermediateCatchEvent.getEventDefinitions().get(0); } if (eventDefinition == null) { Map<String, List<ExtensionElement>> extensionElements = intermediateCatchEvent.getExtensionElements(); if (!extensionElements.isEmpty()) { List<ExtensionElement> eventTypeExtensionElements = intermediateCatchEvent.getExtensionElements().get(BpmnXMLConstants.ELEMENT_EVENT_TYPE); if (eventTypeExtensionElements != null && !eventTypeExtensionElements.isEmpty()) { String eventTypeValue = eventTypeExtensionElements.get(0).getElementText(); if (StringUtils.isNotEmpty(eventTypeValue)) { intermediateCatchEvent.setBehavior(bpmnParse.getActivityBehaviorFactory().createIntermediateCatchEventRegistryEventActivityBehavior(intermediateCatchEvent, eventTypeValue)); return;
} } } intermediateCatchEvent.setBehavior(bpmnParse.getActivityBehaviorFactory().createIntermediateCatchEventActivityBehavior(intermediateCatchEvent)); } else { if (eventDefinition instanceof TimerEventDefinition || eventDefinition instanceof SignalEventDefinition || eventDefinition instanceof MessageEventDefinition || eventDefinition instanceof ConditionalEventDefinition || eventDefinition instanceof VariableListenerEventDefinition) { bpmnParse.getBpmnParserHandlers().parseElement(bpmnParse, eventDefinition); } else { LOGGER.warn("Unsupported intermediate catch event type for event {}", intermediateCatchEvent.getId()); } } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\parser\handler\IntermediateCatchEventParseHandler.java
1
请完成以下Java代码
private void init() { ColumnInfo[] s_layoutRelated = new ColumnInfo[] { new ColumnInfo(Msg.translate(Env.getCtx(), "Warehouse"), "orgname", String.class), new ColumnInfo( Msg.translate(Env.getCtx(), "Value"), "(Select Value from M_Product p where p.M_Product_ID=M_PRODUCT_SUBSTITUTERELATED_V.Substitute_ID)", String.class), new ColumnInfo(Msg.translate(Env.getCtx(), "Name"), "Name", String.class), new ColumnInfo(Msg.translate(Env.getCtx(), "QtyAvailable"), "QtyAvailable", Double.class), new ColumnInfo(Msg.translate(Env.getCtx(), "QtyOnHand"), "QtyOnHand", Double.class), new ColumnInfo(Msg.translate(Env.getCtx(), "QtyReserved"), "QtyReserved", Double.class), new ColumnInfo(Msg.translate(Env.getCtx(), "PriceStd"), "PriceStd", Double.class) }; String s_sqlFrom = "M_PRODUCT_SUBSTITUTERELATED_V"; String s_sqlWhere = "M_Product_ID = ? AND M_PriceList_Version_ID = ? and RowType = 'R'"; m_sqlRelated = relatedTbl.prepareTable(s_layoutRelated, s_sqlFrom, s_sqlWhere, false, "M_PRODUCT_SUBSTITUTERELATED_V"); relatedTbl.setMultiSelection(false); // relatedTbl.addMouseListener(this); // relatedTbl.getSelectionModel().addListSelectionListener(this); relatedTbl.autoSize(); } private void refresh(int M_Product_ID, int M_PriceList_Version_ID) { String sql = m_sqlRelated; log.trace(sql); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, M_Product_ID); pstmt.setInt(2, M_PriceList_Version_ID); rs = pstmt.executeQuery(); relatedTbl.loadTable(rs); rs.close(); } catch (Exception e) { log.warn(sql, e);
} finally { DB.close(rs, pstmt); rs = null; pstmt = null; } } public java.awt.Component getComponent() { return (java.awt.Component)relatedTbl; } @Override public void refresh(int M_Product_ID, int M_Warehouse_ID, int M_AttributeSetInstance_ID, int M_PriceList_Version_ID) { refresh( M_Product_ID, M_PriceList_Version_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoProductRelated.java
1
请完成以下Java代码
public Collection<T> provideVariables() { if (variables == null) { return new ArrayList<T>(); } else { return variables; } } @Override public Collection<T> provideVariables(Collection<String> variablesNames) { if (variablesNames == null) { return provideVariables(); } List<T> result = new ArrayList<T>();
if (variables != null) { for (T variable : variables) { if (variablesNames.contains(variable.getName())) { result.add(variable); } } } return result; } public static <T extends CoreVariableInstance> VariableCollectionProvider<T> emptyVariables() { return new VariableCollectionProvider<T>(Collections.<T>emptySet()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\VariableCollectionProvider.java
1
请完成以下Java代码
public class SysThirdAccount { /**编号*/ @TableId(type = IdType.ASSIGN_ID) @Schema(description = "编号") private java.lang.String id; /**第三方登录id*/ @Excel(name = "第三方登录id", width = 15) @Schema(description = "第三方登录id") private java.lang.String sysUserId; /**登录来源*/ @Excel(name = "登录来源", width = 15) @Schema(description = "登录来源") private java.lang.String thirdType; /**头像*/ @Excel(name = "头像", width = 15) @Schema(description = "头像") private java.lang.String avatar; /**状态(1-正常,2-冻结)*/ @Excel(name = "状态(1-正常,2-冻结)", width = 15) @Schema(description = "状态(1-正常,2-冻结)") private java.lang.Integer status; /**删除状态(0-正常,1-已删除)*/ @Excel(name = "删除状态(0-正常,1-已删除)", width = 15) @Schema(description = "删除状态(0-正常,1-已删除)") private java.lang.Integer delFlag; /**真实姓名*/ @Excel(name = "真实姓名", width = 15) @Schema(description = "真实姓名") private java.lang.String realname; /**第三方用户uuid*/ @Excel(name = "第三方用户uuid", width = 15) @Schema(description = "第三方用户uuid") private java.lang.String thirdUserUuid; /**第三方用户账号*/ @Excel(name = "第三方用户账号", width = 15) @Schema(description = "第三方用户账号") private java.lang.String thirdUserId;
/**创建人*/ @Excel(name = "创建人", width = 15) private java.lang.String createBy; /**创建日期*/ @Excel(name = "创建日期", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private java.util.Date createTime; /**修改人*/ @Excel(name = "修改人", width = 15) private java.lang.String updateBy; /**修改日期*/ @Excel(name = "修改日期", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private java.util.Date updateTime; /**租户id*/ private java.lang.Integer tenantId; }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysThirdAccount.java
1
请在Spring Boot框架中完成以下Java代码
public class DispatcherServletRegistrationBean extends ServletRegistrationBean<DispatcherServlet> implements DispatcherServletPath { private final String path; /** * Create a new {@link DispatcherServletRegistrationBean} instance for the given * servlet and path. * @param servlet the dispatcher servlet * @param path the dispatcher servlet path */ public DispatcherServletRegistrationBean(DispatcherServlet servlet, String path) { super(servlet); Assert.notNull(path, "'path' must not be null"); this.path = path; super.addUrlMappings(getServletUrlMapping()); } @Override
public String getPath() { return this.path; } @Override public void setUrlMappings(Collection<String> urlMappings) { throw new UnsupportedOperationException("URL Mapping cannot be changed on a DispatcherServlet registration"); } @Override public void addUrlMappings(String... urlMappings) { throw new UnsupportedOperationException("URL Mapping cannot be changed on a DispatcherServlet registration"); } }
repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\DispatcherServletRegistrationBean.java
2
请完成以下Java代码
public Builder type(String type) { this.type = type; return this; } /** * Annotate the parameter with the specified annotation. * @param className the class of the annotation * @return this for method chaining * @deprecated in favor of {@link #singleAnnotate(ClassName)} and * {@link #repeatableAnnotate(ClassName)} */ @Deprecated(forRemoval = true) public Builder annotate(ClassName className) { return annotate(className, null); } /** * Annotate the parameter with the specified annotation, customized by the * specified consumer. * @param className the class of the annotation * @param annotation a consumer of the builder * @return this for method chaining * @deprecated in favor of {@link #singleAnnotate(ClassName, Consumer)} and * {@link #singleAnnotate(ClassName)} */ @Deprecated(forRemoval = true) @SuppressWarnings("removal") public Builder annotate(ClassName className, Consumer<Annotation.Builder> annotation) { this.annotations.add(className, annotation); return this; } /** * Annotate the parameter with the specified single annotation. * @param className the class of the annotation * @return this for method chaining */ public Builder singleAnnotate(ClassName className) { return singleAnnotate(className, null); } /** * Annotate the parameter with the specified single annotation, customized by the * specified consumer. * @param className the class of the annotation * @param annotation a consumer of the builder * @return this for method chaining */ public Builder singleAnnotate(ClassName className, Consumer<Annotation.Builder> annotation) { this.annotations.addSingle(className, annotation); return this; }
/** * Annotate the parameter with the specified repeatable annotation. * @param className the class of the annotation * @return this for method chaining */ public Builder repeatableAnnotate(ClassName className) { return repeatableAnnotate(className, null); } /** * Annotate the parameter with the specified repeatable annotation, customized by * the specified consumer. * @param className the class of the annotation * @param annotation a consumer of the builder * @return this for method chaining */ public Builder repeatableAnnotate(ClassName className, Consumer<Annotation.Builder> annotation) { this.annotations.addRepeatable(className, annotation); return this; } public Parameter build() { return new Parameter(this); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\Parameter.java
1
请完成以下Java代码
public String getDbName() { return getProperty(PROP_DB_NAME, "metasfresh"); } public String getDbUser() { return getProperty(PROP_DB_USER, "metasfresh"); } public String getDbType() { return getProperty(PROP_DB_TYPE, "postgresql"); } public String getDbHostname() { return getProperty(PROP_DB_SERVER, "localhost"); } public String getDbPort() { return getProperty(PROP_DB_PORT, "5432"); } public String getDbPassword() { return getProperty(PROP_DB_PASSWORD, // Default value is null because in case is not configured we shall use other auth methods IDatabase.PASSWORD_NA); } @Override public String toString()
{ final HashMap<Object, Object> result = new HashMap<>(properties); result.put(PROP_DB_PASSWORD, "******"); return result.toString(); } public DBConnectionSettings toDBConnectionSettings() { return DBConnectionSettings.builder() .dbHostname(getDbHostname()) .dbPort(getDbPort()) .dbName(getDbName()) .dbUser(getDbUser()) .dbPassword(getDbPassword()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\DBConnectionSettingProperties.java
1
请完成以下Java代码
abstract class LazyDelegatingInputStream extends InputStream { private volatile InputStream in; @Override public int read() throws IOException { return in().read(); } @Override public int read(byte[] b) throws IOException { return in().read(b); } @Override public int read(byte[] b, int off, int len) throws IOException { return in().read(b, off, len); } @Override public long skip(long n) throws IOException { return in().skip(n); } @Override public int available() throws IOException { return in().available(); } @Override public boolean markSupported() { try { return in().markSupported(); } catch (IOException ex) { return false; } } @Override public synchronized void mark(int readLimit) { try { in().mark(readLimit); } catch (IOException ex) { // Ignore
} } @Override public synchronized void reset() throws IOException { in().reset(); } private InputStream in() throws IOException { InputStream in = this.in; if (in == null) { synchronized (this) { in = this.in; if (in == null) { in = getDelegateInputStream(); this.in = in; } } } return in; } @Override public void close() throws IOException { InputStream in = this.in; if (in != null) { synchronized (this) { in = this.in; if (in != null) { in.close(); } } } } protected abstract InputStream getDelegateInputStream() throws IOException; }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\LazyDelegatingInputStream.java
1
请完成以下Java代码
public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** * PerformanceType AD_Reference_ID=540689 * Reference name: R_Request.PerformanceType */ public static final int PERFORMANCETYPE_AD_Reference_ID=540689; /** Liefer Performance = LP */ public static final String PERFORMANCETYPE_LieferPerformance = "LP"; /** Quality Performance = QP */ public static final String PERFORMANCETYPE_QualityPerformance = "QP"; /** Set PerformanceType. @param PerformanceType PerformanceType */ @Override public void setPerformanceType (java.lang.String PerformanceType) { set_Value (COLUMNNAME_PerformanceType, PerformanceType); } /** Get PerformanceType. @return PerformanceType */ @Override public java.lang.String getPerformanceType () {
return (java.lang.String)get_Value(COLUMNNAME_PerformanceType); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inout\model\X_M_QualityNote.java
1
请完成以下Java代码
public void setC_PaymentTerm_ID (final int C_PaymentTerm_ID) { if (C_PaymentTerm_ID < 1) set_Value (COLUMNNAME_C_PaymentTerm_ID, null); else set_Value (COLUMNNAME_C_PaymentTerm_ID, C_PaymentTerm_ID); } @Override public int getC_PaymentTerm_ID() { return get_ValueAsInt(COLUMNNAME_C_PaymentTerm_ID); } @Override public void setDueAmt (final BigDecimal DueAmt) { set_Value (COLUMNNAME_DueAmt, DueAmt); } @Override public BigDecimal getDueAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DueAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setDueDate (final java.sql.Timestamp DueDate) { set_Value (COLUMNNAME_DueDate, DueDate); } @Override public java.sql.Timestamp getDueDate() { return get_ValueAsTimestamp(COLUMNNAME_DueDate); } @Override public void setOffsetDays (final int OffsetDays) { set_Value (COLUMNNAME_OffsetDays, OffsetDays); } @Override public int getOffsetDays() { return get_ValueAsInt(COLUMNNAME_OffsetDays); } @Override public void setPercent (final int Percent) { set_Value (COLUMNNAME_Percent, Percent); } @Override public int getPercent() { return get_ValueAsInt(COLUMNNAME_Percent); } /** * ReferenceDateType AD_Reference_ID=541989 * Reference name: ReferenceDateType */ public static final int REFERENCEDATETYPE_AD_Reference_ID=541989; /** InvoiceDate = IV */
public static final String REFERENCEDATETYPE_InvoiceDate = "IV"; /** BLDate = BL */ public static final String REFERENCEDATETYPE_BLDate = "BL"; /** OrderDate = OD */ public static final String REFERENCEDATETYPE_OrderDate = "OD"; /** LCDate = LC */ public static final String REFERENCEDATETYPE_LCDate = "LC"; /** ETADate = ET */ public static final String REFERENCEDATETYPE_ETADate = "ET"; @Override public void setReferenceDateType (final java.lang.String ReferenceDateType) { set_Value (COLUMNNAME_ReferenceDateType, ReferenceDateType); } @Override public java.lang.String getReferenceDateType() { return get_ValueAsString(COLUMNNAME_ReferenceDateType); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } /** * Status AD_Reference_ID=541993 * Reference name: C_OrderPaySchedule_Status */ public static final int STATUS_AD_Reference_ID=541993; /** Pending_Ref = PR */ public static final String STATUS_Pending_Ref = "PR"; /** Awaiting_Pay = WP */ public static final String STATUS_Awaiting_Pay = "WP"; /** Paid = P */ public static final String STATUS_Paid = "P"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrderPaySchedule.java
1
请完成以下Java代码
public static void main(String[] args) throws Exception { ApplicationContext context = SpringApplication.run(RedisSentinelApplication.class, args); var template = context.getBean(StringRedisTemplate.class); template.opsForValue().set("loop-forever", "0"); var stopWatch = new StopWatch(); while (true) { try { var value = "IT:= " + template.opsForValue().increment("loop-forever", 1); printBackFromErrorStateInfoIfStopWatchIsRunning(stopWatch); System.out.println(value); } catch (RuntimeException e) { System.err.println(e.getCause().getMessage()); startStopWatchIfNotRunning(stopWatch); } Thread.sleep(1000); } } public @Bean StringRedisTemplate redisTemplate() { return new StringRedisTemplate(connectionFactory()); }
public @Bean RedisConnectionFactory connectionFactory() { return new LettuceConnectionFactory(sentinelConfig(), LettuceClientConfiguration.defaultConfiguration()); } public @Bean RedisSentinelConfiguration sentinelConfig() { return SENTINEL_CONFIG; } /** * Clear database before shut down. */ public @PreDestroy void flushTestDb() { factory.getConnection().flushDb(); } private static void startStopWatchIfNotRunning(StopWatch stopWatch) { if (!stopWatch.isRunning()) { stopWatch.start(); } } private static void printBackFromErrorStateInfoIfStopWatchIsRunning(StopWatch stopWatch) { if (stopWatch.isRunning()) { stopWatch.stop(); System.err.println("INFO: Recovered after: " + stopWatch.getLastTaskInfo().getTimeSeconds()); } } }
repos\spring-data-examples-main\redis\sentinel\src\main\java\example\springdata\redis\sentinel\RedisSentinelApplication.java
1
请完成以下Java代码
public Map<String, Long> countStudentsByCourse() { ViewQuery query = ViewQuery.from("studentGrades", "countStudentsByCourse") .reduce() .groupLevel(1); ViewResult result = bucket.query(query); Map<String, Long> numStudentsByCourse = new HashMap<>(); for(ViewRow row : result.allRows()) { JsonArray keyArray = (JsonArray) row.key(); String course = keyArray.getString(0); long count = Long.valueOf(row.value().toString()); numStudentsByCourse.put(course, count); } return numStudentsByCourse; } public Map<String, Long> sumCreditHoursByStudent() { ViewQuery query = ViewQuery.from("studentGrades", "sumHoursByStudent") .reduce() .groupLevel(1); ViewResult result = bucket.query(query); Map<String, Long> creditHoursByStudent = new HashMap<>(); for(ViewRow row : result.allRows()) { String course = (String) row.key(); long sum = Long.valueOf(row.value().toString()); creditHoursByStudent.put(course, sum); } return creditHoursByStudent; }
public Map<String, Long> sumGradePointsByStudent() { ViewQuery query = ViewQuery.from("studentGrades", "sumGradePointsByStudent") .reduce() .groupLevel(1); ViewResult result = bucket.query(query); Map<String, Long> gradePointsByStudent = new HashMap<>(); for(ViewRow row : result.allRows()) { String course = (String) row.key(); long sum = Long.valueOf(row.value().toString()); gradePointsByStudent.put(course, sum); } return gradePointsByStudent; } public Map<String, Float> calculateGpaByStudent() { Map<String, Long> creditHoursByStudent = sumCreditHoursByStudent(); Map<String, Long> gradePointsByStudent = sumGradePointsByStudent(); Map<String, Float> result = new HashMap<>(); for(Entry<String, Long> creditHoursEntry : creditHoursByStudent.entrySet()) { String name = creditHoursEntry.getKey(); long totalHours = creditHoursEntry.getValue(); long totalGradePoints = gradePointsByStudent.get(name); result.put(name, ((float) totalGradePoints / totalHours)); } return result; } }
repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\mapreduce\StudentGradeService.java
1