instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public org.compiere.model.I_M_Label getM_Label() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Label_ID, org.compiere.model.I_M_Label.class); } @Override public void setM_Label(org.compiere.model.I_M_Label M_Label) { set_ValueFromPO(COLUMNNAME_M_Label_ID, org.compiere.model.I_M_Label.class, M_Label); } /** Set Label List. @param M_Label_ID Label List */ @Override public void setM_Label_ID (int M_Label_ID) { if (M_Label_ID < 1) set_Value (COLUMNNAME_M_Label_ID, null); else set_Value (COLUMNNAME_M_Label_ID, Integer.valueOf(M_Label_ID)); } /** Get Label List. @return Label List */ @Override public int getM_Label_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Label_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Label_ID. @param M_Product_Certificate_ID Label_ID */ @Override public void setM_Product_Certificate_ID (int M_Product_Certificate_ID) { if (M_Product_Certificate_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Certificate_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Certificate_ID, Integer.valueOf(M_Product_Certificate_ID)); } /** Get Label_ID. @return Label_ID */ @Override public int getM_Product_Certificate_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Certificate_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException {
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Certificate.java
1
请完成以下Java代码
public class IncidentContext { protected String processDefinitionId; protected String activityId; protected String executionId; protected String configuration; protected String tenantId; protected String jobDefinitionId; protected String historyConfiguration; protected String failedActivityId; public IncidentContext() {} public IncidentContext(Incident incident) { this.processDefinitionId = incident.getProcessDefinitionId(); this.activityId = incident.getActivityId(); this.executionId = incident.getExecutionId(); this.configuration = incident.getConfiguration(); this.tenantId = incident.getTenantId(); this.jobDefinitionId = incident.getJobDefinitionId(); } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getConfiguration() { return configuration; } public void setConfiguration(String configuration) { this.configuration = configuration; } public String getTenantId() { return tenantId;
} public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getJobDefinitionId() { return jobDefinitionId; } public void setJobDefinitionId(String jobDefinitionId) { this.jobDefinitionId = jobDefinitionId; } public String getHistoryConfiguration() { return historyConfiguration; } public void setHistoryConfiguration(String historicConfiguration) { this.historyConfiguration = historicConfiguration; } public String getFailedActivityId() { return failedActivityId; } public void setFailedActivityId(String failedActivityId) { this.failedActivityId = failedActivityId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\incident\IncidentContext.java
1
请完成以下Java代码
public abstract class ThrowEventImpl extends EventImpl implements ThrowEvent { protected static ChildElementCollection<DataInput> dataInputCollection; protected static ChildElementCollection<DataInputAssociation> dataInputAssociationCollection; protected static ChildElement<InputSet> inputSetChild; protected static ChildElementCollection<EventDefinition> eventDefinitionCollection; protected static ElementReferenceCollection<EventDefinition, EventDefinitionRef> eventDefinitionRefCollection; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ThrowEvent.class, BPMN_ELEMENT_THROW_EVENT) .namespaceUri(BPMN20_NS) .extendsType(Event.class) .abstractType(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); dataInputCollection = sequenceBuilder.elementCollection(DataInput.class) .build(); dataInputAssociationCollection = sequenceBuilder.elementCollection(DataInputAssociation.class) .build(); inputSetChild = sequenceBuilder.element(InputSet.class) .build(); eventDefinitionCollection = sequenceBuilder.elementCollection(EventDefinition.class) .build(); eventDefinitionRefCollection = sequenceBuilder.elementCollection(EventDefinitionRef.class) .qNameElementReferenceCollection(EventDefinition.class) .build();
typeBuilder.build(); } public ThrowEventImpl(ModelTypeInstanceContext context) { super(context); } public Collection<DataInput> getDataInputs() { return dataInputCollection.get(this); } public Collection<DataInputAssociation> getDataInputAssociations() { return dataInputAssociationCollection.get(this); } public InputSet getInputSet() { return inputSetChild.getChild(this); } public void setInputSet(InputSet inputSet) { inputSetChild.setChild(this, inputSet); } public Collection<EventDefinition> getEventDefinitions() { return eventDefinitionCollection.get(this); } public Collection<EventDefinition> getEventDefinitionRefs() { return eventDefinitionRefCollection.getReferenceTargetElements(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ThrowEventImpl.java
1
请完成以下Java代码
public void setRejectReason (final @Nullable java.lang.String RejectReason) { set_Value (COLUMNNAME_RejectReason, RejectReason); } @Override public java.lang.String getRejectReason() { return get_ValueAsString(COLUMNNAME_RejectReason); } /** * Status AD_Reference_ID=540734 * Reference name: M_Picking_Candidate_Status */ public static final int STATUS_AD_Reference_ID=540734; /** Closed = CL */ public static final String STATUS_Closed = "CL";
/** InProgress = IP */ public static final String STATUS_InProgress = "IP"; /** Processed = PR */ public static final String STATUS_Processed = "PR"; /** Voided = VO */ public static final String STATUS_Voided = "VO"; @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.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Candidate.java
1
请完成以下Java代码
public class BoundStack<E extends Comparable<E>> { private E[] stackContent; private int total; public BoundStack(int capacity) { this.stackContent = (E[]) new Object[capacity]; } public void push(E data) { if (total == stackContent.length) { resize(2 * stackContent.length); } stackContent[total++] = data; } public E pop() { if (!isEmpty()) {
E datum = stackContent[total]; stackContent[total--] = null; return datum; } return null; } private void resize(int capacity) { Arrays.copyOf(stackContent, capacity); } public boolean isEmpty() { return total == 0; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-generics\src\main\java\com\baeldung\typeerasure\BoundStack.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_JavaClass_ID (final int AD_JavaClass_ID) { if (AD_JavaClass_ID < 1) set_Value (COLUMNNAME_AD_JavaClass_ID, null); else set_Value (COLUMNNAME_AD_JavaClass_ID, AD_JavaClass_ID); } @Override public int getAD_JavaClass_ID() { return get_ValueAsInt(COLUMNNAME_AD_JavaClass_ID); } @Override public org.compiere.model.I_AD_Sequence getAD_Sequence() { return get_ValueAsPO(COLUMNNAME_AD_Sequence_ID, org.compiere.model.I_AD_Sequence.class); } @Override public void setAD_Sequence(final org.compiere.model.I_AD_Sequence AD_Sequence) { set_ValueFromPO(COLUMNNAME_AD_Sequence_ID, org.compiere.model.I_AD_Sequence.class, AD_Sequence); } @Override public void setAD_Sequence_ID (final int AD_Sequence_ID) { if (AD_Sequence_ID < 1) set_Value (COLUMNNAME_AD_Sequence_ID, null); else set_Value (COLUMNNAME_AD_Sequence_ID, AD_Sequence_ID); } @Override public int getAD_Sequence_ID() { return get_ValueAsInt(COLUMNNAME_AD_Sequence_ID); }
@Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPP_ComponentGenerator_ID (final int PP_ComponentGenerator_ID) { if (PP_ComponentGenerator_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_ComponentGenerator_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_ComponentGenerator_ID, PP_ComponentGenerator_ID); } @Override public int getPP_ComponentGenerator_ID() { return get_ValueAsInt(COLUMNNAME_PP_ComponentGenerator_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PP_ComponentGenerator.java
1
请完成以下Java代码
public MRPQueryBuilder setOnlyActiveRecords(final boolean onlyActiveRecords) { this._onlyActiveRecords = onlyActiveRecords; return this; } @Override public MRPQueryBuilder setOrderType(final String orderType) { this._orderTypes.clear(); if (orderType != null) { this._orderTypes.add(orderType); } return this; } private Set<String> getOrderTypes() { return this._orderTypes; } @Override
public MRPQueryBuilder setReferencedModel(final Object referencedModel) { this._referencedModel = referencedModel; return this; } public Object getReferencedModel() { return this._referencedModel; } @Override public void setPP_Order_BOMLine_Null() { this._ppOrderBOMLine_Null = true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\mrp\api\impl\MRPQueryBuilder.java
1
请完成以下Java代码
public class ObjectTypeImpl extends AbstractValueTypeImpl implements SerializableValueType { private static final long serialVersionUID = 1L; public static final String TYPE_NAME = "object"; public ObjectTypeImpl() { super(TYPE_NAME); } public boolean isPrimitiveValueType() { return false; } public TypedValue createValue(Object value, Map<String, Object> valueInfo) { ObjectValueBuilder builder = Variables.objectValue(value); if(valueInfo != null) { applyValueInfo(builder, valueInfo); } return builder.create(); } public Map<String, Object> getValueInfo(TypedValue typedValue) { if(!(typedValue instanceof ObjectValue)) { throw new IllegalArgumentException("Value not of type Object."); } ObjectValue objectValue = (ObjectValue) typedValue; Map<String, Object> valueInfo = new HashMap<String, Object>(); String serializationDataFormat = objectValue.getSerializationDataFormat(); if(serializationDataFormat != null) { valueInfo.put(VALUE_INFO_SERIALIZATION_DATA_FORMAT, serializationDataFormat); } String objectTypeName = objectValue.getObjectTypeName(); if(objectTypeName != null) { valueInfo.put(VALUE_INFO_OBJECT_TYPE_NAME, objectTypeName); } if (objectValue.isTransient()) { valueInfo.put(VALUE_INFO_TRANSIENT, objectValue.isTransient()); } return valueInfo;
} public SerializableValue createValueFromSerialized(String serializedValue, Map<String, Object> valueInfo) { SerializedObjectValueBuilder builder = Variables.serializedObjectValue(serializedValue); if(valueInfo != null) { applyValueInfo(builder, valueInfo); } return builder.create(); } protected void applyValueInfo(ObjectValueBuilder builder, Map<String, Object> valueInfo) { String objectValueTypeName = (String) valueInfo.get(VALUE_INFO_OBJECT_TYPE_NAME); if (builder instanceof SerializedObjectValueBuilder) { ((SerializedObjectValueBuilder) builder).objectTypeName(objectValueTypeName); } String serializationDataFormat = (String) valueInfo.get(VALUE_INFO_SERIALIZATION_DATA_FORMAT); if(serializationDataFormat != null) { builder.serializationDataFormat(serializationDataFormat); } builder.setTransient(isTransient(valueInfo)); } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\type\ObjectTypeImpl.java
1
请完成以下Java代码
public java.lang.String getSourceClassName() { return get_ValueAsString(COLUMNNAME_SourceClassName); } @Override public void setSourceMethodName (final @Nullable java.lang.String SourceMethodName) { set_Value (COLUMNNAME_SourceMethodName, SourceMethodName); } @Override public java.lang.String getSourceMethodName() { return get_ValueAsString(COLUMNNAME_SourceMethodName); } @Override public void setStackTrace (final @Nullable java.lang.String StackTrace) { set_Value (COLUMNNAME_StackTrace, StackTrace); } @Override public java.lang.String getStackTrace() { return get_ValueAsString(COLUMNNAME_StackTrace); } @Override public void setStatisticsInfo (final @Nullable java.lang.String StatisticsInfo) { set_ValueNoCheck (COLUMNNAME_StatisticsInfo, StatisticsInfo); } @Override public java.lang.String getStatisticsInfo() { return get_ValueAsString(COLUMNNAME_StatisticsInfo); } @Override public void setSupportEMail (final @Nullable java.lang.String SupportEMail) { set_Value (COLUMNNAME_SupportEMail, SupportEMail); } @Override public java.lang.String getSupportEMail() { return get_ValueAsString(COLUMNNAME_SupportEMail); } /** * SystemStatus AD_Reference_ID=374 * Reference name: AD_System Status */ public static final int SYSTEMSTATUS_AD_Reference_ID=374; /** Evaluation = E */ public static final String SYSTEMSTATUS_Evaluation = "E";
/** Implementation = I */ public static final String SYSTEMSTATUS_Implementation = "I"; /** Production = P */ public static final String SYSTEMSTATUS_Production = "P"; @Override public void setSystemStatus (final java.lang.String SystemStatus) { set_Value (COLUMNNAME_SystemStatus, SystemStatus); } @Override public java.lang.String getSystemStatus() { return get_ValueAsString(COLUMNNAME_SystemStatus); } @Override public void setUserAgent (final @Nullable java.lang.String UserAgent) { set_Value (COLUMNNAME_UserAgent, UserAgent); } @Override public java.lang.String getUserAgent() { return get_ValueAsString(COLUMNNAME_UserAgent); } @Override public void setUserName (final java.lang.String UserName) { set_ValueNoCheck (COLUMNNAME_UserName, UserName); } @Override public java.lang.String getUserName() { return get_ValueAsString(COLUMNNAME_UserName); } @Override public void setVersion (final java.lang.String Version) { set_ValueNoCheck (COLUMNNAME_Version, Version); } @Override public java.lang.String getVersion() { return get_ValueAsString(COLUMNNAME_Version); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Issue.java
1
请完成以下Java代码
public void setIncluded_Aggregation_ID (int Included_Aggregation_ID) { if (Included_Aggregation_ID < 1) set_Value (COLUMNNAME_Included_Aggregation_ID, null); else set_Value (COLUMNNAME_Included_Aggregation_ID, Integer.valueOf(Included_Aggregation_ID)); } /** Get Included Aggregation. @return Included Aggregation */ @Override public int getIncluded_Aggregation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Included_Aggregation_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Include Logic. @param IncludeLogic If expression is evaluated as true, the item will be included. If evaluated as false, the item will be excluded. */ @Override public void setIncludeLogic (java.lang.String IncludeLogic) { set_Value (COLUMNNAME_IncludeLogic, IncludeLogic); } /** Get Include Logic. @return If expression is evaluated as true, the item will be included. If evaluated as false, the item will be excluded. */ @Override public java.lang.String getIncludeLogic () { return (java.lang.String)get_Value(COLUMNNAME_IncludeLogic); } /** * Type AD_Reference_ID=540532 * Reference name: C_AggregationItem_Type */
public static final int TYPE_AD_Reference_ID=540532; /** Column = COL */ public static final String TYPE_Column = "COL"; /** IncludedAggregation = INC */ public static final String TYPE_IncludedAggregation = "INC"; /** Attribute = ATR */ public static final String TYPE_Attribute = "ATR"; /** Set Art. @param Type Type of Validation (SQL, Java Script, Java Language) */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java-gen\de\metas\aggregation\model\X_C_AggregationItem.java
1
请完成以下Java代码
protected void configureKeepAlive(final T builder) { if (this.properties.isEnableKeepAlive()) { throw new IllegalStateException("KeepAlive is enabled but this implementation does not support keepAlive!"); } } /** * Configures the keep alive options that should be used by the server. * * @param builder The server builder to configure. */ protected void configureConnectionLimits(final T builder) { if (this.properties.getMaxConnectionIdle() != null) { throw new IllegalStateException( "MaxConnectionIdle is set but this implementation does not support maxConnectionIdle!"); } if (this.properties.getMaxConnectionAge() != null) { throw new IllegalStateException( "MaxConnectionAge is set but this implementation does not support maxConnectionAge!"); } if (this.properties.getMaxConnectionAgeGrace() != null) { throw new IllegalStateException( "MaxConnectionAgeGrace is set but this implementation does not support maxConnectionAgeGrace!"); } } /** * Configures the security options that should be used by the server. * * @param builder The server builder to configure. */ protected void configureSecurity(final T builder) { if (this.properties.getSecurity().isEnabled()) { throw new IllegalStateException("Security is enabled but this implementation does not support security!");
} } /** * Configures limits such as max message sizes that should be used by the server. * * @param builder The server builder to configure. */ protected void configureLimits(final T builder) { final DataSize maxInboundMessageSize = this.properties.getMaxInboundMessageSize(); if (maxInboundMessageSize != null) { builder.maxInboundMessageSize((int) maxInboundMessageSize.toBytes()); } final DataSize maxInboundMetadataSize = this.properties.getMaxInboundMetadataSize(); if (maxInboundMetadataSize != null) { builder.maxInboundMetadataSize((int) maxInboundMetadataSize.toBytes()); } } @Override public String getAddress() { return this.properties.getAddress(); } @Override public int getPort() { return this.properties.getPort(); } @Override public void addService(final GrpcServiceDefinition service) { this.serviceList.add(service); } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\serverfactory\AbstractGrpcServerFactory.java
1
请完成以下Java代码
public int getDIM_Dimension_Spec_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DIM_Dimension_Spec_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Dimensionsattributwert. @param DIM_Dimension_Spec_AttributeValue_ID Dimensionsattributwert */ @Override public void setDIM_Dimension_Spec_AttributeValue_ID (int DIM_Dimension_Spec_AttributeValue_ID) { if (DIM_Dimension_Spec_AttributeValue_ID < 1) set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Spec_AttributeValue_ID, null); else set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Spec_AttributeValue_ID, Integer.valueOf(DIM_Dimension_Spec_AttributeValue_ID)); } /** Get Dimensionsattributwert. @return Dimensionsattributwert */ @Override public int getDIM_Dimension_Spec_AttributeValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DIM_Dimension_Spec_AttributeValue_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Merkmals-Wert. @param M_AttributeValue_ID Product Attribute Value */ @Override public void setM_AttributeValue_ID (int M_AttributeValue_ID) { if (M_AttributeValue_ID < 1) set_Value (COLUMNNAME_M_AttributeValue_ID, null); else set_Value (COLUMNNAME_M_AttributeValue_ID, Integer.valueOf(M_AttributeValue_ID)); } /** Get Merkmals-Wert. @return Product Attribute Value */ @Override public int getM_AttributeValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Spec_AttributeValue.java
1
请完成以下Java代码
private boolean isMissing(InvocationContext context, OperationParameter parameter) { if (!parameter.isMandatory()) { return false; } if (context.canResolve(parameter.getType())) { return false; } return context.getArguments().get(parameter.getName()) == null; } private @Nullable Object[] resolveArguments(InvocationContext context) { return this.operationMethod.getParameters() .stream() .map((parameter) -> resolveArgument(parameter, context)) .toArray(); } private @Nullable Object resolveArgument(OperationParameter parameter, InvocationContext context) { Object resolvedByType = context.resolveArgument(parameter.getType());
if (resolvedByType != null) { return resolvedByType; } Object value = context.getArguments().get(parameter.getName()); return this.parameterValueMapper.mapParameterValue(parameter, value); } @Override public String toString() { return new ToStringCreator(this).append("target", this.target) .append("method", this.operationMethod) .toString(); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\invoke\reflect\ReflectiveOperationInvoker.java
1
请完成以下Java代码
public void destroy() { } /** * Iterate over a number of filter rules and match them against * the specified request. * * @param request * @param filterRules * * @return the joined {@link AuthorizationStatus} for this request matched against all filter rules */ public static Authorization authorize(String requestMethod, String requestUri, List<SecurityFilterRule> filterRules) { return FilterRules.authorize(requestMethod, requestUri, filterRules); } protected void loadFilterRules(FilterConfig filterConfig, String applicationPath) throws ServletException { String configFileName = filterConfig.getInitParameter("configFile"); InputStream configFileResource = filterConfig.getServletContext().getResourceAsStream(configFileName); if (configFileResource == null) { throw new ServletException("Could not read security filter config file '"+configFileName+"': no such resource in servlet context."); } else { try { filterRules = FilterRules.load(configFileResource, applicationPath); } catch (Exception e) { throw new RuntimeException("Exception while parsing '" + configFileName + "'", e); } finally { IoUtil.closeSilently(configFileResource); }
} } protected void sendForbidden(HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendError(403); } protected void sendUnauthorized(HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendError(401); } protected void sendForbiddenApplicationAccess(String application, HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendError(403, "No access rights for " + application); } protected boolean isAuthenticated(HttpServletRequest request) { return Authentications.getCurrent() != null; } protected String getRequestUri(HttpServletRequest request) { String contextPath = request.getContextPath(); return request.getRequestURI().substring(contextPath.length()); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\SecurityFilter.java
1
请完成以下Java代码
public void close() { // Do nothing if already closed if (closed) { return; } // Assert we are restoring the ctx in same thread. // Because else, we would set the context "back" in another thread which would lead to huge inconsistencies. if (Thread.currentThread().getId() != threadIdOnSet) { throw new IllegalStateException("Error: setting back the context shall be done in the same thread as it was set initially"); } threadLocalContext.set(ctxOld); closed = true; } }; }
/** * Dispose the context from current thread */ public void dispose() { final Properties ctx = threadLocalContext.get(); ctx.clear(); threadLocalContext.remove(); } public void setListener(@NonNull final IContextProviderListener listener) { this.listener = listener; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\context\ThreadLocalServerContext.java
1
请完成以下Java代码
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 getSkipExpression() { return skipExpression; } public void setSkipExpression(String skipExpression) { this.skipExpression = skipExpression; } public UserTask clone() { UserTask clone = new UserTask(); clone.setValues(this); return clone; } public void setValues(UserTask otherElement) { super.setValues(otherElement); setAssignee(otherElement.getAssignee()); setOwner(otherElement.getOwner()); setFormKey(otherElement.getFormKey()); setDueDate(otherElement.getDueDate()); setPriority(otherElement.getPriority()); setCategory(otherElement.getCategory()); setExtensionId(otherElement.getExtensionId()); setSkipExpression(otherElement.getSkipExpression()); setCandidateGroups(new ArrayList<String>(otherElement.getCandidateGroups())); setCandidateUsers(new ArrayList<String>(otherElement.getCandidateUsers())); setCustomGroupIdentityLinks(otherElement.customGroupIdentityLinks); setCustomUserIdentityLinks(otherElement.customUserIdentityLinks); formProperties = new ArrayList<FormProperty>(); if (otherElement.getFormProperties() != null && !otherElement.getFormProperties().isEmpty()) { for (FormProperty property : otherElement.getFormProperties()) { formProperties.add(property.clone());
} } taskListeners = new ArrayList<ActivitiListener>(); if (otherElement.getTaskListeners() != null && !otherElement.getTaskListeners().isEmpty()) { for (ActivitiListener listener : otherElement.getTaskListeners()) { taskListeners.add(listener.clone()); } } } @Override public void accept(ReferenceOverrider referenceOverrider) { referenceOverrider.override(this); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\UserTask.java
1
请完成以下Java代码
public void onAfterDelete(final I_C_BankStatementLine bankStatementLine) { final BankStatementId bankStatementId = BankStatementId.ofRepoId(bankStatementLine.getC_BankStatement_ID()); updateBankStatementHeader(bankStatementId); } private void updateBankStatementHeader(final BankStatementId bankStatementId) { updateStatementDifferenceAndEndingBalance(bankStatementId); updateBankStatementIsReconciledFlag(bankStatementId); CacheMgt.get().resetLocalNowAndBroadcastOnTrxCommit( ITrx.TRXNAME_ThreadInherited, CacheInvalidateMultiRequest.rootRecord(I_C_BankStatement.Table_Name, bankStatementId)); } @VisibleForTesting protected void updateStatementDifferenceAndEndingBalance(final BankStatementId bankStatementId) { // StatementDifference { final String sql = "UPDATE C_BankStatement bs" + " SET StatementDifference=(SELECT COALESCE(SUM(StmtAmt),0) FROM C_BankStatementLine bsl " + "WHERE bsl.C_BankStatement_ID=bs.C_BankStatement_ID AND bsl.IsActive='Y') " + "WHERE C_BankStatement_ID=?"; DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { bankStatementId }, ITrx.TRXNAME_ThreadInherited); } // EndingBalance { final String sql = "UPDATE C_BankStatement bs" + " SET EndingBalance=BeginningBalance+StatementDifference "
+ "WHERE C_BankStatement_ID=?"; DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { bankStatementId }, ITrx.TRXNAME_ThreadInherited); } } @VisibleForTesting protected void updateBankStatementIsReconciledFlag(final BankStatementId bankStatementId) { final String sql = "UPDATE C_BankStatement bs" + " SET IsReconciled=(CASE WHEN (SELECT COUNT(1) FROM C_BankStatementLine bsl WHERE bsl.C_BankStatement_ID = bs.C_BankStatement_ID AND bsl.IsReconciled = 'N') = 0 THEN 'Y' ELSE 'N' END)" + " WHERE C_BankStatement_ID=?"; DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { bankStatementId }, ITrx.TRXNAME_ThreadInherited); } private void assertReconcilationConsistent(final I_C_BankStatementLine line) { if (line.getLink_BankStatementLine_ID() > 0 && line.getC_Payment_ID() > 0) { throw new AdempiereException("Invalid reconcilation: cannot have bank transfer and payment at the same time"); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\model\validator\C_BankStatementLine.java
1
请完成以下Java代码
private final boolean hasType(final QualityInvoiceLineGroupType type) { return type2index.containsKey(type); } /** * Remove from given lines those which their type is not specified in our list. * * NOTE: we assume the list is read-write. * * @param groups */ public void filter(final List<IQualityInvoiceLineGroup> groups) { for (final Iterator<IQualityInvoiceLineGroup> it = groups.iterator(); it.hasNext();) { final IQualityInvoiceLineGroup group = it.next(); final QualityInvoiceLineGroupType type = group.getQualityInvoiceLineGroupType(); if (!hasType(type)) { it.remove(); } } } /** * Sort given lines with this comparator. * * NOTE: we assume the list is read-write.
* * @param lines */ public void sort(final List<IQualityInvoiceLineGroup> lines) { Collections.sort(lines, this); } /** * Remove from given lines those which their type is not specified in our list. Then sort the result. * * NOTE: we assume the list is read-write. * * @param lines */ public void filterAndSort(final List<IQualityInvoiceLineGroup> lines) { filter(lines); sort(lines); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\invoicing\QualityInvoiceLineGroupByTypeComparator.java
1
请在Spring Boot框架中完成以下Java代码
public class SimulatedPurchaseCandidateCleanUpService implements SimulatedCleanUpService { @NonNull private final PurchaseCandidateRepository purchaseCandidateRepository; public SimulatedPurchaseCandidateCleanUpService(final @NonNull PurchaseCandidateRepository purchaseCandidateRepository) { this.purchaseCandidateRepository = purchaseCandidateRepository; } @Override public void cleanUpSimulated() { final DeletePurchaseCandidateQuery deleteQuery = DeletePurchaseCandidateQuery.builder() .onlySimulated(true)
.build(); purchaseCandidateRepository.deletePurchaseCandidates(deleteQuery); } public void deleteSimulatedCandidatesFor(@NonNull final OrderLineId salesOrderLineId) { final DeletePurchaseCandidateQuery deleteQuery = DeletePurchaseCandidateQuery.builder() .salesOrderLineId(salesOrderLineId) .onlySimulated(true) .build(); purchaseCandidateRepository.deletePurchaseCandidates(deleteQuery); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\material\SimulatedPurchaseCandidateCleanUpService.java
2
请完成以下Java代码
public IPricingResult computeOrThrowEx() { final PriceListId priceListId = retrievePriceListForTerm(); return retrievePricingResultUsingPriceList(priceListId); } private PriceListId retrievePriceListForTerm() { final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); final IPriceListDAO priceListDAO = Services.get(IPriceListDAO.class); final PricingSystemId pricingSystemIdToUse = CoalesceUtil.coalesceSuppliersNotNull( () -> PricingSystemId.ofRepoIdOrNull(term.getM_PricingSystem_ID()), () -> PricingSystemId.ofRepoIdOrNull(term.getC_Flatrate_Conditions().getM_PricingSystem_ID()), () -> bpartnerDAO.retrievePricingSystemIdOrNull(BPartnerId.ofRepoId(term.getBill_BPartner_ID()), SOTrx.SALES)); final BPartnerLocationAndCaptureId dropShipLocationId = ContractLocationHelper.extractDropshipLocationId(term); final BPartnerLocationAndCaptureId billLocationId = ContractLocationHelper.extractBillToLocationId(term); final BPartnerLocationAndCaptureId bpLocationIdToUse = dropShipLocationId != null ? dropShipLocationId : billLocationId; final PriceListId priceListId = priceListDAO.retrievePriceListIdByPricingSyst( pricingSystemIdToUse, bpLocationIdToUse, SOTrx.SALES); if (priceListId == null) { final I_C_BPartner_Location billLocationRecord = bpartnerDAO.getBPartnerLocationByIdEvenInactive(billLocationId.getBpartnerLocationId()); throw new AdempiereException(MSG_FLATRATEBL_PRICE_LIST_MISSING_2P, priceListDAO.getPricingSystemName(pricingSystemIdToUse), billLocationRecord.getName()); } return priceListId; } private IPricingResult retrievePricingResultUsingPriceList(@NonNull final PriceListId priceListId) { final IPricingBL pricingBL = Services.get(IPricingBL.class);
final boolean isSOTrx = true; final IEditablePricingContext pricingCtx = pricingBL.createInitialContext( term.getAD_Org_ID(), termRelatedProductId.getRepoId(), term.getBill_BPartner_ID(), Services.get(IProductBL.class).getStockUOMId(termRelatedProductId).getRepoId(), qty, isSOTrx); pricingCtx.setPriceDate(priceDate); pricingCtx.setPriceListId(priceListId); final IPricingResult result = pricingBL.calculatePrice(pricingCtx); throwExceptionIfNotCalculated(result); return result; } private void throwExceptionIfNotCalculated(@NonNull final IPricingResult result) { if (result.isCalculated()) { return; } final String priceListName = Services.get(IPriceListDAO.class).getPriceListName(result.getPriceListId()); final String productName = Services.get(IProductBL.class).getProductValueAndName(termRelatedProductId); throw new AdempiereException(MSG_FLATRATEBL_PRICE_MISSING_2P, priceListName, productName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\FlatrateTermPricing.java
1
请在Spring Boot框架中完成以下Java代码
public H and() { return getBuilder(); } @Override public void configure(H http) { Saml2MetadataResponseResolver metadataResponseResolver = createMetadataResponseResolver(http); http.addFilterBefore(new Saml2MetadataFilter(metadataResponseResolver), BasicAuthenticationFilter.class); } private Saml2MetadataResponseResolver createMetadataResponseResolver(H http) { if (this.metadataResponseResolver != null) { RelyingPartyRegistrationRepository registrations = getRelyingPartyRegistrationRepository(http); return this.metadataResponseResolver.apply(registrations); } Saml2MetadataResponseResolver metadataResponseResolver = getBeanOrNull(Saml2MetadataResponseResolver.class); if (metadataResponseResolver != null) { return metadataResponseResolver; } RelyingPartyRegistrationRepository registrations = getRelyingPartyRegistrationRepository(http); if (USE_OPENSAML_5) { return new RequestMatcherMetadataResponseResolver(registrations, new OpenSaml5MetadataResolver()); } throw new IllegalArgumentException( "Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5"); }
private RelyingPartyRegistrationRepository getRelyingPartyRegistrationRepository(H http) { Saml2LoginConfigurer<H> login = http.getConfigurer(Saml2LoginConfigurer.class); if (login != null) { return login.relyingPartyRegistrationRepository(http); } else { return getBeanOrNull(RelyingPartyRegistrationRepository.class); } } private <C> C getBeanOrNull(Class<C> clazz) { if (this.context == null) { return null; } return this.context.getBeanProvider(clazz).getIfAvailable(); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\saml2\Saml2MetadataConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
public class WorkpackageLogsRepository implements IWorkpackageLogsRepository { @Override public void saveLogs(@NonNull final List<WorkpackageLogEntry> logEntries) { if (logEntries.isEmpty()) { return; } final String sql = "INSERT INTO " + I_C_Queue_WorkPackage_Log.Table_Name + "(" + I_C_Queue_WorkPackage_Log.COLUMNNAME_AD_Client_ID + "," // 1 + I_C_Queue_WorkPackage_Log.COLUMNNAME_AD_Org_ID + "," // 2 + I_C_Queue_WorkPackage_Log.COLUMNNAME_C_Queue_WorkPackage_ID + "," // 3 + I_C_Queue_WorkPackage_Log.COLUMNNAME_C_Queue_WorkPackage_Log_ID + "," // 4 + I_C_Queue_WorkPackage_Log.COLUMNNAME_Created + "," // 5 + I_C_Queue_WorkPackage_Log.COLUMNNAME_CreatedBy + "," // 6 + I_C_Queue_WorkPackage_Log.COLUMNNAME_IsActive + "," // 7 + I_C_Queue_WorkPackage_Log.COLUMNNAME_MsgText + "," // 8 + I_C_Queue_WorkPackage_Log.COLUMNNAME_Updated + "," // 9 + I_C_Queue_WorkPackage_Log.COLUMNNAME_UpdatedBy + "," // 10 + I_C_Queue_WorkPackage_Log.COLUMNNAME_AD_Issue_ID // 11 + ")" + " VALUES (" + "?," // 1 - AD_Client_ID + "?," // 2 - AD_Org_ID + "?," // 3 - C_Queue_WorkPackage_ID + DB.TO_TABLESEQUENCE_NEXTVAL(I_C_Queue_WorkPackage_Log.Table_Name) + "," // 4 - C_Queue_WorkPackage_Log_ID + "?," // 5 - Created + "?," // 6 - CreatedBy + "'Y'," // 7 - IsActive + "?," // 8 - MsgText + "?," // 9 - Updated + "?," // 10 - UpdatedBy + "?" // 11 - AD_Issue_ID + ")"; PreparedStatement pstmt = null; try { // NOTE: always create the logs out of transaction because we want them to be persisted even if the workpackage processing fails pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); for (final WorkpackageLogEntry logEntry : logEntries) { DB.setParameters(pstmt, new Object[] { logEntry.getAdClientId(), // 1 - AD_Client_ID OrgId.ANY, // 2 - AD_Org_ID
logEntry.getWorkpackageId(), // 3 - C_Queue_WorkPackage_ID // + DB.TO_TABLESEQUENCE_NEXTVAL(I_C_Queue_WorkPackage_Log.Table_Name) + "," // 4 - C_Queue_WorkPackage_Log_ID logEntry.getTimestamp(), // 5 - Created logEntry.getUserId(), // 6 - CreatedBy // + "'Y'," // 7 - IsActive logEntry.getMessage(), // 8 - MsgText logEntry.getTimestamp(), // 9 - Updated logEntry.getUserId(), // 10 - UpdatedBy logEntry.getAdIssueId(), // 11 - AD_Issue_ID }); pstmt.addBatch(); } pstmt.executeBatch(); } catch (final SQLException ex) { throw new DBException(ex, sql); } finally { DB.close(pstmt); } } @Override public void deleteLogsInTrx(@NonNull final QueueWorkPackageId workpackageId) { final String sql = "DELETE FROM " + I_C_Queue_WorkPackage_Log.Table_Name + " WHERE " + I_C_Queue_WorkPackage_Log.COLUMNNAME_C_Queue_WorkPackage_ID + "=?"; DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { workpackageId }, ITrx.TRXNAME_ThreadInherited); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\WorkpackageLogsRepository.java
2
请完成以下Java代码
public Optional<GLCategoryId> getDefaultId(@NonNull final ClientId clientId, @NonNull final GLCategoryType categoryType) { return getDefaults(clientId).getByCategoryType(categoryType); } public Optional<GLCategoryId> getDefaultId(@NonNull final ClientId clientId) { return getDefaults(clientId).getDefaultId(); } private DefaultGLCategories getDefaults(final ClientId clientId) { return defaultsCache.getOrLoad(clientId, this::retrieveDefaults); } private DefaultGLCategories retrieveDefaults(final ClientId clientId) { final ImmutableList<GLCategory> list = queryBL.createQueryBuilder(I_GL_Category.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_GL_Category.COLUMNNAME_AD_Client_ID, clientId) .addEqualsFilter(I_GL_Category.COLUMNNAME_IsDefault, true) .orderBy(I_GL_Category.COLUMNNAME_GL_Category_ID) // just to have a predictable order .create() .stream() .map(GLCategoryRepository::fromRecord) .collect(ImmutableList.toImmutableList()); return new DefaultGLCategories(list); } private static GLCategory fromRecord(@NonNull final I_GL_Category record) { return GLCategory.builder() .id(GLCategoryId.ofRepoId(record.getGL_Category_ID())) .name(record.getName()) .categoryType(GLCategoryType.ofCode(record.getCategoryType())) .isDefault(record.isDefault()) .clientId(ClientId.ofRepoId(record.getAD_Client_ID())) .build(); }
private static class DefaultGLCategories { private final ImmutableMap<GLCategoryType, GLCategory> byCategoryType; private final ImmutableList<GLCategory> list; DefaultGLCategories(final ImmutableList<GLCategory> list) { this.byCategoryType = Maps.uniqueIndex(list, GLCategory::getCategoryType); this.list = list; } public Optional<GLCategoryId> getByCategoryType(@NonNull final GLCategoryType categoryType) { final GLCategory category = byCategoryType.get(categoryType); if (category != null) { return Optional.of(category.getId()); } return getDefaultId(); } public Optional<GLCategoryId> getDefaultId() { return !list.isEmpty() ? Optional.of(list.get(0).getId()) : Optional.empty(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\GLCategoryRepository.java
1
请完成以下Java代码
public static class UserNotificationRequestBuilder { public UserNotificationRequestBuilder recipientUserId(@NonNull final UserId userId) { return recipient(Recipient.user(userId)); } public UserNotificationRequestBuilder topic(final Topic topic) { return notificationGroupName(NotificationGroupName.of(topic)); } } public interface TargetAction { } @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @lombok.Value @lombok.Builder(toBuilder = true) public static class TargetRecordAction implements TargetAction { @NonNull public static TargetRecordAction of(@NonNull final TableRecordReference record) { return builder().record(record).build(); } @Nullable public static TargetRecordAction ofNullable(@Nullable final TableRecordReference record) { return record == null ? null : of(record); } public static TargetRecordAction ofRecordAndWindow(@NonNull final TableRecordReference record, final int adWindowId) { return builder().record(record).adWindowId(AdWindowId.optionalOfRepoId(adWindowId)).build(); }
public static TargetRecordAction ofRecordAndWindow(@NonNull final TableRecordReference record, @NonNull final AdWindowId adWindowId) { return builder().record(record).adWindowId(Optional.of(adWindowId)).build(); } public static TargetRecordAction of(@NonNull final String tableName, final int recordId) { return of(TableRecordReference.of(tableName, recordId)); } public static TargetRecordAction cast(final TargetAction targetAction) { return (TargetRecordAction)targetAction; } @NonNull @Builder.Default Optional<AdWindowId> adWindowId = Optional.empty(); @NonNull TableRecordReference record; String recordDisplayText; } @lombok.Value @lombok.Builder public static class TargetViewAction implements TargetAction { public static TargetViewAction cast(final TargetAction targetAction) { return (TargetViewAction)targetAction; } @Nullable AdWindowId adWindowId; @NonNull String viewId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\UserNotificationRequest.java
1
请完成以下Java代码
public final class DebugProperties { public static final DebugProperties EMPTY = new DebugProperties(); private final ImmutableMap<String, Object> map; private DebugProperties(@NonNull final ImmutableMap<String, Object> map) { this.map = map; } private DebugProperties() { this.map = ImmutableMap.of(); } public static DebugProperties ofNullableMap(final Map<String, ?> map) { if (map == null || map.isEmpty()) { return EMPTY; } return new DebugProperties(ImmutableMap.copyOf(map)); } public boolean isEmpty() { return map.isEmpty();
} public Map<String, Object> toMap() { return map; } public DebugProperties withProperty(@NonNull final String propertyName, final Object propertyValue) { final Object existingValue = map.get(propertyName); if (Objects.equals(propertyValue, existingValue)) { return this; } final LinkedHashMap<String, Object> newMap = new LinkedHashMap<>(map); if (propertyValue == null) { newMap.remove(propertyName); } else { newMap.put(propertyName, propertyValue); } return ofNullableMap(newMap); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DebugProperties.java
1
请完成以下Java代码
public BigDecimal getPercentage() { return percentage; } public void setPercentage(final BigDecimal percentage) { this.percentage = percentage; } @Override public Quantity getQty() { return Quantity.of(qty, uom); } public void setQty(@NonNull final Quantity qty) { this.qty = qty.toBigDecimal(); this.uom = qty.getUOM(); } @Override public IPricingResult getPrice() { return pricingResult; } public void setPrice(final IPricingResult price) { pricingResult = price; } @Override public boolean isDisplayed() { return displayed; } public void setDisplayed(final boolean displayed) { this.displayed = displayed; }
@Override public String getDescription() { return description; } public void setDescription(final String description) { this.description = description; } @Override public IHandlingUnitsInfo getHandlingUnitsInfo() { return handlingUnitsInfo; } public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo) { this.handlingUnitsInfo = handlingUnitsInfo; } @Override public I_PP_Order getPP_Order() { return ppOrder; } public void setPP_Order(I_PP_Order ppOrder) { this.ppOrder = ppOrder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\invoicing\impl\QualityInvoiceLine.java
1
请在Spring Boot框架中完成以下Java代码
public PatientPayer copaymentFromDate(LocalDate copaymentFromDate) { this.copaymentFromDate = copaymentFromDate; return this; } /** * Zuzahlungsbefreit ab Datum - Feld bleibt leer, wenn keine Zuzahlungsbefreiung * @return copaymentFromDate **/ @Schema(example = "Mon Jan 01 00:00:00 GMT 2018", description = "Zuzahlungsbefreit ab Datum - Feld bleibt leer, wenn keine Zuzahlungsbefreiung") public LocalDate getCopaymentFromDate() { return copaymentFromDate; } public void setCopaymentFromDate(LocalDate copaymentFromDate) { this.copaymentFromDate = copaymentFromDate; } public PatientPayer copaymentToDate(LocalDate copaymentToDate) { this.copaymentToDate = copaymentToDate; return this; } /** * Zuzahlungsbefreit bis Datum - Feld bleibt leer, wenn keine Zuzahlungsbefreiung * @return copaymentToDate **/ @Schema(example = "Wed Jan 31 00:00:00 GMT 2018", description = "Zuzahlungsbefreit bis Datum - Feld bleibt leer, wenn keine Zuzahlungsbefreiung") public LocalDate getCopaymentToDate() { return copaymentToDate; } public void setCopaymentToDate(LocalDate copaymentToDate) { this.copaymentToDate = copaymentToDate; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatientPayer patientPayer = (PatientPayer) o; return Objects.equals(this.payerId, patientPayer.payerId) && Objects.equals(this.payerType, patientPayer.payerType) && Objects.equals(this.numberOfInsured, patientPayer.numberOfInsured) && Objects.equals(this.copaymentFromDate, patientPayer.copaymentFromDate) && Objects.equals(this.copaymentToDate, patientPayer.copaymentToDate); } @Override public int hashCode() {
return Objects.hash(payerId, payerType, numberOfInsured, copaymentFromDate, copaymentToDate); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientPayer {\n"); sb.append(" payerId: ").append(toIndentedString(payerId)).append("\n"); sb.append(" payerType: ").append(toIndentedString(payerType)).append("\n"); sb.append(" numberOfInsured: ").append(toIndentedString(numberOfInsured)).append("\n"); sb.append(" copaymentFromDate: ").append(toIndentedString(copaymentFromDate)).append("\n"); sb.append(" copaymentToDate: ").append(toIndentedString(copaymentToDate)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\PatientPayer.java
2
请在Spring Boot框架中完成以下Java代码
public String toString() { return new ToStringCreator(this).append("useInsecureTrustManager", useInsecureTrustManager) .append("trustedX509Certificates", trustedX509Certificates) .append("handshakeTimeout", handshakeTimeout) .append("closeNotifyFlushTimeout", closeNotifyFlushTimeout) .append("closeNotifyReadTimeout", closeNotifyReadTimeout) .toString(); } } public static class Websocket { /** Max frame payload length. */ private Integer maxFramePayloadLength; /** Proxy ping frames to downstream services, defaults to true. */ private boolean proxyPing = true; public Integer getMaxFramePayloadLength() { return this.maxFramePayloadLength; } public void setMaxFramePayloadLength(Integer maxFramePayloadLength) { this.maxFramePayloadLength = maxFramePayloadLength; } public boolean isProxyPing() {
return proxyPing; } public void setProxyPing(boolean proxyPing) { this.proxyPing = proxyPing; } @Override public String toString() { return new ToStringCreator(this).append("maxFramePayloadLength", maxFramePayloadLength) .append("proxyPing", proxyPing) .toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\HttpClientProperties.java
2
请完成以下Java代码
protected Long getSpecificPriority(ExecutionEntity execution, JobDeclaration<?, ?> param, String jobDefinitionId) { Long specificPriority = null; JobDefinitionEntity jobDefinition = getJobDefinitionFor(jobDefinitionId); if (jobDefinition != null) specificPriority = jobDefinition.getOverridingJobPriority(); if (specificPriority == null) { ParameterValueProvider priorityProvider = param.getJobPriorityProvider(); if (priorityProvider != null) { specificPriority = evaluateValueProvider(priorityProvider, execution, describeContext(param, execution)); } } return specificPriority; } @Override protected Long getProcessDefinitionPriority(ExecutionEntity execution, JobDeclaration<?, ?> jobDeclaration) { ProcessDefinitionImpl processDefinition = jobDeclaration.getProcessDefinition(); return getProcessDefinedPriority(processDefinition, BpmnParse.PROPERTYNAME_JOB_PRIORITY, execution, describeContext(jobDeclaration, execution)); } protected JobDefinitionEntity getJobDefinitionFor(String jobDefinitionId) { if (jobDefinitionId != null) { return Context.getCommandContext() .getJobDefinitionManager() .findById(jobDefinitionId); } else { return null; } } protected Long getActivityPriority(ExecutionEntity execution, JobDeclaration<?, ?> jobDeclaration) { if (jobDeclaration != null) { ParameterValueProvider priorityProvider = jobDeclaration.getJobPriorityProvider(); if (priorityProvider != null) {
return evaluateValueProvider(priorityProvider, execution, describeContext(jobDeclaration, execution)); } } return null; } @Override protected void logNotDeterminingPriority(ExecutionEntity execution, Object value, ProcessEngineException e) { LOG.couldNotDeterminePriority(execution, value, e); } protected String describeContext(JobDeclaration<?, ?> jobDeclaration, ExecutionEntity executionEntity) { return "Job " + jobDeclaration.getActivityId() + "/" + jobDeclaration.getJobHandlerType() + " instantiated " + "in context of " + executionEntity; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\DefaultJobPriorityProvider.java
1
请完成以下Java代码
public class UelExpressionCondition implements Condition { protected Expression expression; public UelExpressionCondition(Expression expression) { this.expression = expression; } @Override public boolean evaluate(DelegateExecution execution) { return evaluate(execution, execution); } @Override public boolean evaluate(VariableScope scope, DelegateExecution execution) { Object result = expression.getValue(scope, execution); ensureNotNull("condition expression returns null", "result", result); ensureInstanceOf("condition expression returns non-Boolean", "result", result, Boolean.class); return (Boolean) result;
} @Override public boolean tryEvaluate(VariableScope scope, DelegateExecution execution) { boolean result = false; try { result = evaluate(scope, execution); } catch (ProcessEngineException pex) { if (!(pex.getCause() instanceof PropertyNotFoundException)) { throw pex; } } return result; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\el\UelExpressionCondition.java
1
请完成以下Java代码
public boolean isEnableExecutionRelationshipCounts() { return enableExecutionRelationshipCounts; } public void setEnableExecutionRelationshipCounts(boolean enableExecutionRelationshipCounts) { this.enableExecutionRelationshipCounts = enableExecutionRelationshipCounts; } public boolean isEnableTaskRelationshipCounts() { return enableTaskRelationshipCounts; } public void setEnableTaskRelationshipCounts(boolean enableTaskRelationshipCounts) { this.enableTaskRelationshipCounts = enableTaskRelationshipCounts; } public boolean isValidateExecutionRelationshipCountConfigOnBoot() { return validateExecutionRelationshipCountConfigOnBoot; } public void setValidateExecutionRelationshipCountConfigOnBoot(boolean validateExecutionRelationshipCountConfigOnBoot) { this.validateExecutionRelationshipCountConfigOnBoot = validateExecutionRelationshipCountConfigOnBoot; } public boolean isValidateTaskRelationshipCountConfigOnBoot() { return validateTaskRelationshipCountConfigOnBoot;
} public void setValidateTaskRelationshipCountConfigOnBoot(boolean validateTaskRelationshipCountConfigOnBoot) { this.validateTaskRelationshipCountConfigOnBoot = validateTaskRelationshipCountConfigOnBoot; } public boolean isEnableLocalization() { return enableLocalization; } public void setEnableLocalization(boolean enableLocalization) { this.enableLocalization = enableLocalization; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cfg\PerformanceSettings.java
1
请完成以下Java代码
public void setReplaceRegExp (final @Nullable java.lang.String ReplaceRegExp) { set_Value (COLUMNNAME_ReplaceRegExp, ReplaceRegExp); } @Override public java.lang.String getReplaceRegExp() { return get_ValueAsString(COLUMNNAME_ReplaceRegExp); } @Override public void setTargetFieldName (final java.lang.String TargetFieldName) { set_Value (COLUMNNAME_TargetFieldName, TargetFieldName); } @Override public java.lang.String getTargetFieldName() { return get_ValueAsString(COLUMNNAME_TargetFieldName); } /** * TargetFieldType AD_Reference_ID=541611 * Reference name: AttributeTypeList */ public static final int TARGETFIELDTYPE_AD_Reference_ID=541611; /** textArea = textArea */ public static final String TARGETFIELDTYPE_TextArea = "textArea"; /** EAN13 = EAN13 */ public static final String TARGETFIELDTYPE_EAN13 = "EAN13";
/** EAN128 = EAN128 */ public static final String TARGETFIELDTYPE_EAN128 = "EAN128"; /** numberField = numberField */ public static final String TARGETFIELDTYPE_NumberField = "numberField"; /** date = date */ public static final String TARGETFIELDTYPE_Date = "date"; /** unitChar = unitChar */ public static final String TARGETFIELDTYPE_UnitChar = "unitChar"; /** graphic = graphic */ public static final String TARGETFIELDTYPE_Graphic = "graphic"; @Override public void setTargetFieldType (final java.lang.String TargetFieldType) { set_Value (COLUMNNAME_TargetFieldType, TargetFieldType); } @Override public java.lang.String getTargetFieldType() { return get_ValueAsString(COLUMNNAME_TargetFieldType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_LeichMehl_PluFile_Config.java
1
请完成以下Java代码
public class JWTToken implements AuthenticationToken { private static final long serialVersionUID = 1282057025599826155L; private String token; private String exipreAt; public JWTToken(String token) { this.token = token; } public JWTToken(String token, String exipreAt) { this.token = token; this.exipreAt = exipreAt; } @Override public Object getPrincipal() { return token; } @Override public Object getCredentials() { return token; } public String getToken() {
return token; } public void setToken(String token) { this.token = token; } public String getExipreAt() { return exipreAt; } public void setExipreAt(String exipreAt) { this.exipreAt = exipreAt; } }
repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\authentication\JWTToken.java
1
请在Spring Boot框架中完成以下Java代码
private void documentToUserUpsert(@NonNull final Exchange exchange) throws ApiException { final Document document = exchange.getIn().getBody(Document.class); final GetAttachmentRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, GetAttachmentRouteConstants.ROUTE_PROPERTY_GET_ATTACHMENT_CONTEXT, GetAttachmentRouteContext.class); routeContext.setDocument(document); final Users createdBy = getUserOrNull(routeContext.getUserApi(), routeContext.getApiKey(), document.getCreatedBy()); final Users updatedBy = getUserOrNull(routeContext.getUserApi(), routeContext.getApiKey(), document.getUpdatedBy()); final Optional<BPUpsertCamelRequest> contactUpsertRequest = DataMapper .usersToBPartnerUpsert(routeContext.getOrgCode(), routeContext.getRootBPartnerIdForUsers(), createdBy, updatedBy); if (contactUpsertRequest.isEmpty()) { exchange.getIn().setBody(null); return; } exchange.getIn().setBody(contactUpsertRequest.get()); } private void attachmentToUserUpsert(@NonNull final Exchange exchange) throws ApiException { final Attachment attachment = exchange.getIn().getBody(Attachment.class); final GetAttachmentRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, GetAttachmentRouteConstants.ROUTE_PROPERTY_GET_ATTACHMENT_CONTEXT, GetAttachmentRouteContext.class); routeContext.setAttachment(attachment); final Users createdBy = getUserOrNull(routeContext.getUserApi(), routeContext.getApiKey(), attachment.getMetadata().getCreatedBy()); final Optional<BPUpsertCamelRequest> contactUpsertRequest = DataMapper .usersToBPartnerUpsert(routeContext.getOrgCode(), routeContext.getRootBPartnerIdForUsers(), createdBy); if (contactUpsertRequest.isEmpty()) {
exchange.getIn().setBody(null); return; } exchange.getIn().setBody(contactUpsertRequest.get()); } @Nullable private Users getUserOrNull( @NonNull final UserApi userApi, @NonNull final String apiKey, @Nullable final String userId) throws ApiException { if (EmptyUtil.isBlank(userId)) { return null; } final Users user = userApi.getUser(apiKey, userId); if (user == null) { throw new RuntimeException("No info returned for user: " + userId); } return user; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\attachment\GetAlbertaAttachmentRoute.java
2
请完成以下Java代码
public Builder setLayoutType(final PanelLayoutType layoutType) { this.layoutType = layoutType; return this; } public Builder setCaption(final ITranslatableString caption) { this.caption = caption; return this; } public Builder setDescription(final ITranslatableString description) { this.description = description; return this; } public ITranslatableString getDescription() { return description; } public Builder addElement(final DocumentLayoutElementDescriptor element) { Check.assumeNotNull(element, "Parameter element is not null"); elements.add(element); return this; } public Builder addElement(final DocumentFieldDescriptor processParaDescriptor) { Check.assumeNotNull(processParaDescriptor, "Parameter processParaDescriptor is not null"); final DocumentLayoutElementDescriptor element = DocumentLayoutElementDescriptor.builder() .setCaption(processParaDescriptor.getCaption()) .setDescription(processParaDescriptor.getDescription()) .setWidgetType(processParaDescriptor.getWidgetType()) .setAllowShowPassword(processParaDescriptor.isAllowShowPassword()) .barcodeScannerType(processParaDescriptor.getBarcodeScannerType())
.addField(DocumentLayoutElementFieldDescriptor.builder(processParaDescriptor.getFieldName()) .setLookupInfos(processParaDescriptor.getLookupDescriptor().orElse(null)) .setPublicField(true) .setSupportZoomInto(processParaDescriptor.isSupportZoomInto())) .build(); addElement(element); return this; } public Builder addElements(@Nullable final DocumentEntityDescriptor parametersDescriptor) { if (parametersDescriptor != null) { parametersDescriptor.getFields().forEach(this::addElement); } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\descriptor\ProcessLayout.java
1
请完成以下Java代码
private static ImmutableTranslatableString retrieveWindowCaption(final ResultSet rs) throws SQLException { final ImmutableTranslatableString.ImmutableTranslatableStringBuilder result = ImmutableTranslatableString.builder() .defaultValue(rs.getString(I_AD_Window.COLUMNNAME_Name)); final Array sqlArray = rs.getArray("name_trls"); if (sqlArray != null) { final String[][] trls = (String[][])sqlArray.getArray(); for (final String[] languageAndName : trls) { final String adLanguage = languageAndName[0]; final String name = languageAndName[1]; result.trl(adLanguage, name); } } return result.build(); } @Override public void assertNoCycles(@NonNull final AdWindowId adWindowId) { final LinkedHashSet<AdWindowId> seenWindowIds = new LinkedHashSet<>(); AdWindowId currentWindowId = adWindowId; while (currentWindowId != null) {
if (!seenWindowIds.add(currentWindowId)) { throw new AdempiereException("Avoid cycles in customization window chain: " + seenWindowIds); } currentWindowId = retrieveBaseWindowId(currentWindowId); } } @Nullable private AdWindowId retrieveBaseWindowId(@NonNull final AdWindowId customizationWindowId) { final String sql = "SELECT " + I_AD_Window.COLUMNNAME_Overrides_Window_ID + " FROM " + I_AD_Window.Table_Name + " WHERE " + I_AD_Window.COLUMNNAME_AD_Window_ID + "=?"; final int baseWindowRepoId = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql, customizationWindowId); return AdWindowId.ofRepoIdOrNull(baseWindowRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\zoom_into\SqlCustomizedWindowInfoMapRepository.java
1
请在Spring Boot框架中完成以下Java代码
SecurityFilterChain loginFilterChain(HttpSecurity http) throws Exception { return http.authorizeHttpRequests( r -> r.anyRequest().authenticated()) .formLogin(Customizer.withDefaults()) .build(); } @Bean public RegisteredClientRepository registeredClientRepository(RegistrationProperties props) { RegisteredClient registrarClient = RegisteredClient.withId(UUID.randomUUID().toString()) .clientId(props.getRegistrarClientId()) .clientSecret(props.getRegistrarClientSecret()) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS) .clientSettings(ClientSettings.builder() .requireProofKey(false) .requireAuthorizationConsent(false) .build()) .scope("client.create")
.scope("client.read") .build(); RegisteredClientRepository delegate = new InMemoryRegisteredClientRepository(registrarClient); return new CustomRegisteredClientRepository(delegate); } @ConfigurationProperties(prefix = "baeldung.security.server.registration") @Getter @Setter public static class RegistrationProperties { private String registrarClientId; private String registrarClientSecret; } }
repos\tutorials-master\spring-security-modules\spring-security-dynamic-registration\oauth2-authorization-server\src\main\java\com\baeldung\spring\security\authserver\config\SecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class DisposableWorkerIdAssigner implements WorkerIdAssigner { private static final Logger LOGGER = LoggerFactory.getLogger(DisposableWorkerIdAssigner.class); @Resource private WorkerNodeDAO workerNodeDAO; /** * Assign worker id base on database.<p> * If there is host name & port in the environment, we considered that the node runs in Docker container<br> * Otherwise, the node runs on an actual machine. * * @return assigned worker id */ @Transactional public long assignWorkerId() { // build worker node entity WorkerNodeEntity workerNodeEntity = buildWorkerNode(); // add worker node for new (ignore the same IP + PORT) workerNodeDAO.addWorkerNode(workerNodeEntity); LOGGER.info("Add worker node:" + workerNodeEntity);
return workerNodeEntity.getId(); } /** * Build worker node entity by IP and PORT */ private WorkerNodeEntity buildWorkerNode() { WorkerNodeEntity workerNodeEntity = new WorkerNodeEntity(); if (DockerUtils.isDocker()) { workerNodeEntity.setType(WorkerNodeType.CONTAINER.value()); workerNodeEntity.setHostName(DockerUtils.getDockerHost()); workerNodeEntity.setPort(DockerUtils.getDockerPort()); } else { workerNodeEntity.setType(WorkerNodeType.ACTUAL.value()); workerNodeEntity.setHostName(NetUtils.getLocalAddress()); workerNodeEntity.setPort(System.currentTimeMillis() + "-" + RandomUtils.nextInt(100000)); } return workerNodeEntity; } }
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\worker\DisposableWorkerIdAssigner.java
2
请完成以下Java代码
public class PropertiesToHashMapConverter { @SuppressWarnings({"rawtypes", "unchecked"}) public static HashMap<String, String> typeCastConvert(Properties prop) { Map step1 = prop; Map<String, String> step2 = (Map<String, String>) step1; return new HashMap<>(step2); } public static HashMap<String, String> loopConvert(Properties prop) { HashMap<String, String> retMap = new HashMap<>(); for (Map.Entry<Object, Object> entry : prop.entrySet()) { retMap.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); } return retMap;
} public static HashMap<String, String> streamConvert(Properties prop) { return prop.entrySet().stream().collect( Collectors.toMap( e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()), (prev, next) -> next, HashMap::new )); } public static HashMap<String, String> guavaConvert(Properties prop) { return Maps.newHashMap(Maps.fromProperties(prop)); } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-3\src\main\java\com\baeldung\map\propertieshashmap\PropertiesToHashMapConverter.java
1
请完成以下Java代码
public String getName() { return this.name; } /** * The <a href= * "https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrpentity-id">id</a> * property is a unique identifier for the Relying Party entity, which sets the * <a href="https://www.w3.org/TR/webauthn-3/#rp-id">RP ID</a>. * @return the relying party id */ public String getId() { return this.id; } /** * Creates a new {@link PublicKeyCredentialRpEntityBuilder} * @return a new {@link PublicKeyCredentialRpEntityBuilder} */ public static PublicKeyCredentialRpEntityBuilder builder() { return new PublicKeyCredentialRpEntityBuilder(); } /** * Used to create a {@link PublicKeyCredentialRpEntity}. * * @author Rob Winch * @since 6.4 */ public static final class PublicKeyCredentialRpEntityBuilder { private @Nullable String name; private @Nullable String id; private PublicKeyCredentialRpEntityBuilder() { } /** * Sets the {@link #getName()} property. * @param name the name property * @return the {@link PublicKeyCredentialRpEntityBuilder} */ public PublicKeyCredentialRpEntityBuilder name(String name) { this.name = name;
return this; } /** * Sets the {@link #getId()} property. * @param id the id * @return the {@link PublicKeyCredentialRpEntityBuilder} */ public PublicKeyCredentialRpEntityBuilder id(String id) { this.id = id; return this; } /** * Creates a new {@link PublicKeyCredentialRpEntity}. * @return a new {@link PublicKeyCredentialRpEntity}. */ public PublicKeyCredentialRpEntity build() { Assert.notNull(this.name, "name cannot be null"); Assert.notNull(this.id, "id cannot be null"); return new PublicKeyCredentialRpEntity(this.name, this.id); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\PublicKeyCredentialRpEntity.java
1
请完成以下Java代码
public JsonPrintingDataResponse getNextPrintingData( @PathVariable("printingQueueId") final int printingQueueId, @Autowired final HttpServletResponse response) { final I_C_Printing_Queue queueRecord = InterfaceWrapperHelper.load(printingQueueId, I_C_Printing_Queue.class); if(queueRecord == null) { response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } final ImmutableList<PrintingData> data = printingDataFactory.createPrintingDataForQueueItem(queueRecord); return printDataRequestHandler.createResponse(data); } /** * Sends feedback regarding the print */ @PostMapping("/setPrintingResult/{printingQueueId}") public ResponseEntity<Object> setPrintingResult( @PathVariable("printingQueueId") final int printingQueueId, @RequestBody @NonNull final JsonPrintingResultRequest input) { final I_C_Printing_Queue queueRecord = InterfaceWrapperHelper.load(printingQueueId, I_C_Printing_Queue.class); if(queueRecord == null) { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); } final I_C_Print_Job_Line printJobLineRecord = queryBL.createQueryBuilder(I_C_Print_Job_Line.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(X_C_Print_Job_Line.COLUMNNAME_C_Printing_Queue_ID, printingQueueId) .create() .firstOnlyNotNull(I_C_Print_Job_Line.class); final int printJobId = printJobLineRecord.getC_Print_Job_ID();
final I_C_Print_Job_Instructions printJobInstructionsRecord = queryBL.createQueryBuilder(I_C_Print_Job_Instructions.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(X_C_Print_Job_Instructions.COLUMNNAME_C_Print_Job_ID, printJobId) .create() .firstOnlyNotNull(I_C_Print_Job_Instructions.class); if(input.isProcessed()) { final I_C_Print_Job printJobRecord = InterfaceWrapperHelper.load(printJobId, I_C_Print_Job.class); printJobRecord.setProcessed(true); save(printJobRecord); CacheMgt.get().reset(X_C_Print_Job.Table_Name, printJobId); printJobInstructionsRecord.setStatus(X_C_Print_Job_Instructions.STATUS_Done); } else { if(!Check.isEmpty(input.getErrorMsg())) { printJobInstructionsRecord.setErrorMsg(input.getErrorMsg()); } printJobInstructionsRecord.setStatus(X_C_Print_Job_Instructions.STATUS_Error); } save(printJobInstructionsRecord); CacheMgt.get().reset(X_C_Print_Job_Instructions.Table_Name, printJobInstructionsRecord.getC_Print_Job_Instructions_ID()); return ResponseEntity.ok().build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.rest-api-impl\src\main\java\de\metas\printing\rest\v2\PrintingRestController.java
1
请完成以下Java代码
public int getMaxQueueingTimeMs() { return maxQueueingTimeMs; } public void setMaxQueueingTimeMs(int maxQueueingTimeMs) { this.maxQueueingTimeMs = maxQueueingTimeMs; } public int getBurstCount() { return burstCount; } public void setBurstCount(int burstCount) { this.burstCount = burstCount; } public long getDurationInSec() { return durationInSec; } public void setDurationInSec(long durationInSec) { this.durationInSec = durationInSec; } public List<ParamFlowItem> getParamFlowItemList() { return paramFlowItemList; } public void setParamFlowItemList(List<ParamFlowItem> paramFlowItemList) { this.paramFlowItemList = paramFlowItemList; } public Map<Object, Integer> getHotItems() { return hotItems; } public void setHotItems(Map<Object, Integer> hotItems) { this.hotItems = hotItems; } public boolean isClusterMode() { return clusterMode; } public void setClusterMode(boolean clusterMode) { this.clusterMode = clusterMode; } public ParamFlowClusterConfig getClusterConfig() { return clusterConfig; } public void setClusterConfig(ParamFlowClusterConfig clusterConfig) { this.clusterConfig = clusterConfig; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getApp() { return app; } public void setApp(String app) { this.app = app; } @Override public String getIp() { return ip;
} public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getLimitApp() { return limitApp; } public void setLimitApp(String limitApp) { this.limitApp = limitApp; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } @Override public Rule toRule() { ParamFlowRule rule = new ParamFlowRule(); return rule; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\ParamFlowRuleCorrectEntity.java
1
请完成以下Java代码
private final Optional<I_M_InOutLine> getInOutLine() { if (_inoutLine == null) { _inoutLine = Optional.ofNullable(M_InOutLine_Handler.getM_InOutLineOrNull(invoiceCandidate)); } return _inoutLine; } private final Optional<BPartnerLocationId> getShipReceiptBPLocationId() { Optional<BPartnerLocationId> shipReceiptBPLocationId = this._shipReceiptBPLocationId; if (shipReceiptBPLocationId == null) { shipReceiptBPLocationId = this._shipReceiptBPLocationId = computeShipReceiptBPLocationId(); } return shipReceiptBPLocationId; } private final Optional<BPartnerLocationId> computeShipReceiptBPLocationId() { final I_M_InOutLine inoutLine = getInOutLine().orElse(null); if (inoutLine != null) { final I_M_InOut inout = inoutLine.getM_InOut(); return Optional.of(BPartnerLocationId.ofRepoId(inout.getC_BPartner_ID(), inout.getC_BPartner_Location_ID())); } final I_C_Order order = invoiceCandidate.getC_Order(); if (order != null)
{ return Optional.of(BPartnerLocationId.ofRepoId(order.getC_BPartner_ID(), order.getC_BPartner_Location_ID())); } return Optional.empty(); } public ArrayKey getInvoiceLineAttributesKey() { ArrayKey invoiceLineAttributesKey = _invoiceLineAttributesKey; if (invoiceLineAttributesKey == null) { invoiceLineAttributesKey = _invoiceLineAttributesKey = computeInvoiceLineAttributesKey(); } return invoiceLineAttributesKey; } private ArrayKey computeInvoiceLineAttributesKey() { final ArrayKeyBuilder keyBuilder = ArrayKey.builder(); for (final IInvoiceLineAttribute invoiceLineAttribute : invoiceLineAttributes) { keyBuilder.append(invoiceLineAttribute.toAggregationKey()); } return keyBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\AggregationKeyEvaluationContext.java
1
请完成以下Java代码
public class BentleyMcIlroyPartioning { public static Partition partition(int input[], int begin, int end) { int left = begin, right = end; int leftEqualKeysCount = 0, rightEqualKeysCount = 0; int partitioningValue = input[end]; while (true) { while (input[left] < partitioningValue) left++; while (input[right] > partitioningValue) { if (right == begin) break; right--; } if (left == right && input[left] == partitioningValue) { swap(input, begin + leftEqualKeysCount, left); leftEqualKeysCount++; left++; } if (left >= right) { break; } swap(input, left, right); if (input[left] == partitioningValue) { swap(input, begin + leftEqualKeysCount, left); leftEqualKeysCount++; } if (input[right] == partitioningValue) { swap(input, right, end - rightEqualKeysCount); rightEqualKeysCount++; } left++; right--; } right = left - 1;
for (int k = begin; k < begin + leftEqualKeysCount; k++, right--) { if (right >= begin + leftEqualKeysCount) swap(input, k, right); } for (int k = end; k > end - rightEqualKeysCount; k--, left++) { if (left <= end - rightEqualKeysCount) swap(input, left, k); } return new Partition(right + 1, left - 1); } public static void quicksort(int input[], int begin, int end) { if (end <= begin) return; Partition middlePartition = partition(input, begin, end); quicksort(input, begin, middlePartition.getLeft() - 1); quicksort(input, middlePartition.getRight() + 1, end); } }
repos\tutorials-master\algorithms-modules\algorithms-sorting-2\src\main\java\com\baeldung\algorithms\quicksort\BentleyMcIlroyPartioning.java
1
请完成以下Java代码
public class X_C_DocType_Invoicing_Pool extends org.compiere.model.PO implements I_C_DocType_Invoicing_Pool, org.compiere.model.I_Persistent { private static final long serialVersionUID = 130875898L; /** Standard Constructor */ public X_C_DocType_Invoicing_Pool (final Properties ctx, final int C_DocType_Invoicing_Pool_ID, @Nullable final String trxName) { super (ctx, C_DocType_Invoicing_Pool_ID, trxName); } /** Load Constructor */ public X_C_DocType_Invoicing_Pool (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_DocType_Invoicing_Pool_ID (final int C_DocType_Invoicing_Pool_ID) { if (C_DocType_Invoicing_Pool_ID < 1) set_ValueNoCheck (COLUMNNAME_C_DocType_Invoicing_Pool_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DocType_Invoicing_Pool_ID, C_DocType_Invoicing_Pool_ID); } @Override public int getC_DocType_Invoicing_Pool_ID() { return get_ValueAsInt(COLUMNNAME_C_DocType_Invoicing_Pool_ID); } @Override public void setIsOnDistinctICTypes (final boolean IsOnDistinctICTypes) { set_Value (COLUMNNAME_IsOnDistinctICTypes, IsOnDistinctICTypes); } @Override public boolean isOnDistinctICTypes() { return get_ValueAsBoolean(COLUMNNAME_IsOnDistinctICTypes); } @Override public void setIsSOTrx (final boolean IsSOTrx)
{ set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setNegative_Amt_C_DocType_ID (final int Negative_Amt_C_DocType_ID) { if (Negative_Amt_C_DocType_ID < 1) set_Value (COLUMNNAME_Negative_Amt_C_DocType_ID, null); else set_Value (COLUMNNAME_Negative_Amt_C_DocType_ID, Negative_Amt_C_DocType_ID); } @Override public int getNegative_Amt_C_DocType_ID() { return get_ValueAsInt(COLUMNNAME_Negative_Amt_C_DocType_ID); } @Override public void setPositive_Amt_C_DocType_ID (final int Positive_Amt_C_DocType_ID) { if (Positive_Amt_C_DocType_ID < 1) set_Value (COLUMNNAME_Positive_Amt_C_DocType_ID, null); else set_Value (COLUMNNAME_Positive_Amt_C_DocType_ID, Positive_Amt_C_DocType_ID); } @Override public int getPositive_Amt_C_DocType_ID() { return get_ValueAsInt(COLUMNNAME_Positive_Amt_C_DocType_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType_Invoicing_Pool.java
1
请在Spring Boot框架中完成以下Java代码
public void setTime(Date time) { this.time = time; } public String getTaskUrl() { return taskUrl; } public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } @JsonInclude(JsonInclude.Include.NON_NULL) public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } public List<String> getMessage() {
return message; } public void setMessage(List<String> message) { this.message = message; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\engine\EventResponse.java
2
请在Spring Boot框架中完成以下Java代码
public class ADUIColumnNameFQ { int seqNo; ADUISectionNameFQ uiSectionName; String missing; public static ADUIColumnNameFQ missing(@NonNull final AdUIColumnId uiColumnId) { return builder().missing("<" + uiColumnId.getRepoId() + ">").build(); } @Override public String toString() {return toShortString();} public String toShortString() { if (missing != null) { return missing; }
else { final StringBuilder sb = new StringBuilder(); if (uiSectionName != null) { sb.append(uiSectionName.toShortString()); } if (sb.length() > 0) { sb.append(" -> "); } sb.append(seqNo); return sb.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\validator\sql_migration_context_info\names\ADUIColumnNameFQ.java
2
请完成以下Java代码
public int getAD_Index_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Index_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Column SQL. @param ColumnSQL Virtual Column (r/o) */ public void setColumnSQL (String ColumnSQL) { set_Value (COLUMNNAME_ColumnSQL, ColumnSQL); } /** Get Column SQL. @return Virtual Column (r/o) */ public String getColumnSQL () { return (String)get_Value(COLUMNNAME_ColumnSQL); } /** EntityType AD_Reference_ID=389 */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization
*/ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Index_Column.java
1
请完成以下Java代码
public String getFromName() { return fromName; } public void setFromName(String fromName) { this.fromName = fromName; } @Schema(description = "Name of the entity for [to] direction.", accessMode = Schema.AccessMode.READ_ONLY, example = "A4B72CCDFF35") public String getToName() { return toName; } public void setToName(String toName) { this.toName = toName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false; EntityRelationInfo that = (EntityRelationInfo) o; return toName != null ? toName.equals(that.toName) : that.toName == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (toName != null ? toName.hashCode() : 0); return result; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\relation\EntityRelationInfo.java
1
请在Spring Boot框架中完成以下Java代码
private RedisSerializer getJacksonSerializer() { ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); return new GenericJackson2JsonRedisSerializer(om); } @Bean public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForHash(); } @Bean public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForValue(); } @Bean public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList(); } @Bean public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForSet(); } @Bean public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForZSet(); } @Bean(destroyMethod = "destroy") public RedisLockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory) { return new RedisLockRegistry(redisConnectionFactory, "lock"); } }
repos\spring-boot-best-practice-master\spring-boot-redis\src\main\java\cn\javastack\springboot\redis\config\RedisConfig.java
2
请完成以下Java代码
class OpenTelemetryMetricsDockerComposeConnectionDetailsFactory extends DockerComposeConnectionDetailsFactory<OtlpMetricsConnectionDetails> { private static final String[] OPENTELEMETRY_IMAGE_NAMES = { "otel/opentelemetry-collector-contrib", "grafana/otel-lgtm" }; private static final int OTLP_PORT = 4318; OpenTelemetryMetricsDockerComposeConnectionDetailsFactory() { super(OPENTELEMETRY_IMAGE_NAMES, "org.springframework.boot.micrometer.metrics.autoconfigure.export.otlp.OtlpMetricsExportAutoConfiguration"); } @Override protected OtlpMetricsConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) { return new OpenTelemetryMetricsDockerComposeConnectionDetails(source.getRunningService()); } private static final class OpenTelemetryMetricsDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements OtlpMetricsConnectionDetails { private final String host;
private final int port; private OpenTelemetryMetricsDockerComposeConnectionDetails(RunningService source) { super(source); this.host = source.host(); this.port = source.ports().get(OTLP_PORT); } @Override public String getUrl() { return "http://%s:%d/v1/metrics".formatted(this.host, this.port); } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\docker\compose\otlp\OpenTelemetryMetricsDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
public List<I_M_Source_HU> retrieveActiveSourceHuMarkers(@NonNull final MatchingSourceHusQuery query) { if (query.getProductIds().isEmpty()) { return ImmutableList.of(); } final IQueryBL queryBL = Services.get(IQueryBL.class); final IQuery<I_M_HU> huQuery = queryBL.createQueryBuilder(I_M_HU.class) .addOnlyActiveRecordsFilter() .filter(createHuFilter(query)) .create(); return queryBL.createQueryBuilder(I_M_Source_HU.class) .addOnlyActiveRecordsFilter() .addInSubQueryFilter(I_M_Source_HU.COLUMN_M_HU_ID, I_M_HU.COLUMN_M_HU_ID, huQuery) .create() .list(); } @VisibleForTesting static ICompositeQueryFilter<I_M_HU> createHuFilter(@NonNull final MatchingSourceHusQuery query) { final IQueryBL queryBL = Services.get(IQueryBL.class); final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); final ICompositeQueryFilter<I_M_HU> huFilters = queryBL.createCompositeQueryFilter(I_M_HU.class) .setJoinOr();
final IHUQueryBuilder huQueryBuilder = handlingUnitsDAO.createHUQueryBuilder() .setOnlyActiveHUs(true) .setAllowEmptyStorage() .addOnlyWithProductIds(query.getProductIds()); final ImmutableSet<WarehouseId> warehouseIds = query.getWarehouseIds(); if (warehouseIds != null && !warehouseIds.isEmpty()) { huQueryBuilder.addOnlyInWarehouseIds(warehouseIds); } final IQueryFilter<I_M_HU> huFilter = huQueryBuilder.createQueryFilter(); huFilters.addFilter(huFilter); return huFilters; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\sourcehu\impl\SourceHuDAO.java
1
请完成以下Java代码
public int hashCode() { final PropertyChangeListener delegate = getDelegate(); final int prime = 31; int result = 1; result = prime * result + (delegate == null ? 0 : delegate.hashCode()); return result; } /** * This equal method basically compares <code>this</code> instance's delegate to the given <code>obj</code>'s deleget (ofc only if that given object is also a WeakpropertyChangeListener). * <p> * NOTE: please pay attention to this method because based on this, the Listener will be removed or not * * @see org.adempiere.util.beans.WeakPropertyChangeSupport#removePropertyChangeListener(PropertyChangeListener) * @see org.adempiere.util.beans.WeakPropertyChangeSupport#removePropertyChangeListener(String, PropertyChangeListener) */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final WeakPropertyChangeListener other = (WeakPropertyChangeListener)obj; final PropertyChangeListener thisDelegate = getDelegate(); final PropertyChangeListener otherDelegate = other.getDelegate(); if (thisDelegate == null) { if (otherDelegate != null) { return false; } } else if (!thisDelegate.equals(otherDelegate)) { return false; } return true; } public boolean isWeak() { return delegate == null; } public PropertyChangeListener getDelegate() { if (delegate != null) { return delegate; } final PropertyChangeListener delegate = delegateRef.get(); return delegate; } @Override public void propertyChange(final PropertyChangeEvent evt) { final boolean DEBUG = false; final PropertyChangeListener delegate = getDelegate(); if (delegate == null) { // delegate reference expired if (DEBUG) { // TODO remove before integrating into base line!! System.out.println(StringUtils.formatMessage("delegate of {0} is expired", this)); } return;
} final Object source = evt.getSource(); final PropertyChangeEvent evtNew; if (source instanceof Reference) { final Reference<?> sourceRef = (Reference<?>)source; final Object sourceObj = sourceRef.get(); if (sourceObj == null) { // reference expired if (DEBUG) { // TODO remove before integrating into base line!! System.out.println(StringUtils.formatMessage("sourceObj of {0} is expired", this)); } return; } evtNew = new PropertyChangeEvent(sourceObj, evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); evtNew.setPropagationId(evt.getPropagationId()); } else { evtNew = evt; } delegate.propertyChange(evtNew); } @Override public String toString() { return "WeakPropertyChangeListener [delegate=" + delegate + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\beans\WeakPropertyChangeListener.java
1
请完成以下Java代码
public Class<? extends DbEntity> getEntityType() { return ExternalTaskEntity.class; } @Override public OptimisticLockingResult failedOperation(DbOperation operation) { if (operation instanceof DbEntityOperation) { DbEntityOperation dbEntityOperation = (DbEntityOperation) operation; DbEntity dbEntity = dbEntityOperation.getEntity(); boolean failedOperationEntityInList = false; Iterator<LockedExternalTask> it = tasks.iterator(); while (it.hasNext()) { LockedExternalTask resultTask = it.next(); if (resultTask.getId().equals(dbEntity.getId())) { it.remove(); failedOperationEntityInList = true; break; } } // If the entity that failed with an OLE is not in the list, // we rethrow the OLE to the caller. if (!failedOperationEntityInList) { return OptimisticLockingResult.THROW; } // If the entity that failed with an OLE has been removed // from the list, we suppress the OLE. return OptimisticLockingResult.IGNORE; } // If none of the conditions are satisfied, this might indicate a bug, // so we throw the OLE. return OptimisticLockingResult.THROW; } });
} protected void validateInput() { EnsureUtil.ensureNotNull("workerId", workerId); EnsureUtil.ensureGreaterThanOrEqual("maxResults", maxResults, 0); for (TopicFetchInstruction instruction : fetchInstructions.values()) { EnsureUtil.ensureNotNull("topicName", instruction.getTopicName()); EnsureUtil.ensurePositive("lockTime", instruction.getLockDuration()); } } protected List<QueryOrderingProperty> orderingPropertiesWithPriority(boolean usePriority, List<QueryOrderingProperty> queryOrderingProperties) { List<QueryOrderingProperty> results = new ArrayList<>(); // Priority needs to be the first item in the list because it takes precedence over other sorting options // Multi level ordering works by going through the list of ordering properties from first to last item if (usePriority) { results.add(new QueryOrderingProperty(PRIORITY, DESCENDING)); } results.addAll(queryOrderingProperties); return results; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\FetchExternalTasksCmd.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } final LocationCaptureSequence other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(parts, other.parts) .isEqual(); } public final Collection<Part> getParts() { return parts.values(); } public boolean hasPart(final String partName) { return parts.containsKey(partName); } public boolean isPartMandatory(final String partName) { final Part part = parts.get(partName); return part != null && part.isMandatory(); } /** Location capture part */ public static final class Part { private final String name; private final int index; private final boolean mandatory; private Integer _hashcode; private Part(final String name, final int index, final boolean mandatory) { super(); this.name = name; this.index = index; this.mandatory = mandatory; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(name); if (mandatory) { sb.append("!"); } return sb.toString(); } @Override public int hashCode() { if (_hashcode == null) { _hashcode = new HashcodeBuilder() .append(name) .append(index) .append(mandatory) .toHashcode();
} return _hashcode; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } final Part other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(name, other.name) .append(index, other.index) .append(mandatory, other.mandatory) .isEqual(); } public String getName() { return name; } public boolean isMandatory() { return mandatory; } public int getIndex() { return index; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\LocationCaptureSequence.java
1
请完成以下Java代码
public void store(OutputStream out, String comments) throws IOException { getDelegate().store(out, comments); } @Override public void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException { getDelegate().loadFromXML(in); } @Override public void storeToXML(OutputStream os, String comment) throws IOException { getDelegate().storeToXML(os, comment); } @Override public void storeToXML(OutputStream os, String comment, String encoding) throws IOException { getDelegate().storeToXML(os, comment, encoding); } @Override public String getProperty(String key) { return getDelegate().getProperty(key); } @Override public String getProperty(String key, String defaultValue)
{ return getDelegate().getProperty(key, defaultValue); } @Override public Enumeration<?> propertyNames() { return getDelegate().propertyNames(); } @Override public Set<String> stringPropertyNames() { return getDelegate().stringPropertyNames(); } @Override public void list(PrintStream out) { getDelegate().list(out); } @Override public void list(PrintWriter out) { getDelegate().list(out); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\AbstractPropertiesProxy.java
1
请完成以下Java代码
protected void handleIncident(MigratingInstanceParseContext parseContext, IncidentEntity incident) { MigratingActivityInstance owningInstance = parseContext.getMigratingActivityInstanceById(incident.getExecution().getActivityInstanceId()); if (owningInstance != null) { parseContext.consume(incident); MigratingIncident migratingIncident = new MigratingIncident(incident, owningInstance.getTargetScope()); owningInstance.addMigratingDependentInstance(migratingIncident); } } protected boolean isFailedJobIncident(IncidentEntity incident) { return IncidentEntity.FAILED_JOB_HANDLER_TYPE.equals(incident.getIncidentType()); } protected void handleFailedJobIncident(MigratingInstanceParseContext parseContext, IncidentEntity incident) { MigratingJobInstance owningInstance = parseContext.getMigratingJobInstanceById(incident.getConfiguration()); if (owningInstance != null) { parseContext.consume(incident); if (owningInstance.migrates()) { MigratingIncident migratingIncident = new MigratingIncident(incident, owningInstance.getTargetScope()); JobDefinitionEntity targetJobDefinitionEntity = owningInstance.getTargetJobDefinitionEntity(); if (targetJobDefinitionEntity != null) { migratingIncident.setTargetJobDefinitionId(targetJobDefinitionEntity.getId()); } owningInstance.addMigratingDependentInstance(migratingIncident); } }
} protected boolean isExternalTaskIncident(IncidentEntity incident) { return IncidentEntity.EXTERNAL_TASK_HANDLER_TYPE.equals(incident.getIncidentType()); } protected void handleExternalTaskIncident(MigratingInstanceParseContext parseContext, IncidentEntity incident) { MigratingExternalTaskInstance owningInstance = parseContext.getMigratingExternalTaskInstanceById(incident.getConfiguration()); if (owningInstance != null) { parseContext.consume(incident); MigratingIncident migratingIncident = new MigratingIncident(incident, owningInstance.getTargetScope()); owningInstance.addMigratingDependentInstance(migratingIncident); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\IncidentInstanceHandler.java
1
请完成以下Java代码
public static Predicate<I_M_Product> toPredicate(@NonNull final DocumentFilterList filters) { if (filters.isEmpty()) { return Predicates.alwaysTrue(); } final ProductFilterVO productFilterVO = extractProductFilterVO(filters); return product -> doesProductMatchFilter(product, productFilterVO); } public static boolean doesProductMatchFilter( @NonNull final I_M_Product product, @NonNull final ProductFilterVO filterVO) { final boolean ignoreCase = true; // ProductName final String productName = filterVO.getProductName(); if (!Check.isEmpty(productName, true)) { final StringLikeFilter<I_M_Product> likeFilter = new StringLikeFilter<>(I_M_Product.COLUMNNAME_Name, productName, ignoreCase); if (!likeFilter.accept(product)) { return false; } } // ProductValue final String productValue = filterVO.getProductValue(); if (!Check.isEmpty(productValue, true)) { final StringLikeFilter<I_M_Product> likeFilter = new StringLikeFilter<>(I_M_Product.COLUMNNAME_Value, productValue, ignoreCase); if (!likeFilter.accept(product)) { return false; } } // Product Category if (filterVO.getProductCategoryId() > 0 && product.getM_Product_Category_ID() != filterVO.getProductCategoryId()) { return false; }
// IsPurchase if (filterVO.getIsPurchased() != null && filterVO.getIsPurchased() != product.isPurchased()) { return false; } // IsSold if (filterVO.getIsSold() != null && filterVO.getIsSold() != product.isSold()) { return false; } // IsActive if (filterVO.getIsActive() != null && filterVO.getIsActive() != product.isActive()) { return false; } // Discontinued if (filterVO.getIsDiscontinued() != null && filterVO.getIsDiscontinued() != product.isDiscontinued()) { return false; } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\filters\ProductFilterUtil.java
1
请完成以下Java代码
public PageData<EntityView> findEntityViewsByTenantIdAndEdgeId(UUID tenantId, UUID edgeId, PageLink pageLink) { log.debug("Try to find entity views by tenantId [{}], edgeId [{}] and pageLink [{}]", tenantId, edgeId, pageLink); return DaoUtil.toPageData(entityViewRepository .findByTenantIdAndEdgeId( tenantId, edgeId, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public List<EntityView> findEntityViewsByTenantIdAndIds(UUID tenantId, List<UUID> entityViewIds) { return DaoUtil.convertDataList(entityViewRepository.findEntityViewsByTenantIdAndIdIn(tenantId, entityViewIds)); } @Override public PageData<EntityView> findEntityViewsByTenantIdAndEdgeIdAndType(UUID tenantId, UUID edgeId, String type, PageLink pageLink) { log.debug("Try to find entity views by tenantId [{}], edgeId [{}], type [{}] and pageLink [{}]", tenantId, edgeId, type, pageLink); return DaoUtil.toPageData(entityViewRepository .findByTenantIdAndEdgeIdAndType( tenantId, edgeId, type, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public EntityView findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(entityViewRepository.findByTenantIdAndExternalId(tenantId, externalId)); } @Override public PageData<EntityView> findByTenantId(UUID tenantId, PageLink pageLink) { return findEntityViewsByTenantId(tenantId, pageLink); }
@Override public EntityViewId getExternalIdByInternal(EntityViewId internalId) { return Optional.ofNullable(entityViewRepository.getExternalIdById(internalId.getId())) .map(EntityViewId::new).orElse(null); } @Override public EntityView findByTenantIdAndName(UUID tenantId, String name) { return findEntityViewByTenantIdAndName(tenantId, name).orElse(null); } @Override public PageData<EntityView> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override public List<EntityViewFields> findNextBatch(UUID id, int batchSize) { return entityViewRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public List<EntityInfo> findEntityInfosByNamePrefix(TenantId tenantId, String name) { return entityViewRepository.findEntityInfosByNamePrefix(tenantId.getId(), name); } @Override public EntityType getEntityType() { return EntityType.ENTITY_VIEW; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\entityview\JpaEntityViewDao.java
1
请完成以下Java代码
public void dispose() { if (m_frame != null) m_frame.dispose(); m_frame = null; removeAll(); } // dispose /** Window No */ private int m_WindowNo = 0; /** FormFrame */ private FormFrame m_frame; /** Logger */ private static Logger log = LogManager.getLogger(ViewPI.class); /** Confirmation Panel */ private ConfirmPanel confirmPanel = ConfirmPanel.newWithOK(); /** * Init Panel */ private void initPanel() { BoxLayout layout = new BoxLayout(this, BoxLayout.PAGE_AXIS); MGoal[] goals = MGoal.getGoals(Env.getCtx()); for (int i = 0; i < goals.length; i++) { PerformanceIndicator pi = new PerformanceIndicator(goals[i]); pi.addActionListener(this); add (pi); }
} // initPanel /** * Action Listener for Drill Down * @param e event */ @Override public void actionPerformed (ActionEvent e) { if (e.getActionCommand().equals(ConfirmPanel.A_OK)) dispose(); else if (e.getSource() instanceof PerformanceIndicator) { PerformanceIndicator pi = (PerformanceIndicator)e.getSource(); log.info(pi.getName()); MGoal goal = pi.getGoal(); if (goal.getMeasure() != null) new PerformanceDetail(goal); } } // actionPerformed } // ViewPI
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\adempiere\apps\graph\ViewPI.java
1
请在Spring Boot框架中完成以下Java代码
public void appendPackedItem(@NonNull final PackingSlot slot, @NonNull final IPackingItem packedItem) { for (final IPackingItem item : items.get(slot)) { // add new item into the list only if is a real new item // NOTE: should be only one item with same grouping key if (PackingItemGroupingKey.equals(item.getGroupingKey(), packedItem.getGroupingKey())) { item.addParts(packedItem); return; } } // // No matching existing packed item where our item could be added was found // => add it here as a new item addItem(slot, packedItem); } /** * * @return true if there exists at least one packed item */ public boolean hasPackedItems() { return streamPackedItems().findAny().isPresent(); } public boolean hasPackedItemsMatching(@NonNull final Predicate<IPackingItem> predicate) { return streamPackedItems().anyMatch(predicate); }
public Stream<IPackingItem> streamPackedItems() { return items .entries() .stream() .filter(e -> !e.getKey().isUnpacked()) .map(e -> e.getValue()); } /** * * @return true if there exists at least one unpacked item */ public boolean hasUnpackedItems() { return !items.get(PackingSlot.UNPACKED).isEmpty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItemsMap.java
2
请在Spring Boot框架中完成以下Java代码
public long findCaseDefinitionCountByQueryCriteria(CaseDefinitionQueryImpl caseDefinitionQuery) { configureCaseDefinitionQuery(caseDefinitionQuery); return (Long) getDbEntityManager().selectOne("selectCaseDefinitionCountByQueryCriteria", caseDefinitionQuery); } @SuppressWarnings("unchecked") public List<CaseDefinition> findCaseDefinitionByDeploymentId(String deploymentId) { return getDbEntityManager().selectList("selectCaseDefinitionByDeploymentId", deploymentId); } protected void configureCaseDefinitionQuery(CaseDefinitionQueryImpl query) { getTenantManager().configureQuery(query); } protected ListQueryParameterObject configureParameterizedQuery(Object parameter) { return getTenantManager().configureQuery(parameter); } @Override public CaseDefinitionEntity findLatestDefinitionByKey(String key) { return findLatestCaseDefinitionByKey(key); } @Override public CaseDefinitionEntity findLatestDefinitionById(String id) { return findCaseDefinitionById(id); } @Override public CaseDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) { return getDbEntityManager().getCachedEntity(CaseDefinitionEntity.class, definitionId); } @Override public CaseDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) { return findLatestCaseDefinitionByKeyAndTenantId(definitionKey, tenantId);
} @Override public CaseDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) { throw new UnsupportedOperationException("Currently finding case definition by version tag and tenant is not implemented."); } @Override public CaseDefinitionEntity findDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) { return findCaseDefinitionByKeyVersionAndTenantId(definitionKey, definitionVersion, tenantId); } @Override public CaseDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) { return findCaseDefinitionByDeploymentAndKey(deploymentId, definitionKey); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\repository\CaseDefinitionManager.java
2
请在Spring Boot框架中完成以下Java代码
public class Company implements Serializable { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; @Column(name = "name") private String name; @OneToMany @JoinColumn(name = "workplace_id") private Set<Employee> employees = new HashSet<>(); public Company() { } public Company(String name) { this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Employee> getEmployees() { return this.employees; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Company company = (Company) o; return Objects.equals(id, company.id) && Objects.equals(name, company.name); } @Override public int hashCode() { return Objects.hash(id, name); } }
repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\proxy\Company.java
2
请完成以下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); } @Override public org.compiere.model.I_AD_User getSubstitute() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Substitute_ID, org.compiere.model.I_AD_User.class); } @Override public void setSubstitute(org.compiere.model.I_AD_User Substitute) { set_ValueFromPO(COLUMNNAME_Substitute_ID, org.compiere.model.I_AD_User.class, Substitute); } /** Set Ersatz. @param Substitute_ID Entity which can be used in place of this entity */ @Override public void setSubstitute_ID (int Substitute_ID) { if (Substitute_ID < 1) set_Value (COLUMNNAME_Substitute_ID, null); else set_Value (COLUMNNAME_Substitute_ID, Integer.valueOf(Substitute_ID)); } /** Get Ersatz. @return Entity which can be used in place of this entity */ @Override public int getSubstitute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Substitute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Gültig ab.
@param ValidFrom Valid from including this date (first day) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Valid from including this date (first day) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Valid to including this date (last day) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Valid to including this date (last day) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Substitute.java
1
请完成以下Java代码
private void throwExceptionIfErrorItemsExist( final List<PurchaseItem> remotePurchaseItems, final Collection<PurchaseCandidate> purchaseCandidatesWithVendorId, final BPartnerId vendorId) { final List<PurchaseErrorItem> purchaseErrorItems = remotePurchaseItems.stream() .filter(item -> item instanceof PurchaseErrorItem) .map(item -> (PurchaseErrorItem)item) .collect(ImmutableList.toImmutableList()); if (purchaseErrorItems.isEmpty()) { return; // nothing to do } final I_C_BPartner vendor = Services.get(IBPartnerDAO.class).getById(vendorId); throw new AdempiereException( MSG_ERROR_WHILE_PLACING_REMOTE_PURCHASE_ORDER, vendor.getValue(), vendor.getName()) .appendParametersToMessage() .setParameter("purchaseCandidatesWithVendorId", purchaseCandidatesWithVendorId) .setParameter("purchaseErrorItems", purchaseErrorItems); } private void logAndRethrow( final Throwable throwable, final BPartnerId vendorId, final Collection<PurchaseCandidate> purchaseCandidates) { final ILoggable loggable = Loggables.get(); final String message = StringUtils.formatMessage( "Caught {} while working with vendorId={}; message={}, purchaseCandidates={}", throwable.getClass(), vendorId, throwable.getMessage(), purchaseCandidates);
logger.error(message, throwable); loggable.addLog(message); for (final PurchaseCandidate purchaseCandidate : purchaseCandidates) { purchaseCandidate.createErrorItem() .throwable(throwable) .buildAndAdd(); } purchaseCandidateRepo.saveAll(purchaseCandidates); exceptions.add(throwable); throw new AdempiereException(message, throwable); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\PurchaseCandidateToOrderWorkflow.java
1
请完成以下Java代码
private SbomType detectSbomType(Resource resource) throws IOException { String content = resource.getContentAsString(StandardCharsets.UTF_8); for (SbomType candidate : SbomType.values()) { if (candidate.matches(content)) { return candidate; } } return SbomType.UNKNOWN; } enum SbomType { CYCLONE_DX(MimeType.valueOf("application/vnd.cyclonedx+json")) { @Override boolean matches(String content) { return content.replaceAll("\\s", "").contains("\"bomFormat\":\"CycloneDX\""); } }, SPDX(MimeType.valueOf("application/spdx+json")) { @Override boolean matches(String content) { return content.contains("\"spdxVersion\""); } }, SYFT(MimeType.valueOf("application/vnd.syft+json")) { @Override
boolean matches(String content) { return content.contains("\"FoundBy\"") || content.contains("\"foundBy\""); } }, UNKNOWN(null) { @Override boolean matches(String content) { return false; } }; private final @Nullable MimeType mediaType; SbomType(@Nullable MimeType mediaType) { this.mediaType = mediaType; } @Nullable MimeType getMediaType() { return this.mediaType; } abstract boolean matches(String content); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\sbom\SbomEndpointWebExtension.java
1
请完成以下Java代码
class Cat extends Animal implements Comparable<Cat> { public Cat(String type, String name) { super(type, name); } @Override public String makeSound() { return "Meow"; } /** * Warning: Inconsistent with the equals method. */ @Override public int compareTo(Cat cat) { return this.getName().length() - cat.getName().length(); } @Override public String toString() { return "Cat{" + "type='" + type + '\'' + ", name='" + name + '\'' + '}'; }
@Override public int hashCode() { return Objects.hash(type, name); } @Override public boolean equals(Object o) { if(o == this) return true; if(!(o instanceof Cat)) return false; Cat cat = (Cat) o; return type.equals(cat.type) && name.equals(cat.name); } }
repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\generics\Cat.java
1
请完成以下Java代码
public boolean isDirty() { return !dbEntity.getPersistentState().equals(copy); } public void forceSetDirty() { // set the value of the copy to some value which will always be different from the new entity state. this.copy = -1; } public void makeCopy() { copy = dbEntity.getPersistentState(); } public String toString() { return entityState + " " + dbEntity.getClass().getSimpleName() + "["+dbEntity.getId()+"]"; } public void determineEntityReferences() { if (dbEntity instanceof HasDbReferences) { flushRelevantEntityReferences = ((HasDbReferences) dbEntity).getReferencedEntityIds(); } else { flushRelevantEntityReferences = Collections.emptySet(); } } public boolean areFlushRelevantReferencesDetermined() { return flushRelevantEntityReferences != null; } public Set<String> getFlushRelevantEntityReferences() { return flushRelevantEntityReferences;
} // getters / setters //////////////////////////// public DbEntity getEntity() { return dbEntity; } public void setEntity(DbEntity dbEntity) { this.dbEntity = dbEntity; } public DbEntityState getEntityState() { return entityState; } public void setEntityState(DbEntityState entityState) { this.entityState = entityState; } public Class<? extends DbEntity> getEntityType() { return dbEntity.getClass(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\cache\CachedDbEntity.java
1
请完成以下Java代码
public static void main(String[] args) { int a = -12; int result = pow(a); System.out.println(result); Map<String, Integer> dictionary = createDictionary(); dictionary.forEach((s, integer) -> System.out.println(s + " " + integer)); } public static int pow(int number) { int pow = number * number; return pow; } public static String checkNumber(int number) { if (number == 0) { return "It's equals to zero"; }
for (int i = 0; i < number; i++) { if (i > 100) { return "It's a big number"; } } return "It's a negative number"; } public static Map<String, Integer> createDictionary() { List<String> words = Arrays.asList("Hello", "World"); return words.stream() .collect(Collectors.toMap(s -> s, s -> 1)); } }
repos\tutorials-master\core-java-modules\core-java-exceptions-4\src\main\java\com\baeldung\exception\missingreturnstatement\MissingReturnStatement.java
1
请完成以下Java代码
public void writeTo(IndentingWriter writer, ComposeFile compose) { if (compose.services().isEmpty()) { writer.println("services: {}"); return; } writer.println("services:"); compose.services() .values() .sorted(Comparator.comparing(ComposeService::getName)) .forEach((service) -> writeService(writer, service)); } private void writeService(IndentingWriter writer, ComposeService service) { writer.indented(() -> { writer.println(service.getName() + ":"); writer.indented(() -> { writer.println("image: '%s:%s'".formatted(service.getImage(), service.getImageTag())); writerServiceEnvironment(writer, service.getEnvironment()); writerServiceLabels(writer, service.getLabels()); writerServicePorts(writer, service.getPorts()); writeServiceCommand(writer, service.getCommand()); }); }); } private void writerServiceEnvironment(IndentingWriter writer, Map<String, String> environment) { if (environment.isEmpty()) { return; } writer.println("environment:"); writer.indented(() -> { for (Map.Entry<String, String> env : environment.entrySet()) { writer.println("- '%s=%s'".formatted(env.getKey(), env.getValue())); } }); } private void writerServicePorts(IndentingWriter writer, Set<Integer> ports) { if (ports.isEmpty()) { return; } writer.println("ports:"); writer.indented(() -> { for (Integer port : ports) { writer.println("- '%d'".formatted(port)); }
}); } private void writeServiceCommand(IndentingWriter writer, String command) { if (!StringUtils.hasText(command)) { return; } writer.println("command: '%s'".formatted(command)); } private void writerServiceLabels(IndentingWriter writer, Map<String, String> labels) { if (labels.isEmpty()) { return; } writer.println("labels:"); writer.indented(() -> { for (Map.Entry<String, String> label : labels.entrySet()) { writer.println("- \"%s=%s\"".formatted(label.getKey(), label.getValue())); } }); } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\container\docker\compose\ComposeFileWriter.java
1
请完成以下Java代码
public void handleEvent(@NonNull final AbstractStockEstimateEvent event) { final UpdateMainDataRequest dataUpdateRequest = createDataUpdateRequestForEvent(event); dataUpdateRequestHandler.handleDataUpdateRequest(dataUpdateRequest); } private UpdateMainDataRequest createDataUpdateRequestForEvent( @NonNull final AbstractStockEstimateEvent stockEstimateEvent) { final OrgId orgId = stockEstimateEvent.getOrgId(); final ZoneId timeZone = orgDAO.getTimeZone(orgId); final MainDataRecordIdentifier identifier = MainDataRecordIdentifier.builder() .productDescriptor(stockEstimateEvent.getMaterialDescriptor()) .date(TimeUtil.getDay(stockEstimateEvent.getDate(), timeZone)) .warehouseId(stockEstimateEvent.getMaterialDescriptor().getWarehouseId()) .build();
final BigDecimal qtyStockEstimate = stockEstimateEvent instanceof StockEstimateDeletedEvent ? BigDecimal.ZERO : stockEstimateEvent.getQuantityDelta(); final Integer qtyStockSeqNo = stockEstimateEvent instanceof StockEstimateDeletedEvent ? 0 : stockEstimateEvent.getQtyStockEstimateSeqNo(); return UpdateMainDataRequest.builder() .identifier(identifier) .qtyStockEstimateSeqNo(qtyStockSeqNo) .qtyStockEstimateCount(qtyStockEstimate) .qtyStockEstimateTime(stockEstimateEvent.getDate()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\eventhandler\AbstractStockEstimateHandler.java
1
请完成以下Java代码
public void rollback() { final I_AD_Column column = getAD_Column(); final Object value; if (data.isBackupNull()) { value = null; } else { final String valueStr = data.getBackupValue(); value = converter.stringToObject(column, valueStr); } if (value == IDataConverter.VALUE_Unknown) { return; } po.set_ValueNoCheck(column.getColumnName(), value); } private I_AD_Column getAD_Column() { I_AD_Column column = data.getAD_Column(); if (column != null && column.getAD_Table_ID() != adTableId) {
logger.warn("Column '" + column.getColumnName() + "' (ID=" + column.getAD_Column_ID() + ") does not match AD_Table_ID from parent. Attempting to retrieve column by name and tableId."); column = null; } final String dataColumnName = data.getColumnName(); if (column != null && !dataColumnName.equalsIgnoreCase(column.getColumnName())) { logger.warn("Column ID collision '" + dataColumnName + "' with existing '" + column.getColumnName() + "' (ID=" + column.getAD_Column_ID() + "). Attempting to retrieve column by name and tableId."); column = null; } if (column == null) { final Properties ctx = InterfaceWrapperHelper.getCtx(data); final String trxName = InterfaceWrapperHelper.getTrxName(data); final String whereClause = I_AD_Column.COLUMNNAME_AD_Table_ID + "=?" + " AND " + I_AD_Column.COLUMNNAME_ColumnName + "=?"; column = new TypedSqlQuery<I_AD_Column>(ctx, I_AD_Column.class, whereClause, trxName) .setParameters(adTableId, dataColumnName) .firstOnly(I_AD_Column.class); } return column; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\MigrationDataExecutor.java
1
请完成以下Java代码
public class MAttribute extends X_M_Attribute { /** * */ private static final long serialVersionUID = 7869800574413317999L; @SuppressWarnings("unused") public MAttribute(final Properties ctx, final int M_Attribute_ID, final String trxName) { super(ctx, M_Attribute_ID, trxName); if (is_new()) { setAttributeValueType(ATTRIBUTEVALUETYPE_StringMax40); setIsInstanceAttribute(false); setIsMandatory(false); } } @SuppressWarnings("unused") public MAttribute(final Properties ctx, final ResultSet rs, final String trxName) { super(ctx, rs, trxName); } @Override public String toString() { return "MAttribute[" + get_ID() + "-" + getName() + ",Type=" + getAttributeValueType() + ",Instance=" + isInstanceAttribute() + "]"; } // toString @Override protected boolean afterSave(final boolean newRecord, final boolean success) { // Changed to Instance Attribute
if (!newRecord && is_ValueChanged(COLUMNNAME_IsInstanceAttribute) && isInstanceAttribute()) { final String sql = "UPDATE M_AttributeSet mas " + "SET IsInstanceAttribute='Y' " + "WHERE IsInstanceAttribute='N'" + " AND EXISTS (SELECT * FROM M_AttributeUse mau " + "WHERE mas.M_AttributeSet_ID=mau.M_AttributeSet_ID" + " AND mau.M_Attribute_ID=" + getM_Attribute_ID() + ")"; final int no = DB.executeUpdateAndThrowExceptionOnFail(sql, get_TrxName()); log.debug("AttributeSet Instance set #{}", no); } return success; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MAttribute.java
1
请完成以下Java代码
public Object getValue(final String propertyName, final int idx, final Class<?> returnType) { return po.get_Value(idx); } @Override public Object getValue(final String propertyName, final Class<?> returnType) { return po.get_Value(propertyName); } @Override public boolean setValue(final String columnName, final Object value) { final Object valueToSet = POWrapper.checkZeroIdValue(columnName, value); final POInfo poInfo = po.getPOInfo(); if (!poInfo.isColumnUpdateable(columnName)) { // If the column is not updateable we need to use set_ValueNoCheck // because else is not consistent with how the generated classes were created // see org.adempiere.util.ModelClassGenerator.createColumnMethods return po.set_ValueNoCheck(columnName, valueToSet); } else { return po.set_ValueOfColumn(columnName, valueToSet); } } @Override public boolean setValueNoCheck(String propertyName, Object value) { return po.set_ValueOfColumn(propertyName, value); } @Override public Object getReferencedObject(final String propertyName, final Method interfaceMethod) throws Exception { final Class<?> returnType = interfaceMethod.getReturnType(); return po.get_ValueAsPO(propertyName, returnType); } @Override public void setValueFromPO(final String idPropertyName, final Class<?> parameterType, final Object value) { po.set_ValueFromPO(idPropertyName, parameterType, value); }
@Override public boolean invokeEquals(final Object[] methodArgs) { if (methodArgs == null || methodArgs.length != 1) { throw new IllegalArgumentException("Invalid method arguments to be used for equals(): " + methodArgs); } return po.equals(methodArgs[0]); } @Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { return method.invoke(po, methodArgs); } @Override public boolean isCalculated(final String columnName) { return getPOInfo().isCalculated(columnName); } @Override public boolean hasColumnName(final String columnName) { return getPOInfo().hasColumnName(columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POModelInternalAccessor.java
1
请在Spring Boot框架中完成以下Java代码
public class CarMaker { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Column(name = "name") private String name; @OneToMany(mappedBy = "maker", orphanRemoval = true, cascade = CascadeType.ALL) private List<CarModel> models; /** * @return the id */ public Long getId() { return id; } /** * @param id the id to set */ public void setId(Long id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the models */ public List<CarModel> getModels() { return models; } /** * @param models the models to set */ public void setModels(List<CarModel> models) {
this.models = models; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((models == null) ? 0 : models.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CarMaker other = (CarMaker) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (models == null) { if (other.models != null) return false; } else if (!models.equals(other.models)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\domain\CarMaker.java
2
请在Spring Boot框架中完成以下Java代码
public class AmqApplication { public static void main(String[] args) throws Exception { SpringApplication.run(AmqApplication.class, args); try (CamelContext context = new DefaultCamelContext()) { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory( "vm://localhost?broker.persistent=false"); connectionFactory.setTrustAllPackages(true); context.addComponent("direct", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory)); addRoute(context); try (ProducerTemplate template = context.createProducerTemplate()) { context.start(); MyPayload payload = new MyPayload("One"); template.sendBody("direct:source", payload); Thread.sleep(10000); } finally { context.stop(); } } } private static void addRoute(CamelContext context) throws Exception { context.addRoutes(newExchangeRoute()); } static RoutesBuilder traditionalWireTapRoute() { return new RouteBuilder() { public void configure() { from("direct:source").log("Main route: Send '${body}' to tap router").wireTap("direct:tap").delay(1000) .log("Main route: Add 'two' to '${body}'").bean(MyBean.class, "addTwo").to("direct:destination")
.log("Main route: Output '${body}'"); from("direct:tap").log("Tap Wire route: received '${body}'") .log("Tap Wire route: Add 'three' to '${body}'").bean(MyBean.class, "addThree") .log("Tap Wire route: Output '${body}'"); from("direct:destination").log("Output at destination: '${body}'"); } }; } static RoutesBuilder newExchangeRoute() throws Exception { return new RouteBuilder() { public void configure() throws Exception { from("direct:source").wireTap("direct:tap").onPrepare(new MyPayloadClonePrepare()).end().delay(1000); from("direct:tap").bean(MyBean.class, "addThree"); } }; } }
repos\tutorials-master\patterns-modules\enterprise-patterns\src\main\java\com\baeldung\AmqApplication.java
2
请完成以下Java代码
public class Role implements Serializable { @Serial private static final long serialVersionUID = 1L; /** * 主键 */ @Schema(description = "主键") @TableId(value = "id", type = IdType.ASSIGN_ID) @JsonSerialize(using = ToStringSerializer.class) private Long id; /** * 租户ID */ @Schema(description = "租户ID") private String tenantId; /** * 父主键 */ @Schema(description = "父主键") @JsonSerialize(using = ToStringSerializer.class) private Long parentId; /**
* 角色名 */ @Schema(description = "角色名") private String roleName; /** * 排序 */ @Schema(description = "排序") private Integer sort; /** * 角色别名 */ @Schema(description = "角色别名") private String roleAlias; /** * 是否已删除 */ @TableLogic @Schema(description = "是否已删除") private Integer isDeleted; }
repos\SpringBlade-master\blade-service-api\blade-system-api\src\main\java\org\springblade\system\entity\Role.java
1
请完成以下Java代码
public StockQtyAndUOMQty getQtysAlreadyShipped() { final I_M_InOutLine inOutLine = getM_InOutLine(); if (inOutLine == null) { return StockQtyAndUOMQtys.createZero(productId, icUomId); } final InvoicableQtyBasedOn invoicableQtyBasedOn = InvoicableQtyBasedOn.ofNullableCodeOrNominal(ic.getInvoicableQtyBasedOn()); final BigDecimal uomQty; if (!isNull(iciol, I_C_InvoiceCandidate_InOutLine.COLUMNNAME_QtyDeliveredInUOM_Override)) { uomQty = iciol.getQtyDeliveredInUOM_Override(); } else { switch (invoicableQtyBasedOn) { case CatchWeight: uomQty = coalesceNotNull(iciol.getQtyDeliveredInUOM_Catch(), iciol.getQtyDeliveredInUOM_Nominal()); break; case NominalWeight: uomQty = iciol.getQtyDeliveredInUOM_Nominal(); break; default: throw fail("Unexpected invoicableQtyBasedOn={}", invoicableQtyBasedOn); } } final Quantity shippedUomQuantityInIcUOM = uomConversionBL.convertQuantityTo(Quantitys.of(uomQty, UomId.ofRepoId(iciol.getC_UOM_ID())), productId, icUomId); final BigDecimal stockQty = inOutLine.getMovementQty();
final StockQtyAndUOMQty deliveredQty = StockQtyAndUOMQtys .create( stockQty, productId, shippedUomQuantityInIcUOM.toBigDecimal(), shippedUomQuantityInIcUOM.getUomId()); if (inOutBL.isReturnMovementType(inOutLine.getM_InOut().getMovementType())) { return deliveredQty.negate(); } return deliveredQty; } public boolean isShipped() { return getM_InOutLine() != null; } public I_C_InvoiceCandidate_InOutLine getC_InvoiceCandidate_InOutLine() { return iciol; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\aggregator\standard\InvoiceCandidateWithInOutLine.java
1
请完成以下Java代码
public class AddIdentityLinkCmd extends NeedsActiveTaskCmd<Void> { private static final long serialVersionUID = 1L; public static int IDENTITY_USER = 1; public static int IDENTITY_GROUP = 2; protected String identityId; protected int identityIdType; protected String identityType; public AddIdentityLinkCmd(String taskId, String identityId, int identityIdType, String identityType) { super(taskId); validateParams(taskId, identityId, identityIdType, identityType); this.taskId = taskId; this.identityId = identityId; this.identityIdType = identityIdType; this.identityType = identityType; } protected void validateParams(String taskId, String identityId, int identityIdType, String identityType) { if (taskId == null) { throw new ActivitiIllegalArgumentException("taskId is null"); } if (identityType == null) { throw new ActivitiIllegalArgumentException("type is required when adding a new task identity link"); } if (identityId == null && (identityIdType == IDENTITY_GROUP || (!IdentityLinkType.ASSIGNEE.equals(identityType) && !IdentityLinkType.OWNER.equals(identityType)))) { throw new ActivitiIllegalArgumentException("identityId is null"); } if (identityIdType != IDENTITY_USER && identityIdType != IDENTITY_GROUP) { throw new ActivitiIllegalArgumentException("identityIdType allowed values are 1 and 2"); } } @Override protected Void execute(CommandContext commandContext, TaskEntity task) {
boolean assignedToNoOne = false; if (IdentityLinkType.ASSIGNEE.equals(identityType)) { task.setAssignee(identityId, true, true); assignedToNoOne = identityId == null; } else if (IdentityLinkType.OWNER.equals(identityType)) { task.setOwner(identityId, true); } else if (IDENTITY_USER == identityIdType) { task.addUserIdentityLink(identityId, identityType); } else if (IDENTITY_GROUP == identityIdType) { task.addGroupIdentityLink(identityId, identityType); } boolean forceNullUserId = false; if (assignedToNoOne) { // ACT-1317: Special handling when assignee is set to NULL, a // CommentEntity notifying of assignee-delete should be created forceNullUserId = true; } if (IDENTITY_USER == identityIdType) { commandContext.getHistoryManager().createUserIdentityLinkComment(taskId, identityId, identityType, true, forceNullUserId); } else { commandContext.getHistoryManager().createGroupIdentityLinkComment(taskId, identityId, identityType, true); } return null; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\AddIdentityLinkCmd.java
1
请完成以下Java代码
public class Vehicles { abstract static class Vehicle { private final String registrationNumber; public Vehicle(String registrationNumber) { this.registrationNumber = registrationNumber; } public String getRegistrationNumber() { return registrationNumber; } } public static final class Car extends Vehicle { private final int numberOfSeats; public Car(int numberOfSeats, String registrationNumber) { super(registrationNumber); this.numberOfSeats = numberOfSeats; } public int getNumberOfSeats() { return numberOfSeats; } }
public static final class Truck extends Vehicle { private final int loadCapacity; public Truck(int loadCapacity, String registrationNumber) { super(registrationNumber); this.loadCapacity = loadCapacity; } public int getLoadCapacity() { return loadCapacity; } } }
repos\tutorials-master\core-java-modules\core-java-17\src\main\java\com\baeldung\sealed\alternative\Vehicles.java
1
请完成以下Java代码
public class XtraAmbulatoryType { @XmlAttribute(name = "hospitalization_type") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String hospitalizationType; @XmlAttribute(name = "hospitalization_mode") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String hospitalizationMode; @XmlAttribute(name = "class") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String clazz; @XmlAttribute(name = "section_major") protected String sectionMajor; /** * Gets the value of the hospitalizationType property. * * @return * possible object is * {@link String } * */ public String getHospitalizationType() { return hospitalizationType; } /** * Sets the value of the hospitalizationType property. * * @param value * allowed object is * {@link String } * */ public void setHospitalizationType(String value) { this.hospitalizationType = value; } /** * Gets the value of the hospitalizationMode property. * * @return * possible object is * {@link String } * */ public String getHospitalizationMode() { return hospitalizationMode; } /** * Sets the value of the hospitalizationMode property. * * @param value * allowed object is * {@link String } *
*/ public void setHospitalizationMode(String value) { this.hospitalizationMode = value; } /** * Gets the value of the clazz property. * * @return * possible object is * {@link String } * */ public String getClazz() { return clazz; } /** * Sets the value of the clazz property. * * @param value * allowed object is * {@link String } * */ public void setClazz(String value) { this.clazz = value; } /** * Gets the value of the sectionMajor property. * * @return * possible object is * {@link String } * */ public String getSectionMajor() { return sectionMajor; } /** * Sets the value of the sectionMajor property. * * @param value * allowed object is * {@link String } * */ public void setSectionMajor(String value) { this.sectionMajor = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\XtraAmbulatoryType.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<ResponseEntity<Flux<AdminUserDTO>>> getAllUsers( @org.springdoc.core.annotations.ParameterObject ServerHttpRequest request, @org.springdoc.core.annotations.ParameterObject Pageable pageable ) { log.debug("REST request to get all User for an admin"); if (!onlyContainsAllowedProperties(pageable)) { return Mono.just(ResponseEntity.badRequest().build()); } return userService .countManagedUsers() .map(total -> new PageImpl<>(new ArrayList<>(), pageable, total)) .map( page -> PaginationUtil.generatePaginationHttpHeaders( ForwardedHeaderUtils.adaptFromForwardedHeaders(request.getURI(), request.getHeaders()), page ) ) .map(headers -> ResponseEntity.ok().headers(headers).body(userService.getAllManagedUsers(pageable))); } private boolean onlyContainsAllowedProperties(Pageable pageable) { return pageable.getSort().stream().map(Sort.Order::getProperty).allMatch(ALLOWED_ORDERED_PROPERTIES::contains); } /** * {@code GET /admin/users/:login} : get the "login" user. * * @param login the login of the user to find. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the "login" user, or with status {@code 404 (Not Found)}. */ @GetMapping("/users/{login}") @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") public Mono<AdminUserDTO> getUser(@PathVariable("login") String login) { log.debug("REST request to get User : {}", login); return userService .getUserWithAuthoritiesByLogin(login) .map(AdminUserDTO::new) .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))); } /**
* {@code DELETE /admin/users/:login} : delete the "login" User. * * @param login the login of the user to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/users/{login}") @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") public Mono<ResponseEntity<Void>> deleteUser(@PathVariable("login") @Pattern(regexp = Constants.LOGIN_REGEX) String login) { log.debug("REST request to delete User: {}", login); return userService .deleteUser(login) .then( Mono.just( ResponseEntity.noContent() .headers(HeaderUtil.createAlert(applicationName, "A user is deleted with identifier " + login, login)) .build() ) ); } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\web\rest\UserResource.java
2
请完成以下Java代码
public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; }
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EventSubscriptionEntityImpl other = (EventSubscriptionEntityImpl) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventSubscriptionEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class UserRowMapper implements BiFunction<Row, String, User> { private final ColumnConverter converter; public UserRowMapper(ColumnConverter converter) { this.converter = converter; } /** * Take a {@link Row} and a column prefix, and extract all the fields. * @return the {@link User} stored in the database. */ @Override public User apply(Row row, String prefix) { User entity = new User();
entity.setId(row.get(prefix + "_id", Long.class)); entity.setLogin(converter.fromRow(row, prefix + "_login", String.class)); entity.setPassword(converter.fromRow(row, prefix + "_password", String.class)); entity.setFirstName(converter.fromRow(row, prefix + "_first_name", String.class)); entity.setLastName(converter.fromRow(row, prefix + "_last_name", String.class)); entity.setEmail(converter.fromRow(row, prefix + "_email", String.class)); entity.setActivated(Boolean.TRUE.equals(converter.fromRow(row, prefix + "_activated", Boolean.class))); entity.setLangKey(converter.fromRow(row, prefix + "_lang_key", String.class)); entity.setImageUrl(converter.fromRow(row, prefix + "_image_url", String.class)); entity.setActivationKey(converter.fromRow(row, prefix + "_activation_key", String.class)); entity.setResetKey(converter.fromRow(row, prefix + "_reset_key", String.class)); entity.setResetDate(converter.fromRow(row, prefix + "_reset_date", Instant.class)); return entity; } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\repository\rowmapper\UserRowMapper.java
2
请完成以下Java代码
private void setConstraints(IntVar[][] sudokuCells, int[][] preSolvedSudokuMatrix) { setConstraints(sudokuCells); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (preSolvedSudokuMatrix[i][j] != 0) { sudokuCells[i][j].eq(preSolvedSudokuMatrix[i][j]) .post(); } } } } private IntVar[] getRowCells(IntVar[][] sudokuCells, int rowNum) { return sudokuCells[rowNum]; } private IntVar[] getColumnCells(IntVar[][] sudokuCells, int columnNum) { IntVar[] columnCells = new IntVar[9]; for (int i = 0; i < 9; i++) { columnCells[i] = sudokuCells[i][columnNum]; } return columnCells; } private IntVar[] getCellsInRange(int columnLb, int columnUb, int rowLb, int rowUb, IntVar[][] sudokuCells) { int size = (columnUb - columnLb + 1) * (rowUb - rowLb + 1); IntVar[] cellsInRange = new IntVar[size]; int index = 0; for (int i = rowLb; i <= rowUb; i++) { for (int j = columnLb; j <= columnUb; j++) { cellsInRange[index++] = sudokuCells[i][j]; } } return cellsInRange; } private Integer[][] getNineByNineMatrix(IntVar[] sudokuCells) { Integer[][] sudokuCellsMatrix = new Integer[9][9]; int index = 0; for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) { sudokuCellsMatrix[i][j] = sudokuCells[index++].getValue(); } } return sudokuCellsMatrix; } public void printSolution(Integer[][] solvedSudokuBoards) { StringBuilder stringBuilder = new StringBuilder("\n"); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { stringBuilder.append(solvedSudokuBoards[i][j]).append(" "); if ((j + 1) % 3 == 0 && (j + 1) % 9 != 0) { stringBuilder.append("| "); } } stringBuilder.append("\n"); if ((i + 1) % 3 == 0 && (i + 1) % 9 != 0) { stringBuilder.append("---------------------\n"); } } stringBuilder.append("\n"); logger.info(stringBuilder.toString()); } }
repos\tutorials-master\choco-solver\src\main\java\com\baeldung\cp\SudokuSolver.java
1
请完成以下Java代码
public class ImmutableData { private final String someData; private final AnotherImmutableData anotherImmutableData; public ImmutableData(final String someData, final AnotherImmutableData anotherImmutableData) { this.someData = someData; this.anotherImmutableData = anotherImmutableData; } public String getSomeData() { return someData; } public AnotherImmutableData getAnotherImmutableData() { return anotherImmutableData;
} public class AnotherImmutableData { private final Integer someOtherData; public AnotherImmutableData(final Integer someData) { this.someOtherData = someData; } public Integer getSomeOtherData() { return someOtherData; } } }
repos\tutorials-master\core-java-modules\core-java-functional\src\main\java\com\baeldung\functional\ImmutableData.java
1
请完成以下Java代码
private List<IQualityInvoiceLineGroup> createQualityInvoiceLineGroups( final IMaterialTrackingDocuments materialTrackingDocuments, @SuppressWarnings("rawtypes") final IVendorReceipt vendorReceipt, // only the add() and getModels methods are parameterized and the won't use them here, so it's safe to suppress final IVendorInvoicingInfo vendorInvoicingInfo) { Check.assumeNotNull(materialTrackingDocuments, "materialTrackingDocuments not null"); Check.assumeNotNull(vendorReceipt, "vendorReceipt not null;\nmaterialTrackingDocuments={}", materialTrackingDocuments); final IQualityInspectionOrder qiOrder = materialTrackingDocuments.getQualityInspectionOrderOrNull(); // we can be sure it's not null because if it was then this method would not be called. Check.assumeNotNull(qiOrder, "qiOrder of materialTrackingDocuments {} is not null", materialTrackingDocuments); final IQualityInvoiceLineGroupsBuilder invoiceLineGroupsBuilder = qualityBasedSpiProviderService .getQualityInvoiceLineGroupsBuilderProvider() .provideBuilderFor(materialTrackingDocuments); // // Configure: Qty received from Vendor (reference Qty) invoiceLineGroupsBuilder.setVendorReceipt(vendorReceipt);
// // Configure: pricing context to be used final IPricingContext pricingContext = new PricingContextBuilder() .setVendorInvoicingInfo(vendorInvoicingInfo) .create(); invoiceLineGroupsBuilder.setPricingContext(pricingContext); // // Execute builder and create invoice line groups final List<IQualityInvoiceLineGroup> invoiceLineGroups = invoiceLineGroupsBuilder .create() .getCreatedInvoiceLineGroups(); // Log builder configuration and status logger.info("{}", invoiceLineGroupsBuilder); // // Return created invoice line groups return invoiceLineGroups; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\ic\spi\impl\PPOrder2InvoiceCandidatesProducer.java
1
请完成以下Java代码
public NoCacheStrategy getNoCacheStrategy() { return noCacheStrategy; } public void setNoCacheStrategy(NoCacheStrategy noCacheStrategy) { this.noCacheStrategy = noCacheStrategy; } @Override public String toString() { return "RequestOptions{" + "noCacheStrategy=" + noCacheStrategy + '}'; } } /** * When client sends "no-cache" directive in "Cache-Control" header, the response * should be re-validated from upstream. There are several strategies that indicates * what to do with the new fresh response. */
public enum NoCacheStrategy { /** * Update the cache entry by the fresh response coming from upstream with a new * time to live. */ UPDATE_CACHE_ENTRY, /** * Skip the update. The client will receive the fresh response, other clients will * receive the old entry in cache. */ SKIP_UPDATE_CACHE_ENTRY } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\LocalResponseCacheProperties.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> getCalledFromActivityIds() { return calledFromActivityIds; } public String getCallingProcessDefinitionId() { return callingProcessDefinitionId; } public static CalledProcessDefinitionDto from(CalledProcessDefinition definition){ CalledProcessDefinitionDto dto = new CalledProcessDefinitionDto(); dto.callingProcessDefinitionId = definition.getCallingProcessDefinitionId(); dto.calledFromActivityIds = definition.getCalledFromActivityIds(); dto.id = definition.getId(); dto.key = definition.getKey(); dto.category = definition.getCategory();
dto.description = definition.getDescription(); dto.name = definition.getName(); dto.version = definition.getVersion(); dto.resource = definition.getResourceName(); dto.deploymentId = definition.getDeploymentId(); dto.diagram = definition.getDiagramResourceName(); dto.suspended = definition.isSuspended(); dto.tenantId = definition.getTenantId(); dto.versionTag = definition.getVersionTag(); dto.historyTimeToLive = definition.getHistoryTimeToLive(); dto.isStartableInTasklist = definition.isStartableInTasklist(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\CalledProcessDefinitionDto.java
2
请在Spring Boot框架中完成以下Java代码
public BatchBuilder createBatchBuilder() { return new BatchBuilderImpl(configuration); } @Override public void insertBatch(Batch batch) { getBatchEntityManager().insert((BatchEntity) batch); } @Override public Batch updateBatch(Batch batch) { return getBatchEntityManager().update((BatchEntity) batch); } @Override public void deleteBatch(String batchId) { getBatchEntityManager().delete(batchId); } @Override public BatchPartEntity getBatchPart(String id) { return getBatchPartEntityManager().findById(id); } @Override public List<BatchPart> findBatchPartsByBatchId(String batchId) { return getBatchPartEntityManager().findBatchPartsByBatchId(batchId); } @Override public List<BatchPart> findBatchPartsByBatchIdAndStatus(String batchId, String status) { return getBatchPartEntityManager().findBatchPartsByBatchIdAndStatus(batchId, status); } @Override public List<BatchPart> findBatchPartsByScopeIdAndType(String scopeId, String scopeType) { return getBatchPartEntityManager().findBatchPartsByScopeIdAndType(scopeId, scopeType); } @Override public BatchPart createBatchPart(Batch batch, String status, String scopeId, String subScopeId, String scopeType) { return getBatchPartEntityManager().createBatchPart((BatchEntity) batch, status, scopeId, subScopeId, scopeType); }
@Override public BatchPart completeBatchPart(String batchPartId, String status, String resultJson) { return getBatchPartEntityManager().completeBatchPart(batchPartId, status, resultJson); } @Override public Batch completeBatch(String batchId, String status) { return getBatchEntityManager().completeBatch(batchId, status); } public Batch createBatch(BatchBuilder batchBuilder) { return getBatchEntityManager().createBatch(batchBuilder); } public BatchEntityManager getBatchEntityManager() { return configuration.getBatchEntityManager(); } public BatchPartEntityManager getBatchPartEntityManager() { return configuration.getBatchPartEntityManager(); } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchServiceImpl.java
2
请完成以下Java代码
public int getC_CreditLimit_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_CreditLimit_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Auto Approval. @param IsAutoApproval Auto Approval */ @Override public void setIsAutoApproval (boolean IsAutoApproval) { set_Value (COLUMNNAME_IsAutoApproval, Boolean.valueOf(IsAutoApproval)); } /** Get Auto Approval. @return Auto Approval */ @Override public boolean isAutoApproval () { Object oo = get_Value(COLUMNNAME_IsAutoApproval); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity
*/ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set 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_C_CreditLimit_Type.java
1
请完成以下Java代码
public Date resolveDuedate(String duedateDescription, int maxIterations) { try { if (duedateDescription != null && duedateDescription.startsWith("R")) { return new DurationHelper(duedateDescription, maxIterations, clockReader).getDateAfter(); } else { CronExpression ce = new CronExpression(duedateDescription, clockReader); return ce.getTimeAfter(clockReader.getCurrentTime()); } } catch (Exception e) { throw new FlowableException("Failed to parse cron expression: " + duedateDescription, e); } } @Override public Boolean validateDuedate(String duedateDescription, int maxIterations, Date endDate, Date newTimer) { if (endDate != null) { return super.validateDuedate(duedateDescription, maxIterations, endDate, newTimer); }
// end date could be part of the cron expression try { if (duedateDescription != null && duedateDescription.startsWith("R")) { return new DurationHelper(duedateDescription, maxIterations, clockReader).isValidDate(newTimer); } else { return true; } } catch (Exception e) { throw new FlowableException("Failed to parse cron expression: " + duedateDescription, e); } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\calendar\CycleBusinessCalendar.java
1
请完成以下Java代码
public String getActivityType() { return activityType; } public String getAssignee() { return assignee; } public boolean isFinished() { return finished; } public boolean isUnfinished() { return unfinished; } public String getActivityInstanceId() { return activityInstanceId; } public Date getStartedAfter() { return startedAfter; }
public Date getStartedBefore() { return startedBefore; } public Date getFinishedAfter() { return finishedAfter; } public Date getFinishedBefore() { return finishedBefore; } public ActivityInstanceState getActivityInstanceState() { return activityInstanceState; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricActivityInstanceQueryImpl.java
1
请完成以下Java代码
public int getM_HU_PackingMaterial_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PackingMaterial_ID); } @Override public void setM_HU_PI_Item_ID (final int M_HU_PI_Item_ID) { if (M_HU_PI_Item_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, M_HU_PI_Item_ID); } @Override public int getM_HU_PI_Item_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_ID); } @Override public de.metas.handlingunits.model.I_M_HU_PI_Version getM_HU_PI_Version() { return get_ValueAsPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class); } @Override public void setM_HU_PI_Version(final de.metas.handlingunits.model.I_M_HU_PI_Version M_HU_PI_Version) { set_ValueFromPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class, M_HU_PI_Version); } @Override public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID) { if (M_HU_PI_Version_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, null); else
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID); } @Override public int getM_HU_PI_Version_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_ID); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Item.java
1
请完成以下Java代码
public class ObjectValueImpl extends AbstractTypedValue<Object> implements ObjectValue { private static final long serialVersionUID = 1L; protected String objectTypeName; protected String serializationDataFormat; protected String serializedValue; protected boolean isDeserialized; public ObjectValueImpl( Object deserializedValue, String serializedValue, String serializationDataFormat, String objectTypeName, boolean isDeserialized) { super(deserializedValue, ValueType.OBJECT); this.serializedValue = serializedValue; this.serializationDataFormat = serializationDataFormat; this.objectTypeName = objectTypeName; this.isDeserialized = isDeserialized; } public ObjectValueImpl(Object value) { this(value, null, null, null, true); } public ObjectValueImpl(Object value, boolean isTransient) { this(value, null, null, null, true); this.isTransient = isTransient; } public String getSerializationDataFormat() { return serializationDataFormat; } public void setSerializationDataFormat(String serializationDataFormat) { this.serializationDataFormat = serializationDataFormat; } public String getObjectTypeName() { return objectTypeName; } public void setObjectTypeName(String objectTypeName) { this.objectTypeName = objectTypeName; } public String getValueSerialized() { return serializedValue; } public void setSerializedValue(String serializedValue) { this.serializedValue = serializedValue; } public boolean isDeserialized() { return isDeserialized; } @Override public Object getValue() { if(isDeserialized) { return super.getValue(); } else { throw new IllegalStateException("Object is not deserialized."); } }
@SuppressWarnings("unchecked") public <T> T getValue(Class<T> type) { Object value = getValue(); if(type.isAssignableFrom(value.getClass())) { return (T) value; } else { throw new IllegalArgumentException("Value '"+value+"' is not of type '"+type+"'."); } } public Class<?> getObjectType() { Object value = getValue(); if(value == null) { return null; } else { return value.getClass(); } } @Override public SerializableValueType getType() { return (SerializableValueType) super.getType(); } public void setTransient(boolean isTransient) { this.isTransient = isTransient; } @Override public String toString() { return "ObjectValue [" + "value=" + value + ", isDeserialized=" + isDeserialized + ", serializationDataFormat=" + serializationDataFormat + ", objectTypeName=" + objectTypeName + ", serializedValue="+ (serializedValue != null ? (serializedValue.length() + " chars") : null) + ", isTransient=" + isTransient + "]"; } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\value\ObjectValueImpl.java
1
请完成以下Java代码
private void afterConnectionEstablished(WebSocketSession wsSession) { Principal principal = wsSession.getPrincipal(); if (principal == null) { return; } String httpSessionId = getHttpSessionId(wsSession); registerWsSession(httpSessionId, wsSession); } private String getHttpSessionId(WebSocketSession wsSession) { Map<String, Object> attributes = wsSession.getAttributes(); return SessionRepositoryMessageInterceptor.getSessionId(attributes); } private void afterConnectionClosed(String httpSessionId, String wsSessionId) { if (httpSessionId == null) { return; } Map<String, WebSocketSession> sessions = this.httpSessionIdToWsSessions.get(httpSessionId); if (sessions != null) { boolean result = sessions.remove(wsSessionId) != null; if (logger.isDebugEnabled()) { logger.debug("Removal of " + wsSessionId + " was " + result); } if (sessions.isEmpty()) { this.httpSessionIdToWsSessions.remove(httpSessionId); if (logger.isDebugEnabled()) { logger.debug("Removed the corresponding HTTP Session for " + wsSessionId + " since it contained no WebSocket mappings"); } } } } private void registerWsSession(String httpSessionId, WebSocketSession wsSession) { Map<String, WebSocketSession> sessions = this.httpSessionIdToWsSessions.get(httpSessionId); if (sessions == null) {
sessions = new ConcurrentHashMap<>(); this.httpSessionIdToWsSessions.putIfAbsent(httpSessionId, sessions); sessions = this.httpSessionIdToWsSessions.get(httpSessionId); } sessions.put(wsSession.getId(), wsSession); } private void closeWsSessions(String httpSessionId) { Map<String, WebSocketSession> sessionsToClose = this.httpSessionIdToWsSessions.remove(httpSessionId); if (sessionsToClose == null) { return; } if (logger.isDebugEnabled()) { logger.debug("Closing WebSocket connections associated to expired HTTP Session " + httpSessionId); } for (WebSocketSession toClose : sessionsToClose.values()) { try { toClose.close(SESSION_EXPIRED_STATUS); } catch (IOException ex) { logger.debug("Failed to close WebSocketSession (this is nothing to worry about but for debugging only)", ex); } } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\socket\handler\WebSocketRegistryListener.java
1
请完成以下Java代码
public ViewId getIncludedViewId() { return includedViewId; } public LocatorId getPickingSlotLocatorId() { return pickingSlotLocatorId; } public int getBPartnerId() { return pickingSlotBPartner != null ? pickingSlotBPartner.getIdAsInt() : -1; } public int getBPartnerLocationId() { return pickingSlotBPLocation != null ? pickingSlotBPLocation.getIdAsInt() : -1; } @NonNull public Optional<PickingSlotRow> findRowMatching(@NonNull final Predicate<PickingSlotRow> predicate) { return streamThisRowAndIncludedRowsRecursivelly() .filter(predicate) .findFirst(); } public boolean thereIsAnOpenPickingForOrderId(@NonNull final OrderId orderId) { final HuId huId = getHuId(); if (huId == null) { throw new AdempiereException("Not a PickedHURow!") .appendParametersToMessage()
.setParameter("PickingSlotRow", this); } final boolean hasOpenPickingForOrderId = getPickingOrderIdsForHUId(huId).contains(orderId); if (hasOpenPickingForOrderId) { return true; } if (isLU()) { return findRowMatching(row -> !row.isLU() && row.thereIsAnOpenPickingForOrderId(orderId)) .isPresent(); } return false; } @NonNull private ImmutableSet<OrderId> getPickingOrderIdsForHUId(@NonNull final HuId huId) { return Optional.ofNullable(huId2OpenPickingOrderIds.get(huId)) .orElse(ImmutableSet.of()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotRow.java
1
请完成以下Java代码
private PreparedStatement getFindLatestStmt() { if (findLatestStmt == null) { findLatestStmt = prepare(SELECT_PREFIX + ModelConstants.KEY_COLUMN + "," + ModelConstants.TS_COLUMN + "," + ModelConstants.STRING_VALUE_COLUMN + "," + ModelConstants.BOOLEAN_VALUE_COLUMN + "," + ModelConstants.LONG_VALUE_COLUMN + "," + ModelConstants.DOUBLE_VALUE_COLUMN + "," + ModelConstants.JSON_VALUE_COLUMN + " " + "FROM " + ModelConstants.TS_KV_LATEST_CF + " " + "WHERE " + ModelConstants.ENTITY_TYPE_COLUMN + EQUALS_PARAM + "AND " + ModelConstants.ENTITY_ID_COLUMN + EQUALS_PARAM + "AND " + ModelConstants.KEY_COLUMN + EQUALS_PARAM); } return findLatestStmt; }
private PreparedStatement getFindAllLatestStmt() { if (findAllLatestStmt == null) { findAllLatestStmt = prepare(SELECT_PREFIX + ModelConstants.KEY_COLUMN + "," + ModelConstants.TS_COLUMN + "," + ModelConstants.STRING_VALUE_COLUMN + "," + ModelConstants.BOOLEAN_VALUE_COLUMN + "," + ModelConstants.LONG_VALUE_COLUMN + "," + ModelConstants.DOUBLE_VALUE_COLUMN + "," + ModelConstants.JSON_VALUE_COLUMN + " " + "FROM " + ModelConstants.TS_KV_LATEST_CF + " " + "WHERE " + ModelConstants.ENTITY_TYPE_COLUMN + EQUALS_PARAM + "AND " + ModelConstants.ENTITY_ID_COLUMN + EQUALS_PARAM); } return findAllLatestStmt; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\timeseries\CassandraBaseTimeseriesLatestDao.java
1
请完成以下Java代码
public void setServices(Set<String> services) { this.services = services; } public Map<String, String> getInstancesMetadata() { return instancesMetadata; } public void setInstancesMetadata(Map<String, String> instancesMetadata) { this.instancesMetadata = instancesMetadata; } public Map<String, String> getIgnoredInstancesMetadata() { return ignoredInstancesMetadata; } public void setIgnoredInstancesMetadata(Map<String, String> ignoredInstancesMetadata) { this.ignoredInstancesMetadata = ignoredInstancesMetadata; } private boolean isInstanceAllowedBasedOnMetadata(ServiceInstance instance) { if (instancesMetadata.isEmpty()) { return true; } for (Map.Entry<String, String> metadata : instance.getMetadata().entrySet()) { if (isMapContainsEntry(instancesMetadata, metadata)) { return true; } }
return false; } private boolean isInstanceIgnoredBasedOnMetadata(ServiceInstance instance) { if (ignoredInstancesMetadata.isEmpty()) { return false; } for (Map.Entry<String, String> metadata : instance.getMetadata().entrySet()) { if (isMapContainsEntry(ignoredInstancesMetadata, metadata)) { return true; } } return false; } private boolean isMapContainsEntry(Map<String, String> map, Map.Entry<String, String> entry) { String value = map.get(entry.getKey()); return value != null && value.equals(entry.getValue()); } }
repos\spring-boot-admin-master\spring-boot-admin-server-cloud\src\main\java\de\codecentric\boot\admin\server\cloud\discovery\InstanceDiscoveryListener.java
1