instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | DataFetcherExceptionResolver annotatedControllerConfigurerDataFetcherExceptionResolver(
AnnotatedControllerConfigurer annotatedControllerConfigurer) {
return annotatedControllerConfigurer.getExceptionResolver();
}
@ConditionalOnClass(ScrollPosition.class)
@Configuration(proxyBeanMethods = false)
static class GraphQlDataAutoConfiguration {
@Bean
@ConditionalOnMissingBean
EncodingCursorStrategy<ScrollPosition> cursorStrategy() {
return CursorStrategy.withEncoder(new ScrollPositionCursorStrategy(), CursorEncoder.base64());
}
@Bean
@SuppressWarnings("unchecked")
GraphQlSourceBuilderCustomizer cursorStrategyCustomizer(CursorStrategy<?> cursorStrategy) {
if (cursorStrategy.supports(ScrollPosition.class)) {
CursorStrategy<ScrollPosition> scrollCursorStrategy = (CursorStrategy<ScrollPosition>) cursorStrategy;
ConnectionFieldTypeVisitor connectionFieldTypeVisitor = ConnectionFieldTypeVisitor
.create(List.of(new WindowConnectionAdapter(scrollCursorStrategy),
new SliceConnectionAdapter(scrollCursorStrategy))); | return (builder) -> builder.typeVisitors(List.of(connectionFieldTypeVisitor));
}
return (builder) -> {
};
}
}
static class GraphQlResourcesRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern("graphql/**/*.graphqls").registerPattern("graphql/**/*.gqls");
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-graphql\src\main\java\org\springframework\boot\graphql\autoconfigure\GraphQlAutoConfiguration.java | 2 |
请完成以下Java代码 | protected Object instantiate(String className) {
return ReflectUtil.instantiate(className);
}
public static void applyFieldExtensions(List<FieldExtension> fieldExtensions, Object target, boolean throwExceptionOnMissingField) {
if (fieldExtensions != null) {
for (FieldExtension fieldExtension : fieldExtensions) {
applyFieldExtension(fieldExtension, target, throwExceptionOnMissingField);
}
}
}
protected static void applyFieldExtension(FieldExtension fieldExtension, Object target, boolean throwExceptionOnMissingField) {
Object value = null;
if (fieldExtension.getExpression() != null) {
ExpressionManager expressionManager = CommandContextUtil.getCmmnEngineConfiguration().getExpressionManager();
value = expressionManager.createExpression(fieldExtension.getExpression());
} else {
value = new FixedValue(fieldExtension.getStringValue());
}
ReflectUtil.invokeSetterOrField(target, fieldExtension.getFieldName(), value, throwExceptionOnMissingField);
}
@Override
public String getSourceState() {
return sourceState;
}
public void setSourceState(String sourceState) {
this.sourceState = sourceState;
} | @Override
public String getTargetState() {
return targetState;
}
public void setTargetState(String targetState) {
this.targetState = targetState;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public List<FieldExtension> getFieldExtensions() {
return fieldExtensions;
}
public void setFieldExtensions(List<FieldExtension> fieldExtensions) {
this.fieldExtensions = fieldExtensions;
}
public CmmnActivityBehavior getActivityBehaviorInstance() {
return activityBehaviorInstance;
}
public void setActivityBehaviorInstance(CmmnActivityBehavior activityBehaviorInstance) {
this.activityBehaviorInstance = activityBehaviorInstance;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\CmmnClassDelegate.java | 1 |
请完成以下Java代码 | public class MWFNode extends X_AD_WF_Node
{
private static final long serialVersionUID = 4330589837679937718L;
public MWFNode(final Properties ctx, final int AD_WF_Node_ID, final String trxName)
{
super(ctx, AD_WF_Node_ID, trxName);
if (is_new())
{
// setAD_WF_Node_ID (0);
// setAD_Workflow_ID (0);
// setValue (null);
// setName (null);
setAction(ACTION_WaitSleep);
setCost(BigDecimal.ZERO);
setDuration(0);
setEntityType(ENTITYTYPE_UserMaintained); // U
setIsCentrallyMaintained(true); // Y
setJoinElement(JOINELEMENT_XOR); // X
setDurationLimit(0);
setSplitElement(SPLITELEMENT_XOR); // X
setWaitingTime(0); | setXPosition(0);
setYPosition(0);
}
}
public MWFNode(final Properties ctx, final ResultSet rs, final String trxName)
{
super(ctx, rs, trxName);
}
@Override
protected boolean beforeSave(final boolean newRecord)
{
Services.get(IADWorkflowDAO.class).onBeforeSave(this, newRecord);
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\wf\MWFNode.java | 1 |
请完成以下Java代码 | private static FTSSearchResultItem.KeyValueMap extractKey(
@NonNull final SearchHit hit,
@NonNull final FTSFilterDescriptor filterDescriptor,
@NonNull final FTSConfig ftsConfig)
{
final FTSJoinColumnList joinColumns = filterDescriptor.getJoinColumns();
final ArrayList<FTSSearchResultItem.KeyValue> keyValues = new ArrayList<>(joinColumns.size());
for (final FTSJoinColumn joinColumn : joinColumns)
{
final ESFieldName esFieldName = ftsConfig.getEsFieldNameById(joinColumn.getEsFieldId());
final Object value = extractValue(hit, esFieldName, joinColumn.getValueType());
keyValues.add(FTSSearchResultItem.KeyValue.ofJoinColumnAndValue(joinColumn, value));
}
return new FTSSearchResultItem.KeyValueMap(keyValues);
}
@Nullable
private static Object extractValue(
@NonNull final SearchHit hit,
@NonNull final ESFieldName esFieldName,
@NonNull final FTSJoinColumn.ValueType valueType)
{
if (ESFieldName.ID.equals(esFieldName))
{
final String esDocumentId = hit.getId();
return convertValueToType(esDocumentId, valueType);
}
else
{
final Object value = hit.getSourceAsMap().get(esFieldName.getAsString());
return convertValueToType(value, valueType);
}
} | @Nullable
private static Object convertValueToType(@Nullable final Object valueObj, @NonNull final FTSJoinColumn.ValueType valueType)
{
if (valueObj == null)
{
return null;
}
if (valueType == FTSJoinColumn.ValueType.INTEGER)
{
return NumberUtils.asIntegerOrNull(valueObj);
}
else if (valueType == FTSJoinColumn.ValueType.STRING)
{
return valueObj.toString();
}
else
{
throw new AdempiereException("Cannot convert `" + valueObj + "` (" + valueObj.getClass() + ") to " + valueType);
}
}
private static String toJson(@NonNull final SearchHit hit)
{
return Strings.toString(hit, true, true);
}
public FTSConfig getConfigById(@NonNull final FTSConfigId ftsConfigId)
{
return ftsConfigService.getConfigById(ftsConfigId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\query\FTSSearchService.java | 1 |
请完成以下Java代码 | public String getTableName()
{
return I_C_Invoice_Candidate.Table_Name;
}
@Override
public List<String> getDependsOnColumnNames()
{
return columnNames;
}
@Override
public AggregationKey buildAggregationKey(I_C_Invoice_Candidate model)
{
final List<Object> keyValues = extractKeyValues(model);
final ArrayKey key = Util.mkKey(keyValues.toArray()); | final AggregationId aggregationId = null;
return new AggregationKey(key, aggregationId);
}
private final List<Object> extractKeyValues(final I_C_Invoice_Candidate ic)
{
final List<Object> values = new ArrayList<>();
final de.metas.materialtracking.model.I_C_Invoice_Candidate icExt = InterfaceWrapperHelper.create(ic, de.metas.materialtracking.model.I_C_Invoice_Candidate.class);
//
// Bind the Material Tracking ID for the reference of the Invoice Candidate
values.add(icExt.getM_Material_Tracking_ID());
return values;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\agg\key\impl\MaterialTrackingICHeaderAggregationKeyBuilder_OLD.java | 1 |
请完成以下Java代码 | private Set<LocatorId> getEligibleLocatorIds(final ImmutableList<I_M_HU> hus)
{
if (hus.isEmpty())
{
return ImmutableSet.of();
}
final Set<LocatorId> huLocatorIds = handlingUnitsDAO.getLocatorIds(hus);
// use the org of first HU to decide which warehouses to fetch (preserved already existing logic)
final OrgId orgId = OrgId.ofRepoId(hus.get(0).getAD_Org_ID());
final Set<WarehouseId> orgWarehouseIds = warehouseDAO.getWarehouseIdsByOrgId(orgId);
final ImmutableSet<LocatorId> orgLocatorIds = warehouseDAO.getLocatorIdsByWarehouseIds(orgWarehouseIds);
return Sets.difference(orgLocatorIds, huLocatorIds);
}
private LocatorId getMoveToLocatorId()
{
if (warehouseId == null)
{
throw new FillMandatoryException(I_M_Locator.COLUMNNAME_M_Warehouse_ID);
}
if (moveToLocatorRepoId <= 0)
{
throw new FillMandatoryException(I_M_Locator.COLUMNNAME_M_Locator_ID);
}
return LocatorId.ofRepoId(warehouseId, moveToLocatorRepoId);
}
protected final ImmutableList<I_M_HU> getSelectedHUs()
{
return streamSelectedHUs(Select.ONLY_TOPLEVEL).collect(ImmutableList.toImmutableList());
}
@Override
protected String doIt()
{
final LocatorId locatorId = getMoveToLocatorId();
final List<I_M_HU> hus = getSelectedHUs(); | if (hus.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
checkHUsEligible().throwExceptionIfRejected();
movementResult = huMovementBL.moveHUsToLocator(hus, locatorId);
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
if (movementResult != null)
{
getView().invalidateAll();
}
}
public abstract ProcessPreconditionsResolution checkHUsEligible();
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_MoveToAnotherWarehouse_Template.java | 1 |
请完成以下Java代码 | public String getErrorValue() {
return errorValue;
}
/**
* Sets the value of the errorValue property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setErrorValue(String value) {
this.errorValue = value;
}
/**
* Gets the value of the validValue property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValidValue() {
return validValue;
}
/**
* Sets the value of the validValue property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValidValue(String value) {
this.validValue = value;
}
/**
* Gets the value of the recordId property.
*
* @return | * possible object is
* {@link BigInteger }
*
*/
public BigInteger getRecordId() {
return recordId;
}
/**
* Sets the value of the recordId property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setRecordId(BigInteger value) {
this.recordId = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\ErrorType.java | 1 |
请完成以下Java代码 | public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
} | @Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", pid=").append(pid);
sb.append(", name=").append(name);
sb.append(", value=").append(value);
sb.append(", icon=").append(icon);
sb.append(", type=").append(type);
sb.append(", uri=").append(uri);
sb.append(", status=").append(status);
sb.append(", createTime=").append(createTime);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsPermission.java | 1 |
请完成以下Java代码 | byte[] bodyAsByteArray() throws IOException {
var bodyStream = new ByteArrayOutputStream();
var channel = Channels.newChannel(bodyStream);
for (ByteBuffer byteBuffer : body()) {
channel.write(byteBuffer);
}
return bodyStream.toByteArray();
}
String bodyAsString() throws IOException {
InputStream byteStream = new ByteArrayInputStream(bodyAsByteArray());
if (headers.getOrEmpty(HttpHeaders.CONTENT_ENCODING).contains("gzip")) {
byteStream = new GZIPInputStream(byteStream);
}
return new String(FileCopyUtils.copyToByteArray(byteStream));
}
public static class Builder {
private final HttpStatusCode statusCode;
private final HttpHeaders headers = new HttpHeaders();
private final List<ByteBuffer> body = new ArrayList<>();
private @Nullable Instant timestamp;
public Builder(HttpStatusCode statusCode) {
this.statusCode = statusCode;
}
public Builder header(String name, String value) {
this.headers.add(name, value);
return this;
}
public Builder headers(HttpHeaders headers) { | this.headers.addAll(headers);
return this;
}
public Builder timestamp(Instant timestamp) {
this.timestamp = timestamp;
return this;
}
public Builder timestamp(Date timestamp) {
this.timestamp = timestamp.toInstant();
return this;
}
public Builder body(String data) {
return appendToBody(ByteBuffer.wrap(data.getBytes(StandardCharsets.UTF_8)));
}
public Builder appendToBody(ByteBuffer byteBuffer) {
this.body.add(byteBuffer);
return this;
}
public CachedResponse build() {
return new CachedResponse(statusCode, headers, body, timestamp == null ? new Date() : Date.from(timestamp));
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\CachedResponse.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static CassandraManagedTypes cassandraManagedTypes(BeanFactory beanFactory) throws ClassNotFoundException {
List<String> packages = EntityScanPackages.get(beanFactory).getPackageNames();
if (packages.isEmpty() && AutoConfigurationPackages.has(beanFactory)) {
packages = AutoConfigurationPackages.get(beanFactory);
}
if (!packages.isEmpty()) {
return CassandraManagedTypes.fromIterable(CassandraEntityClassScanner.scan(packages));
}
return CassandraManagedTypes.empty();
}
@Bean
@ConditionalOnMissingBean
CassandraMappingContext cassandraMappingContext(CassandraManagedTypes cassandraManagedTypes,
CassandraCustomConversions conversions) {
CassandraMappingContext context = new CassandraMappingContext();
context.setManagedTypes(cassandraManagedTypes);
context.setSimpleTypeHolder(conversions.getSimpleTypeHolder());
return context;
}
@Bean
@ConditionalOnMissingBean
CassandraConverter cassandraConverter(CassandraMappingContext mapping, CassandraCustomConversions conversions) {
MappingCassandraConverter converter = new MappingCassandraConverter(mapping);
converter.setCodecRegistry(() -> this.session.getContext().getCodecRegistry());
converter.setCustomConversions(conversions);
converter.setUserTypeResolver(new SimpleUserTypeResolver(this.session));
return converter;
}
@Bean
@ConditionalOnMissingBean(SessionFactory.class)
SessionFactoryFactoryBean cassandraSessionFactory(Environment environment, CassandraConverter converter) {
SessionFactoryFactoryBean session = new SessionFactoryFactoryBean();
session.setSession(this.session);
session.setConverter(converter);
Binder binder = Binder.get(environment);
binder.bind("spring.cassandra.schema-action", SchemaAction.class).ifBound(session::setSchemaAction); | return session;
}
@Bean
@ConditionalOnMissingBean(CqlOperations.class)
CqlTemplate cqlTemplate(SessionFactory sessionFactory) {
return new CqlTemplate(sessionFactory);
}
@Bean
@ConditionalOnMissingBean(CassandraOperations.class)
CassandraTemplate cassandraTemplate(CqlTemplate cqlTemplate, CassandraConverter converter) {
return new CassandraTemplate(cqlTemplate, converter);
}
@Bean
@ConditionalOnMissingBean
CassandraCustomConversions cassandraCustomConversions() {
return new CassandraCustomConversions(Collections.emptyList());
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-cassandra\src\main\java\org\springframework\boot\data\cassandra\autoconfigure\DataCassandraAutoConfiguration.java | 2 |
请完成以下Java代码 | public List<GrantedAuthority> getGrantedAuthorities(Collection<String> attributes) {
List<GrantedAuthority> result = new ArrayList<>(attributes.size());
for (String attribute : attributes) {
result.add(getGrantedAuthority(attribute));
}
return result;
}
/**
* Map the given role one-on-one to a Spring Security GrantedAuthority, optionally
* doing case conversion and/or adding a prefix.
* @param attribute The attribute for which to get a GrantedAuthority
* @return GrantedAuthority representing the given role.
*/
private GrantedAuthority getGrantedAuthority(String attribute) {
if (isConvertAttributeToLowerCase()) {
attribute = attribute.toLowerCase(Locale.ROOT);
}
else if (isConvertAttributeToUpperCase()) {
attribute = attribute.toUpperCase(Locale.ROOT);
}
if (isAddPrefixIfAlreadyExisting() || !attribute.startsWith(getAttributePrefix())) {
return new SimpleGrantedAuthority(getAttributePrefix() + attribute);
}
else {
return new SimpleGrantedAuthority(attribute);
}
}
private boolean isConvertAttributeToLowerCase() {
return this.convertAttributeToLowerCase;
}
public void setConvertAttributeToLowerCase(boolean b) {
this.convertAttributeToLowerCase = b;
} | private boolean isConvertAttributeToUpperCase() {
return this.convertAttributeToUpperCase;
}
public void setConvertAttributeToUpperCase(boolean b) {
this.convertAttributeToUpperCase = b;
}
private String getAttributePrefix() {
return (this.attributePrefix != null) ? this.attributePrefix : "";
}
public void setAttributePrefix(String string) {
this.attributePrefix = string;
}
private boolean isAddPrefixIfAlreadyExisting() {
return this.addPrefixIfAlreadyExisting;
}
public void setAddPrefixIfAlreadyExisting(boolean b) {
this.addPrefixIfAlreadyExisting = b;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\core\authority\mapping\SimpleAttributes2GrantedAuthoritiesMapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void addParameter(String name, String value, UriComponentsBuilder builder) {
Assert.hasText(name, "name cannot be empty or null");
if (StringUtils.hasText(value)) {
builder.queryParam(UriUtils.encode(name, StandardCharsets.ISO_8859_1),
UriUtils.encode(value, StandardCharsets.ISO_8859_1));
}
}
private void sendPost(HttpServletRequest request, HttpServletResponse response,
Saml2PostAuthenticationRequest authenticationRequest) throws IOException {
this.authenticationRequestRepository.saveAuthenticationRequest(authenticationRequest, request, response);
String html = createSamlPostRequestFormData(authenticationRequest);
response.setContentType(MediaType.TEXT_HTML_VALUE);
response.getWriter().write(html);
}
private String createSamlPostRequestFormData(Saml2PostAuthenticationRequest authenticationRequest) {
String authenticationRequestUri = authenticationRequest.getAuthenticationRequestUri();
String relayState = authenticationRequest.getRelayState();
String samlRequest = authenticationRequest.getSamlRequest();
StringBuilder html = new StringBuilder();
html.append("<!DOCTYPE html>\n");
html.append("<html>\n").append(" <head>\n");
html.append(" <meta http-equiv=\"Content-Security-Policy\" ")
.append("content=\"script-src 'sha256-oZhLbc2kO8b8oaYLrUc7uye1MgVKMyLtPqWR4WtKF+c='\">\n");
html.append(" <meta charset=\"utf-8\" />\n");
html.append(" </head>\n");
html.append(" <body>\n");
html.append(" <noscript>\n");
html.append(" <p>\n");
html.append(" <strong>Note:</strong> Since your browser does not support JavaScript,\n");
html.append(" you must press the Continue button once to proceed.\n");
html.append(" </p>\n");
html.append(" </noscript>\n");
html.append(" \n");
html.append(" <form action=\"");
html.append(authenticationRequestUri);
html.append("\" method=\"post\">\n");
html.append(" <div>\n");
html.append(" <input type=\"hidden\" name=\"SAMLRequest\" value=\"");
html.append(HtmlUtils.htmlEscape(samlRequest));
html.append("\"/>\n");
if (StringUtils.hasText(relayState)) { | html.append(" <input type=\"hidden\" name=\"RelayState\" value=\"");
html.append(HtmlUtils.htmlEscape(relayState));
html.append("\"/>\n");
}
html.append(" </div>\n");
html.append(" <noscript>\n");
html.append(" <div>\n");
html.append(" <input type=\"submit\" value=\"Continue\"/>\n");
html.append(" </div>\n");
html.append(" </noscript>\n");
html.append(" </form>\n");
html.append(" \n");
html.append(" <script>window.onload = function() { document.forms[0].submit(); }</script>\n");
html.append(" </body>\n");
html.append("</html>");
return html.toString();
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\Saml2WebSsoAuthenticationRequestFilter.java | 2 |
请完成以下Java代码 | protected BuiltinAggregator getAggregator() {
return BuiltinAggregator.COUNT;
}
@Override
protected TypedValue aggregateValues(List<TypedValue> values) {
return Variables.integerValue(values.size());
}
@Override
protected Integer aggregateIntegerValues(List<Integer> intValues) {
// not used
return 0;
}
@Override
protected Long aggregateLongValues(List<Long> longValues) { | // not used
return 0L;
}
@Override
protected Double aggregateDoubleValues(List<Double> doubleValues) {
// not used
return 0.0;
}
@Override
public String toString() {
return "CollectCountHitPolicyHandler{}";
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\hitpolicy\CollectCountHitPolicyHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Employee {
@Id
private Long id;
private String fullName;
private String department;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
} | public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Employee() {
}
public Employee(Long id, String fullName, String department) {
this.id = id;
this.fullName = fullName;
this.department = department;
}
} | repos\tutorials-master\persistence-modules\java-jpa-5\src\main\java\com\baeldung\jakarta\Employee.java | 2 |
请完成以下Java代码 | public void setDocument_Currency_ID (final int Document_Currency_ID)
{
if (Document_Currency_ID < 1)
set_Value (COLUMNNAME_Document_Currency_ID, null);
else
set_Value (COLUMNNAME_Document_Currency_ID, Document_Currency_ID);
}
@Override
public int getDocument_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_Document_Currency_ID);
}
@Override
public void setFact_Acct_UserChange_ID (final int Fact_Acct_UserChange_ID)
{
if (Fact_Acct_UserChange_ID < 1)
set_ValueNoCheck (COLUMNNAME_Fact_Acct_UserChange_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Fact_Acct_UserChange_ID, Fact_Acct_UserChange_ID);
}
@Override
public int getFact_Acct_UserChange_ID()
{
return get_ValueAsInt(COLUMNNAME_Fact_Acct_UserChange_ID);
}
@Override
public void setLocal_Currency_ID (final int Local_Currency_ID)
{
if (Local_Currency_ID < 1)
set_Value (COLUMNNAME_Local_Currency_ID, null);
else
set_Value (COLUMNNAME_Local_Currency_ID, Local_Currency_ID);
}
@Override
public int getLocal_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_Local_Currency_ID);
}
@Override
public void setMatchKey (final @Nullable java.lang.String MatchKey)
{
set_Value (COLUMNNAME_MatchKey, MatchKey);
}
@Override
public java.lang.String getMatchKey()
{
return get_ValueAsString(COLUMNNAME_MatchKey);
} | @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);
}
/**
* PostingSign AD_Reference_ID=541699
* Reference name: PostingSign
*/
public static final int POSTINGSIGN_AD_Reference_ID=541699;
/** DR = D */
public static final String POSTINGSIGN_DR = "D";
/** CR = C */
public static final String POSTINGSIGN_CR = "C";
@Override
public void setPostingSign (final java.lang.String PostingSign)
{
set_Value (COLUMNNAME_PostingSign, PostingSign);
}
@Override
public java.lang.String getPostingSign()
{
return get_ValueAsString(COLUMNNAME_PostingSign);
}
@Override
public void setUserElementString1 (final @Nullable java.lang.String UserElementString1)
{
set_Value (COLUMNNAME_UserElementString1, UserElementString1);
}
@Override
public java.lang.String getUserElementString1()
{
return get_ValueAsString(COLUMNNAME_UserElementString1);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_UserChange.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyFilterSecurityInterceptor myFilterSecurityInterceptor;
@Bean
UserDetailsService customUserService() { //注册UserDetailsService 的bean
return new CustomUserService();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService()); //user Details Service验证
}
@Override
protected void configure(HttpSecurity http) throws Exception { | http.authorizeRequests()
.anyRequest().authenticated() //任何请求,登录后可以访问
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.permitAll() //登录页面用户任意访问
.and()
.logout().permitAll(); //注销行为任意访问
http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class)
.csrf().disable();
}
} | repos\springBoot-master\springboot-springSecurity3\src\main\java\com\us\example\config\WebSecurityConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setCode(String code) {
this.code = code;
}
private BusCategoryEnum(String code,String desc,String minAmount,String maxAmount,String beginTime,String endTime) {
this.code = code;
this.desc = desc;
this.minAmount = minAmount;
this.maxAmount = maxAmount;
this.beginTime = beginTime;
this.endTime = endTime;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public static BusCategoryEnum getEnum(String enumName) {
BusCategoryEnum resultEnum = null;
BusCategoryEnum[] enumAry = BusCategoryEnum.values();
for (int i = 0; i < enumAry.length; i++) {
if (enumAry[i].name().equals(enumName)) {
resultEnum = enumAry[i];
break;
}
}
return resultEnum;
}
public static Map<String, Map<String, Object>> toMap() {
BusCategoryEnum[] ary = BusCategoryEnum.values();
Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>();
for (int num = 0; num < ary.length; num++) {
Map<String, Object> map = new HashMap<String, Object>();
String key = ary[num].name();
map.put("desc", ary[num].getDesc());
enumMap.put(key, map);
}
return enumMap;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List toList() {
BusCategoryEnum[] ary = BusCategoryEnum.values();
List list = new ArrayList();
for (int i = 0; i < ary.length; i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("name", ary[i].name());
map.put("desc", ary[i].getDesc()); | map.put("minAmount", ary[i].getMinAmount());
map.put("maxAmount", ary[i].getMaxAmount());
map.put("beginTime", ary[i].getBeginTime());
map.put("endTime", ary[i].getEndTime());
list.add(map);
}
return list;
}
/**
* 取枚举的json字符串
*
* @return
*/
public static String getJsonStr() {
BusCategoryEnum[] enums = BusCategoryEnum.values();
StringBuffer jsonStr = new StringBuffer("[");
for (BusCategoryEnum senum : enums) {
if (!"[".equals(jsonStr.toString())) {
jsonStr.append(",");
}
jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}");
}
jsonStr.append("]");
return jsonStr.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\enums\BusCategoryEnum.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setImportMetadata(AnnotationMetadata importMetadata) {
if (isAnnotationPresent(importMetadata)) {
AnnotationAttributes distributedSystemIdAttributes = getAnnotationAttributes(importMetadata);
setDistributedSystemId(distributedSystemIdAttributes.containsKey("value")
? distributedSystemIdAttributes.getNumber("value") : null);
setDistributedSystemId(distributedSystemIdAttributes.containsKey("id")
? distributedSystemIdAttributes.getNumber("id") : null);
}
}
protected void setDistributedSystemId(Integer distributedSystemId) {
this.distributedSystemId = Optional.ofNullable(distributedSystemId)
.filter(id -> id > -1)
.orElse(this.distributedSystemId);
}
protected Optional<Integer> getDistributedSystemId() {
return Optional.ofNullable(this.distributedSystemId)
.filter(id -> id > -1);
}
protected Logger getLogger() {
return this.logger;
}
private int validateDistributedSystemId(int distributedSystemId) {
Assert.isTrue(distributedSystemId >= -1 && distributedSystemId < 256,
String.format("Distributed System ID [%d] must be between -1 and 255", distributedSystemId));
return distributedSystemId;
}
@Bean | ClientCacheConfigurer clientCacheDistributedSystemIdConfigurer() {
return (beanName, clientCacheFactoryBean) -> getDistributedSystemId().ifPresent(distributedSystemId -> {
Logger logger = getLogger();
if (logger.isWarnEnabled()) {
logger.warn("Distributed System Id [{}] was set on the ClientCache instance, which will not have any effect",
distributedSystemId);
}
});
}
@Bean
PeerCacheConfigurer peerCacheDistributedSystemIdConfigurer() {
return (beanName, cacheFactoryBean) ->
getDistributedSystemId().ifPresent(id -> cacheFactoryBean.getProperties()
.setProperty(GEMFIRE_DISTRIBUTED_SYSTEM_ID_PROPERTY,
String.valueOf(validateDistributedSystemId(id))));
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\DistributedSystemIdConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Flux<AdminUserDTO> getAllManagedUsers(Pageable pageable) {
return userRepository.findAllWithAuthorities(pageable).map(AdminUserDTO::new);
}
@Transactional(readOnly = true)
public Flux<UserDTO> getAllPublicUsers(Pageable pageable) {
return userRepository.findAllByIdNotNullAndActivatedIsTrue(pageable).map(UserDTO::new);
}
@Transactional(readOnly = true)
public Mono<Long> countManagedUsers() {
return userRepository.count();
}
@Transactional(readOnly = true)
public Mono<User> getUserWithAuthoritiesByLogin(String login) {
return userRepository.findOneWithAuthoritiesByLogin(login);
}
@Transactional(readOnly = true)
public Mono<User> getUserWithAuthorities() {
return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin);
}
/**
* Not activated users should be automatically deleted after 3 days.
* <p>
* This is scheduled to get fired everyday, at 01:00 (am).
*/
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
removeNotActivatedUsersReactively().blockLast();
} | @Transactional
public Flux<User> removeNotActivatedUsersReactively() {
return userRepository
.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(
LocalDateTime.ofInstant(Instant.now().minus(3, ChronoUnit.DAYS), ZoneOffset.UTC)
)
.flatMap(user -> userRepository.delete(user).thenReturn(user))
.doOnNext(user -> log.debug("Deleted User: {}", user));
}
/**
* Gets a list of all the authorities.
* @return a list of all the authorities.
*/
@Transactional(readOnly = true)
public Flux<String> getAuthorities() {
return authorityRepository.findAll().map(Authority::getName);
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\service\UserService.java | 2 |
请完成以下Java代码 | public BigDecimal getRate()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSurchargeAmt (final BigDecimal SurchargeAmt)
{
set_ValueNoCheck (COLUMNNAME_SurchargeAmt, SurchargeAmt);
}
@Override
public BigDecimal getSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTaxAmt (final @Nullable BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
@Override
public BigDecimal getTaxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTaxAmtWithSurchargeAmt (final BigDecimal TaxAmtWithSurchargeAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxAmtWithSurchargeAmt, TaxAmtWithSurchargeAmt);
}
@Override
public BigDecimal getTaxAmtWithSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtWithSurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTaxBaseAmt (final @Nullable BigDecimal TaxBaseAmt)
{
set_Value (COLUMNNAME_TaxBaseAmt, TaxBaseAmt);
}
@Override
public BigDecimal getTaxBaseAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmt);
return bd != null ? bd : BigDecimal.ZERO; | }
@Override
public void setTaxBaseAmtWithSurchargeAmt (final BigDecimal TaxBaseAmtWithSurchargeAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxBaseAmtWithSurchargeAmt, TaxBaseAmtWithSurchargeAmt);
}
@Override
public BigDecimal getTaxBaseAmtWithSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmtWithSurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalAmt (final @Nullable BigDecimal TotalAmt)
{
set_Value (COLUMNNAME_TotalAmt, TotalAmt);
}
@Override
public BigDecimal getTotalAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_901_991_v.java | 1 |
请完成以下Java代码 | public Path getResourcesDirectory() {
return this.resourcesDirectory;
}
/**
* Resolve a source file.
* @param packageName the name of the package
* @param fileName the name of the file (without its extension)
* @return the {@link Path file} to use to store a {@code CompilationUnit} with the
* specified package and name
* @see #getSourcesDirectory()
*/
public Path resolveSourceFile(String packageName, String fileName) {
String file = fileName + "." + this.sourceFileExtension;
return resolvePackage(this.sourcesDirectory, packageName).resolve(file);
}
/**
* Create a source file, creating its package structure if necessary.
* @param packageName the name of the package
* @param fileName the name of the file (without its extension)
* @return the {@link Path file} to use to store a {@code CompilationUnit} with the
* specified package and name
* @throws IOException if an error occurred while trying to create the directory
* structure or the file itself
* @see #getSourcesDirectory()
*/
public Path createSourceFile(String packageName, String fileName) throws IOException {
Path sourceFile = resolveSourceFile(packageName, fileName);
createFile(sourceFile);
return sourceFile;
}
/**
* Resolve a resource file defined in the specified package.
* @param packageName the name of the package
* @param file the name of the file (including its extension) | * @return the {@link Path file} to use to store a resource with the specified package
* @see #getResourcesDirectory()
*/
public Path resolveResourceFile(String packageName, String file) {
return resolvePackage(this.resourcesDirectory, packageName).resolve(file);
}
/**
* Create a resource file, creating its package structure if necessary.
* @param packageName the name of the package
* @param file the name of the file (including its extension)
* @return the {@link Path file} to use to store a resource with the specified package
* @throws IOException if an error occurred while trying to create the directory
* structure or the file itself
* @see #getResourcesDirectory()
*/
public Path createResourceFile(String packageName, String file) throws IOException {
Path resourceFile = resolveResourceFile(packageName, file);
createFile(resourceFile);
return resourceFile;
}
private void createFile(Path file) throws IOException {
Files.createDirectories(file.getParent());
Files.createFile(file);
}
private static Path resolvePackage(Path directory, String packageName) {
return directory.resolve(packageName.replace('.', '/'));
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\SourceStructure.java | 1 |
请完成以下Java代码 | private static class AvailableSelectionKeyColumnNames
{
private final ArrayList<String> availableIntKeys = new ArrayList<>(I_T_ES_FTS_Search_Result.COLUMNNAME_IntKeys);
private final ArrayList<String> availableStringKeys = new ArrayList<>(I_T_ES_FTS_Search_Result.COLUMNNAME_StringKeys);
public String reserveNext(@NonNull final FTSJoinColumn.ValueType valueType)
{
final ArrayList<String> availableKeys;
if (valueType == FTSJoinColumn.ValueType.INTEGER)
{
availableKeys = availableIntKeys;
}
else if (valueType == FTSJoinColumn.ValueType.STRING)
{
availableKeys = availableStringKeys; | }
else
{
availableKeys = new ArrayList<>();
}
if (availableKeys.isEmpty())
{
throw new AdempiereException("No more available key columns left for valueType=" + valueType + " in " + this);
}
return availableKeys.remove(0);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\FTSFilterDescriptorRepository.java | 1 |
请完成以下Java代码 | public boolean isInheritable()
{
return false;
}
private OrgId getLoginOrgId()
{
return loginOrgId;
}
private boolean isOrgLoginMandatory()
{
return orgLoginMandatory;
}
public boolean isValidOrg(final OrgResource org)
{
if (isOrgLoginMandatory() && !org.isRegularOrg())
{ | logger.debug("Not valid {} because is OrgLoginMandatory is set", org);
return false;
}
// Enforce Login_Org_ID:
final OrgId loginOrgId = getLoginOrgId();
if (loginOrgId != null && !OrgId.equals(loginOrgId, org.getOrgId()))
{
logger.debug("Not valid {} because is not Login_Org_ID", org);
return false;
}
return true;
}
public Predicate<OrgResource> asOrgResourceMatcher()
{
return this::isValidOrg;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\LoginOrgConstraint.java | 1 |
请完成以下Java代码 | public String getOverrideDefinitionTenantId() {
return overrideDefinitionTenantId;
}
@Override
public String getOutcome() {
return outcome;
}
@Override
public Map<String, Object> getStartFormVariables() {
return startFormVariables;
}
@Override
public String getCallbackId() {
return this.callbackId;
}
@Override
public String getCallbackType() {
return this.callbackType;
}
@Override
public String getReferenceId() { | return referenceId;
}
@Override
public String getReferenceType() {
return referenceType;
}
@Override
public String getParentId() {
return this.parentId;
}
@Override
public boolean isFallbackToDefaultTenant() {
return this.fallbackToDefaultTenant;
}
@Override
public boolean isStartWithForm() {
return this.startWithForm;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceBuilderImpl.java | 1 |
请完成以下Java代码 | public java.lang.String getCreditLimitIndicator ()
{
return (java.lang.String)get_Value(COLUMNNAME_CreditLimitIndicator);
}
/** Set Offene Posten.
@param OpenItems Offene Posten */
@Override
public void setOpenItems (java.math.BigDecimal OpenItems)
{
set_Value (COLUMNNAME_OpenItems, OpenItems);
}
/** Get Offene Posten.
@return Offene Posten */
@Override
public java.math.BigDecimal getOpenItems ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenItems);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Kredit gewährt.
@param SO_CreditUsed
Gegenwärtiger Aussenstand
*/
@Override
public void setSO_CreditUsed (java.math.BigDecimal SO_CreditUsed)
{
set_Value (COLUMNNAME_SO_CreditUsed, SO_CreditUsed);
}
/** Get Kredit gewährt.
@return Gegenwärtiger Aussenstand
*/
@Override
public java.math.BigDecimal getSO_CreditUsed ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SO_CreditUsed);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/**
* SOCreditStatus AD_Reference_ID=289
* Reference name: C_BPartner SOCreditStatus
*/
public static final int SOCREDITSTATUS_AD_Reference_ID=289;
/** CreditStop = S */
public static final String SOCREDITSTATUS_CreditStop = "S";
/** CreditHold = H */
public static final String SOCREDITSTATUS_CreditHold = "H"; | /** CreditWatch = W */
public static final String SOCREDITSTATUS_CreditWatch = "W";
/** NoCreditCheck = X */
public static final String SOCREDITSTATUS_NoCreditCheck = "X";
/** CreditOK = O */
public static final String SOCREDITSTATUS_CreditOK = "O";
/** NurEineRechnung = I */
public static final String SOCREDITSTATUS_NurEineRechnung = "I";
/** Set Kreditstatus.
@param SOCreditStatus
Kreditstatus des Geschäftspartners
*/
@Override
public void setSOCreditStatus (java.lang.String SOCreditStatus)
{
set_Value (COLUMNNAME_SOCreditStatus, SOCreditStatus);
}
/** Get Kreditstatus.
@return Kreditstatus des Geschäftspartners
*/
@Override
public java.lang.String getSOCreditStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_SOCreditStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Stats.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setEndedBefore(Date endedBefore) {
this.endedBefore = endedBefore;
}
public Date getEndedAfter() {
return endedAfter;
}
public void setEndedAfter(Date endedAfter) {
this.endedAfter = endedAfter;
}
public String getStartUserId() {
return startUserId;
}
public void setStartUserId(String startUserId) {
this.startUserId = startUserId;
}
public String getReferenceId() {
return referenceId;
}
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
} | public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Boolean getIncludeLocalVariables() {
return includeLocalVariables;
}
public void setIncludeLocalVariables(Boolean includeLocalVariables) {
this.includeLocalVariables = includeLocalVariables;
}
public Set<String> getCaseInstanceIds() {
return caseInstanceIds;
}
public void setCaseInstanceIds(Set<String> caseInstanceIds) {
this.caseInstanceIds = caseInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\planitem\HistoricPlanItemInstanceQueryRequest.java | 2 |
请完成以下Java代码 | Board getBoard() {
return board;
}
void setBoard(Board board) {
this.board = board;
}
int getPlayerNo() {
return playerNo;
}
void setPlayerNo(int playerNo) {
this.playerNo = playerNo;
}
int getOpponent() {
return 3 - playerNo;
}
public int getVisitCount() {
return visitCount;
}
public void setVisitCount(int visitCount) {
this.visitCount = visitCount;
}
double getWinScore() {
return winScore;
}
void setWinScore(double winScore) {
this.winScore = winScore;
}
public List<State> getAllPossibleStates() {
List<State> possibleStates = new ArrayList<>();
List<Position> availablePositions = this.board.getEmptyPositions();
availablePositions.forEach(p -> {
State newState = new State(this.board);
newState.setPlayerNo(3 - this.playerNo);
newState.getBoard().performMove(newState.getPlayerNo(), p);
possibleStates.add(newState);
});
return possibleStates; | }
void incrementVisit() {
this.visitCount++;
}
void addScore(double score) {
if (this.winScore != Integer.MIN_VALUE)
this.winScore += score;
}
void randomPlay() {
List<Position> availablePositions = this.board.getEmptyPositions();
int totalPossibilities = availablePositions.size();
int selectRandom = (int) (Math.random() * totalPossibilities);
this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
}
void togglePlayer() {
this.playerNo = 3 - this.playerNo;
}
} | repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\mcts\montecarlo\State.java | 1 |
请完成以下Java代码 | public OrderFactory docType(final DocTypeId docTypeTargetId)
{
this.docTypeTargetId = docTypeTargetId;
try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(order))
{
assertNotBuilt();
orderBL.setDocTypeTargetIdAndUpdateDescription(order, docTypeTargetId);
return this;
}
}
public OrderFactory warehouseId(@Nullable final WarehouseId warehouseId)
{
assertNotBuilt();
order.setM_Warehouse_ID(WarehouseId.toRepoId(warehouseId));
return this;
}
public OrderFactory orgId(@NonNull final OrgId orgId)
{
assertNotBuilt();
order.setAD_Org_ID(orgId.getRepoId());
return this;
}
public OrgId getOrgId()
{
return OrgId.ofRepoId(order.getAD_Org_ID());
}
public OrderFactory dateOrdered(final LocalDate dateOrdered)
{
assertNotBuilt();
order.setDateOrdered(TimeUtil.asTimestamp(dateOrdered));
return this;
}
public OrderFactory datePromised(final ZonedDateTime datePromised)
{
assertNotBuilt();
order.setDatePromised(TimeUtil.asTimestamp(datePromised));
return this;
}
public ZonedDateTime getDatePromised()
{
final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(order.getAD_Org_ID()));
return TimeUtil.asZonedDateTime(order.getDatePromised(), timeZone);
}
public OrderFactory shipBPartner(
@NonNull final BPartnerId bpartnerId,
@Nullable final BPartnerLocationId bpartnerLocationId,
@Nullable final BPartnerContactId contactId)
{
assertNotBuilt();
OrderDocumentLocationAdapterFactory
.locationAdapter(order)
.setFrom(DocumentLocation.builder()
.bpartnerId(bpartnerId)
.bpartnerLocationId(bpartnerLocationId)
.contactId(contactId)
.build());
return this;
} | public OrderFactory shipBPartner(final BPartnerId bpartnerId)
{
shipBPartner(bpartnerId, null, null);
return this;
}
public BPartnerId getShipBPartnerId()
{
return BPartnerId.ofRepoId(order.getC_BPartner_ID());
}
public OrderFactory pricingSystemId(@NonNull final PricingSystemId pricingSystemId)
{
assertNotBuilt();
order.setM_PricingSystem_ID(pricingSystemId.getRepoId());
return this;
}
public OrderFactory poReference(@Nullable final String poReference)
{
assertNotBuilt();
order.setPOReference(poReference);
return this;
}
public OrderFactory salesRepId(@Nullable final UserId salesRepId)
{
assertNotBuilt();
order.setSalesRep_ID(UserId.toRepoId(salesRepId));
return this;
}
public OrderFactory projectId(@Nullable final ProjectId projectId)
{
assertNotBuilt();
order.setC_Project_ID(ProjectId.toRepoId(projectId));
return this;
}
public OrderFactory campaignId(final int campaignId)
{
assertNotBuilt();
order.setC_Campaign_ID(campaignId);
return this;
}
public DocTypeId getDocTypeTargetId()
{
return docTypeTargetId;
}
public void setDocTypeTargetId(final DocTypeId docTypeTargetId)
{
this.docTypeTargetId = docTypeTargetId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderFactory.java | 1 |
请完成以下Java代码 | public static String toHumanReadableSIPrefixesWithEnum(long size) {
final List<SizeUnitSIPrefixes> units = SizeUnitSIPrefixes.unitsInDescending();
if (size < 0)
throw new IllegalArgumentException("Invalid file size: " + size);
String result = null;
for (SizeUnitSIPrefixes unit : units) {
if (size >= unit.getUnitBase()) {
result = formatSize(size, unit.getUnitBase(), unit.name());
break;
}
}
return result == null ? formatSize(size, SizeUnitSIPrefixes.Bytes.getUnitBase(), SizeUnitSIPrefixes.Bytes.name()) : result;
}
public static String toHumanReadableByNumOfLeadingZeros(long size) {
if (size < 0)
throw new IllegalArgumentException("Invalid file size: " + size);
if (size < 1024) return size + " Bytes";
int unitIdx = (63 - Long.numberOfLeadingZeros(size)) / 10;
return formatSize(size, 1L << (unitIdx * 10), " KMGTPE".charAt(unitIdx) + "iB");
}
enum SizeUnitBinaryPrefixes {
Bytes(1L),
KiB(Bytes.unitBase << 10),
MiB(KiB.unitBase << 10),
GiB(MiB.unitBase << 10),
TiB(GiB.unitBase << 10),
PiB(TiB.unitBase << 10),
EiB(PiB.unitBase << 10);
private final Long unitBase;
public static List<SizeUnitBinaryPrefixes> unitsInDescending() {
List<SizeUnitBinaryPrefixes> list = Arrays.asList(values());
Collections.reverse(list);
return list;
} | public Long getUnitBase() {
return unitBase;
}
SizeUnitBinaryPrefixes(long unitBase) {
this.unitBase = unitBase;
}
}
enum SizeUnitSIPrefixes {
Bytes(1L),
KB(Bytes.unitBase * 1000),
MB(KB.unitBase * 1000),
GB(MB.unitBase * 1000),
TB(GB.unitBase * 1000),
PB(TB.unitBase * 1000),
EB(PB.unitBase * 1000);
private final Long unitBase;
public static List<SizeUnitSIPrefixes> unitsInDescending() {
List<SizeUnitSIPrefixes> list = Arrays.asList(values());
Collections.reverse(list);
return list;
}
public Long getUnitBase() {
return unitBase;
}
SizeUnitSIPrefixes(long unitBase) {
this.unitBase = unitBase;
}
}
} | repos\tutorials-master\core-java-modules\core-java-numbers-4\src\main\java\com\baeldung\humanreadablebytes\FileSizeFormatUtil.java | 1 |
请完成以下Java代码 | private static ClassLoader getCustomClassLoader() {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
if (processEngineConfiguration != null) {
final ClassLoader classLoader = processEngineConfiguration.getClassLoader();
if (classLoader != null) {
return classLoader;
}
}
return null;
}
private static Class loadClass(ClassLoader classLoader, String className) throws ClassNotFoundException {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
boolean useClassForName =
processEngineConfiguration == null || processEngineConfiguration.isUseClassForNameClassLoading();
return useClassForName ? Class.forName(className, true, classLoader) : classLoader.loadClass(className);
}
public static boolean isGetter(Method method) {
String name = method.getName();
Class<?> type = method.getReturnType();
Class<?> params[] = method.getParameterTypes();
if (!GETTER_PATTERN.matcher(name).matches()) {
return false;
}
// special for isXXX boolean
if (name.startsWith("is")) {
return params.length == 0 && type.getSimpleName().equalsIgnoreCase("boolean");
}
return params.length == 0 && !type.equals(Void.TYPE);
}
public static boolean isSetter(Method method, boolean allowBuilderPattern) {
String name = method.getName();
Class<?> type = method.getReturnType();
Class<?> params[] = method.getParameterTypes();
if (!SETTER_PATTERN.matcher(name).matches()) {
return false;
}
return (
params.length == 1 &&
(type.equals(Void.TYPE) || (allowBuilderPattern && method.getDeclaringClass().isAssignableFrom(type)))
);
}
public static boolean isSetter(Method method) {
return isSetter(method, false);
}
public static String getGetterShorthandName(Method method) {
if (!isGetter(method)) { | return method.getName();
}
String name = method.getName();
if (name.startsWith("get")) {
name = name.substring(3);
name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
} else if (name.startsWith("is")) {
name = name.substring(2);
name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
}
return name;
}
public static String getSetterShorthandName(Method method) {
if (!isSetter(method)) {
return method.getName();
}
String name = method.getName();
if (name.startsWith("set")) {
name = name.substring(3);
name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
}
return name;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\ReflectUtil.java | 1 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_CyclePhase[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_C_CycleStep getC_CycleStep() throws RuntimeException
{
return (I_C_CycleStep)MTable.get(getCtx(), I_C_CycleStep.Table_Name)
.getPO(getC_CycleStep_ID(), get_TrxName()); }
/** Set Cycle Step.
@param C_CycleStep_ID
The step for this Cycle
*/
public void setC_CycleStep_ID (int C_CycleStep_ID)
{
if (C_CycleStep_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CycleStep_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CycleStep_ID, Integer.valueOf(C_CycleStep_ID));
}
/** Get Cycle Step.
@return The step for this Cycle
*/
public int getC_CycleStep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CycleStep_ID);
if (ii == null)
return 0;
return ii.intValue(); | }
public I_C_Phase getC_Phase() throws RuntimeException
{
return (I_C_Phase)MTable.get(getCtx(), I_C_Phase.Table_Name)
.getPO(getC_Phase_ID(), get_TrxName()); }
/** Set Standard Phase.
@param C_Phase_ID
Standard Phase of the Project Type
*/
public void setC_Phase_ID (int C_Phase_ID)
{
if (C_Phase_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Phase_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Phase_ID, Integer.valueOf(C_Phase_ID));
}
/** Get Standard Phase.
@return Standard Phase of the Project Type
*/
public int getC_Phase_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Phase_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CyclePhase.java | 1 |
请完成以下Java代码 | public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public OAuth2AccessToken getToken() {
return token;
}
public void setToken(OAuth2AccessToken token) {
this.token = token;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String getPassword() {
return null; | }
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
} | repos\tutorials-master\spring-security-modules\spring-security-legacy-oidc\src\main\java\com\baeldung\openid\oidc\OpenIdConnectUserDetails.java | 1 |
请完成以下Java代码 | /* package */class GenericAttributeSetInstanceAwareFactory implements IAttributeSetInstanceAwareFactory
{
private final transient Logger logger = LogManager.getLogger(getClass());
@Override
public IAttributeSetInstanceAware createOrNull(final Object referencedObj)
{
if (referencedObj == null)
{
return null;
}
if (!InterfaceWrapperHelper.hasModelColumnName(referencedObj, IAttributeSetInstanceAware.COLUMNNAME_M_Product_ID))
{
return null;
}
if (!InterfaceWrapperHelper.hasModelColumnName(referencedObj, IAttributeSetInstanceAware.COLUMNNAME_M_AttributeSetInstance_ID)) | {
return null;
}
try
{
final IAttributeSetInstanceAware asiAware = InterfaceWrapperHelper.create(referencedObj, IAttributeSetInstanceAware.class);
return asiAware;
}
catch (final Exception e)
{
final AdempiereException e2 = new AdempiereException("Cannot wrap " + referencedObj + " to " + IAttributeSetInstanceAware.class, e);
logger.warn(e2.getLocalizedMessage(), e2);
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\asi_aware\factory\impl\GenericAttributeSetInstanceAwareFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RestService
{
private static final Logger log = LogManager.getLogger(RestService.class);
private final RateLimitService rateLimitService;
private final ResponseErrorHandler responseErrorHandler;
private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
public RestService(final RateLimitService rateLimitService,
final ResponseErrorHandler responseErrorHandler)
{
this.rateLimitService = rateLimitService;
this.responseErrorHandler = responseErrorHandler;
}
public <T> ResponseEntity<T> performGet(@NonNull final GetRequest getRequest, final Class<T> clazz)
{
final URI resourceURI;
final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(getRequest.getBaseURL());
if (!Check.isEmpty(getRequest.getPathVariables()))
{
uriBuilder.pathSegment(getRequest.getPathVariables().toArray(new String[0]));
}
if (!Check.isEmpty(getRequest.getQueryParameters()))
{
uriBuilder.queryParams(getRequest.getQueryParameters());
}
final HttpEntity<String> request = new HttpEntity<>(buildHttpHeaders(getRequest.getOAuthToken()));
resourceURI = uriBuilder.build().encode().toUri();
return performWithRetry(resourceURI, HttpMethod.GET, request, clazz);
}
private HttpHeaders buildHttpHeaders(final String oAuthToken)
{
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add(HttpHeaders.ACCEPT, GITHUB_API_VERSION);
headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + oAuthToken);
return headers;
}
private <T> ResponseEntity<T> performWithRetry(final URI resourceURI, final HttpMethod httpMethod,
final HttpEntity<String> request, final Class<T> responseType)
{
ResponseEntity<T> response = null;
boolean retry = true; | while (retry)
{
try
{
log.debug("Performing [{}] on [{}] for request [{}]", httpMethod.name(), resourceURI, request);
retry = false;
response = restTemplate().exchange(resourceURI, httpMethod, request, responseType);
}
catch (final RateLimitExceededException rateLimitEx)
{
Loggables.withLogger(log, Level.ERROR)
.addLog("*** ERROR: RateLimit reached on Github side! ErrorMsg: {}, rateLimitInfo: {}", rateLimitEx.getErrorMessage(), rateLimitEx);
rateLimitService.waitForLimitReset(rateLimitEx.getRateLimit());
retry = true;
}
catch (final Throwable t)
{
log.error("ERROR while trying to fetch from URI: {}, Error message: {}", resourceURI, t.getMessage(), t);
throw t;
}
}
return response;
}
private RestTemplate restTemplate()
{
return new RestTemplateBuilder()
.errorHandler(responseErrorHandler)
.setConnectTimeout(Duration.ofMillis(sysConfigBL.getIntValue(CONNECTION_TIMEOUT.getName(), CONNECTION_TIMEOUT.getDefaultValue())))
.setReadTimeout(Duration.ofMillis(sysConfigBL.getIntValue(READ_TIMEOUT.getName(),READ_TIMEOUT.getDefaultValue())))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.issue.tracking.github\src\main\java\de\metas\issue\tracking\github\api\v3\service\rest\RestService.java | 2 |
请完成以下Java代码 | public List<Deployer> getDeployers() {
return deployers;
}
public void setDeployers(List<Deployer> deployers) {
this.deployers = deployers;
}
public DeploymentCache<EventDefinitionCacheEntry> getEventDefinitionCache() {
return eventDefinitionCache;
}
public void setEventDefinitionCache(DeploymentCache<EventDefinitionCacheEntry> eventDefinitionCache) {
this.eventDefinitionCache = eventDefinitionCache;
}
public DeploymentCache<ChannelDefinitionCacheEntry> getChannelDefinitionCache() {
return channelDefinitionCache;
}
public void setChannelDefinitionCache(DeploymentCache<ChannelDefinitionCacheEntry> channelDefinitionCache) {
this.channelDefinitionCache = channelDefinitionCache;
}
public EventDefinitionEntityManager getEventDefinitionEntityManager() {
return eventDefinitionEntityManager;
}
public void setEventDefinitionEntityManager(EventDefinitionEntityManager eventDefinitionEntityManager) {
this.eventDefinitionEntityManager = eventDefinitionEntityManager; | }
public ChannelDefinitionEntityManager getChannelDefinitionEntityManager() {
return channelDefinitionEntityManager;
}
public void setChannelDefinitionEntityManager(ChannelDefinitionEntityManager channelDefinitionEntityManager) {
this.channelDefinitionEntityManager = channelDefinitionEntityManager;
}
public EventDeploymentEntityManager getDeploymentEntityManager() {
return deploymentEntityManager;
}
public void setDeploymentEntityManager(EventDeploymentEntityManager deploymentEntityManager) {
this.deploymentEntityManager = deploymentEntityManager;
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\deploy\EventDeploymentManager.java | 1 |
请完成以下Java代码 | public void setGeocodingProvider (java.lang.String GeocodingProvider)
{
set_Value (COLUMNNAME_GeocodingProvider, GeocodingProvider);
}
/** Get Geocoding Dienst Provider.
@return Geocoding Dienst Provider */
@Override
public java.lang.String getGeocodingProvider ()
{
return (java.lang.String)get_Value(COLUMNNAME_GeocodingProvider);
}
/** Set Google Maps - API-Schlüssel.
@param gmaps_ApiKey Google Maps - API-Schlüssel */
@Override
public void setgmaps_ApiKey (java.lang.String gmaps_ApiKey)
{
set_Value (COLUMNNAME_gmaps_ApiKey, gmaps_ApiKey);
}
/** Get Google Maps - API-Schlüssel.
@return Google Maps - API-Schlüssel */
@Override
public java.lang.String getgmaps_ApiKey ()
{
return (java.lang.String)get_Value(COLUMNNAME_gmaps_ApiKey);
}
/** Set Open Street Maps - Basis-URL.
@param osm_baseURL
The Base URL after which all parameters are added
*/
@Override
public void setosm_baseURL (java.lang.String osm_baseURL)
{
set_Value (COLUMNNAME_osm_baseURL, osm_baseURL);
} | /** Get Open Street Maps - Basis-URL.
@return The Base URL after which all parameters are added
*/
@Override
public java.lang.String getosm_baseURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_osm_baseURL);
}
/** Set Open Street Maps - Millisekunden zwischen den Anfragen.
@param osm_millisBetweenRequests
How many milliseconds to wait between 2 consecutive requests
*/
@Override
public void setosm_millisBetweenRequests (int osm_millisBetweenRequests)
{
set_Value (COLUMNNAME_osm_millisBetweenRequests, Integer.valueOf(osm_millisBetweenRequests));
}
/** Get Open Street Maps - Millisekunden zwischen den Anfragen.
@return How many milliseconds to wait between 2 consecutive requests
*/
@Override
public int getosm_millisBetweenRequests ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_osm_millisBetweenRequests);
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_GeocodingConfig.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected RestVariable setSimpleVariable(RestVariable restVariable, Task task, boolean isNew) {
if (restVariable.getName() == null) {
throw new FlowableIllegalArgumentException("Variable name is required");
}
// Figure out scope, revert to local is omitted
RestVariableScope scope = restVariable.getVariableScope();
if (scope == null) {
scope = RestVariableScope.LOCAL;
}
Object actualVariableValue = restResponseFactory.getVariableValue(restVariable);
setVariable(task, restVariable.getName(), actualVariableValue, scope, isNew);
return getVariableFromRequestWithoutAccessCheck(task, restVariable.getName(), scope, false);
}
protected void setVariable(Task task, String name, Object value, RestVariableScope scope, boolean isNew) {
// Create can only be done on new variables. Existing variables should
// be updated using PUT
boolean hasVariable = hasVariableOnScope(task, name, scope);
if (isNew && hasVariable) {
throw new FlowableException("Variable '" + name + "' is already present on task '" + task.getId() + "'.");
}
if (!isNew && !hasVariable) {
throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' doesn't have a variable with name: '" + name + "'.", null);
}
if (restApiInterceptor != null) { | if (isNew) {
restApiInterceptor.createTaskVariables(task, Collections.singletonMap(name, value), scope);
} else {
restApiInterceptor.updateTaskVariables(task, Collections.singletonMap(name, value), scope);
}
}
if (scope == RestVariableScope.LOCAL) {
taskService.setVariableLocal(task.getId(), name, value);
} else {
if (ScopeTypes.CMMN.equals(task.getScopeType()) && task.getScopeId() != null) {
// Explicitly set on execution, setting non-local variable on
// task will override local-variable if exists
runtimeService.setVariable(task.getScopeId(), name, value);
} else {
// Standalone task, no global variables possible
throw new FlowableIllegalArgumentException("Cannot set global variable '" + name + "' on task '" + task.getId() + "', task is not part of process.");
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskVariableBaseResource.java | 2 |
请完成以下Java代码 | public int getImpEx_ConnectorType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_ConnectorType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | /** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_ImpEx_ConnectorType.java | 1 |
请完成以下Java代码 | public void snapshotHuIfMarkedAsSourceHu(@NonNull final I_M_HU hu)
{
final I_M_Source_HU sourceHuMarker = sourceHuDAO.retrieveSourceHuMarkerOrNull(hu);
if (sourceHuMarker != null)
{
snapshotSourceHU(sourceHuMarker);
}
}
public List<I_M_Source_HU> retrieveMatchingSourceHuMarkers(@NonNull final MatchingSourceHusQuery query)
{
return sourceHuDAO.retrieveActiveSourceHuMarkers(query);
}
@NonNull
public ImmutableList<I_M_Source_HU> retrieveSourceHuMarkers(@NonNull final Collection<HuId> huIds)
{
return sourceHuDAO.retrieveSourceHuMarkers(huIds);
}
public Set<HuId> retrieveMatchingSourceHUIds(@NonNull final MatchingSourceHusQuery query)
{
return sourceHuDAO.retrieveActiveSourceHUIds(query);
}
public boolean isSourceHu(final HuId huId)
{
return sourceHuDAO.isSourceHu(huId);
}
public void addSourceHUMarkerIfCarringComponents(@NonNull final HuId huId, @NonNull final ProductId productId, @NonNull final WarehouseId warehouseId)
{
addSourceHUMarkerIfCarringComponents(ImmutableSet.of(huId), productId, warehouseId);
}
/**
* Creates an M_Source_HU record for the given HU, if it carries component products and the target warehouse has
* the org.compiere.model.I_M_Warehouse#isReceiveAsSourceHU() flag.
*/
public void addSourceHUMarkerIfCarringComponents(@NonNull final Set<HuId> huIds, @NonNull final ProductId productId, @NonNull final WarehouseId warehouseId)
{
if (huIds.isEmpty()) {return;}
final I_M_Warehouse warehouse = warehousesRepo.getById(warehouseId);
if (!warehouse.isReceiveAsSourceHU())
{
return;
}
final boolean referencedInComponentOrVariant = productBOMDAO.isComponent(productId);
if (!referencedInComponentOrVariant)
{
return;
}
huIds.forEach(this::addSourceHuMarker); | }
/**
* Specifies which source HUs (products and warehouse) to retrieve in particular
*/
@lombok.Value
@lombok.Builder
@Immutable
public static class MatchingSourceHusQuery
{
/**
* Query for HUs that have any of the given product IDs. Empty means that no HUs will be found.
*/
@Singular
ImmutableSet<ProductId> productIds;
@Singular
ImmutableSet<WarehouseId> warehouseIds;
public static MatchingSourceHusQuery fromHuId(final HuId huId)
{
final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
final I_M_HU hu = handlingUnitsBL.getById(huId);
final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory();
final IHUStorage storage = storageFactory.getStorage(hu);
final ImmutableSet<ProductId> productIds = storage.getProductStorages().stream()
.filter(productStorage -> !productStorage.isEmpty())
.map(IProductStorage::getProductId)
.collect(ImmutableSet.toImmutableSet());
final WarehouseId warehouseId = IHandlingUnitsBL.extractWarehouseId(hu);
return new MatchingSourceHusQuery(productIds, ImmutableSet.of(warehouseId));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\sourcehu\SourceHUsService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void delete(SuspendedJobEntity jobEntity) {
delete(jobEntity, false);
deleteByteArrayRef(jobEntity.getExceptionByteArrayRef());
deleteByteArrayRef(jobEntity.getCustomValuesByteArrayRef());
// Send event
if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, jobEntity),
serviceConfiguration.getEngineName());
}
}
@Override
public void delete(SuspendedJobEntity jobEntity, boolean fireDeleteEvent) {
if (serviceConfiguration.getInternalJobManager() != null) {
serviceConfiguration.getInternalJobManager().handleJobDelete(jobEntity);
}
super.delete(jobEntity, fireDeleteEvent);
}
protected SuspendedJobEntity createSuspendedJob(AbstractRuntimeJobEntity job) {
SuspendedJobEntity newSuspendedJobEntity = create();
newSuspendedJobEntity.setJobHandlerConfiguration(job.getJobHandlerConfiguration()); | newSuspendedJobEntity.setCustomValues(job.getCustomValues());
newSuspendedJobEntity.setJobHandlerType(job.getJobHandlerType());
newSuspendedJobEntity.setExclusive(job.isExclusive());
newSuspendedJobEntity.setRepeat(job.getRepeat());
newSuspendedJobEntity.setRetries(job.getRetries());
newSuspendedJobEntity.setEndDate(job.getEndDate());
newSuspendedJobEntity.setExecutionId(job.getExecutionId());
newSuspendedJobEntity.setProcessInstanceId(job.getProcessInstanceId());
newSuspendedJobEntity.setProcessDefinitionId(job.getProcessDefinitionId());
newSuspendedJobEntity.setScopeId(job.getScopeId());
newSuspendedJobEntity.setSubScopeId(job.getSubScopeId());
newSuspendedJobEntity.setScopeType(job.getScopeType());
newSuspendedJobEntity.setScopeDefinitionId(job.getScopeDefinitionId());
// Inherit tenant
newSuspendedJobEntity.setTenantId(job.getTenantId());
newSuspendedJobEntity.setJobType(job.getJobType());
return newSuspendedJobEntity;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\SuspendedJobEntityManagerImpl.java | 2 |
请完成以下Java代码 | public InvoicesView createView(final @NonNull CreateViewRequest request)
{
throw new UnsupportedOperationException();
}
@Override
public WindowId getWindowId()
{
return WINDOW_ID;
}
@Override
public void put(final IView view)
{
throw new UnsupportedOperationException();
}
@Nullable
@Override
public InvoicesView getByIdOrNull(final ViewId invoicesViewId)
{
final ViewId paymentsViewId = toPaymentsViewId(invoicesViewId);
final PaymentsView paymentsView = paymentsViewFactory.getByIdOrNull(paymentsViewId);
return paymentsView != null
? paymentsView.getInvoicesView()
: null;
}
private static ViewId toPaymentsViewId(final ViewId invoicesViewId)
{
return invoicesViewId.withWindowId(PaymentsViewFactory.WINDOW_ID);
}
@Override
public void closeById(final ViewId viewId, final ViewCloseAction closeAction)
{
} | @Override
public Stream<IView> streamAllViews()
{
return paymentsViewFactory.streamAllViews()
.map(PaymentsView::cast)
.map(PaymentsView::getInvoicesView);
}
@Override
public void invalidateView(final ViewId invoicesViewId)
{
final InvoicesView invoicesView = getByIdOrNull(invoicesViewId);
if (invoicesView != null)
{
invoicesView.invalidateAll();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoicesViewFactory.java | 1 |
请完成以下Java代码 | public void setC_PrintPackageData_ID (int C_PrintPackageData_ID)
{
if (C_PrintPackageData_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_PrintPackageData_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_PrintPackageData_ID, Integer.valueOf(C_PrintPackageData_ID));
}
@Override
public int getC_PrintPackageData_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PrintPackageData_ID);
}
@Override
public de.metas.printing.model.I_C_Print_Package getC_Print_Package()
{
return get_ValueAsPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class);
}
@Override
public void setC_Print_Package(de.metas.printing.model.I_C_Print_Package C_Print_Package)
{
set_ValueFromPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class, C_Print_Package);
}
@Override
public void setC_Print_Package_ID (int C_Print_Package_ID)
{
if (C_Print_Package_ID < 1)
set_Value (COLUMNNAME_C_Print_Package_ID, null);
else | set_Value (COLUMNNAME_C_Print_Package_ID, Integer.valueOf(C_Print_Package_ID));
}
@Override
public int getC_Print_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID);
}
@Override
public void setPrintData (byte[] PrintData)
{
set_Value (COLUMNNAME_PrintData, PrintData);
}
@Override
public byte[] getPrintData()
{
return (byte[])get_Value(COLUMNNAME_PrintData);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_PrintPackageData.java | 1 |
请完成以下Java代码 | public PPOrderRef withPPOrderId(@Nullable final PPOrderId ppOrderId)
{
if (PPOrderId.equals(this.ppOrderId, ppOrderId))
{
return this;
}
return toBuilder().ppOrderId(ppOrderId).build();
}
@Nullable
public static PPOrderRef withPPOrderId(@Nullable final PPOrderRef ppOrderRef, @Nullable final PPOrderId newPPOrderId)
{
if (ppOrderRef != null)
{
return ppOrderRef.withPPOrderId(newPPOrderId);
}
else if (newPPOrderId != null)
{
return ofPPOrderId(newPPOrderId);
}
else
{
return null;
} | }
@Nullable
public static PPOrderRef withPPOrderAndBOMLineId(@Nullable final PPOrderRef ppOrderRef, @Nullable final PPOrderAndBOMLineId newPPOrderAndBOMLineId)
{
if (ppOrderRef != null)
{
return ppOrderRef.withPPOrderAndBOMLineId(newPPOrderAndBOMLineId);
}
else if (newPPOrderAndBOMLineId != null)
{
return ofPPOrderBOMLineId(newPPOrderAndBOMLineId);
}
else
{
return null;
}
}
@Nullable
public PPOrderAndBOMLineId getPpOrderAndBOMLineId() {return PPOrderAndBOMLineId.ofNullable(ppOrderId, ppOrderBOMLineId);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\pporder\PPOrderRef.java | 1 |
请完成以下Java代码 | public JsonOLCandCreateBulkRequest validate()
{
for (final JsonOLCandCreateRequest request : requests)
{
request.validate();
}
return this;
}
public JsonOLCandCreateBulkRequest withOrgSyncAdvise(@Nullable final SyncAdvise syncAdvise)
{
return syncAdvise != null
? map(request -> request.withOrgSyncAdvise(syncAdvise))
: this;
}
public JsonOLCandCreateBulkRequest withBPartnersSyncAdvise(@Nullable final SyncAdvise syncAdvise)
{
return syncAdvise != null
? map(request -> request.withBPartnersSyncAdvise(syncAdvise))
: this;
}
public JsonOLCandCreateBulkRequest withProductsSyncAdvise(@Nullable final SyncAdvise syncAdvise)
{
return syncAdvise != null
? map(request -> request.withProductsSyncAdvise(syncAdvise))
: this; | }
private JsonOLCandCreateBulkRequest map(@NonNull final UnaryOperator<JsonOLCandCreateRequest> mapper)
{
if (requests.isEmpty())
{
return this;
}
final ImmutableList<JsonOLCandCreateRequest> newRequests = this.requests.stream()
.map(mapper)
.collect(ImmutableList.toImmutableList());
return new JsonOLCandCreateBulkRequest(newRequests);
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-ordercandidates\src\main\java\de\metas\common\ordercandidates\v1\request\JsonOLCandCreateBulkRequest.java | 1 |
请完成以下Java代码 | public class ForwardingParams implements IParams
{
private final IParams params;
public ForwardingParams(@NonNull final IParams params)
{
this.params = params;
}
@Override
public boolean hasParameter(final String parameterName)
{
return params.hasParameter(parameterName);
}
@Override
public Collection<String> getParameterNames()
{
return params.getParameterNames();
}
@Override
public Object getParameterAsObject(final String parameterName)
{
return params.getParameterAsObject(parameterName);
}
@Override
public String getParameterAsString(final String parameterName)
{
return params.getParameterAsString(parameterName);
}
@Override
public int getParameterAsInt(final String parameterName, final int defaultValue)
{
return params.getParameterAsInt(parameterName, defaultValue);
}
@Override
public <T extends RepoIdAware> T getParameterAsId(String parameterName, Class<T> type)
{
return params.getParameterAsId(parameterName, type);
}
@Override
public BigDecimal getParameterAsBigDecimal(final String parameterName)
{
return params.getParameterAsBigDecimal(parameterName);
}
@Override
public Timestamp getParameterAsTimestamp(final String parameterName)
{
return params.getParameterAsTimestamp(parameterName);
} | @Override
public LocalDate getParameterAsLocalDate(final String parameterName)
{
return params.getParameterAsLocalDate(parameterName);
}
@Override
public ZonedDateTime getParameterAsZonedDateTime(final String parameterName)
{
return params.getParameterAsZonedDateTime(parameterName);
}
@Nullable
@Override
public Instant getParameterAsInstant(final String parameterName)
{
return params.getParameterAsInstant(parameterName);
}
@Override
public boolean getParameterAsBool(final String parameterName)
{
return params.getParameterAsBool(parameterName);
}
@Nullable
@Override
public Boolean getParameterAsBoolean(final String parameterName, @Nullable final Boolean defaultValue)
{
return params.getParameterAsBoolean(parameterName, defaultValue);
}
@Override
public <T extends Enum<T>> Optional<T> getParameterAsEnum(final String parameterName, final Class<T> enumType)
{
return params.getParameterAsEnum(parameterName, enumType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\api\ForwardingParams.java | 1 |
请完成以下Java代码 | public int compareTo(User other) {
return this.getName().compareTo(other.getName());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof User)) {
return false;
}
User that = (User) obj;
return this.getName().equals(that.getName());
}
@Override
public int hashCode() {
int hashValue = 17;
hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getName());
return hashValue;
}
@Override
public String toString() {
return getName();
}
public enum Role {
CLUSTER_OPERATOR,
DEVELOPER; | public static Role of(String name) {
return Arrays.stream(values())
.filter(role -> role.name().equalsIgnoreCase(String.valueOf(name).trim()))
.findFirst()
.orElse(null);
}
public boolean isClusterOperator() {
return CLUSTER_OPERATOR.equals(this);
}
public boolean isDeveloper() {
return DEVELOPER.equals(this);
}
@Override
public String toString() {
return name().toLowerCase();
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\support\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void initNewMember() {
newMember = new Member();
}
public void register() throws Exception {
try {
memberRegistration.register(newMember);
FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_INFO, "Registered!", "Registration successful");
facesContext.addMessage(null, m);
initNewMember();
} catch (Exception e) {
String errorMessage = getRootErrorMessage(e);
FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Registration unsuccessful");
facesContext.addMessage(null, m);
}
}
private String getRootErrorMessage(Exception e) {
// Default to general error message that registration failed.
String errorMessage = "Registration failed. See server log for more information";
if (e == null) {
// This shouldn't happen, but return the default messages | return errorMessage;
}
// Start with the exception and recurse to find the root cause
Throwable t = e;
while (t != null) {
// Get the message from the Throwable class instance
errorMessage = t.getLocalizedMessage();
t = t.getCause();
}
// This is the root cause message
return errorMessage;
}
} | repos\tutorials-master\persistence-modules\deltaspike\src\main\java\baeldung\controller\MemberController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private JSONArray getItemHintValues(ItemHint hint) throws Exception {
JSONArray values = new JSONArray();
for (ItemHint.ValueHint value : hint.getValues()) {
values.put(getItemHintValue(value));
}
return values;
}
private JSONObject getItemHintValue(ItemHint.ValueHint value) throws Exception {
JSONObject result = new JSONObject();
putHintValue(result, value.getValue());
result.putOpt("description", value.getDescription());
return result;
}
private JSONArray getItemHintProviders(ItemHint hint) throws Exception {
JSONArray providers = new JSONArray();
for (ItemHint.ValueProvider provider : hint.getProviders()) {
providers.put(getItemHintProvider(provider));
}
return providers;
}
private JSONObject getItemHintProvider(ItemHint.ValueProvider provider) throws Exception {
JSONObject result = new JSONObject();
result.put("name", provider.getName());
if (provider.getParameters() != null && !provider.getParameters().isEmpty()) {
JSONObject parameters = new JSONObject();
for (Map.Entry<String, Object> entry : provider.getParameters().entrySet()) {
parameters.put(entry.getKey(), extractItemValue(entry.getValue()));
}
result.put("parameters", parameters);
}
return result;
}
private void putHintValue(JSONObject jsonObject, Object value) throws Exception {
Object hintValue = extractItemValue(value);
jsonObject.put("value", hintValue);
}
private void putDefaultValue(JSONObject jsonObject, Object value) throws Exception {
Object defaultValue = extractItemValue(value);
jsonObject.put("defaultValue", defaultValue);
}
private Object extractItemValue(Object value) {
Object defaultValue = value;
if (value.getClass().isArray()) {
JSONArray array = new JSONArray();
int length = Array.getLength(value);
for (int i = 0; i < length; i++) {
array.put(Array.get(value, i));
}
defaultValue = array; | }
return defaultValue;
}
private static final class ItemMetadataComparator implements Comparator<ItemMetadata> {
private static final Comparator<ItemMetadata> GROUP = Comparator.comparing(ItemMetadata::getName)
.thenComparing(ItemMetadata::getSourceType, Comparator.nullsFirst(Comparator.naturalOrder()));
private static final Comparator<ItemMetadata> ITEM = Comparator.comparing(ItemMetadataComparator::isDeprecated)
.thenComparing(ItemMetadata::getName)
.thenComparing(ItemMetadata::getSourceType, Comparator.nullsFirst(Comparator.naturalOrder()));
@Override
public int compare(ItemMetadata o1, ItemMetadata o2) {
if (o1.isOfItemType(ItemType.GROUP)) {
return GROUP.compare(o1, o2);
}
return ITEM.compare(o1, o2);
}
private static boolean isDeprecated(ItemMetadata item) {
return item.getDeprecation() != null;
}
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\JsonConverter.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Demo07Producer {
private Logger logger = LoggerFactory.getLogger(getClass());
@Resource
private KafkaTemplate<Object, Object> kafkaTemplate;
public SendResult syncSend(Integer id) throws ExecutionException, InterruptedException {
// 创建 Demo07Message 消息
Demo07Message message = new Demo07Message();
message.setId(id);
// 同步发送消息
return kafkaTemplate.send(Demo07Message.TOPIC, message).get();
}
public String syncSendInTransaction(Integer id, Runnable runner) throws ExecutionException, InterruptedException {
return kafkaTemplate.executeInTransaction(new KafkaOperations.OperationsCallback<Object, Object, String>() {
@Override
public String doInOperations(KafkaOperations<Object, Object> kafkaOperations) {
// 创建 Demo07Message 消息
Demo07Message message = new Demo07Message();
message.setId(id);
try {
SendResult<Object, Object> sendResult = kafkaOperations.send(Demo07Message.TOPIC, message).get();
logger.info("[doInOperations][发送编号:[{}] 发送结果:[{}]]", id, sendResult); | } catch (Exception e) {
throw new RuntimeException(e);
}
// 本地业务逻辑... biubiubiu
runner.run();
// 返回结果
return "success";
}
});
}
} | repos\SpringBoot-Labs-master\lab-03-kafka\lab-03-kafka-demo-transaction\src\main\java\cn\iocoder\springboot\lab03\kafkademo\producer\Demo07Producer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | Object runAiragFlow(@RequestBody AiragFlowDTO airagFlowDTO) {
return sysBaseApi.runAiragFlow(airagFlowDTO);
}
/**
* 根据部门code或部门id获取部门名称(当前和上级部门)
*
* @param orgCode 部门编码
* @param depId 部门id
* @return String 部门名称
*/
@GetMapping(value = "/getDepartPathNameByOrgCode")
String getDepartPathNameByOrgCode(@RequestParam(name = "orgCode", required = false) String orgCode, @RequestParam(name = "depId", required = false) String depId) {
return sysBaseApi.getDepartPathNameByOrgCode(orgCode, depId);
}
/**
* 根据部门ID查询用户ID | * @param deptIds
* @return
*/
@GetMapping("/queryUserIdsByCascadeDeptIds")
public List<String> queryUserIdsByCascadeDeptIds(@RequestParam("deptIds") List<String> deptIds){
return sysBaseApi.queryUserIdsByCascadeDeptIds(deptIds);
}
/**
* 推送uniapp 消息
* @param pushMessageDTO
* @return
*/
@PostMapping("/uniPushMsgToUser")
public void uniPushMsgToUser(@RequestBody PushMessageDTO pushMessageDTO){
sysBaseApi.uniPushMsgToUser(pushMessageDTO);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\api\controller\SystemApiController.java | 2 |
请完成以下Java代码 | public class StartEventParseHandler extends AbstractActivityBpmnParseHandler<StartEvent> {
@Override
public Class<? extends BaseElement> getHandledType() {
return StartEvent.class;
}
@Override
protected void executeParse(BpmnParse bpmnParse, StartEvent element) {
if (element.getSubProcess() != null && element.getSubProcess() instanceof EventSubProcess) {
if (CollectionUtil.isNotEmpty(element.getEventDefinitions())) {
EventDefinition eventDefinition = element.getEventDefinitions().get(0);
if (eventDefinition instanceof MessageEventDefinition) {
MessageEventDefinition messageDefinition = (MessageEventDefinition) eventDefinition;
BpmnModel bpmnModel = bpmnParse.getBpmnModel();
String messageRef = messageDefinition.getMessageRef();
if (bpmnModel.containsMessageId(messageRef)) {
Message message = bpmnModel.getMessage(messageRef);
messageDefinition.setMessageRef(message.getName());
messageDefinition.setExtensionElements(message.getExtensionElements());
}
element.setBehavior(
bpmnParse
.getActivityBehaviorFactory()
.createEventSubProcessMessageStartEventActivityBehavior(element, messageDefinition)
);
} else if (eventDefinition instanceof ErrorEventDefinition) {
element.setBehavior(
bpmnParse
.getActivityBehaviorFactory()
.createEventSubProcessErrorStartEventActivityBehavior(element)
);
}
}
} else if (CollectionUtil.isEmpty(element.getEventDefinitions())) { | element.setBehavior(bpmnParse.getActivityBehaviorFactory().createNoneStartEventActivityBehavior(element));
}
if (
element.getSubProcess() == null &&
(CollectionUtil.isEmpty(element.getEventDefinitions()) ||
bpmnParse.getCurrentProcess().getInitialFlowElement() == null)
) {
bpmnParse.getCurrentProcess().setInitialFlowElement(element);
}
checkStartFormKey(bpmnParse.getCurrentProcessDefinition(), element);
}
private void checkStartFormKey(ProcessDefinitionEntity processDefinition, StartEvent startEvent) {
if (StringUtils.isNotEmpty(startEvent.getFormKey())) {
processDefinition.setStartFormKey(true);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\StartEventParseHandler.java | 1 |
请完成以下Java代码 | public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
WebOperationRequestPredicate other = (WebOperationRequestPredicate) obj;
boolean result = true;
result = result && this.consumes.equals(other.consumes);
result = result && this.httpMethod == other.httpMethod;
result = result && this.canonicalPath.equals(other.canonicalPath);
result = result && this.produces.equals(other.produces);
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1; | result = prime * result + this.consumes.hashCode();
result = prime * result + this.httpMethod.hashCode();
result = prime * result + this.canonicalPath.hashCode();
result = prime * result + this.produces.hashCode();
return result;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder(this.httpMethod + " to path '" + this.path + "'");
if (!CollectionUtils.isEmpty(this.consumes)) {
result.append(" consumes: ").append(StringUtils.collectionToCommaDelimitedString(this.consumes));
}
if (!CollectionUtils.isEmpty(this.produces)) {
result.append(" produces: ").append(StringUtils.collectionToCommaDelimitedString(this.produces));
}
return result.toString();
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\WebOperationRequestPredicate.java | 1 |
请完成以下Java代码 | private static void storeEmits(int position, State currentState, List<Emit> collectedEmits)
{
Collection<String> emits = currentState.emit();
if (emits != null && !emits.isEmpty())
{
for (String emit : emits)
{
collectedEmits.add(new Emit(position - emit.length() + 1, position, emit));
}
}
}
/**
* 文本是否包含任何模式
*
* @param text 待匹配的文本
* @return 文本包含模式時回傳true
*/ | public boolean hasKeyword(String text)
{
checkForConstructedFailureStates();
State currentState = this.rootState;
for (int i = 0; i < text.length(); ++i)
{
State nextState = getState(currentState, text.charAt(i));
if (nextState != null && nextState != currentState && nextState.emit().size() != 0) {
return true;
}
currentState = nextState;
}
return false;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ahocorasick\trie\Trie.java | 1 |
请完成以下Java代码 | public class WEBUI_PurchaseCandidates_PurchaseView_Launcher
extends ViewBasedProcessTemplate
implements IProcessPrecondition
{
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final Set<TableRecordReference> purchaseCandidateRefs = getSelectedRowIds()
.stream()
.map(DocumentId::toInt) | .map(recordId -> TableRecordReference.of(I_C_PurchaseCandidate.Table_Name, recordId))
.collect(ImmutableSet.toImmutableSet());
if (purchaseCandidateRefs.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
getResult().setRecordsToOpen(
purchaseCandidateRefs,
PurchaseCandidates2PurchaseViewFactory.WINDOW_ID_STRING);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\process\WEBUI_PurchaseCandidates_PurchaseView_Launcher.java | 1 |
请完成以下Java代码 | private Optional<Forecast> buildForecast(
@NonNull final I_M_Forecast forecastRecord,
@NonNull final DocTimingType timing)
{
final List<I_M_ForecastLine> forecastLineRecords = forecastsRepo
.retrieveLinesByForecastId(ForecastId.ofRepoId(forecastRecord.getM_Forecast_ID()));
if (forecastLineRecords.isEmpty())
{
return Optional.empty();
}
return Optional.of(Forecast.builder()
.forecastId(forecastRecord.getM_Forecast_ID())
.docStatus(timing.getDocStatus())
.forecastLines(forecastLineRecords.stream()
.map(line -> createForecastLine(line, forecastRecord))
.collect(ImmutableList.toImmutableList()))
.build());
}
private ForecastLine createForecastLine(
@NonNull final I_M_ForecastLine forecastLine,
@NonNull final I_M_Forecast forecast)
{ | final ProductDescriptor productDescriptor = productDescriptorFactory.createProductDescriptor(forecastLine);
final BPartnerId customerId = BPartnerId.ofRepoIdOrNull(CoalesceUtil.firstGreaterThanZero(forecastLine.getC_BPartner_ID(), forecast.getC_BPartner_ID()));
final MaterialDescriptor materialDescriptor = MaterialDescriptor.builder()
.date(TimeUtil.asInstant(forecastLine.getDatePromised()))
.productDescriptor(productDescriptor)
.customerId(customerId)
.warehouseId(WarehouseId.ofRepoId(forecastLine.getM_Warehouse_ID()))
.quantity(forecastLine.getQty())
.build();
return ForecastLine.builder()
.forecastLineId(forecastLine.getM_ForecastLine_ID())
.materialDescriptor(materialDescriptor)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\material\interceptor\M_ForecastEventCreator.java | 1 |
请完成以下Java代码 | private HttpServer createHttpServer() {
HttpServer server = HttpServer.create().bindAddress(this::getListenAddress);
Ssl ssl = getSsl();
if (Ssl.isEnabled(ssl)) {
server = customizeSslConfiguration(server, ssl);
}
if (getCompression() != null && getCompression().getEnabled()) {
CompressionCustomizer compressionCustomizer = new CompressionCustomizer(getCompression());
server = compressionCustomizer.apply(server);
}
server = server.protocol(listProtocols()).forwarded(this.useForwardHeaders);
return applyCustomizers(server);
}
private HttpServer customizeSslConfiguration(HttpServer httpServer, Ssl ssl) {
SslServerCustomizer customizer = new SslServerCustomizer(getHttp2(), ssl.getClientAuth(), getSslBundle(),
getServerNameSslBundles());
addBundleUpdateHandler(null, ssl.getBundle(), customizer);
ssl.getServerNameBundles()
.forEach((serverNameSslBundle) -> addBundleUpdateHandler(serverNameSslBundle.serverName(),
serverNameSslBundle.bundle(), customizer));
return customizer.apply(httpServer);
}
private void addBundleUpdateHandler(@Nullable String serverName, @Nullable String bundleName,
SslServerCustomizer customizer) {
if (StringUtils.hasText(bundleName)) {
SslBundles sslBundles = getSslBundles();
Assert.state(sslBundles != null, "'sslBundles' must not be null");
sslBundles.addBundleUpdateHandler(bundleName,
(sslBundle) -> customizer.updateSslBundle(serverName, sslBundle));
}
} | private HttpProtocol[] listProtocols() {
List<HttpProtocol> protocols = new ArrayList<>();
protocols.add(HttpProtocol.HTTP11);
if (getHttp2() != null && getHttp2().isEnabled()) {
if (getSsl() != null && getSsl().isEnabled()) {
protocols.add(HttpProtocol.H2);
}
else {
protocols.add(HttpProtocol.H2C);
}
}
return protocols.toArray(new HttpProtocol[0]);
}
private InetSocketAddress getListenAddress() {
if (getAddress() != null) {
return new InetSocketAddress(getAddress().getHostAddress(), getPort());
}
return new InetSocketAddress(getPort());
}
private HttpServer applyCustomizers(HttpServer server) {
for (NettyServerCustomizer customizer : this.serverCustomizers) {
server = customizer.apply(server);
}
return server;
}
} | repos\spring-boot-4.0.1\module\spring-boot-reactor-netty\src\main\java\org\springframework\boot\reactor\netty\NettyReactiveWebServerFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
log.debug("请求路径 {} ,进入方法 {}", request.getRequestURI(), joinPoint.getSignature().getDeclaringTypeName() + ":" + joinPoint.getSignature().getName());
MDC.put("req", getRequestInfo(request).toJSONString());
MDC.put("startTime", String.valueOf(System.currentTimeMillis()));
}
/**
* 打印请求日志
*/
@AfterReturning(pointcut = "webLog()|| exceptions()", returning = "result")
public void afterReturning(Object result) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Map<String, String> map = MDC.getCopyOfContextMap();
if (map != null) {
JSONObject jsonObject = new JSONObject(true);
jsonObject.put("uri", request.getRequestURI());
jsonObject.put("took", System.currentTimeMillis() - Long.parseLong(map.getOrDefault("startTime", String.valueOf(System.currentTimeMillis()))));
jsonObject.put("userId", map.getOrDefault("userId", ""));
jsonObject.put("req", JSON.parseObject(map.getOrDefault("req", "")));
if (result != null) {
jsonObject.put("res", JSON.parseObject(result.toString()));
}
log.info(jsonObject.toJSONString());
}
}
/**
* 读取请求信息,转换为json
*/
private JSONObject getRequestInfo(HttpServletRequest req) {
JSONObject requestInfo = new JSONObject();
try {
StringBuffer requestURL = req.getRequestURL();
requestInfo.put("requestURL", requestURL);
String method = req.getMethod(); | requestInfo.put("method", method);
if (req.getQueryString() != null) {
requestInfo.put("queryString", URLDecoder.decode(req.getQueryString(), "UTF-8"));
}
String remoteAddr = req.getRemoteAddr();
requestInfo.put("remoteAddr", remoteAddr);
if (req instanceof ContentCachingRequestWrapper) {
ContentCachingRequestWrapper wrapper = (ContentCachingRequestWrapper) req;
String bodyStr = new String(wrapper.getContentAsByteArray(), StandardCharsets.UTF_8);
if (bodyStr.startsWith("{")) {
JSONObject jsonObject = JSON.parseObject(bodyStr);
requestInfo.put("requestBody", jsonObject);
}
}
} catch (Exception e) {
log.error("解析请求失败", e);
requestInfo.put("parseError", e.getMessage());
}
return requestInfo;
}
} | repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\config\filter\WebLogAspect.java | 2 |
请完成以下Java代码 | protected String getSQLWhere()
{
StringBuffer sql = new StringBuffer();
addSQLWhere(sql, 0, textField1.getText().toUpperCase());
addSQLWhere(sql, 1, textField2.getText().toUpperCase());
addSQLWhere(sql, 2, textField3.getText().toUpperCase());
addSQLWhere(sql, 3, textField4.getText().toUpperCase());
return sql.toString();
} // getSQLWhere
/**
* Add directly Query as Strings
*
* @param sql sql buffer
* @param index index
* @param value value
*/
private void addSQLWhere(StringBuffer sql, int index, String value)
{
if (!(value.isEmpty() || value.equals("%")) && index < filterByColumns.size())
{
// Angelo Dabala' (genied) nectosoft: [2893220] avoid to append string parameters directly because of special chars like quote(s)
sql.append(" AND UPPER(").append(filterByColumns.get(index).getColumnSql()).append(") LIKE ?");
}
} // addSQLWhere
/**
* Get SQL WHERE parameter
*
* @param f field
* @return sql part
*/
private static String getSQLText(CTextField f)
{
String s = f.getText().toUpperCase();
if (!s.contains("%"))
{
if (!s.endsWith("%"))
{
s += "%";
}
if (!s.startsWith("%"))
{
s = "%" + s;
}
}
return s;
} // getSQLText
/**
* Set Parameters for Query.
* (as defined in getSQLWhere)
*
* @param pstmt statement
* @param forCount for counting records | */
@Override
protected void setParameters(PreparedStatement pstmt, boolean forCount) throws SQLException
{
int index = 1;
if (!textField1.getText().isEmpty())
pstmt.setString(index++, getSQLText(textField1));
if (!textField2.getText().isEmpty())
pstmt.setString(index++, getSQLText(textField2));
if (!textField3.getText().isEmpty())
pstmt.setString(index++, getSQLText(textField3));
if (!textField4.getText().isEmpty())
pstmt.setString(index++, getSQLText(textField4));
} // setParameters
//
//
//
@Value
@Builder
private static class FilterByColumn
{
@NotNull String columnName;
@NotNull String columnSql;
}
} // InfoGeneral | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\InfoGeneral.java | 1 |
请完成以下Java代码 | public MigratingDependentInstanceParseHandler<MigratingActivityInstance, List<EventSubscriptionEntity>> getDependentEventSubscriptionHandler() {
return dependentEventSubscriptionHandler;
}
public MigratingDependentInstanceParseHandler<MigratingActivityInstance, List<JobEntity>> getDependentActivityInstanceJobHandler() {
return dependentActivityInstanceJobHandler;
}
public MigratingDependentInstanceParseHandler<MigratingTransitionInstance, List<JobEntity>> getDependentTransitionInstanceJobHandler() {
return dependentTransitionInstanceJobHandler;
}
public MigratingInstanceParseHandler<IncidentEntity> getIncidentHandler() {
return incidentHandler;
}
public MigratingDependentInstanceParseHandler<MigratingProcessElementInstance, List<VariableInstanceEntity>> getDependentVariablesHandler() {
return dependentVariableHandler;
}
protected List<ExecutionEntity> fetchExecutions(CommandContext commandContext, String processInstanceId) {
return commandContext.getExecutionManager().findExecutionsByProcessInstanceId(processInstanceId);
}
protected List<EventSubscriptionEntity> fetchEventSubscriptions(CommandContext commandContext, String processInstanceId) {
return commandContext.getEventSubscriptionManager().findEventSubscriptionsByProcessInstanceId(processInstanceId);
}
protected List<ExternalTaskEntity> fetchExternalTasks(CommandContext commandContext, String processInstanceId) {
return commandContext.getExternalTaskManager().findExternalTasksByProcessInstanceId(processInstanceId);
} | protected List<JobEntity> fetchJobs(CommandContext commandContext, String processInstanceId) {
return commandContext.getJobManager().findJobsByProcessInstanceId(processInstanceId);
}
protected List<IncidentEntity> fetchIncidents(CommandContext commandContext, String processInstanceId) {
return commandContext.getIncidentManager().findIncidentsByProcessInstance(processInstanceId);
}
protected List<TaskEntity> fetchTasks(CommandContext commandContext, String processInstanceId) {
return commandContext.getTaskManager().findTasksByProcessInstanceId(processInstanceId);
}
protected List<JobDefinitionEntity> fetchJobDefinitions(CommandContext commandContext, String processDefinitionId) {
return commandContext.getJobDefinitionManager().findByProcessDefinitionId(processDefinitionId);
}
protected List<VariableInstanceEntity> fetchVariables(CommandContext commandContext, String processInstanceId) {
return commandContext.getVariableInstanceManager().findVariableInstancesByProcessInstanceId(processInstanceId);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\MigratingInstanceParser.java | 1 |
请完成以下Java代码 | public class ApplicabilityRuleImpl extends CmmnElementImpl implements ApplicabilityRule {
protected static AttributeReference<CaseFileItem> contextRefAttribute;
protected static ChildElement<ConditionExpression> conditionChild;
// cmmn 1.1
protected static Attribute<String> nameAttribute;
public ApplicabilityRuleImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getName() {
return nameAttribute.getValue(this);
}
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public CaseFileItem getContext() {
return contextRefAttribute.getReferenceTargetElement(this);
}
public void setContext(CaseFileItem context) {
contextRefAttribute.setReferenceTargetElement(this, context);
}
public ConditionExpression getCondition() {
return conditionChild.getChild(this);
}
public void setCondition(ConditionExpression expression) { | conditionChild.setChild(this, expression);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ApplicabilityRule.class, CMMN_ELEMENT_APPLICABILITY_RULE)
.namespaceUri(CMMN11_NS)
.extendsType(CmmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<ApplicabilityRule>() {
public ApplicabilityRule newInstance(ModelTypeInstanceContext instanceContext) {
return new ApplicabilityRuleImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
contextRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CONTEXT_REF)
.idAttributeReference(CaseFileItem.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
conditionChild = sequenceBuilder.element(ConditionExpression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ApplicabilityRuleImpl.java | 1 |
请完成以下Java代码 | public List<Integer> listDuplicateUsingCollectionsFrequency(List<Integer> list) {
List<Integer> duplicates = new ArrayList<>();
Set<Integer> set = list.stream()
.filter(i -> Collections.frequency(list, i) > 1)
.collect(Collectors.toSet());
duplicates.addAll(set);
return duplicates;
}
public List<Integer> listDuplicateUsingMapAndCollectorsGroupingBy(List<Integer> list) {
List<Integer> duplicates = new ArrayList<>();
Set<Integer> set = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.filter(m -> m.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
duplicates.addAll(set);
return duplicates;
} | public static <T> Set<T> findDuplicateInArrayWithForLoop(T[] array) {
Set<T> duplicates = new HashSet<>();
Set<T> seen = new HashSet<>();
for (T val : array) {
if (!seen.add(val)) {
duplicates.add(val);
}
}
return duplicates;
}
public static <T> Set<T> findDuplicateInArrayWithStream(T[] array) {
Set<T> seen = new HashSet<>();
return Arrays.stream(array)
.filter(val -> !seen.add(val))
.collect(Collectors.toSet());
}
} | repos\tutorials-master\core-java-modules\core-java-collections-list-5\src\main\java\com\baeldung\listduplicate\ListDuplicate.java | 1 |
请完成以下Java代码 | public void remove(Window window)
{
if (windows.remove(window))
{
window.removeComponentListener(eventListener);
window.removeWindowListener(eventListener);
}
}
/**
* Get list of windows managed by this window manager
*
* @return Array of windows
*/
public Window[] getWindows()
{
Window[] a = new Window[windows.size()];
return windows.toArray(a);
}
/**
* @return Number of windows managed by this window manager
*/
public int getWindowCount()
{
return windows.size();
}
/**
* Find window by ID
*
* @param AD_Window_ID
* @return AWindow reference, null if not found
*/
public AWindow find(final AdWindowId adWindowId)
{
for (Window w : windows)
{
if (w instanceof AWindow)
{
AWindow a = (AWindow)w;
if (AdWindowId.equals(a.getAdWindowId(), adWindowId))
{
return a;
}
}
}
return null;
}
public FormFrame findForm(int AD_FORM_ID)
{
for (Window w : windows)
{
if (w instanceof FormFrame)
{
FormFrame ff = (FormFrame)w;
if (ff.getAD_Form_ID() == AD_FORM_ID)
{
return ff;
}
}
}
return null;
}
}
class WindowEventListener implements ComponentListener, WindowListener
{
WindowManager windowManager;
protected WindowEventListener(WindowManager windowManager) | {
this.windowManager = windowManager;
}
@Override
public void componentHidden(ComponentEvent e)
{
Component c = e.getComponent();
if (c instanceof Window)
{
c.removeComponentListener(this);
((Window)c).removeWindowListener(this);
windowManager.remove((Window)c);
}
}
@Override
public void componentMoved(ComponentEvent e)
{
}
@Override
public void componentResized(ComponentEvent e)
{
}
@Override
public void componentShown(ComponentEvent e)
{
}
@Override
public void windowActivated(WindowEvent e)
{
}
@Override
public void windowClosed(WindowEvent e)
{
Window w = e.getWindow();
if (w instanceof Window)
{
w.removeComponentListener(this);
w.removeWindowListener(this);
windowManager.remove(w);
}
}
@Override
public void windowClosing(WindowEvent e)
{
}
@Override
public void windowDeactivated(WindowEvent e)
{
}
@Override
public void windowDeiconified(WindowEvent e)
{
}
@Override
public void windowIconified(WindowEvent e)
{
}
@Override
public void windowOpened(WindowEvent e)
{
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\WindowManager.java | 1 |
请完成以下Java代码 | private String getContentsOfUrlAsString(URL url) {
StringBuilder sb = new StringBuilder();
try {
try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
}
} catch (IOException ex) {
sb.append("ERROR");
}
return sb.toString();
}
@CliCommand(value = { "web-get", "wg" }, help = "Displays the contents of a URL.")
public String webGet(@CliOption(key = { "", "url" }, help = "URL whose contents will be displayed.") URL url) {
return getContentsOfUrlAsString(url);
}
@CliCommand(value = { "web-save", "ws" }, help = "Saves the contents of a URL.")
public String webSave(@CliOption(key = { "", "url" }, help = "URL whose contents will be saved.") URL url, @CliOption(key = { "out", "file" }, mandatory = true, help = "The name of the file.") String file) {
String contents = getContentsOfUrlAsString(url);
try (PrintWriter out = new PrintWriter(file)) {
out.write(contents);
} catch (FileNotFoundException ex) {
// Ignore
}
return "Done.";
}
private boolean adminEnableExecuted = false;
@CliAvailabilityIndicator(value = { "web-save" }) | public boolean isAdminEnabled() {
return adminEnableExecuted;
}
@CliCommand(value = "admin-enable")
public String adminEnable() {
adminEnableExecuted = true;
return "Admin commands enabled.";
}
@CliCommand(value = "admin-disable")
public String adminDisable() {
adminEnableExecuted = false;
return "Admin commands disabled.";
}
} | repos\tutorials-master\spring-shell\src\main\java\com\baeldung\shell\simple\SimpleCLI.java | 1 |
请完成以下Java代码 | public int getC_VAT_Code_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_VAT_Code_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);
}
/**
* IsSOTrx AD_Reference_ID=319
* Reference name: _YesNo
*/
public static final int ISSOTRX_AD_Reference_ID=319;
/** Yes = Y */
public static final String ISSOTRX_Yes = "Y";
/** No = N */
public static final String ISSOTRX_No = "N";
/** Set Sales Transaction.
@param IsSOTrx
This is a Sales Transaction
*/
@Override
public void setIsSOTrx (java.lang.String IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, IsSOTrx);
}
/** Get Sales Transaction.
@return This is a Sales Transaction
*/
@Override
public java.lang.String getIsSOTrx ()
{
return (java.lang.String)get_Value(COLUMNNAME_IsSOTrx);
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{ | return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
/** Set VAT Code.
@param VATCode VAT Code */
@Override
public void setVATCode (java.lang.String VATCode)
{
set_Value (COLUMNNAME_VATCode, VATCode);
}
/** Get VAT Code.
@return VAT Code */
@Override
public java.lang.String getVATCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_VATCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_C_VAT_Code.java | 1 |
请完成以下Java代码 | public class Student {
@Id
private String id;
@Indexed
private String name;
@Searchable
private String lastName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
} | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
} | repos\springboot-demo-master\RedisSearch\src\main\java\com\et\redis\document\Student.java | 1 |
请完成以下Java代码 | 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 String getCity() {
return city; | }
public void setCity(String city) {
this.city = city;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" + "id=" + id + ", name=" + name + ", city=" + city + ", age=" + age + '}';
}
} | repos\Hibernate-SpringBoot-master\SpringBootPayaraMySqlKickoffApplication\src\main\java\com\jpa\model\Player.java | 1 |
请完成以下Java代码 | public static Quantity getQuantity(
@NonNull final IAllocationRequest request,
@NonNull final AllocationDirection direction)
{
return request
.getQuantity() // => Quantity (absolute)
.negateIf(direction.isOutboundDeallocation()); // => Quantity (relative)
}
/**
* Use this to create a new allocation request, using the given request as template.
*/
public static IAllocationRequestBuilder derive(@NonNull final IAllocationRequest request)
{
return builder().setBaseAllocationRequest(request);
}
@Nullable
private static BPartnerId getBPartnerId(final IAllocationRequest request)
{
final Object referencedModel = AllocationUtils.getReferencedModel(request);
if (referencedModel == null)
{
return null;
} | final Integer bpartnerId = InterfaceWrapperHelper.getValueOrNull(referencedModel, I_M_HU_PI_Item.COLUMNNAME_C_BPartner_ID);
return BPartnerId.ofRepoIdOrNull(bpartnerId);
}
/**
* Creates and configures an {@link IHUBuilder} based on the given <code>request</code> (bPartner and date).
*
* @return HU builder
*/
public static IHUBuilder createHUBuilder(final IAllocationRequest request)
{
final IHUContext huContext = request.getHuContext();
final IHUBuilder huBuilder = Services.get(IHandlingUnitsDAO.class).createHUBuilder(huContext);
huBuilder.setDate(request.getDate());
huBuilder.setBPartnerId(getBPartnerId(request));
// TODO: huBuilder.setC_BPartner_Location if any
// TODO: set the HU Storage from context to builder
return huBuilder;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AllocationUtils.java | 1 |
请完成以下Java代码 | private ImmutableSet<String> computeActions(
@NonNull final List<DDOrderReference> jobReferences,
@NonNull final UserId userId)
{
final ImmutableSet.Builder<String> actions = ImmutableSet.builder();
if (hasInTransitSchedules(jobReferences, userId))
{
actions.add(ACTION_DROP_ALL);
if (warehouseService.getTrolleyByUserId(userId).isPresent())
{
actions.add(ACTION_PRINT_IN_TRANSIT_REPORT);
}
}
return actions.build();
} | private boolean hasInTransitSchedules(
@NonNull final List<DDOrderReference> jobReferences,
@NonNull final UserId userId)
{
final LocatorId inTransitLocatorId = warehouseService.getTrolleyByUserId(userId)
.map(LocatorQRCode::getLocatorId)
.orElse(null);
if (inTransitLocatorId != null)
{
return loadingSupportServices.hasInTransitSchedules(inTransitLocatorId);
}
else
{
return jobReferences.stream().anyMatch(DDOrderReference::isInTransit);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\DistributionWorkflowLaunchersProvider.java | 1 |
请完成以下Java代码 | protected void ensureInitialized() {
if(selfReference == null) {
selfReference = lookupSelfReference();
}
ensureEjbProcessApplicationReferenceInitialized();
}
protected abstract void ensureEjbProcessApplicationReferenceInitialized();
protected abstract ProcessApplicationReference getEjbProcessApplicationReference();
/**
* lookup a proxy object representing the invoked business view of this component.
*/
protected abstract ProcessApplicationInterface lookupSelfReference();
/**
* determine the ee application name based on information obtained from JNDI.
*/
protected String lookupEeApplicationName() {
try {
InitialContext initialContext = new InitialContext();
String appName = (String) initialContext.lookup(JAVA_APP_APP_NAME_PATH);
String moduleName = (String) initialContext.lookup(MODULE_NAME_PATH); | // make sure that if an EAR carries multiple PAs, they are correctly
// identified by appName + moduleName
if (moduleName != null && !moduleName.equals(appName)) {
return appName + "/" + moduleName;
} else {
return appName;
}
}
catch (NamingException e) {
throw LOG.ejbPaCannotAutodetectName(e);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\AbstractEjbProcessApplication.java | 1 |
请完成以下Java代码 | public MultiInstanceLoopCharacteristics getLoopCharacteristics() {
return loopCharacteristics;
}
public void setLoopCharacteristics(MultiInstanceLoopCharacteristics loopCharacteristics) {
this.loopCharacteristics = loopCharacteristics;
}
public boolean hasMultiInstanceLoopCharacteristics() {
return getLoopCharacteristics() != null;
}
public IOSpecification getIoSpecification() {
return ioSpecification;
}
public void setIoSpecification(IOSpecification ioSpecification) {
this.ioSpecification = ioSpecification;
}
public List<DataAssociation> getDataInputAssociations() {
return dataInputAssociations;
}
public void setDataInputAssociations(List<DataAssociation> dataInputAssociations) {
this.dataInputAssociations = dataInputAssociations;
}
public List<DataAssociation> getDataOutputAssociations() {
return dataOutputAssociations;
}
public void setDataOutputAssociations(List<DataAssociation> dataOutputAssociations) {
this.dataOutputAssociations = dataOutputAssociations;
}
public List<MapExceptionEntry> getMapExceptions() {
return mapExceptions; | }
public void setMapExceptions(List<MapExceptionEntry> mapExceptions) {
this.mapExceptions = mapExceptions;
}
public void setValues(Activity otherActivity) {
super.setValues(otherActivity);
setFailedJobRetryTimeCycleValue(otherActivity.getFailedJobRetryTimeCycleValue());
setDefaultFlow(otherActivity.getDefaultFlow());
setForCompensation(otherActivity.isForCompensation());
if (otherActivity.getLoopCharacteristics() != null) {
setLoopCharacteristics(otherActivity.getLoopCharacteristics().clone());
}
if (otherActivity.getIoSpecification() != null) {
setIoSpecification(otherActivity.getIoSpecification().clone());
}
dataInputAssociations = new ArrayList<DataAssociation>();
if (otherActivity.getDataInputAssociations() != null && !otherActivity.getDataInputAssociations().isEmpty()) {
for (DataAssociation association : otherActivity.getDataInputAssociations()) {
dataInputAssociations.add(association.clone());
}
}
dataOutputAssociations = new ArrayList<DataAssociation>();
if (otherActivity.getDataOutputAssociations() != null && !otherActivity.getDataOutputAssociations().isEmpty()) {
for (DataAssociation association : otherActivity.getDataOutputAssociations()) {
dataOutputAssociations.add(association.clone());
}
}
boundaryEvents.clear();
for (BoundaryEvent event : otherActivity.getBoundaryEvents()) {
boundaryEvents.add(event);
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Activity.java | 1 |
请完成以下Java代码 | public B put(Object key, Object value) {
Assert.notNull(key, "key cannot be null");
Assert.notNull(value, "value cannot be null");
getContext().put(key, value);
return getThis();
}
/**
* A {@code Consumer} of the attributes {@code Map} allowing the ability to add,
* replace, or remove.
* @param contextConsumer a {@link Consumer} of the attributes {@code Map}
* @return the {@link AbstractBuilder} for further configuration
*/
public B context(Consumer<Map<Object, Object>> contextConsumer) {
contextConsumer.accept(getContext());
return getThis();
}
@SuppressWarnings("unchecked")
protected <V> V get(Object key) {
return (V) getContext().get(key);
}
protected Map<Object, Object> getContext() {
return this.context; | }
@SuppressWarnings("unchecked")
protected final B getThis() {
return (B) this;
}
/**
* Builds a new {@link OAuth2AuthenticationContext}.
* @return the {@link OAuth2AuthenticationContext}
*/
public abstract T build();
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AuthenticationContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
private EmbeddedLdapServerContainer getContainer() {
if (!unboundIdPresent) {
throw new IllegalStateException("Embedded LDAP server is not provided");
}
UnboundIdContainer unboundIdContainer = new UnboundIdContainer(this.root, this.ldif);
unboundIdContainer.setApplicationContext(this.context);
unboundIdContainer.setPort(getEmbeddedServerPort());
unboundIdContainer.afterPropertiesSet();
return unboundIdContainer;
}
private int getEmbeddedServerPort() {
if (this.port == null) { | this.port = getDefaultEmbeddedServerPort();
}
return this.port;
}
private int getDefaultEmbeddedServerPort() {
try (ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT)) {
return serverSocket.getLocalPort();
}
catch (IOException ex) {
return RANDOM_PORT;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\EmbeddedLdapServerContextSourceFactoryBean.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void savePolicy(Model model) {
LOG.warn("savePolicy is not implemented !");
}
@Override
public void addPolicy(String sec, String ptype, List<String> rule) {
throw new Error("not implemented");
}
@Override
public void removePolicy(String sec, String ptype, List<String> rule) {
throw new Error("not implemented");
}
@Override
public void removeFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) {
throw new Error("not implemented");
}
private void loadPolicyClassPath(Model model, Helper.loadPolicyLineHandler<String, Model> handler) { | InputStream is = IsAdapter.class.getResourceAsStream(classPath);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
try {
while((line = br.readLine()) != null) {
handler.accept(line, model);
}
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
throw new Error("IO error occurred");
}
}
} | repos\spring-examples-java-17\spring-jcasbin\src\main\java\itx\examples\springboot\security\config\IsAdapter.java | 2 |
请完成以下Java代码 | private MailboxRoutingTable getRoutingTable()
{
return routingsCache.getOrLoad(0, this::retrieveRoutingTable);
}
private MailboxRoutingTable retrieveRoutingTable()
{
return queryBL.createQueryBuilderOutOfTrx(I_AD_MailConfig.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(MailboxRepository::fromRecord)
.collect(GuavaCollectors.collectUsingListAccumulator(MailboxRoutingTable::ofList));
}
private static MailboxRouting fromRecord(final I_AD_MailConfig record)
{
return MailboxRouting.builder()
.mailboxId(MailboxId.ofRepoId(record.getAD_MailBox_ID()))
.userToColumnName(StringUtils.trimBlankToNull(record.getColumnUserTo()))
.clientId(ClientId.ofRepoId(record.getAD_Client_ID()))
.orgId(OrgId.ofRepoIdOrAny(record.getAD_Org_ID()))
.docBaseAndSubType(DocBaseAndSubType.ofNullable(record.getDocBaseType(), record.getDocSubType()))
.adProcessId(AdProcessId.ofRepoIdOrNull(record.getAD_Process_ID()))
.emailCustomType(EMailCustomType.ofNullableCode(record.getCustomType()))
.build();
}
//
//
//
//
//
//
@Value
@Builder
private static class MailboxEntry
{ | @NonNull MailboxId id;
boolean active;
@NonNull Mailbox mailbox;
}
private static class MailboxesMap
{
private final ImmutableMap<MailboxId, MailboxEntry> byId;
private MailboxesMap(final List<MailboxEntry> list)
{
this.byId = Maps.uniqueIndex(list, MailboxEntry::getId);
}
public Mailbox getById(final MailboxId mailboxId)
{
return getEntryById(mailboxId).getMailbox();
}
private MailboxEntry getEntryById(final MailboxId mailboxId)
{
final MailboxEntry entry = byId.get(mailboxId);
if (entry == null)
{
throw new AdempiereException("No mailbox found for " + mailboxId);
}
return entry;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\mailboxes\MailboxRepository.java | 1 |
请完成以下Java代码 | public DocumentPrintOptionValue getOption(@NonNull final String name)
{
final Boolean value = options.get(name);
if (value != null)
{
return DocumentPrintOptionValue.builder()
.value(OptionalBoolean.ofBoolean(value))
.sourceName(sourceName)
.build();
}
else if (fallback != null)
{
return fallback.getOption(name);
}
else
{
return DocumentPrintOptionValue.MISSING;
}
}
public DocumentPrintOptions mergeWithFallback(@NonNull final DocumentPrintOptions fallback)
{
if (fallback.isNone())
{
return this;
}
else if (isNone())
{
return fallback;
}
else
{
if (this == fallback)
{ | throw new IllegalArgumentException("Merging with itself is not allowed");
}
final DocumentPrintOptions newFallback;
if (this.fallback != null)
{
newFallback = this.fallback.mergeWithFallback(fallback);
}
else
{
newFallback = fallback;
}
return !Objects.equals(this.fallback, newFallback)
? toBuilder().fallback(newFallback).build()
: this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentPrintOptions.java | 1 |
请完成以下Java代码 | protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!isPickerProfile())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("only picker shall pick");
}
if (rowsService.noRowsEligibleForPicking(getValidRowsForPickAndPack()))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("select only rows that can be picked");
}
return ProcessPreconditionsResolution.accept();
}
@Override
@RunOutOfTrx
protected String doIt()
{
ensureDefaultPackingInstructionExists();
pick();
pack();
invalidateView();
return MSG_OK;
}
private void pick()
{
final ImmutableList<WebuiPickHUResult> result = rowsService.pick(getValidRowsForPickAndPack());
updateViewRowFromPickingCandidate(result);
}
private void pack() | {
final ImmutableList<WebuiPickHUResult> result = rowsService.setPackingInstruction(getValidRowsForPickAndPack(), getPackToSpec());
updateViewRowFromPickingCandidate(result);
}
private List<ProductsToPickRow> getValidRowsForPickAndPack()
{
return getSelectedRows()
.stream()
.filter(row -> !row.getQtyEffective().isZero())
.collect(ImmutableList.toImmutableList());
}
@NonNull
private PackToSpec getPackToSpec()
{
final I_M_HU_PI defaultPIForPicking = handlingUnitsDAO.retrievePIDefaultForPicking();
if (defaultPIForPicking == null)
{
throw new AdempiereException(MSG_SET_DEFAULT_PACKING_INSTRUCTION);
}
return PackToSpec.ofGenericPackingInstructionsId(HuPackingInstructionsId.ofRepoId(defaultPIForPicking.getM_HU_PI_ID()));
}
private void ensureDefaultPackingInstructionExists()
{
getPackToSpec();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\process\ProductsToPick_PickAndPackSelected.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Collection<Class<? extends ForecastCreatedEvent>> getHandledEventType()
{
return ImmutableList.of(ForecastCreatedEvent.class);
}
@Override
public void handleEvent(@NonNull final ForecastCreatedEvent event)
{
final Forecast forecast = event.getForecast();
final CandidateBuilder candidateBuilder = Candidate.builderForEventDescriptor(event.getEventDescriptor())
//.status(EventUtil.getCandidateStatus(forecast.getDocStatus()))
.type(CandidateType.STOCK_UP)
.businessCase(CandidateBusinessCase.FORECAST);
for (final ForecastLine forecastLine : forecast.getForecastLines())
{
complementBuilderFromForecastLine(candidateBuilder, forecast, forecastLine);
final Candidate demandCandidate = candidateBuilder.build(); | candidateChangeHandler.onCandidateNewOrChange(demandCandidate);
}
}
private void complementBuilderFromForecastLine(
@NonNull final CandidateBuilder candidateBuilder,
@NonNull final Forecast forecast,
@NonNull final ForecastLine forecastLine)
{
candidateBuilder
.materialDescriptor(forecastLine.getMaterialDescriptor())
.businessCaseDetail(DemandDetail.forForecastLineId(
forecastLine.getForecastLineId(),
forecast.getForecastId(),
forecastLine.getMaterialDescriptor().getQuantity()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\foreacast\ForecastCreatedHandler.java | 2 |
请完成以下Java代码 | public boolean hasNext() {
this.maybeFetchNext();
return next != null;
}
public T next() {
if (next == null) {
throw new NoSuchElementException();
}
T val = next;
next = null;
return val;
}
private void maybeFetchNext() {
if (next == null) {
if (source.hasNext()) { | U val = source.next();
if (filter.test(val)) {
next = transform.apply(val);
}
}
}
}
public void remove() {
throw new UnsupportedOperationException();
}
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\util\Iterables.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private PaymentAllocationPayableItem createPaymentAllocationPayableItem(
@NonNull final RemittanceAdviceLine remittanceAdviceLine,
@NonNull final RemittanceAdvice remittanceAdvice,
@Nullable final I_C_Invoice invoice)
{
if (invoice == null)
{
throw new AdempiereException("Missing invoice for remittance line!")
.appendParametersToMessage()
.setParameter("C_RemittanceAdvice_Line_ID", RemittanceAdviceLineId.toRepoId(remittanceAdviceLine.getRemittanceAdviceLineId()))
.setParameter("remittanceAdviceLine", remittanceAdviceLine);
}
final Amount paymentDiscountAmt = remittanceAdviceLine.getPaymentDiscountAmount() != null
? remittanceAdviceLine.getPaymentDiscountAmount()
: Amount.zero(moneyService.getCurrencyCodeByCurrencyId(remittanceAdvice.getRemittedAmountCurrencyId()));
final Amount serviceFeeInREMADVCurrency = remittanceAdviceService.getServiceFeeInREMADVCurrency(remittanceAdviceLine).orElse(null);
if (remittanceAdviceLine.getInvoiceAmtInREMADVCurrencyAdjusted() == null)
{
throw new AdempiereException("Amount cannot be null if the invoice is resolved!")
.appendParametersToMessage()
.setParameter("C_RemittanceAdvice_Line_ID", RemittanceAdviceLineId.toRepoId(remittanceAdviceLine.getRemittanceAdviceLineId()))
.setParameter("remittanceAdviceLine", remittanceAdviceLine);
}
// create a "noop" multiplier that won't mess with the +/- signs
final InvoiceAmtMultiplier multiplier = InvoiceAmtMultiplier.adjustedFor(remittanceAdviceLine.getExternalInvoiceDocBaseType());
final SOTrx remittanceAdviceSOTrx = SOTrx.ofBooleanNotNull(remittanceAdvice.isSOTrx());
final ZoneId timeZone = orgDAO.getTimeZone(remittanceAdvice.getOrgId());
return PaymentAllocationPayableItem.builder()
.amtMultiplier(multiplier)
.payAmt(remittanceAdviceLine.getRemittedAmountAdjusted())
.openAmt(remittanceAdviceLine.getInvoiceAmtInREMADVCurrencyAdjusted()) | .serviceFeeAmt(serviceFeeInREMADVCurrency)
.discountAmt(paymentDiscountAmt)
.invoiceId(InvoiceId.ofRepoId(invoice.getC_Invoice_ID()))
.invoiceBPartnerId(BPartnerId.ofRepoId(invoice.getC_BPartner_ID()))
.orgId(remittanceAdvice.getOrgId())
.clientId(remittanceAdvice.getClientId())
.bPartnerId(remittanceAdviceSOTrx.isSales() ? remittanceAdvice.getSourceBPartnerId() : remittanceAdvice.getDestinationBPartnerId())
.documentNo(invoice.getDocumentNo())
.soTrx(remittanceAdviceSOTrx)
.dateInvoiced(TimeUtil.asLocalDate(invoice.getDateInvoiced(), timeZone))
.build();
}
@NonNull
private List<I_C_InvoiceLine> getInvoiceLines(final InvoiceId invoiceId)
{
return invoiceDAO.retrieveLines(invoiceId)
.stream()
.map(invoiceLine -> InterfaceWrapperHelper.create(invoiceLine, I_C_InvoiceLine.class))
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\service\RemittanceAdviceBankingService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public AbstractSaml2AuthenticationRequest loadAuthenticationRequest(HttpServletRequest request) {
HttpSession httpSession = request.getSession(false);
if (httpSession == null) {
return null;
}
return (AbstractSaml2AuthenticationRequest) httpSession.getAttribute(this.saml2AuthnRequestAttributeName);
}
@Override
public void saveAuthenticationRequest(AbstractSaml2AuthenticationRequest authenticationRequest,
HttpServletRequest request, HttpServletResponse response) {
if (authenticationRequest == null) {
removeAuthenticationRequest(request, response);
return;
}
HttpSession httpSession = request.getSession();
httpSession.setAttribute(this.saml2AuthnRequestAttributeName, authenticationRequest); | }
@Override
public AbstractSaml2AuthenticationRequest removeAuthenticationRequest(HttpServletRequest request,
HttpServletResponse response) {
AbstractSaml2AuthenticationRequest authenticationRequest = loadAuthenticationRequest(request);
if (authenticationRequest == null) {
return null;
}
HttpSession httpSession = request.getSession();
httpSession.removeAttribute(this.saml2AuthnRequestAttributeName);
return authenticationRequest;
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\HttpSessionSaml2AuthenticationRequestRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ClearHURouteBuilder extends RouteBuilder
{
public static final String CLEAR_HU_ROUTE_ID = "GRSSignum-clearHU";
public static final String CLEAR_HU_PROCESSOR_ID = "GRSSignum-clearHUProcessorID";
@Override
public void configure()
{
errorHandler(defaultErrorHandler());
onException(Exception.class)
.to(direct(MF_ERROR_ROUTE_ID));
from(direct(CLEAR_HU_ROUTE_ID))
.routeId(CLEAR_HU_ROUTE_ID)
.log("Route invoked!")
.unmarshal(setupJacksonDataFormatFor(getContext(), JsonHUClear.class))
.process(this::getAndAttachClearanceStatusRequest).id(CLEAR_HU_PROCESSOR_ID)
.to(direct(MF_CLEAR_HU_V2_CAMEL_ROUTE_ID));
}
private void getAndAttachClearanceStatusRequest(@NonNull final Exchange exchange)
{
final JsonHUClear requestBody = exchange.getIn().getBody(JsonHUClear.class);
final JsonMetasfreshId metasfreshId = JsonMetasfreshId.of(Integer.parseInt(requestBody.getMetasfreshId()));
final JsonSetClearanceStatusRequest clearanceStatusRequest = JsonSetClearanceStatusRequest.builder()
.huIdentifier(JsonSetClearanceStatusRequest.JsonHUIdentifier.ofJsonMetasfreshId(metasfreshId))
.clearanceStatus(toJsonClearanceStatus(requestBody.getClearanceStatus()))
.clearanceNote(requestBody.getClearanceNote()) | .build();
exchange.getIn().setBody(clearanceStatusRequest, JsonSetClearanceStatusRequest.class);
}
@NonNull
private static JsonClearanceStatus toJsonClearanceStatus(@NonNull final String status)
{
try
{
return JsonClearanceStatus.valueOf(status);
}
catch (final Exception e)
{
throw new RuntimeCamelException("Unknown status " + status + ". Clearance status needs to be value of JsonClearanceStatus.");
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\hu\ClearHURouteBuilder.java | 2 |
请完成以下Java代码 | public static int getC_BPartner_ID(final String uuid)
{
return UUIDs.toId(uuid);
}
public static String toUUIDString(final I_AD_User contact)
{
return UUIDs.fromIdAsString(contact.getAD_User_ID());
}
public static UserId getUserId(@NonNull final String uuid)
{
return UserId.ofRepoId(UUIDs.toId(uuid));
}
public static String toUUIDString(final I_PMM_Product pmmProduct)
{
return UUIDs.fromIdAsString(pmmProduct.getPMM_Product_ID());
}
public static int getPMM_Product_ID(final String uuid)
{
return UUIDs.toId(uuid);
} | public static String toUUIDString(final I_C_Flatrate_Term contract)
{
return UUIDs.fromIdAsString(contract.getC_Flatrate_Term_ID());
}
public static int getC_Flatrate_Term_ID(final String uuid)
{
return UUIDs.toId(uuid);
}
public static String toUUIDString(final I_C_RfQResponseLine rfqResponseLine)
{
return toC_RfQReponseLine_UUID(rfqResponseLine.getC_RfQResponseLine_ID());
}
public static String toC_RfQReponseLine_UUID(final int C_RfQResponseLine_ID)
{
return UUIDs.fromIdAsString(C_RfQResponseLine_ID);
}
public static int getC_RfQResponseLine_ID(final String uuid)
{
return UUIDs.toId(uuid);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\SyncUUIDs.java | 1 |
请完成以下Java代码 | public java.lang.String getRequestReason ()
{
return (java.lang.String)get_Value(COLUMNNAME_RequestReason);
}
/** Set REST API URL.
@param RestApiBaseURL REST API URL */
@Override
public void setRestApiBaseURL (java.lang.String RestApiBaseURL)
{
set_Value (COLUMNNAME_RestApiBaseURL, RestApiBaseURL);
}
/** Get REST API URL.
@return REST API URL */
@Override
public java.lang.String getRestApiBaseURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_RestApiBaseURL);
}
/** Set Creditpass-Prüfung wiederholen .
@param RetryAfterDays Creditpass-Prüfung wiederholen */
@Override
public void setRetryAfterDays (java.math.BigDecimal RetryAfterDays)
{
set_Value (COLUMNNAME_RetryAfterDays, RetryAfterDays);
}
/** Get Creditpass-Prüfung wiederholen .
@return Creditpass-Prüfung wiederholen */
@Override
public java.math.BigDecimal getRetryAfterDays () | {
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RetryAfterDays);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set 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));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_Config.java | 1 |
请完成以下Java代码 | public Void execute(CommandContext commandContext) {
ensureNotEmpty(BadUserRequestException.class,"processInstanceIds", processInstanceIds);
ensureNotContainsNull(BadUserRequestException.class, "processInstanceId is null", "processInstanceIds", processInstanceIds);
// Check if process instance is still running
List<HistoricProcessInstance> instances = commandContext.runWithoutAuthorization(new Callable<List<HistoricProcessInstance>>() {
@Override
public List<HistoricProcessInstance> call() throws Exception {
return new HistoricProcessInstanceQueryImpl().processInstanceIds(new HashSet<String>(processInstanceIds)).list();
}
});
if (failIfNotExists) {
if (processInstanceIds.size() == 1) {
ensureNotEmpty(BadUserRequestException.class, "No historic process instance found with id: " + processInstanceIds.get(0), "historicProcessInstanceIds",
instances);
} else {
ensureNotEmpty(BadUserRequestException.class, "No historic process instances found", "historicProcessInstanceIds", instances);
}
}
List<String> existingIds = new ArrayList<String>();
for (HistoricProcessInstance historicProcessInstance : instances) {
existingIds.add(historicProcessInstance.getId());
for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkDeleteHistoricProcessInstance(historicProcessInstance);
}
ensureNotNull(BadUserRequestException.class, "Process instance is still running, cannot delete historic process instance: " + historicProcessInstance, "instance.getEndTime()", historicProcessInstance.getEndTime());
} | if(failIfNotExists) {
ArrayList<String> nonExistingIds = new ArrayList<String>(processInstanceIds);
nonExistingIds.removeAll(existingIds);
if(nonExistingIds.size() != 0) {
throw new BadUserRequestException("No historic process instance found with id: " + nonExistingIds);
}
}
if(existingIds.size() > 0) {
commandContext.getHistoricProcessInstanceManager().deleteHistoricProcessInstanceByIds(existingIds);
}
writeUserOperationLog(commandContext, existingIds.size());
return null;
}
protected void writeUserOperationLog(CommandContext commandContext, int numInstances) {
List<PropertyChange> propertyChanges = new ArrayList<>();
propertyChanges.add(new PropertyChange("nrOfInstances", null, numInstances));
propertyChanges.add(new PropertyChange("async", null, false));
commandContext.getOperationLogManager()
.logProcessInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE_HISTORY,
null,
null,
null,
propertyChanges);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteHistoricProcessInstancesCmd.java | 1 |
请完成以下Java代码 | public String mset(final HashMap<String, String> keysValues) {
try (Jedis jedis = jedisPool.getResource()) {
ArrayList<String> keysValuesArrayList = new ArrayList<>();
keysValues.forEach((key, value) -> {
keysValuesArrayList.add(key);
keysValuesArrayList.add(value);
});
return jedis.mset((keysValuesArrayList.toArray(new String[keysValues.size()])));
} catch (Exception ex) {
log.error("Exception caught in mset", ex);
}
return null;
}
public Set<String> keys(final String pattern) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.keys(pattern);
} catch (Exception ex) {
log.error("Exception caught in keys", ex);
}
return new HashSet<String>();
}
public RedisIterator iterator(int initialScanCount, String pattern, ScanStrategy strategy) { | return new RedisIterator(jedisPool, initialScanCount, pattern, strategy);
}
public void flushAll() {
try (Jedis jedis = jedisPool.getResource()) {
jedis.flushAll();
} catch (Exception ex) {
log.error("Exception caught in flushAll", ex);
}
}
public void destroyInstance() {
jedisPool = null;
instance = null;
}
} | repos\tutorials-master\persistence-modules\redis\src\main\java\com\baeldung\redis_scan\client\RedisClient.java | 1 |
请完成以下Java代码 | private void processMetadataChanges(PO po, int type)
{
final I_AD_Table_MView mview = InterfaceWrapperHelper.create(po, I_AD_Table_MView.class);
if (TYPE_AFTER_NEW == type
|| (TYPE_AFTER_CHANGE == type && po.is_ValueChanged(I_AD_Table_MView.COLUMNNAME_IsValid) && mview.isValid()))
{
addMView(mview, false);
}
}
private void refreshFromSource(PO sourcePO, int changeType)
{
final String sourceTableName = sourcePO.get_TableName();
final ITableMViewBL mviewBL = Services.get(ITableMViewBL.class);
for (I_AD_Table_MView mview : mviewBL.fetchAll(Env.getCtx()))
{
MViewMetadata mdata = mviewBL.getMetadata(mview);
if (mdata == null)
{
mview.setIsValid(false);
InterfaceWrapperHelper.save(mview);
log.info("No metadata found for " + mview + " [SKIP]");
continue;
}
if (!mdata.getSourceTables().contains(sourceTableName))
{
// not relevant PO for this MView
continue;
}
if (!mviewBL.isSourceChanged(mdata, sourcePO, changeType))
{
// no relevant changes for this view
continue;
}
refreshFromSource(mdata, sourcePO, new RefreshMode[] { RefreshMode.Partial });
}
}
public void refreshFromSource(MViewMetadata mdata, PO sourcePO, RefreshMode[] refreshModes)
{
final ITableMViewBL mviewBL = Services.get(ITableMViewBL.class);
final I_AD_Table_MView mview = mviewBL.fetchForTableName(sourcePO.getCtx(), mdata.getTargetTableName(), sourcePO.get_TrxName());
boolean staled = true;
for (RefreshMode refreshMode : refreshModes)
{
if (mviewBL.isAllowRefresh(mview, sourcePO, refreshMode))
{
mviewBL.refresh(mview, sourcePO, refreshMode, sourcePO.get_TrxName());
staled = false;
break;
}
}
//
// We should do a complete refresh => marking mview as staled
if (staled)
{
mviewBL.setStaled(mview);
}
} | private boolean addMView(I_AD_Table_MView mview, boolean invalidateIfNecessary)
{
final ITableMViewBL mviewBL = Services.get(ITableMViewBL.class);
MViewMetadata mdata = mviewBL.getMetadata(mview);
if (mdata == null)
{
// no metadata found => IGNORE
if (invalidateIfNecessary)
{
mview.setIsValid(false);
InterfaceWrapperHelper.save(mview);
}
return false;
}
for (String sourceTableName : mdata.getSourceTables())
{
engine.addModelChange(sourceTableName, this);
}
registeredTables.add(mview.getAD_Table_ID());
return true;
}
@Override
public String docValidate(PO po, int timing)
{
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\engine\MViewModelValidator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExecutionRestServiceImpl extends AbstractRestProcessEngineAware implements ExecutionRestService {
public ExecutionRestServiceImpl(String engineName, ObjectMapper objectMapper) {
super(engineName, objectMapper);
}
@Override
public ExecutionResource getExecution(String executionId) {
return new ExecutionResourceImpl(getProcessEngine(), executionId, getObjectMapper());
}
@Override
public List<ExecutionDto> getExecutions(UriInfo uriInfo, Integer firstResult,
Integer maxResults) {
ExecutionQueryDto queryDto = new ExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryExecutions(queryDto, firstResult, maxResults);
}
@Override
public List<ExecutionDto> queryExecutions(
ExecutionQueryDto queryDto, Integer firstResult, Integer maxResults) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
ExecutionQuery query = queryDto.toQuery(engine);
List<Execution> matchingExecutions = QueryUtil.list(query, firstResult, maxResults);
List<ExecutionDto> executionResults = new ArrayList<ExecutionDto>();
for (Execution execution : matchingExecutions) {
ExecutionDto resultExecution = ExecutionDto.fromExecution(execution);
executionResults.add(resultExecution);
}
return executionResults;
} | @Override
public CountResultDto getExecutionsCount(UriInfo uriInfo) {
ExecutionQueryDto queryDto = new ExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryExecutionsCount(queryDto);
}
@Override
public CountResultDto queryExecutionsCount(ExecutionQueryDto queryDto) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
ExecutionQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\ExecutionRestServiceImpl.java | 2 |
请完成以下Java代码 | public void setPromotionName(String promotionName) {
this.promotionName = promotionName;
}
public BigDecimal getPromotionAmount() {
return promotionAmount;
}
public void setPromotionAmount(BigDecimal promotionAmount) {
this.promotionAmount = promotionAmount;
}
public BigDecimal getCouponAmount() {
return couponAmount;
}
public void setCouponAmount(BigDecimal couponAmount) {
this.couponAmount = couponAmount;
}
public BigDecimal getIntegrationAmount() {
return integrationAmount;
}
public void setIntegrationAmount(BigDecimal integrationAmount) {
this.integrationAmount = integrationAmount;
}
public BigDecimal getRealAmount() {
return realAmount;
}
public void setRealAmount(BigDecimal realAmount) {
this.realAmount = realAmount;
}
public Integer getGiftIntegration() {
return giftIntegration;
}
public void setGiftIntegration(Integer giftIntegration) {
this.giftIntegration = giftIntegration;
}
public Integer getGiftGrowth() {
return giftGrowth;
}
public void setGiftGrowth(Integer giftGrowth) {
this.giftGrowth = giftGrowth;
}
public String getProductAttr() {
return productAttr;
}
public void setProductAttr(String productAttr) {
this.productAttr = productAttr;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(); | sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", orderId=").append(orderId);
sb.append(", orderSn=").append(orderSn);
sb.append(", productId=").append(productId);
sb.append(", productPic=").append(productPic);
sb.append(", productName=").append(productName);
sb.append(", productBrand=").append(productBrand);
sb.append(", productSn=").append(productSn);
sb.append(", productPrice=").append(productPrice);
sb.append(", productQuantity=").append(productQuantity);
sb.append(", productSkuId=").append(productSkuId);
sb.append(", productSkuCode=").append(productSkuCode);
sb.append(", productCategoryId=").append(productCategoryId);
sb.append(", promotionName=").append(promotionName);
sb.append(", promotionAmount=").append(promotionAmount);
sb.append(", couponAmount=").append(couponAmount);
sb.append(", integrationAmount=").append(integrationAmount);
sb.append(", realAmount=").append(realAmount);
sb.append(", giftIntegration=").append(giftIntegration);
sb.append(", giftGrowth=").append(giftGrowth);
sb.append(", productAttr=").append(productAttr);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderItem.java | 1 |
请完成以下Java代码 | private IFileRef downloadUrl(final URL url)
{
logger.info("Downloading {}......", url);
Stopwatch stopwatch = Stopwatch.createStarted();
final File file = FileUtils.downloadUrl(url);
final FileRef fileRef = new FileRef(file);
stopwatch.stop();
logger.info("Downloaded {} in {}.", url, stopwatch);
return fileRef;
}
private static String stripQuotes(final String rolloutDir)
{
if (rolloutDir == null)
{
return null;
}
return rolloutDir
.replaceAll("^\"|\"$", "")
.replaceAll("^'|'$", "");
}
public final void printHelp(final PrintStream out)
{
final PrintWriter writer = new PrintWriter(out);
final String commandName = "RolloutMigrate";
final String header = "Util to apply metasfresh migration scripts to a POstgresSQL database. The database settings are read from a settings (properties) file.\n"
+ "The tool will by default only run if its own version (as set in in the " + RolloutVersionLoader.PROP_VERSION + " property of its " + RolloutVersionLoader.BUILD_INFO_FILENAME + ")"
+ " is higher than the version selected from the DB (AD_System.DBVersion).";
final String footer = "\nHints: "
+ "* For each individual migration file the tool checks against the Table AD_MigrationScript if the migration file was already been applied"
+ "* The migration files are ordered by their filenames \"globally\", no matter in thich directory they are";
final HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(
writer, // output
200, // width, | stripQuotes(commandName), // cmdLineSyntax
stripQuotes(header), // header,
options, // options
4, // leftPad,
4, // descPad,
stripQuotes(footer), // footer,
true // autoUsage
);
writer.flush();
}
public final String printHelpToString()
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream out = new PrintStream(baos);
printHelp(out);
final String content = baos.toString();
return stripQuotes(content);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\CommandlineParams.java | 1 |
请完成以下Java代码 | private AdIssueId createAdIssueId(final Throwable ex)
{
return errorManager.createIssue(IssueCreateRequest.builder()
.throwable(ex)
.loggerName(logger.getName())
.sourceClassname(ManufacturingOrderAPIService.class.getName())
.summary(ex.getMessage())
.build());
}
private List<I_PP_Order_BOMLine> getBOMLinesByOrderId(final PPOrderId orderId)
{
return getBOMLinesByOrderId().get(orderId);
}
private ImmutableListMultimap<PPOrderId, I_PP_Order_BOMLine> getBOMLinesByOrderId()
{
if (_bomLinesByOrderId != null)
{
return _bomLinesByOrderId;
}
final ImmutableSet<PPOrderId> orderIds = getOrders()
.stream()
.map(order -> PPOrderId.ofRepoId(order.getPP_Order_ID()))
.collect(ImmutableSet.toImmutableSet());
_bomLinesByOrderId = ppOrderBOMDAO.retrieveOrderBOMLines(orderIds, I_PP_Order_BOMLine.class)
.stream()
.collect(ImmutableListMultimap.toImmutableListMultimap(
bomLine -> PPOrderId.ofRepoId(bomLine.getPP_Order_ID()),
bomLine -> bomLine));
return _bomLinesByOrderId;
} | private Product getProductById(@NonNull final ProductId productId)
{
if (_productsById == null)
{
final HashSet<ProductId> allProductIds = new HashSet<>();
allProductIds.add(productId);
getOrders().stream()
.map(order -> ProductId.ofRepoId(order.getM_Product_ID()))
.forEach(allProductIds::add);
getBOMLinesByOrderId()
.values()
.stream()
.map(bomLine -> ProductId.ofRepoId(bomLine.getM_Product_ID()))
.forEach(allProductIds::add);
_productsById = productRepo.getByIds(allProductIds)
.stream()
.collect(GuavaCollectors.toHashMapByKey(Product::getId));
}
return _productsById.computeIfAbsent(productId, productRepo::getById);
}
private List<I_PP_Order> getOrders()
{
if (_orders == null)
{
_orders = ppOrderDAO.retrieveManufacturingOrders(query);
}
return _orders;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\v1\ManufacturingOrdersExportCommand.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BootGeodeSecurityClientApplication {
private static final Logger logger = LoggerFactory.getLogger("example.app.security");
public static void main(String[] args) {
new SpringApplicationBuilder(BootGeodeSecurityClientApplication.class)
.web(WebApplicationType.SERVLET)
.build()
.run(args);
}
// tag::runner[]
@Bean
ApplicationRunner runner(@Qualifier("customersTemplate") GemfireTemplate customersTemplate) {
return args -> {
Customer williamEvans = Customer.newCustomer(2L, "William Evans");
customersTemplate.put(williamEvans.getId(), williamEvans); | logger.info("Successfully put [{}] in Region [{}]",
williamEvans, customersTemplate.getRegion().getName());
try {
logger.info("Attempting to read from Region [{}]...", customersTemplate.getRegion().getName());
customersTemplate.get(2L);
}
catch (Exception cause) {
logger.info("Read failed because \"{}\"", cause.getCause().getCause().getMessage());
}
};
}
// end::runner[]
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\boot\security\src\main\java\example\app\security\client\BootGeodeSecurityClientApplication.java | 2 |
请完成以下Java代码 | public void disable() {
DisableCaseExecutionCmd command = new DisableCaseExecutionCmd(this);
executeCommand(command);
}
public void reenable() {
ReenableCaseExecutionCmd command = new ReenableCaseExecutionCmd(this);
executeCommand(command);
}
public void complete() {
CompleteCaseExecutionCmd command = new CompleteCaseExecutionCmd(this);
executeCommand(command);
}
public void close() {
CloseCaseInstanceCmd command = new CloseCaseInstanceCmd(this);
executeCommand(command);
}
public void terminate() {
TerminateCaseExecutionCmd command = new TerminateCaseExecutionCmd(this);
executeCommand(command);
}
protected void executeCommand(Command<?> command) {
try {
if(commandExecutor != null) {
commandExecutor.execute(command);
} else {
command.execute(commandContext);
}
} catch (NullValueException e) {
throw new NotValidException(e.getMessage(), e);
} catch (CaseExecutionNotFoundException e) { | throw new NotFoundException(e.getMessage(), e);
} catch (CaseDefinitionNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
} catch (CaseIllegalStateTransitionException e) {
throw new NotAllowedException(e.getMessage(), e);
}
}
// getters ////////////////////////////////////////////////////////////////////////////////
public String getCaseExecutionId() {
return caseExecutionId;
}
public VariableMap getVariables() {
return variables;
}
public VariableMap getVariablesLocal() {
return variablesLocal;
}
public Collection<String> getVariableDeletions() {
return variableDeletions;
}
public Collection<String> getVariableLocalDeletions() {
return variableLocalDeletions;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\CaseExecutionCommandBuilderImpl.java | 1 |
请完成以下Java代码 | public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModified() {
return gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
this.resourceCode = resource.hashCode();
}
public Long getPassQps() {
return passQps;
}
public void setPassQps(Long passQps) {
this.passQps = passQps;
}
public Long getBlockQps() {
return blockQps;
}
public void setBlockQps(Long blockQps) {
this.blockQps = blockQps;
}
public Long getExceptionQps() { | return exceptionQps;
}
public void setExceptionQps(Long exceptionQps) {
this.exceptionQps = exceptionQps;
}
public double getRt() {
return rt;
}
public void setRt(double rt) {
this.rt = rt;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getResourceCode() {
return resourceCode;
}
public Long getSuccessQps() {
return successQps;
}
public void setSuccessQps(Long successQps) {
this.successQps = successQps;
}
@Override
public String toString() {
return "MetricEntity{" +
"id=" + id +
", gmtCreate=" + gmtCreate +
", gmtModified=" + gmtModified +
", app='" + app + '\'' +
", timestamp=" + timestamp +
", resource='" + resource + '\'' +
", passQps=" + passQps +
", blockQps=" + blockQps +
", successQps=" + successQps +
", exceptionQps=" + exceptionQps +
", rt=" + rt +
", count=" + count +
", resourceCode=" + resourceCode +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MetricEntity.java | 1 |
请完成以下Java代码 | public X_C_DirectDebitLine[] getLines() {
X_C_DirectDebitLine[] retValue = null;
String sql = "SELECT C_DirectDebitLine_ID FROM C_DirectDebitLine WHERE C_DirectDebit_ID = ? ";
PreparedStatement pstmt = null;
try {
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, this.get_ID());
ResultSet rs = pstmt.executeQuery();
List<Integer> a = new ArrayList<Integer>();
while (rs.next()) {
a.add(rs.getInt(1));
}
retValue = new X_C_DirectDebitLine[a.size()];
int count = 0;
for (int i : a) {
retValue[count] = new X_C_DirectDebitLine(Env.getCtx(), i, null);
count++;
}
rs.close();
pstmt.close();
pstmt = null; | } catch (Exception e) {
e.printStackTrace();
}
try {
if (pstmt != null) {
pstmt.close();
}
pstmt = null;
} catch (Exception e) {
pstmt = null;
}
return retValue;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\model\MDirectDebit.java | 1 |
请完成以下Java代码 | public static class LogFormatter extends Formatter {
public String format(LogRecord record) {
StringBuilder line = new StringBuilder();
line.append(dateFormat.format(new Date()));
if (Level.FINE.equals(record.getLevel())) {
line.append(" FIN ");
} else if (Level.FINEST.equals(record.getLevel())) {
line.append(" FST ");
} else if (Level.INFO.equals(record.getLevel())) {
line.append(" INF ");
} else if (Level.SEVERE.equals(record.getLevel())) {
line.append(" SEV ");
} else if (Level.WARNING.equals(record.getLevel())) {
line.append(" WRN ");
} else if (Level.FINER.equals(record.getLevel())) {
line.append(" FNR ");
} else if (Level.CONFIG.equals(record.getLevel())) {
line.append(" CFG ");
}
int threadId = record.getThreadID();
String threadIndent = getThreadIndent(threadId);
line.append(threadIndent);
line.append(" | ");
line.append(record.getMessage());
if (record.getThrown() != null) {
line.append(LINE_SEPARATOR);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
record.getThrown().printStackTrace(printWriter);
line.append(stringWriter.toString());
}
line.append(" [");
line.append(record.getLoggerName());
line.append("]");
line.append(LINE_SEPARATOR);
return line.toString();
}
protected static String getThreadIndent(int threadId) { | Integer threadIdInteger = threadId;
if (threadLogMode==ThreadLogMode.NONE) {
return "";
}
if (threadLogMode==ThreadLogMode.PRINT_ID) {
return ""+threadId;
}
String threadIndent = threadIndents.get(threadIdInteger);
if (threadIndent == null) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < threadIndents.size(); i++) {
stringBuilder.append(" ");
}
threadIndent = stringBuilder.toString();
threadIndents.put(threadIdInteger, threadIndent);
}
return threadIndent;
}
}
public static void resetThreadIndents() {
threadIndents = new HashMap<>();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\LogUtil.java | 1 |
请完成以下Java代码 | private static final ViewActionMethodArgumentExtractor createViewActionMethodArgumentExtractor(final String parameterName, final Class<?> parameterType, final ViewActionParam annotation)
{
if (annotation != null)
{
return (view, processParameters, selectedDocumentIds) -> processParameters.getFieldView(parameterName).getValueAs(parameterType);
}
//
// selectedDocumentIds internal parameter
else if (DocumentIdsSelection.class.isAssignableFrom(parameterType))
{
return (view, processParameters, selectedDocumentIds) -> selectedDocumentIds;
}
//
// View parameter
else if (IView.class.isAssignableFrom(parameterType))
{
return (view, processParameters, selectedDocumentIds) -> view;
}
//
// Primitive type => not supported
else if (parameterType.isPrimitive())
{
throw new IllegalArgumentException("Action method's primitive parameter " + parameterType + " is not supported for parameterName: " + parameterName);
}
//
// Try getting the bean from spring context
else
{
return (view, processParameters, selectedDocumentIds) -> Adempiere.getBean(parameterType);
}
}
/** Helper class used to generate unique actionIds based on annotated method name */
private static final class ActionIdGenerator
{
private final Map<String, MutableInt> methodName2counter = new HashMap<>();
public String getActionId(final Method actionMethod)
{
final String methodName = actionMethod.getName(); | final MutableInt counter = methodName2counter.computeIfAbsent(methodName, k -> new MutableInt(0));
final int methodNameSuffix = counter.incrementAndGet();
if (methodNameSuffix == 1)
{
return methodName;
}
else if (methodNameSuffix > 1)
{
return methodName + methodNameSuffix;
}
else
{
// shall NEVER happen
throw new IllegalStateException("internal error: methodNameSuffix <= 0");
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\view\ViewActionDescriptorsFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserDTO implements Serializable {
/**
* 用户编号
*/
private Integer id;
/**
* 昵称
*/
private String name;
/**
* 性别
*/
private Integer gender;
public Integer getId() {
return id;
}
public UserDTO setId(Integer id) {
this.id = id; | return this;
}
public String getName() {
return name;
}
public UserDTO setName(String name) {
this.name = name;
return this;
}
public Integer getGender() {
return gender;
}
public UserDTO setGender(Integer gender) {
this.gender = gender;
return this;
}
} | repos\SpringBoot-Labs-master\lab-30\lab-30-dubbo-annotations-demo\user-rpc-service-api-02\src\main\java\cn\iocoder\springboot\lab30\rpc\dto\UserDTO.java | 2 |
请完成以下Java代码 | public int hashCode() {
return Objects.hash(
businessKey,
entity,
id,
parentProcessInstanceId,
processDefinitionId,
processDefinitionKey,
processDefinitionVersion,
processInstanceId,
timestamp,
getEventType()
);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) { | return false;
}
if (getClass() != obj.getClass()) {
return false;
}
RuntimeEventImpl other = (RuntimeEventImpl) obj;
return (
Objects.equals(businessKey, other.businessKey) &&
Objects.equals(entity, other.entity) &&
Objects.equals(id, other.id) &&
Objects.equals(parentProcessInstanceId, other.parentProcessInstanceId) &&
Objects.equals(processDefinitionId, other.processDefinitionId) &&
Objects.equals(processDefinitionKey, other.processDefinitionKey) &&
Objects.equals(processDefinitionVersion, other.processDefinitionVersion) &&
Objects.equals(processInstanceId, other.processInstanceId) &&
Objects.equals(timestamp, other.timestamp)
);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-model-shared-impl\src\main\java\org\activiti\api\runtime\event\impl\RuntimeEventImpl.java | 1 |
请完成以下Java代码 | public void setTaxBaseAmt(final BigDecimal taxBaseAmt)
{
if (isAccountSignDR())
{
glJournalLine.setDR_TaxBaseAmt(taxBaseAmt);
}
else
{
glJournalLine.setCR_TaxBaseAmt(taxBaseAmt);
}
}
@Override
public BigDecimal getTaxTotalAmt()
{
return isAccountSignDR() ? glJournalLine.getDR_TaxTotalAmt() : glJournalLine.getCR_TaxTotalAmt();
}
@Override
public void setTaxTotalAmt(final BigDecimal totalAmt)
{
if (isAccountSignDR())
{
glJournalLine.setDR_TaxTotalAmt(totalAmt);
}
else
{
glJournalLine.setCR_TaxTotalAmt(totalAmt);
}
//
// Update AmtSourceDr/Cr
// NOTE: we are updating both sides because they shall be the SAME
glJournalLine.setAmtSourceDr(totalAmt);
glJournalLine.setAmtSourceCr(totalAmt);
}
@Override
public I_C_ValidCombination getTaxBase_Acct() | {
return isAccountSignDR() ? glJournalLine.getAccount_DR() : glJournalLine.getAccount_CR();
}
@Override
public I_C_ValidCombination getTaxTotal_Acct()
{
return isAccountSignDR() ? glJournalLine.getAccount_CR() : glJournalLine.getAccount_DR();
}
@Override
public CurrencyPrecision getPrecision()
{
final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(glJournalLine.getC_Currency_ID());
return currencyId != null
? Services.get(ICurrencyDAO.class).getStdPrecision(currencyId)
: CurrencyPrecision.TWO;
}
@Override
public AcctSchemaId getAcctSchemaId()
{
return AcctSchemaId.ofRepoId(glJournalLine.getGL_Journal().getC_AcctSchema_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal\impl\GLJournalLineTaxAccountable.java | 1 |
请完成以下Java代码 | public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return this.matcher.matches(exchange)
.filter(ServerWebExchangeMatcher.MatchResult::isMatch)
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.flatMap((matchResult) -> sendContent(exchange));
}
private Mono<Void> sendContent(ServerWebExchange exchange) {
exchange.getResponse().setStatusCode(HttpStatus.OK);
ResourceHttpMessageWriter writer = new ResourceHttpMessageWriter();
return writer.write(Mono.just(this.resource), ResolvableType.forClass(Resource.class),
ResolvableType.forClass(Resource.class), this.mediaType, exchange.getRequest(), exchange.getResponse(),
Collections.emptyMap());
}
@Override
public String toString() {
return "%s{matcher=%s, resource='%s'}".formatted(getClass().getSimpleName(), this.matcher,
this.resource.getPath());
}
/**
* Create an instance of {@link DefaultResourcesWebFilter} serving Spring Security's
* default CSS stylesheet. | * <p>
* The created {@link DefaultResourcesFilter} matches requests
* {@code HTTP GET /default-ui.css}, and returns the default stylesheet at
* {@code org/springframework/security/default-ui.css} with content-type
* {@code text/css;charset=UTF-8}.
* @return -
*/
public static DefaultResourcesWebFilter css() {
return new DefaultResourcesWebFilter(
new PathPatternParserServerWebExchangeMatcher("/default-ui.css", HttpMethod.GET),
new ClassPathResource("org/springframework/security/default-ui.css"),
new MediaType("text", "css", StandardCharsets.UTF_8));
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\ui\DefaultResourcesWebFilter.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.