instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public void delete() {
if (commandExecutor != null) {
commandExecutor.execute(context -> {
executeDelete(context);
return null;
});
} else {
executeDelete(Context.getCommandContext());
}
}
protected void executeDelete(CommandContext commandContext) {
batchServiceConfiguration.getBatchEntityManager().deleteBatches(this);
}
@Override
@Deprecated
public void deleteWithRelatedData() {
delete();
}
// getters //////////////////////////////////////////
@Override
public String getId() {
return id;
}
public String getBatchType() {
return batchType;
}
public Collection<String> getBatchTypes() {
return batchTypes;
}
public String getSearchKey() {
return searchKey;
}
|
public String getSearchKey2() {
return searchKey2;
}
public Date getCreateTimeHigherThan() {
return createTimeHigherThan;
}
public Date getCreateTimeLowerThan() {
return createTimeLowerThan;
}
public String getStatus() {
return status;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchQueryImpl.java
| 2
|
请完成以下Java代码
|
public boolean isProcessed()
{
return false;
}
@Override
public DocumentPath getDocumentPath()
{
return documentPath;
}
public TableRecordReference getTableRecordReference()
{
return createTableRecordReferenceFromShipmentScheduleId(getShipmentScheduleId());
}
@Override
public ImmutableSet<String> getFieldNames()
{
return values.getFieldNames();
}
@Override
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return values.get(this);
}
@Override
public List<? extends IViewRow> getIncludedRows()
{
return ImmutableList.of();
}
@Override
public boolean hasAttributes()
{
return false;
}
@Override
public IViewRowAttributes getAttributes() throws EntityNotFoundException
{
throw new EntityNotFoundException("Row does not support attributes");
|
}
@Override
public ViewId getIncludedViewId()
{
return includedViewId;
}
public ShipmentScheduleId getShipmentScheduleId()
{
return shipmentScheduleId;
}
public Optional<OrderLineId> getSalesOrderLineId()
{
return salesOrderLineId;
}
public ProductId getProductId()
{
return product != null ? ProductId.ofRepoIdOrNull(product.getIdAsInt()) : null;
}
public Quantity getQtyOrderedWithoutPicked()
{
return qtyOrdered.subtract(qtyPicked).toZeroIfNegative();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\PackageableRow.java
| 1
|
请完成以下Java代码
|
static class OnPropertyEnabled {
}
@ConditionalOnPropertyExists
static class OnTrustedProxiesNotEmpty {
}
}
class XForwardedTrustedProxiesCondition extends AllNestedConditions {
public XForwardedTrustedProxiesCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(name = GatewayProperties.PREFIX + ".x-forwarded.enabled", matchIfMissing = true)
static class OnPropertyEnabled {
}
@ConditionalOnPropertyExists
static class OnTrustedProxiesNotEmpty {
}
}
class OnPropertyExistsCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
|
try {
String property = context.getEnvironment().getProperty(PROPERTY);
if (!StringUtils.hasText(property)) {
return ConditionOutcome.noMatch(PROPERTY + " property is not set or is empty.");
}
return ConditionOutcome.match(PROPERTY + " property is not empty.");
}
catch (NoSuchElementException e) {
return ConditionOutcome.noMatch("Missing required property 'value' of @ConditionalOnPropertyExists");
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyExistsCondition.class)
@interface ConditionalOnPropertyExists {
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\TrustedProxies.java
| 1
|
请完成以下Java代码
|
private LULoaderInstance createLULoaderInstanceForTU(final I_M_HU tuHU)
{
final BPartnerId bpartnerId = IHandlingUnitsBL.extractBPartnerIdOrNull(tuHU);
final int bpartnerLocationId = tuHU.getC_BPartner_Location_ID();
final LocatorId locatorId = warehousesRepo.getLocatorIdByRepoIdOrNull(tuHU.getM_Locator_ID());
final String huStatus = tuHU.getHUStatus();
final I_M_HU_PI_Version tuPIVersion = Services.get(IHandlingUnitsBL.class).getPIVersion(tuHU);
final ClearanceStatusInfo clearanceStatusInfo = ClearanceStatusInfo.ofHU(tuHU);
final LULoaderInstance luInstance = new LULoaderInstance(huContext, bpartnerId, bpartnerLocationId, locatorId, huStatus, tuPIVersion, clearanceStatusInfo);
luInstances.add(luInstance);
return luInstance;
}
/**
* Gets created Loading Units (LUs)
*
* @return created loading units
*/
public List<I_M_HU> getLU_HUs()
{
if (luInstances.isEmpty())
|
{
return Collections.emptyList();
}
final List<I_M_HU> luHUs = new ArrayList<>(luInstances.size());
for (final LULoaderInstance luInstance : luInstances)
{
final I_M_HU luHU = luInstance.getLU_HU();
luHUs.add(luHU);
}
return luHUs;
}
public void close()
{
luInstances.forEach(LULoaderInstance::close);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\LULoader.java
| 1
|
请完成以下Java代码
|
default BigDecimal getWeightTareTotal()
{
BigDecimal weightTareTotal = BigDecimal.ZERO;
if (hasWeightTare())
{
final BigDecimal weightTare = getWeightTare();
weightTareTotal = weightTareTotal.add(weightTare);
}
// 07023_Tara_changeable_in_LU
// We have to also check if there is any tare adjust
if (hasWeightTareAdjust())
{
final BigDecimal weightTareAdjust = getWeightTareAdjust();
weightTareTotal = weightTareTotal.add(weightTareAdjust);
}
return weightTareTotal;
}
AttributeCode getWeightNetAttribute();
void setWeightNetNoPropagate(final BigDecimal weightNet);
void setWeightNet(final BigDecimal weightNet);
/** @return net weight or null if weight net is not available */
BigDecimal getWeightNetOrNull();
/** @return weight net; never return null */
BigDecimal getWeightNet();
I_C_UOM getWeightNetUOM();
|
AttributeCode getWeightGrossAttribute();
void setWeightGross(final BigDecimal weightGross);
BigDecimal getWeightGross();
Quantity getWeightGrossAsQuantity();
/**
* @return true if given attribute is the attribute used for the weight tare adjust
*/
boolean isWeightTareAdjustAttribute(final AttributeCode attribute);
/**
* @return true if given attribute is the attribute used for the weight tare
*/
boolean isWeightTareAttribute(final AttributeCode attribute);
/**
* @return true if given attribute is the attribute used for the weight net
*/
boolean isWeightNetAttribute(final AttributeCode attribute);
/**
* @return true if given attribute is the attribute used for the weight gross
*/
boolean isWeightGrossAttribute(final AttributeCode attribute);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\weightable\IWeightable.java
| 1
|
请完成以下Java代码
|
private UserAuthToken authenticate(@NonNull final UserAuthTokenSupplier authTokenStringSupplier, @NonNull final AuthResolution authResolution)
{
if (authResolution.isDoNotAuthenticate())
{
return null;
}
try
{
final String authTokenString = StringUtils.trimBlankToNull(authTokenStringSupplier.getAuthToken());
if (authTokenString == null)
{
if (authResolution.isAuthenticateIfTokenAvailable())
{
return null;
}
else
{
throw new UserNotAuthorizedException("No token provided. If you are calling from an REST API, please provide then token in `" + UserAuthTokenFilter.HEADER_Authorization + "` HTTP header" + " or `" + UserAuthTokenFilter.QUERY_PARAM_API_KEY + "` query parameter");
}
}
else
{
return userAuthTokenRepo.getByToken(authTokenString);
}
}
catch (final UserNotAuthorizedException ex)
{
throw ex;
}
catch (final Exception ex)
{
throw new UserNotAuthorizedException(ex);
}
}
private IAutoCloseable createContextAndSwitchIfToken(@Nullable final UserAuthToken token)
{
if (token == null)
{
return IAutoCloseable.NOP;
}
else
{
final Properties ctx = createContext(token);
return Env.switchContext(ctx);
}
}
private Properties createContext(final UserAuthToken token)
{
final IUserRolePermissions permissions = userRolePermissionsDAO.getUserRolePermissions(UserRolePermissionsKey.builder()
.userId(token.getUserId())
.roleId(token.getRoleId())
.clientId(token.getClientId())
.date(SystemTime.asDayTimestamp())
.build());
final UserInfo userInfo = getUserInfo(token.getUserId());
final Properties ctx = Env.newTemporaryCtx();
Env.setContext(ctx, Env.CTXNAME_AD_Client_ID, permissions.getClientId().getRepoId());
Env.setContext(ctx, Env.CTXNAME_AD_Org_ID, OrgId.toRepoId(token.getOrgId()));
Env.setContext(ctx, Env.CTXNAME_AD_User_ID, UserId.toRepoId(permissions.getUserId()));
Env.setContext(ctx, Env.CTXNAME_AD_Role_ID, RoleId.toRepoId(permissions.getRoleId()));
Env.setContext(ctx, Env.CTXNAME_AD_Language, userInfo.getAdLanguage());
|
return ctx;
}
public UserAuthToken getOrCreateNewToken(@NonNull final CreateUserAuthTokenRequest request)
{
return userAuthTokenRepo.getOrCreateNew(request);
}
private UserInfo getUserInfo(@NonNull final UserId userId)
{
return userInfoById.getOrLoad(userId, this::retrieveUserInfo);
}
private UserInfo retrieveUserInfo(@NonNull final UserId userId)
{
final I_AD_User user = userDAO.getById(userId);
return UserInfo.builder()
.userId(userId)
.adLanguage(StringUtils.trimBlankToOptional(user.getAD_Language()).orElseGet(Language::getBaseAD_Language))
.build();
}
//
//
//
@Value
@Builder
private static class UserInfo
{
@NonNull UserId userId;
@NonNull String adLanguage;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\security\UserAuthTokenService.java
| 1
|
请完成以下Java代码
|
public void configureApiVersioning(ApiVersionConfigurer configurer) {
Boolean required = versionProperties.getRequired();
Boolean detectSupported = versionProperties.getDetectSupported();
Apiversion.Use use = versionProperties.getUse();
// only set defaults is one or more use options is set
if (StringUtils.hasText(use.getHeader()) || StringUtils.hasText(use.getQueryParameter())
|| use.getPathSegment() != null || !CollectionUtils.isEmpty(use.getMediaTypeParameter())) {
if (required == null) {
configurer.setVersionRequired(false);
}
if (detectSupported == null) {
configurer.detectSupportedVersions(true);
}
configurer.setSupportedVersionPredicate(comparable -> true);
}
}
}
static class GatewayHttpClientEnvironmentPostProcessor implements EnvironmentPostProcessor {
static final boolean APACHE = ClassUtils.isPresent("org.apache.hc.client5.http.impl.classic.HttpClients", null);
static final boolean JETTY = ClassUtils.isPresent("org.eclipse.jetty.client.HttpClient", null);
static final boolean REACTOR_NETTY = ClassUtils.isPresent("reactor.netty.http.client.HttpClient", null);
static final boolean JDK = ClassUtils.isPresent("java.net.http.HttpClient", null);
static final boolean HIGHER_PRIORITY = APACHE || JETTY || REACTOR_NETTY;
static final String SPRING_REDIRECTS_PROPERTY = "spring.http.clients.redirects";
static final String SPRING_HTTP_FACTORY_PROPERTY = "spring.http.clients.imperative.factory";
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
HttpRedirects redirects = environment.getProperty(SPRING_REDIRECTS_PROPERTY, HttpRedirects.class);
if (redirects == null) {
// the user hasn't set anything, change the default
environment.getPropertySources()
.addFirst(new MapPropertySource("gatewayHttpClientProperties",
Map.of(SPRING_REDIRECTS_PROPERTY, HttpRedirects.DONT_FOLLOW)));
}
Factory factory = environment.getProperty(SPRING_HTTP_FACTORY_PROPERTY, Factory.class);
boolean setJdkHttpClientProperties = false;
if (factory == null && !HIGHER_PRIORITY) {
// autodetect
setJdkHttpClientProperties = JDK;
|
}
else if (factory == Factory.JDK) {
setJdkHttpClientProperties = JDK;
}
if (setJdkHttpClientProperties) {
// TODO: customize restricted headers
String restrictedHeaders = System.getProperty("jdk.httpclient.allowRestrictedHeaders");
if (!StringUtils.hasText(restrictedHeaders)) {
System.setProperty("jdk.httpclient.allowRestrictedHeaders", "host");
}
else if (StringUtils.hasText(restrictedHeaders) && !restrictedHeaders.contains("host")) {
System.setProperty("jdk.httpclient.allowRestrictedHeaders", restrictedHeaders + ",host");
}
}
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\GatewayServerMvcAutoConfiguration.java
| 1
|
请完成以下Java代码
|
public void setAD_BoilerPlate_ID (final int AD_BoilerPlate_ID)
{
if (AD_BoilerPlate_ID < 1)
set_Value (COLUMNNAME_AD_BoilerPlate_ID, null);
else
set_Value (COLUMNNAME_AD_BoilerPlate_ID, AD_BoilerPlate_ID);
}
@Override
public int getAD_BoilerPlate_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_BoilerPlate_ID);
}
@Override
public void setAD_DocType_BoilerPlate_ID (final int AD_DocType_BoilerPlate_ID)
{
if (AD_DocType_BoilerPlate_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_DocType_BoilerPlate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_DocType_BoilerPlate_ID, AD_DocType_BoilerPlate_ID);
}
@Override
public int getAD_DocType_BoilerPlate_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_DocType_BoilerPlate_ID);
}
@Override
|
public void setC_DocType_ID (final int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_Value (COLUMNNAME_C_DocType_ID, null);
else
set_Value (COLUMNNAME_C_DocType_ID, C_DocType_ID);
}
@Override
public int getC_DocType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DocType_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_DocType_BoilerPlate.java
| 1
|
请完成以下Java代码
|
public final class CasGatewayAuthenticationRedirectFilter extends GenericFilterBean {
public static final String CAS_GATEWAY_AUTHENTICATION_ATTR = "CAS_GATEWAY_AUTHENTICATION";
private final String casLoginUrl;
private final ServiceProperties serviceProperties;
private RequestMatcher requestMatcher;
private RequestCache requestCache = new HttpSessionRequestCache();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
/**
* Constructs a new instance of this class
* @param serviceProperties the {@link ServiceProperties}
*/
public CasGatewayAuthenticationRedirectFilter(String casLoginUrl, ServiceProperties serviceProperties) {
Assert.hasText(casLoginUrl, "casLoginUrl cannot be null or empty");
Assert.notNull(serviceProperties, "serviceProperties cannot be null");
this.casLoginUrl = casLoginUrl;
this.serviceProperties = serviceProperties;
this.requestMatcher = new CasGatewayResolverRequestMatcher(this.serviceProperties);
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (!this.requestMatcher.matches(request)) {
chain.doFilter(request, response);
return;
}
|
this.requestCache.saveRequest(request, response);
HttpSession session = request.getSession(true);
session.setAttribute(CAS_GATEWAY_AUTHENTICATION_ATTR, true);
String urlEncodedService = WebUtils.constructServiceUrl(request, response, this.serviceProperties.getService(),
null, this.serviceProperties.getServiceParameter(), this.serviceProperties.getArtifactParameter(),
true);
String redirectUrl = CommonUtils.constructRedirectUrl(this.casLoginUrl,
this.serviceProperties.getServiceParameter(), urlEncodedService, false, true);
this.redirectStrategy.sendRedirect(request, response, redirectUrl);
}
/**
* Sets the {@link RequestMatcher} used to trigger this filter. Defaults to
* {@link CasGatewayResolverRequestMatcher}.
* @param requestMatcher the {@link RequestMatcher} to use
*/
public void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
this.requestMatcher = requestMatcher;
}
/**
* Sets the {@link RequestCache} used to store the current request to be replayed
* after redirect from the CAS server. Defaults to {@link HttpSessionRequestCache}.
* @param requestCache the {@link RequestCache} to use
*/
public void setRequestCache(RequestCache requestCache) {
Assert.notNull(requestCache, "requestCache cannot be null");
this.requestCache = requestCache;
}
}
|
repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\web\CasGatewayAuthenticationRedirectFilter.java
| 1
|
请完成以下Java代码
|
protected String doIt()
{
if (Check.isEmpty(barcode, true))
{
throw new FillMandatoryException(PARAM_Barcode);
}
final GlobalActionEvent event = GlobalActionEvent.parseQRCode(barcode);
final GlobalActionHandlerResult result = globalActionsDispatcher.dispatchEvent(event);
updateProcessResult(result);
return MSG_OK;
}
private void updateProcessResult(final GlobalActionHandlerResult result)
{
// Tolerate null result but do nothing
if (result == null)
{
return;
}
if (result instanceof OpenViewGlobalActionHandlerResult)
|
{
final OpenViewGlobalActionHandlerResult openViewResult = (OpenViewGlobalActionHandlerResult)result;
final ViewId viewId = openViewResult.getViewId();
final ViewProfileId viewProfileId = openViewResult.getViewProfileId();
getResult().setWebuiViewToOpen(WebuiViewToOpen.builder()
.viewId(viewId.toJson())
.profileId(viewProfileId != null ? viewProfileId.toJson() : null)
.target(ViewOpenTarget.ModalOverlay)
.build());
}
else
{
throw new AdempiereException("Unknown result: " + result);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\globalaction\process\GlobalActionReadProcess.java
| 1
|
请完成以下Java代码
|
private void createBalanceLine()
{
StringBuffer sb = new StringBuffer ("INSERT INTO T_ReportStatement "
+ "(AD_PInstance_ID, Fact_Acct_ID, LevelNo,"
+ "DateAcct, Name, Description,"
+ "AmtAcctDr, AmtAcctCr, Balance, Qty) ");
sb.append("SELECT ").append(getPinstanceId().getRepoId()).append(",0,0,")
.append(DB.TO_DATE(p_DateAcct_From)).append(",")
.append(DB.TO_STRING(Msg.getMsg(Env.getCtx(), "BeginningBalance"))).append(",NULL,"
+ "COALESCE(SUM(AmtAcctDr),0), COALESCE(SUM(AmtAcctCr),0), COALESCE(SUM(AmtAcctDr-AmtAcctCr),0), COALESCE(SUM(Qty),0) "
+ "FROM Fact_Acct "
+ "WHERE ").append(m_parameterWhere)
.append(" AND TRUNC(DateAcct) < ").append(DB.TO_DATE(p_DateAcct_From));
// Start Beginning of Year
if (p_Account_ID > 0)
{
m_acct = new MElementValue (getCtx(), p_Account_ID, get_TrxName());
if (!m_acct.isBalanceSheet())
{
MPeriod first = MPeriod.getFirstInYear (getCtx(), p_DateAcct_From, p_AD_Org_ID);
if (first != null)
sb.append(" AND TRUNC(DateAcct) >= ").append(DB.TO_DATE(first.getStartDate()));
else
log.error("First period not found");
}
}
//
int no = DB.executeUpdateAndSaveErrorOnFail(sb.toString(), get_TrxName());
log.debug("#" + no + " (Account_ID=" + p_Account_ID + ")");
log.trace(sb.toString());
} // createBalanceLine
/**
* Create Beginning Balance Line
*/
private void createDetailLines()
{
StringBuffer sb = new StringBuffer ("INSERT INTO T_ReportStatement "
+ "(AD_PInstance_ID, Fact_Acct_ID, LevelNo,"
+ "DateAcct, Name, Description,"
|
+ "AmtAcctDr, AmtAcctCr, Balance, Qty) ");
sb.append("SELECT ").append(getPinstanceId().getRepoId()).append(",Fact_Acct_ID,1,")
.append("TRUNC(DateAcct),NULL,NULL,"
+ "AmtAcctDr, AmtAcctCr, AmtAcctDr-AmtAcctCr, Qty "
+ "FROM Fact_Acct "
+ "WHERE ").append(m_parameterWhere)
.append(" AND TRUNC(DateAcct) BETWEEN ").append(DB.TO_DATE(p_DateAcct_From))
.append(" AND ").append(DB.TO_DATE(p_DateAcct_To));
//
int no = DB.executeUpdateAndSaveErrorOnFail(sb.toString(), get_TrxName());
log.debug("#" + no);
log.trace(sb.toString());
// Set Name,Description
String sql_select = "SELECT e.Name, fa.Description "
+ "FROM Fact_Acct fa"
+ " INNER JOIN AD_Table t ON (fa.AD_Table_ID=t.AD_Table_ID)"
+ " INNER JOIN AD_Element e ON (t.TableName||'_ID'=e.ColumnName) "
+ "WHERE r.Fact_Acct_ID=fa.Fact_Acct_ID";
// Translated Version ...
sb = new StringBuffer ("UPDATE T_ReportStatement r SET (Name,Description)=(")
.append(sql_select).append(") "
+ "WHERE Fact_Acct_ID <> 0 AND AD_PInstance_ID=").append(getPinstanceId().getRepoId());
//
no = DB.executeUpdateAndSaveErrorOnFail(DB.convertSqlToNative(sb.toString()), get_TrxName());
log.debug("Name #" + no);
log.trace("Name - " + sb);
} // createDetailLines
} // FinStatement
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\report\FinStatement.java
| 1
|
请完成以下Java代码
|
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 static Optional<ContactPerson> cast(@Nullable final DataRecord dataRecord)
{
return dataRecord instanceof ContactPerson
? Optional.of((ContactPerson)dataRecord)
: Optional.empty();
}
String name;
@Nullable
UserId userId;
@Nullable
BPartnerId bPartnerId;
@Nullable
ContactAddress address;
/**
* might be null if the contact person was not stored yet
*/
@Nullable
ContactPersonId contactPersonId;
/**
* the remote system's ID which we can use to sync with the campaign on the remote marketing tool
*/
String remoteId;
@NonNull
PlatformId platformId;
@Nullable
BPartnerLocationId bpLocationId;
/**
* If a {@link #bPartnerId} is not-null, then this is always the locationId of the respective {@link #bpLocationId}.
* In that case, if the respective {@link #bpLocationId} is {@code null}, then this is also {@code null}.
*/
@Nullable
|
LocationId locationId;
@Nullable
BoilerPlateId boilerPlateId;
@Nullable
Language language;
public String getEmailAddressStringOrNull()
{
return EmailAddress.getEmailAddressStringOrNull(getAddress());
}
public boolean hasEmailAddress()
{
return getEmailAddressStringOrNull() != null;
}
public DeactivatedOnRemotePlatform getDeactivatedOnRemotePlatform()
{
return EmailAddress.getDeactivatedOnRemotePlatform(getAddress());
}
public ContactPerson withContactPersonId(@NonNull final ContactPersonId contactPersonId)
{
return !ContactPersonId.equals(this.contactPersonId, contactPersonId)
? toBuilder().contactPersonId(contactPersonId).build()
: this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\ContactPerson.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void cancelShipment(String orderId) {
String sql = "UPDATE shipments SET status=? WHERE orderId=?;";
try (Connection conn = this.connect(); PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, Shipment.Status.CANCELED.name());
pstmt.setString(2, orderId);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public void confirmShipment(String orderId) {
String sql = "UPDATE shipments SET status=? WHERE orderId=?;";
try (Connection conn = this.connect(); PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, Shipment.Status.CONFIRMED.name());
pstmt.setString(2, orderId);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
|
public void readDriver(int driverId, Driver driver) {
String sql = "SELECT name, contact FROM drivers WHERE id = ?";
try (Connection conn = this.connect(); PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, driverId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
driver.setId(driverId);
driver.setName(rs.getString("name"));
driver.setContact(rs.getString("contact"));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
|
repos\tutorials-master\microservices-modules\saga-pattern\src\main\java\io\orkes\example\saga\dao\ShipmentDAO.java
| 2
|
请完成以下Java代码
|
private ImmutableSet<ElementValueId> getElementValueIdsBetween_NUMERIC(final String accountValueFrom, final String accountValueTo)
{
final BigDecimal from = NumberUtils.asBigDecimal(accountValueFrom);
final BigDecimal to = NumberUtils.asBigDecimal(accountValueTo);
final StringToNumericModifier stringToNumericModifier = new StringToNumericModifier();
return queryBL.createQueryBuilder(I_C_ElementValue.class)
.addOnlyActiveRecordsFilter()
.addBetweenFilter(I_C_ElementValue.COLUMNNAME_Value, from, to, stringToNumericModifier)
.create()
.idsAsSet(ElementValueId::ofRepoId);
}
@VisibleForTesting
public List<I_C_ElementValue> getAllRecordsByChartOfAccountsId(final ChartOfAccountsId chartOfAccountsId)
{
return queryBL.createQueryBuilder(I_C_ElementValue.class)
//.addOnlyActiveRecordsFilter() // commented because we return ALL
.addEqualsFilter(I_C_ElementValue.COLUMNNAME_C_Element_ID, chartOfAccountsId)
.create()
.list();
}
public IValidationRule isOpenItemRule()
{
return SQLValidationRule.ofSqlWhereClause(I_C_ElementValue.COLUMNNAME_IsOpenItem + "=" + DB.TO_BOOLEAN(true));
}
//
//
//
//
//
|
private static final class ElementValuesMap
{
private final ImmutableMap<ElementValueId, ElementValue> byId;
private ImmutableSet<ElementValueId> _openItemIds;
private ElementValuesMap(final List<ElementValue> list)
{
byId = Maps.uniqueIndex(list, ElementValue::getId);
}
public ElementValue getById(final ElementValueId id)
{
final ElementValue elementValue = byId.get(id);
if (elementValue == null)
{
throw new AdempiereException("No Element Value found for " + id);
}
return elementValue;
}
public ImmutableSet<ElementValueId> getOpenItemIds()
{
ImmutableSet<ElementValueId> openItemIds = this._openItemIds;
if (openItemIds == null)
{
openItemIds = this._openItemIds = byId.values()
.stream()
.filter(ElementValue::isOpenItem)
.map(ElementValue::getId)
.collect(ImmutableSet.toImmutableSet());
}
return openItemIds;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\elementvalue\ElementValueRepository.java
| 1
|
请完成以下Java代码
|
public boolean ask(final int WindowNo, final String AD_Message)
{
return getCurrentInstance().ask(WindowNo, AD_Message);
}
@Override
public boolean ask(final int WindowNo, final String AD_Message, final String message)
{
return getCurrentInstance().ask(WindowNo, AD_Message, message);
}
@Override
public void warn(final int WindowNo, final String AD_Message)
{
getCurrentInstance().warn(WindowNo, AD_Message);
}
@Override
public void warn(final int WindowNo, final String AD_Message, final String message)
{
getCurrentInstance().warn(WindowNo, AD_Message, message);
}
@Override
public void warn(final int WindowNo, final Throwable e)
{
getCurrentInstance().warn(WindowNo, e);
}
@Override
public void error(final int WindowNo, final String AD_Message)
{
getCurrentInstance().error(WindowNo, AD_Message);
}
@Override
public void error(final int WindowNo, final String AD_Message, final String message)
{
getCurrentInstance().error(WindowNo, AD_Message, message);
}
@Override
public void error(int WindowNo, Throwable e)
{
getCurrentInstance().error(WindowNo, e);
}
@Override
public void download(final byte[] data, final String contentType, final String filename)
{
getCurrentInstance().download(data, contentType, filename);
}
@Override
public void downloadNow(final InputStream content, final String contentType, final String filename)
{
getCurrentInstance().downloadNow(content, contentType, filename);
}
@Override
public void invokeLater(final int windowNo, final Runnable runnable)
{
getCurrentInstance().invokeLater(windowNo, runnable);
}
@Override
public Thread createUserThread(final Runnable runnable, final String threadName)
{
|
return getCurrentInstance().createUserThread(runnable, threadName);
}
@Override
public String getClientInfo()
{
return getCurrentInstance().getClientInfo();
}
/**
* This method does nothing.
*
* @deprecated please check out the deprecation notice in {@link IClientUIInstance#hideBusyDialog()}.
*/
@Deprecated
@Override
public void hideBusyDialog()
{
// nothing
}
@Override
public void showWindow(final Object model)
{
getCurrentInstance().showWindow(model);
}
@Override
public void executeLongOperation(final Object component, final Runnable runnable)
{
getCurrentInstance().executeLongOperation(component, runnable);
}
@Override
public IClientUIInvoker invoke()
{
return getCurrentInstance().invoke();
}
@Override
public IClientUIAsyncInvoker invokeAsync()
{
return getCurrentInstance().invokeAsync();
}
@Override
public void showURL(String url)
{
getCurrentInstance().showURL(url);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\AbstractClientUI.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SyncProductSupply implements IConfirmableDTO
{
String uuid;
boolean deleted;
long syncConfirmationId;
String bpartner_uuid;
String product_uuid;
String contractLine_uuid;
BigDecimal qty;
LocalDate day;
boolean weekPlanning;
int version;
@Builder(toBuilder = true)
@JsonCreator
public SyncProductSupply(
@JsonProperty("uuid") final String uuid,
@JsonProperty("deleted") final boolean deleted,
@JsonProperty("syncConfirmationId") final long syncConfirmationId,
@JsonProperty("bpartner_uuid") final String bpartner_uuid,
@JsonProperty("product_uuid") final String product_uuid,
@JsonProperty("contractLine_uuid") final String contractLine_uuid,
@JsonProperty("qty") final BigDecimal qty,
@JsonProperty("day") final LocalDate day,
@JsonProperty("weekPlanning") final boolean weekPlanning,
@JsonProperty("version") final int version)
{
this.uuid = uuid;
this.deleted = deleted;
this.syncConfirmationId = syncConfirmationId;
this.bpartner_uuid = bpartner_uuid;
this.product_uuid = product_uuid;
this.contractLine_uuid = contractLine_uuid;
this.qty = qty;
this.day = day;
this.weekPlanning = weekPlanning;
this.version = version;
|
}
@Override
public String toString()
{
return "SyncProductSupply ["
+ "bpartner_uuid=" + bpartner_uuid
+ ", product_uuid=" + product_uuid
+ ", contractLine_uuid=" + contractLine_uuid
+ ", qty=" + qty
+ ", day=" + day
+ ", weekPlanning=" + weekPlanning
+ ", version=" + version
+ ", uuid=" + getUuid()
+ "]";
}
@Override
public IConfirmableDTO withNotDeleted()
{
return toBuilder().deleted(false).build();
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-procurement\src\main\java\de\metas\common\procurement\sync\protocol\dto\SyncProductSupply.java
| 2
|
请完成以下Java代码
|
public int getNoInventoryCount ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NoInventoryCount);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Number of Product counts.
@param NoProductCount
Frequency of product counts per year
*/
public void setNoProductCount (int NoProductCount)
{
set_Value (COLUMNNAME_NoProductCount, Integer.valueOf(NoProductCount));
}
/** Get Number of Product counts.
@return Frequency of product counts per year
*/
public int getNoProductCount ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NoProductCount);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Number of runs.
@param NumberOfRuns
Frequency of processing Perpetual Inventory
*/
public void setNumberOfRuns (int NumberOfRuns)
{
|
set_Value (COLUMNNAME_NumberOfRuns, Integer.valueOf(NumberOfRuns));
}
/** Get Number of runs.
@return Frequency of processing Perpetual Inventory
*/
public int getNumberOfRuns ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NumberOfRuns);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PerpetualInv.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getMemberId() {
return memberId;
}
public void setMemberId(Long memberId) {
this.memberId = memberId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Integer getDefaultStatus() {
return defaultStatus;
}
public void setDefaultStatus(Integer defaultStatus) {
this.defaultStatus = defaultStatus;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
|
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getDetailAddress() {
return detailAddress;
}
public void setDetailAddress(String detailAddress) {
this.detailAddress = detailAddress;
}
@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(", memberId=").append(memberId);
sb.append(", name=").append(name);
sb.append(", phoneNumber=").append(phoneNumber);
sb.append(", defaultStatus=").append(defaultStatus);
sb.append(", postCode=").append(postCode);
sb.append(", province=").append(province);
sb.append(", city=").append(city);
sb.append(", region=").append(region);
sb.append(", detailAddress=").append(detailAddress);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberReceiveAddress.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void fetchAuthorAsDtoClass() {
List<AuthorDto> authors = authorRepository.fetchAsDto();
authors.forEach(System.out::println);
briefOverviewOfPersistentContextContent();
}
@Transactional(readOnly = true)
public void fetchAuthorAsDtoClassColumns() {
List<AuthorDto> authors = authorRepository.fetchAsDtoColumns();
authors.forEach(a -> System.out.println("Author{id=" + a.getId()
+ ", name=" + a.getName() + ", genre=" + a.getGenre()
+ ", age=" + a.getAge() + "}"));
briefOverviewOfPersistentContextContent();
}
@Transactional(readOnly = true)
public void fetchAuthorAsDtoClassNative() {
List<AuthorDto> authors = authorRepository.fetchAsDtoNative();
authors.forEach(a -> System.out.println("Author{id=" + a.getId()
+ ", name=" + a.getName() + ", genre=" + a.getGenre()
+ ", age=" + a.getAge() + "}"));
briefOverviewOfPersistentContextContent();
}
@Transactional(readOnly = true)
public void fetchAuthorByGenreAsDtoClassQueryBuilderMechanism() {
List<AuthorDto> authors = authorRepository.findBy();
authors.forEach(a -> System.out.println("Author{id=" + a.getId()
+ ", name=" + a.getName() + ", genre=" + a.getGenre()
+ ", age=" + a.getAge() + "}"));
briefOverviewOfPersistentContextContent();
}
|
private void briefOverviewOfPersistentContextContent() {
org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext();
int managedEntities = persistenceContext.getNumberOfManagedEntities();
System.out.println("\n-----------------------------------");
System.out.println("Total number of managed entities: " + managedEntities);
// getEntitiesByKey() will be removed and probably replaced with #iterateEntities()
Map<EntityKey, Object> entitiesByKey = persistenceContext.getEntitiesByKey();
entitiesByKey.forEach((key, value) -> System.out.println(key + ": " + value));
for (Object entry : entitiesByKey.values()) {
EntityEntry ee = persistenceContext.getEntry(entry);
System.out.println(
"Entity name: " + ee.getEntityName()
+ " | Status: " + ee.getStatus()
+ " | State: " + Arrays.toString(ee.getLoadedState()));
};
System.out.println("\n-----------------------------------\n");
}
private org.hibernate.engine.spi.PersistenceContext getPersistenceContext() {
SharedSessionContractImplementor sharedSession = entityManager.unwrap(
SharedSessionContractImplementor.class
);
return sharedSession.getPersistenceContext();
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinDtoAllFields\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请完成以下Java代码
|
public org.compiere.model.I_API_Request_Audit getAPI_Request_Audit()
{
return get_ValueAsPO(COLUMNNAME_API_Request_Audit_ID, org.compiere.model.I_API_Request_Audit.class);
}
@Override
public void setAPI_Request_Audit(final org.compiere.model.I_API_Request_Audit API_Request_Audit)
{
set_ValueFromPO(COLUMNNAME_API_Request_Audit_ID, org.compiere.model.I_API_Request_Audit.class, API_Request_Audit);
}
@Override
public void setAPI_Request_Audit_ID (final int API_Request_Audit_ID)
{
if (API_Request_Audit_ID < 1)
set_Value (COLUMNNAME_API_Request_Audit_ID, null);
else
set_Value (COLUMNNAME_API_Request_Audit_ID, API_Request_Audit_ID);
}
@Override
public int getAPI_Request_Audit_ID()
{
return get_ValueAsInt(COLUMNNAME_API_Request_Audit_ID);
}
@Override
public void setAPI_Response_Audit_ID (final int API_Response_Audit_ID)
{
if (API_Response_Audit_ID < 1)
set_ValueNoCheck (COLUMNNAME_API_Response_Audit_ID, null);
else
set_ValueNoCheck (COLUMNNAME_API_Response_Audit_ID, API_Response_Audit_ID);
}
@Override
public int getAPI_Response_Audit_ID()
{
return get_ValueAsInt(COLUMNNAME_API_Response_Audit_ID);
}
@Override
public void setBody (final @Nullable java.lang.String Body)
{
set_Value (COLUMNNAME_Body, Body);
}
@Override
public java.lang.String getBody()
{
return get_ValueAsString(COLUMNNAME_Body);
}
@Override
public void setHttpCode (final @Nullable java.lang.String HttpCode)
{
set_Value (COLUMNNAME_HttpCode, HttpCode);
}
@Override
public java.lang.String getHttpCode()
{
|
return get_ValueAsString(COLUMNNAME_HttpCode);
}
@Override
public void setHttpHeaders (final @Nullable java.lang.String HttpHeaders)
{
set_Value (COLUMNNAME_HttpHeaders, HttpHeaders);
}
@Override
public java.lang.String getHttpHeaders()
{
return get_ValueAsString(COLUMNNAME_HttpHeaders);
}
@Override
public void setTime (final @Nullable java.sql.Timestamp Time)
{
set_Value (COLUMNNAME_Time, Time);
}
@Override
public java.sql.Timestamp getTime()
{
return get_ValueAsTimestamp(COLUMNNAME_Time);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Response_Audit.java
| 1
|
请完成以下Java代码
|
public MultipleArticleModel getArticlesByAuthor(@RequestParam String author, Pageable pageable) {
final var articles = articleService.getArticlesByAuthorName(author, pageable);
return MultipleArticleModel.fromArticles(articles);
}
@GetMapping(value = "/articles", params = {"tag"})
public MultipleArticleModel getArticlesByTag(@RequestParam String tag, Pageable pageable) {
final var articles = articleService.getArticlesByTag(tag, pageable);
return MultipleArticleModel.fromArticles(articles);
}
@GetMapping(value = "/articles", params = {"favorited"})
public MultipleArticleModel getArticleByFavoritedUsername(@RequestParam UserName favorited, Pageable pageable) {
final var articles = articleService.getArticleFavoritedByUsername(favorited, pageable);
return MultipleArticleModel.fromArticles(articles);
}
@GetMapping("/articles/feed")
public MultipleArticleModel getFeed(@AuthenticationPrincipal UserJWTPayload jwtPayload, Pageable pageable) {
final var articles = articleService.getFeedByUserId(jwtPayload.getUserId(), pageable);
return MultipleArticleModel.fromArticles(articles);
}
@GetMapping("/articles/{slug}")
public ResponseEntity<ArticleModel> getArticleBySlug(@PathVariable String slug) {
return of(articleService.getArticleBySlug(slug)
.map(ArticleModel::fromArticle));
}
@PutMapping("/articles/{slug}")
public ArticleModel putArticleBySlug(@AuthenticationPrincipal UserJWTPayload jwtPayload,
@PathVariable String slug,
@RequestBody ArticlePutRequestDTO dto) {
final var articleUpdated = articleService.updateArticle(jwtPayload.getUserId(), slug, dto.toUpdateRequest());
return ArticleModel.fromArticle(articleUpdated);
}
|
@PostMapping("/articles/{slug}/favorite")
public ArticleModel favoriteArticleBySlug(@AuthenticationPrincipal UserJWTPayload jwtPayload,
@PathVariable String slug) {
var articleFavorited = articleService.favoriteArticle(jwtPayload.getUserId(), slug);
return ArticleModel.fromArticle(articleFavorited);
}
@DeleteMapping("/articles/{slug}/favorite")
public ArticleModel unfavoriteArticleBySlug(@AuthenticationPrincipal UserJWTPayload jwtPayload,
@PathVariable String slug) {
var articleUnfavored = articleService.unfavoriteArticle(jwtPayload.getUserId(), slug);
return ArticleModel.fromArticle(articleUnfavored);
}
@ResponseStatus(NO_CONTENT)
@DeleteMapping("/articles/{slug}")
public void deleteArticleBySlug(@AuthenticationPrincipal UserJWTPayload jwtPayload,
@PathVariable String slug) {
articleService.deleteArticleBySlug(jwtPayload.getUserId(), slug);
}
}
|
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\application\article\ArticleRestController.java
| 1
|
请完成以下Java代码
|
public EventModelBuilder category(String category) {
this.category = category;
return this;
}
@Override
public EventModelBuilder parentDeploymentId(String parentDeploymentId) {
this.parentDeploymentId = parentDeploymentId;
return this;
}
@Override
public EventModelBuilder deploymentTenantId(String deploymentTenantId) {
this.deploymentTenantId = deploymentTenantId;
return this;
}
@Override
public EventModelBuilder header(String name, String type) {
eventPayloadDefinitions.put(name, EventPayload.header(name, type));
return this;
}
@Override
public EventModelBuilder headerWithCorrelation(String name, String type) {
eventPayloadDefinitions.put(name, EventPayload.headerWithCorrelation(name, type));
return this;
}
@Override
public EventModelBuilder correlationParameter(String name, String type) {
eventPayloadDefinitions.put(name, EventPayload.correlation(name, type));
return this;
}
@Override
public EventModelBuilder payload(String name, String type) {
eventPayloadDefinitions.put(name, new EventPayload(name, type));
return this;
}
@Override
public EventModelBuilder metaParameter(String name, String type) {
EventPayload payload = new EventPayload(name, type);
payload.setMetaParameter(true);
eventPayloadDefinitions.put(name, payload);
return this;
}
@Override
public EventModelBuilder fullPayload(String name) {
|
eventPayloadDefinitions.put(name, EventPayload.fullPayload(name));
return this;
}
@Override
public EventModel createEventModel() {
return buildEventModel();
}
@Override
public EventDeployment deploy() {
if (resourceName == null) {
throw new FlowableIllegalArgumentException("A resource name is mandatory");
}
EventModel eventModel = buildEventModel();
return eventRepository.createDeployment()
.name(deploymentName)
.addEventDefinition(resourceName, eventJsonConverter.convertToJson(eventModel))
.category(category)
.parentDeploymentId(parentDeploymentId)
.tenantId(deploymentTenantId)
.deploy();
}
protected EventModel buildEventModel() {
EventModel eventModel = new EventModel();
if (StringUtils.isNotEmpty(key)) {
eventModel.setKey(key);
} else {
throw new FlowableIllegalArgumentException("An event definition key is mandatory");
}
eventModel.setPayload(eventPayloadDefinitions.values());
return eventModel;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\model\EventModelBuilderImpl.java
| 1
|
请完成以下Java代码
|
public class ExtensionImpl extends BpmnModelElementInstanceImpl implements Extension {
protected static Attribute<String> definitionAttribute;
protected static Attribute<Boolean> mustUnderstandAttribute;
protected static ChildElementCollection<Documentation> documentationCollection;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Extension.class, BPMN_ELEMENT_EXTENSION)
.namespaceUri(BPMN20_NS)
.instanceProvider(new ModelTypeInstanceProvider<Extension>() {
public Extension newInstance(ModelTypeInstanceContext instanceContext) {
return new ExtensionImpl(instanceContext);
}
});
// TODO: qname reference extension definition
definitionAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_DEFINITION)
.build();
mustUnderstandAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_MUST_UNDERSTAND)
.defaultValue(false)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
documentationCollection = sequenceBuilder.elementCollection(Documentation.class)
.build();
typeBuilder.build();
}
public ExtensionImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
|
}
public String getDefinition() {
return definitionAttribute.getValue(this);
}
public void setDefinition(String Definition) {
definitionAttribute.setValue(this, Definition);
}
public boolean mustUnderstand() {
return mustUnderstandAttribute.getValue(this);
}
public void setMustUnderstand(boolean mustUnderstand) {
mustUnderstandAttribute.setValue(this, mustUnderstand);
}
public Collection<Documentation> getDocumentations() {
return documentationCollection.get(this);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ExtensionImpl.java
| 1
|
请完成以下Java代码
|
public class GraphElement extends PrintElement
{
/**
* Constructor
* @param pg graph model
*/
public GraphElement(MPrintGraph pg)
{
} // GraphElement
/**
* Layout and Calculate Size
* Set p_width & p_height
* @return true if calculated
*/
protected boolean calculateSize()
{
|
return false;
} // calcluateSize
/**
* Paint/Print.
* @param g2D Graphics
* @param pageNo page number for multi page support (0 = header/footer)
* @param pageStart top left Location of page
* @param ctx context
* @param isView true if online view (IDs are links)
*/
public void paint (Graphics2D g2D, int pageNo, Point2D pageStart, Properties ctx, boolean isView)
{
} // paint
} // GraphElement
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\GraphElement.java
| 1
|
请完成以下Java代码
|
private List<ServiceInstance> resolveInternal() {
// Discover servers
final List<ServiceInstance> newInstanceList = discoverServers();
if (CollectionUtils.isEmpty(newInstanceList)) {
log.error("No servers found for {}", getName());
this.savedListener.onError(Status.UNAVAILABLE.withDescription("No servers found for " + getName()));
return Lists.newArrayList();
} else {
log.debug("Got {} candidate servers for {}", newInstanceList.size(), getName());
}
// Check for changes
if (!needsToUpdateConnections(newInstanceList)) {
log.debug("Nothing has changed... skipping update for {}", getName());
return KEEP_PREVIOUS;
}
// Set new servers
log.debug("Ready to update server list for {}", getName());
this.savedListener.onResult(ResolutionResult.newBuilder()
.setAddresses(toTargets(newInstanceList))
.setServiceConfig(resolveServiceConfig(newInstanceList))
.build());
|
log.info("Done updating server list for {}", getName());
return newInstanceList;
}
private List<EquivalentAddressGroup> toTargets(final List<ServiceInstance> newInstanceList) {
final List<EquivalentAddressGroup> targets = Lists.newArrayList();
for (final ServiceInstance instance : newInstanceList) {
targets.add(toTarget(instance));
}
return targets;
}
private EquivalentAddressGroup toTarget(final ServiceInstance instance) {
final String host = instance.getHost();
final int port = getGrpcPort(instance);
final Attributes attributes = getAttributes(instance);
log.debug("Found gRPC server {}:{} for {}", host, port, getName());
return new EquivalentAddressGroup(new InetSocketAddress(host, port), attributes);
}
}
}
|
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\nameresolver\DiscoveryClientNameResolver.java
| 1
|
请完成以下Java代码
|
public ResponseEntity deleteComment(
@PathVariable("slug") String slug,
@PathVariable("id") String commentId,
@AuthenticationPrincipal User user) {
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
return commentRepository
.findById(article.getId(), commentId)
.map(
comment -> {
if (!AuthorizationService.canWriteComment(user, article, comment)) {
throw new NoAuthorizationException();
}
commentRepository.remove(comment);
return ResponseEntity.noContent().build();
})
.orElseThrow(ResourceNotFoundException::new);
}
private Map<String, Object> commentResponse(CommentData commentData) {
|
return new HashMap<String, Object>() {
{
put("comment", commentData);
}
};
}
}
@Getter
@NoArgsConstructor
@JsonRootName("comment")
class NewCommentParam {
@NotBlank(message = "can't be empty")
private String body;
}
|
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\CommentsApi.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class GemFireProperties {
private static final boolean DEFAULT_USE_BEAN_FACTORY_LOCATOR = false;
private boolean useBeanFactoryLocator = DEFAULT_USE_BEAN_FACTORY_LOCATOR;
@NestedConfigurationProperty
private final CacheProperties cache = new CacheProperties();
@NestedConfigurationProperty
private final ClusterProperties cluster = new ClusterProperties();
@NestedConfigurationProperty
private final DiskStoreProperties disk = new DiskStoreProperties();
@NestedConfigurationProperty
private final EntityProperties entities = new EntityProperties();
@NestedConfigurationProperty
private final LocatorProperties locator = new LocatorProperties();
@NestedConfigurationProperty
private final LoggingProperties logging = new LoggingProperties();
@NestedConfigurationProperty
private final ManagementProperties management = new ManagementProperties();
@NestedConfigurationProperty
private final ManagerProperties manager = new ManagerProperties();
@NestedConfigurationProperty
private final PdxProperties pdx = new PdxProperties();
@NestedConfigurationProperty
private final PoolProperties pool = new PoolProperties();
@NestedConfigurationProperty
private final SecurityProperties security = new SecurityProperties();
@NestedConfigurationProperty
private final ServiceProperties service = new ServiceProperties();
private String name;
private String[] locators;
public CacheProperties getCache() {
return this.cache;
}
public ClusterProperties getCluster() {
return this.cluster;
}
public DiskStoreProperties getDisk() {
return this.disk;
}
public EntityProperties getEntities() {
return this.entities;
}
public LocatorProperties getLocator() {
return this.locator;
}
public String[] getLocators() {
|
return this.locators;
}
public void setLocators(String[] locators) {
this.locators = locators;
}
public LoggingProperties getLogging() {
return this.logging;
}
public ManagementProperties getManagement() {
return this.management;
}
public ManagerProperties getManager() {
return this.manager;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PdxProperties getPdx() {
return this.pdx;
}
public PoolProperties getPool() {
return this.pool;
}
public SecurityProperties getSecurity() {
return this.security;
}
public ServiceProperties getService() {
return this.service;
}
public boolean isUseBeanFactoryLocator() {
return this.useBeanFactoryLocator;
}
public void setUseBeanFactoryLocator(boolean useBeanFactoryLocator) {
this.useBeanFactoryLocator = useBeanFactoryLocator;
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\GemFireProperties.java
| 2
|
请完成以下Spring Boot application配置
|
# DataSource settings: set here configurations for the database connection
spring.datasource.url = jdbc:mysql://localhost:8889/netgloo_blog
spring.datasource.username = root
spring.datasource.password = root
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate s
|
ettings
spring.jpa.hibernate.ddl-auto = create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
|
repos\spring-boot-samples-master\spring-boot-springdatajpa-inheritance\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public void updateExternalTaskSuspensionStateByProcessInstanceId(String processInstanceId, SuspensionState suspensionState) {
updateExternalTaskSuspensionState(processInstanceId, null, null, suspensionState);
}
public void updateExternalTaskSuspensionStateByProcessDefinitionId(String processDefinitionId, SuspensionState suspensionState) {
updateExternalTaskSuspensionState(null, processDefinitionId, null, suspensionState);
}
public void updateExternalTaskSuspensionStateByProcessDefinitionKey(String processDefinitionKey, SuspensionState suspensionState) {
updateExternalTaskSuspensionState(null, null, processDefinitionKey, suspensionState);
}
public void updateExternalTaskSuspensionStateByProcessDefinitionKeyAndTenantId(String processDefinitionKey, String processDefinitionTenantId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processDefinitionKey", processDefinitionKey);
parameters.put("isProcessDefinitionTenantIdSet", true);
parameters.put("processDefinitionTenantId", processDefinitionTenantId);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(ExternalTaskEntity.class, "updateExternalTaskSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
protected void configureQuery(ExternalTaskQueryImpl query) {
getAuthorizationManager().configureExternalTaskQuery(query);
getTenantManager().configureQuery(query);
}
protected void configureQuery(ListQueryParameterObject parameter) {
getAuthorizationManager().configureExternalTaskFetch(parameter);
getTenantManager().configureQuery(parameter);
}
protected ListQueryParameterObject configureParameterizedQuery(Object parameter) {
return getTenantManager().configureQuery(parameter);
}
protected boolean shouldApplyOrdering(boolean usePriority, boolean useCreateTime) {
return usePriority || useCreateTime;
}
|
protected boolean useCreateTime(List<QueryOrderingProperty> orderingProperties) {
return orderingProperties.stream()
.anyMatch(orderingProperty -> CREATE_TIME.getName().equals(orderingProperty.getQueryProperty().getName()));
}
public void fireExternalTaskAvailableEvent() {
Context.getCommandContext()
.getTransactionContext()
.addTransactionListener(TransactionState.COMMITTED, new TransactionListener() {
@Override
public void execute(CommandContext commandContext) {
ProcessEngineImpl.EXT_TASK_CONDITIONS.signalAll();
}
});
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ExternalTaskManager.java
| 1
|
请完成以下Java代码
|
public static SshClient setUpSshClient() {
SshClient client = SshClient.setUpDefaultClient();
client.start();
client.setServerKeyVerifier(AcceptAllServerKeyVerifier.INSTANCE);
return client;
}
public static ClientSession connectToServer(SshClient client) throws IOException {
ClientSession session = client.connect(USER, HOST, PORT)
.verify(10000)
.getSession();
FileKeyPairProvider fileKeyPairProvider = new FileKeyPairProvider(Paths.get(PRIVATE_KEY));
Iterable<KeyPair> keyPairs = fileKeyPairProvider.loadKeys(null);
for (KeyPair keyPair : keyPairs) {
session.addPublicKeyIdentity(keyPair);
}
session.auth()
.verify(10000);
return session;
}
public static SftpClient createSftpClient(ClientSession session) throws IOException {
|
SftpClientFactory factory = SftpClientFactory.instance();
return factory.createSftpClient(session);
}
public static List<SftpClient.DirEntry> listDirectory(SftpClient sftp, String remotePath) throws IOException {
Iterable<SftpClient.DirEntry> entriesIterable = sftp.readDir(remotePath);
return StreamSupport.stream(entriesIterable.spliterator(), false)
.collect(Collectors.toList());
}
public static void printDirectoryEntries(List<SftpClient.DirEntry> entries) {
for (SftpClient.DirEntry entry : entries) {
LOGGER.info(entry.getFilename());
LOGGER.info(entry.getLongFilename());
}
}
}
|
repos\tutorials-master\libraries-security\src\main\java\com\baeldung\listfilesremoteserver\RemoteServerApacheSshd.java
| 1
|
请完成以下Java代码
|
protected void prepare()
{
ProcessInfoParameter[] para = getParametersAsArray();
for (ProcessInfoParameter element : para)
{
String name = element.getParameterName();
if (element.getParameter() == null)
{
}
else
{
log.error("Unknown Parameter: " + name);
}
}
} // prepare
/**
* Perform process.
* @return Message
* @throws Exception
*/
@Override
protected String doIt() throws Exception
{
final ClientId clientId = ClientId.ofRepoId(getAD_Client_ID());
if(Services.get(IClientDAO.class).isMultilingualDocumentsEnabled(clientId))
{
throw new AdempiereException("@AD_Client_ID@: @IsMultiLingualDocument@");
}
//
String sql = "SELECT * FROM AD_Table "
+ "WHERE TableName LIKE '%_Trl' AND TableName NOT LIKE 'AD%' "
+ "ORDER BY TableName";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
rs = pstmt.executeQuery ();
while (rs.next ())
{
processTable (new MTable(getCtx(), rs, null), clientId);
}
}
catch (Exception e)
{
log.error(sql, e);
}
finally
{
|
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
return "OK";
} // doIt
/**
* Process Translation Table
* @param table table
*/
private void processTable (MTable table, ClientId clientId)
{
StringBuffer sql = new StringBuffer();
MColumn[] columns = table.getColumns(false);
for (MColumn column : columns)
{
if (column.getAD_Reference_ID() == DisplayType.String
|| column.getAD_Reference_ID() == DisplayType.Text)
{
String columnName = column.getColumnName();
if (sql.length() != 0)
{
sql.append(",");
}
sql.append(columnName);
}
}
String baseTable = table.getTableName();
baseTable = baseTable.substring(0, baseTable.length()-4);
log.info(baseTable + ": " + sql);
String columnNames = sql.toString();
sql = new StringBuffer();
sql.append("UPDATE ").append(table.getTableName()).append(" t SET (")
.append(columnNames).append(") = (SELECT ").append(columnNames)
.append(" FROM ").append(baseTable).append(" b WHERE t.")
.append(baseTable).append("_ID=b.").append(baseTable).append("_ID) WHERE AD_Client_ID=")
.append(clientId.getRepoId());
int no = DB.executeUpdateAndSaveErrorOnFail(DB.convertSqlToNative(sql.toString()), get_TrxName());
addLog(0, null, new BigDecimal(no), baseTable);
} // processTable
} // TranslationDocSync
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\TranslationDocSync.java
| 1
|
请完成以下Java代码
|
public Object getCellEditorValue()
{
if (m_editor == null)
{
return null;
}
final Object valueEditor = m_editor.getValue();
//
// Check and convert the value if needed
final Object valueModel;
if (valueEditor instanceof Number && modelValueClass == KeyNamePair.class)
{
final int key = ((Number)valueEditor).intValue();
final String name = m_editor.getDisplay();
valueModel = new KeyNamePair(key, name);
}
else
{
valueModel = valueEditor;
}
return valueModel;
}
@Override
public boolean stopCellEditing()
{
try
{
return super.stopCellEditing();
}
catch (Exception e)
{
final Component comp = (Component)m_editor;
final int windowNo = Env.getWindowNo(comp);
Services.get(IClientUI.class).warn(windowNo, e);
}
return false;
}
|
@Override
public void cancelCellEditing()
{
super.cancelCellEditing();
}
private Object convertToEditorValue(final Object valueModel)
{
final Object valueEditor;
if (valueModel instanceof KeyNamePair && editorValueClass == Integer.class)
{
valueEditor = ((KeyNamePair)valueModel).getKey();
}
else
{
valueEditor = valueModel;
}
return valueEditor;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableModelCellEditor.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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
}
|
repos\springboot-learning-example-master\spring-data-elasticsearch-crud\src\main\java\org\spring\springboot\domain\City.java
| 1
|
请完成以下Java代码
|
public abstract class BaseData<I extends UUIDBased> extends IdBased<I> implements Serializable {
private static final long serialVersionUID = 5422817607129962637L;
public static final ObjectMapper mapper = new ObjectMapper();
protected long createdTime;
public BaseData() {
super();
}
public BaseData(I id) {
super(id);
}
public BaseData(BaseData<I> data) {
super(data.getId());
this.createdTime = data.getCreatedTime();
}
@Schema(
description = "Entity creation timestamp in milliseconds since Unix epoch",
example = "1746028547220",
accessMode = Schema.AccessMode.READ_ONLY
)
public long getCreatedTime() {
return createdTime;
}
public void setCreatedTime(long createdTime) {
this.createdTime = createdTime;
}
@Override
public int hashCode() {
|
final int prime = 31;
int result = super.hashCode();
result = prime * result + Long.hashCode(createdTime);
return result;
}
@SuppressWarnings("rawtypes")
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
BaseData other = (BaseData) obj;
return createdTime == other.createdTime;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BaseData [createdTime=");
builder.append(createdTime);
builder.append(", id=");
builder.append(id);
builder.append("]");
return builder.toString();
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\BaseData.java
| 1
|
请完成以下Java代码
|
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
public Map<String, Object> getTransientVariables() {
return transientVariables;
}
public void setTransientVariables(Map<String, Object> transientVariables) {
this.transientVariables = transientVariables;
}
public FlowElement getInitialFlowElement() {
return initialFlowElement;
}
public void setInitialFlowElement(FlowElement initialFlowElement) {
this.initialFlowElement = initialFlowElement;
|
}
public Process getProcess() {
return process;
}
public void setProcess(Process process) {
this.process = process;
}
public ProcessDefinition getProcessDefinition() {
return processDefinition;
}
public void setProcessDefinition(ProcessDefinition processDefinition) {
this.processDefinition = processDefinition;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\interceptor\AbstractStartProcessInstanceAfterContext.java
| 1
|
请完成以下Java代码
|
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@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(", name=").append(name);
sb.append(", growthPoint=").append(growthPoint);
|
sb.append(", defaultStatus=").append(defaultStatus);
sb.append(", freeFreightPoint=").append(freeFreightPoint);
sb.append(", commentGrowthPoint=").append(commentGrowthPoint);
sb.append(", priviledgeFreeFreight=").append(priviledgeFreeFreight);
sb.append(", priviledgeSignIn=").append(priviledgeSignIn);
sb.append(", priviledgeComment=").append(priviledgeComment);
sb.append(", priviledgePromotion=").append(priviledgePromotion);
sb.append(", priviledgeMemberPrice=").append(priviledgeMemberPrice);
sb.append(", priviledgeBirthday=").append(priviledgeBirthday);
sb.append(", note=").append(note);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberLevel.java
| 1
|
请完成以下Java代码
|
public void setRfQType (java.lang.String RfQType)
{
set_Value (COLUMNNAME_RfQType, RfQType);
}
/** Get Ausschreibung Art.
@return Ausschreibung Art */
@Override
public java.lang.String getRfQType ()
{
return (java.lang.String)get_Value(COLUMNNAME_RfQType);
}
@Override
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep)
{
set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep);
|
}
/** Set Aussendienst.
@param SalesRep_ID Aussendienst */
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Aussendienst.
@return Aussendienst */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ.java
| 1
|
请完成以下Java代码
|
public void setActorId (final @Nullable java.lang.String ActorId)
{
set_Value (COLUMNNAME_ActorId, ActorId);
}
@Override
public java.lang.String getActorId()
{
return get_ValueAsString(COLUMNNAME_ActorId);
}
@Override
public void setBase_url (final @Nullable java.lang.String Base_url)
{
set_Value (COLUMNNAME_Base_url, Base_url);
}
@Override
public java.lang.String getBase_url()
{
return get_ValueAsString(COLUMNNAME_Base_url);
}
@Override
public void setCarrier_Config_ID (final int Carrier_Config_ID)
{
if (Carrier_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_Carrier_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Carrier_Config_ID, Carrier_Config_ID);
}
@Override
public int getCarrier_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_Config_ID);
}
@Override
public void setClient_Id (final @Nullable java.lang.String Client_Id)
{
set_Value (COLUMNNAME_Client_Id, Client_Id);
}
@Override
public java.lang.String getClient_Id()
{
return get_ValueAsString(COLUMNNAME_Client_Id);
}
@Override
public void setClient_Secret (final @Nullable java.lang.String Client_Secret)
{
set_Value (COLUMNNAME_Client_Secret, Client_Secret);
}
@Override
public java.lang.String getClient_Secret()
{
return get_ValueAsString(COLUMNNAME_Client_Secret);
}
@Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
|
else
set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
}
@Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setPassword (final @Nullable java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
@Override
public java.lang.String getPassword()
{
return get_ValueAsString(COLUMNNAME_Password);
}
@Override
public void setServiceLevel (final @Nullable java.lang.String ServiceLevel)
{
set_Value (COLUMNNAME_ServiceLevel, ServiceLevel);
}
@Override
public java.lang.String getServiceLevel()
{
return get_ValueAsString(COLUMNNAME_ServiceLevel);
}
@Override
public void setUserName (final @Nullable java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return get_ValueAsString(COLUMNNAME_UserName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_Config.java
| 1
|
请完成以下Java代码
|
public String toString(final boolean includeTagMarkers)
{
return includeTagMarkers ? toStringWithMarkers() : toStringWithoutMarkers();
}
@NonNull
public String toStringWithMarkers()
{
String cachedToStringWithTagMarkers = this.cachedToStringWithTagMarkers;
if (cachedToStringWithTagMarkers == null)
{
cachedToStringWithTagMarkers = this.cachedToStringWithTagMarkers = CtxNames.NAME_Marker + toStringWithoutMarkers() + CtxNames.NAME_Marker;
}
return cachedToStringWithTagMarkers;
}
public String toStringWithoutMarkers()
{
String cachedToStringWithoutTagMarkers = this.cachedToStringWithoutTagMarkers;
if (cachedToStringWithoutTagMarkers == null)
{
final StringBuilder sb = new StringBuilder();
sb.append(name);
if (modifiers != null && !modifiers.isEmpty())
{
for (final String m : modifiers)
{
sb.append(CtxNames.SEPARATOR).append(m);
}
}
if (isDefaultValuePresent(defaultValue))
{
sb.append(CtxNames.SEPARATOR).append(defaultValue);
}
cachedToStringWithoutTagMarkers = this.cachedToStringWithoutTagMarkers = sb.toString();
}
return cachedToStringWithoutTagMarkers;
}
private static boolean isDefaultValuePresent(@Nullable String defaultValue)
{
return !Check.isEmpty(defaultValue);
}
@Override
public String toString()
{
return toStringWithoutMarkers();
}
@Override
public int hashCode()
{
if (_hashcode == null)
{
final int prime = 31;
int result = 1;
result = prime * result + (defaultValue == null ? 0 : defaultValue.hashCode());
result = prime * result + (modifiers == null ? 0 : modifiers.hashCode());
result = prime * result + (name == null ? 0 : name.hashCode());
_hashcode = result;
}
return _hashcode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
|
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final CtxName other = (CtxName)obj;
if (defaultValue == null)
{
if (other.defaultValue != null)
{
return false;
}
}
else if (!defaultValue.equals(other.defaultValue))
{
return false;
}
if (modifiers == null)
{
if (other.modifiers != null)
{
return false;
}
}
else if (!modifiers.equals(other.modifiers))
{
return false;
}
if (name == null)
{
if (other.name != null)
{
return false;
}
}
else if (!name.equals(other.name))
{
return false;
}
return true;
}
public boolean equalsByName(@Nullable final CtxName other)
{
return other != null && this.name.equals(other.name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\CtxName.java
| 1
|
请完成以下Java代码
|
public static void main(String[] args) {
System.out.println("Please enter your name and surname: ");
Scanner scanner = new Scanner(System.in);
String nameSurname = scanner.nextLine();
System.out.println("Please enter your gender: ");
char gender = scanner.next().charAt(0);
System.out.println("Please enter your age: ");
int age = scanner.nextInt();
System.out.println("Please enter your height in meters: ");
double height = scanner.nextDouble();
System.out.println(nameSurname + ", " + age + ", is a great " + (gender == 'm' ? "guy" : "girl") + " with " + height + " meters height" + " and " + (gender == 'm' ? "he" : "she") + " reads Baeldung.");
System.out.print("Have a good");
System.out.print(" one!");
System.out.println("\nPlease enter number of years of experience as a developer: ");
BufferedReader buffReader = new BufferedReader(new InputStreamReader(System.in));
int i = 0;
try {
i = Integer.parseInt(buffReader.readLine());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
|
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("You are a " + (i > 5 ? "great" : "good") + " developer!");
int sum = 0, count = 0;
System.out.println("Please enter your college degrees. To finish, enter baeldung website url");
while (scanner.hasNextInt()) {
int nmbr = scanner.nextInt();
sum += nmbr;
count++;
}
int mean = sum / count;
System.out.println("Your average degree is " + mean);
if (scanner.hasNext(Pattern.compile("www.baeldung.com")))
System.out.println("Correct!");
else
System.out.println("Baeldung website url is www.baeldung.com");
if (scanner != null)
scanner.close();
}
}
|
repos\tutorials-master\core-java-modules\core-java-console\src\main\java\com\baeldung\console\ConsoleScannerClass.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ImageGenerator {
private final ImageModel imageModel;
public ImageGenerator(ImageModel imageModel) {
this.imageModel = imageModel;
}
public String generate(String prompt) {
ImagePrompt imagePrompt = new ImagePrompt(prompt);
ImageResponse imageResponse = imageModel.call(imagePrompt);
return resolveImageContent(imageResponse);
}
public String generate(ImageGenerationRequest request) {
ImageOptions imageOptions = OpenAiImageOptions
.builder()
|
.withUser(request.username())
.withHeight(request.height())
.withWidth(request.width())
.build();
ImagePrompt imagePrompt = new ImagePrompt(request.prompt(), imageOptions);
ImageResponse imageResponse = imageModel.call(imagePrompt);
return resolveImageContent(imageResponse);
}
private String resolveImageContent(ImageResponse imageResponse) {
Image image = imageResponse.getResult().getOutput();
return Optional
.ofNullable(image.getUrl())
.orElseGet(image::getB64Json);
}
}
|
repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\imagegen\ImageGenerator.java
| 2
|
请完成以下Java代码
|
public class ProcessDefinitionFormType extends AbstractFormType {
private static final long serialVersionUID = 1L;
public static final String TYPE_NAME = "processDefinition";
@Override
public String getName() {
return TYPE_NAME;
}
@Override
public Object convertFormValueToModelValue(String propertyValue) {
if (propertyValue != null) {
ProcessDefinition processDefinition = ProcessEngines.getDefaultProcessEngine().getRepositoryService().createProcessDefinitionQuery().processDefinitionId(propertyValue).singleResult();
if (processDefinition == null) {
throw new FlowableObjectNotFoundException("Process definition with id " + propertyValue + " does not exist", ProcessDefinitionEntity.class);
}
|
return processDefinition;
}
return null;
}
@Override
public String convertModelValueToFormValue(Object modelValue) {
if (modelValue == null) {
return null;
}
if (!(modelValue instanceof ProcessDefinition)) {
throw new FlowableIllegalArgumentException("This form type only support process definitions, but is " + modelValue.getClass());
}
return ((ProcessDefinition) modelValue).getId();
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\form\ProcessDefinitionFormType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BatchBuilder batchDocumentJson(String batchDocumentJson) {
this.batchDocumentJson = batchDocumentJson;
return this;
}
@Override
public BatchBuilder tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
@Override
public Batch create() {
if (commandExecutor != null) {
BatchBuilder selfBatchBuilder = this;
return commandExecutor.execute(new Command<>() {
@Override
public Batch execute(CommandContext commandContext) {
return batchServiceConfiguration.getBatchEntityManager().createBatch(selfBatchBuilder);
}
});
} else {
return ((BatchServiceImpl) batchServiceConfiguration.getBatchService()).createBatch(this);
}
}
@Override
public String getBatchType() {
return batchType;
}
@Override
public String getSearchKey() {
return searchKey;
}
@Override
public String getSearchKey2() {
|
return searchKey2;
}
@Override
public String getStatus() {
return status;
}
@Override
public String getBatchDocumentJson() {
return batchDocumentJson;
}
@Override
public String getTenantId() {
return tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchBuilderImpl.java
| 2
|
请完成以下Java代码
|
public void setDatePattern(String datePattern) {
this.datePattern = datePattern;
}
public boolean isReadable() {
return readable;
}
public void setReadable(boolean readable) {
this.readable = readable;
}
public boolean isWriteable() {
return writeable;
}
public void setWriteable(boolean writeable) {
this.writeable = writeable;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public List<FormValue> getFormValues() {
return formValues;
}
public void setFormValues(List<FormValue> formValues) {
this.formValues = formValues;
}
@Override
|
public FormProperty clone() {
FormProperty clone = new FormProperty();
clone.setValues(this);
return clone;
}
public void setValues(FormProperty otherProperty) {
super.setValues(otherProperty);
setName(otherProperty.getName());
setExpression(otherProperty.getExpression());
setVariable(otherProperty.getVariable());
setType(otherProperty.getType());
setDefaultExpression(otherProperty.getDefaultExpression());
setDatePattern(otherProperty.getDatePattern());
setReadable(otherProperty.isReadable());
setWriteable(otherProperty.isWriteable());
setRequired(otherProperty.isRequired());
formValues = new ArrayList<>();
if (otherProperty.getFormValues() != null && !otherProperty.getFormValues().isEmpty()) {
for (FormValue formValue : otherProperty.getFormValues()) {
formValues.add(formValue.clone());
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\FormProperty.java
| 1
|
请完成以下Java代码
|
public static class ShortTypeImpl extends PrimitiveValueTypeImpl {
private static final long serialVersionUID = 1L;
public ShortTypeImpl() {
super(Short.class);
}
public ShortValue createValue(Object value, Map<String, Object> valueInfo) {
return Variables.shortValue((Short) value, isTransient(valueInfo));
}
@Override
public ValueType getParent() {
return ValueType.NUMBER;
}
@Override
public ShortValue convertFromTypedValue(TypedValue typedValue) {
if (typedValue.getType() != ValueType.NUMBER) {
throw unsupportedConversion(typedValue.getType());
}
ShortValueImpl shortValue = null;
NumberValue numberValue = (NumberValue) typedValue;
if (numberValue.getValue() != null) {
shortValue = (ShortValueImpl) Variables.shortValue(numberValue.getValue().shortValue());
} else {
shortValue = (ShortValueImpl) Variables.shortValue(null);
}
shortValue.setTransient(numberValue.isTransient());
return shortValue;
}
@Override
public boolean canConvertFromTypedValue(TypedValue typedValue) {
if (typedValue.getType() != ValueType.NUMBER) {
return false;
}
if (typedValue.getValue() != null) {
NumberValue numberValue = (NumberValue) typedValue;
double doubleValue = numberValue.getValue().doubleValue();
// returns false if the value changes due to conversion (e.g. by overflows
// or by loss in precision)
if (numberValue.getValue().shortValue() != doubleValue) {
return false;
}
}
|
return true;
}
}
public static class StringTypeImpl extends PrimitiveValueTypeImpl {
private static final long serialVersionUID = 1L;
public StringTypeImpl() {
super(String.class);
}
public StringValue createValue(Object value, Map<String, Object> valueInfo) {
return Variables.stringValue((String) value, isTransient(valueInfo));
}
}
public static class NumberTypeImpl extends PrimitiveValueTypeImpl {
private static final long serialVersionUID = 1L;
public NumberTypeImpl() {
super(Number.class);
}
public NumberValue createValue(Object value, Map<String, Object> valueInfo) {
return Variables.numberValue((Number) value, isTransient(valueInfo));
}
@Override
public boolean isAbstract() {
return true;
}
}
}
|
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\type\PrimitiveValueTypeImpl.java
| 1
|
请完成以下Java代码
|
public class OrderResponse {
private String orderId;
private Map<String, Integer> products;
private OrderStatusResponse orderStatus;
OrderResponse(Order order) {
this.orderId = order.getOrderId();
this.products = order.getProducts();
this.orderStatus = toResponse(order.getOrderStatus());
}
/**
* Added for the integration test, since it's using Jackson for the response
*/
|
OrderResponse() {
}
public String getOrderId() {
return orderId;
}
public Map<String, Integer> getProducts() {
return products;
}
public OrderStatusResponse getOrderStatus() {
return orderStatus;
}
}
|
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\querymodel\OrderResponse.java
| 1
|
请完成以下Java代码
|
private ImmutableList<IDocumentFieldCallout> buildCallouts()
{
return ImmutableList.copyOf(callouts);
}
public Builder setButtonActionDescriptor(@Nullable final ButtonFieldActionDescriptor buttonActionDescriptor)
{
this.buttonActionDescriptor = buttonActionDescriptor;
return this;
}
public boolean isSupportZoomInto()
{
// Allow zooming into key column. It shall open precisely this record in a new window
// (see https://github.com/metasfresh/metasfresh/issues/1687 to understand the use-case)
// In future we shall think to narrow it down only to included tabs and only for those tables which also have a window where they are the header document.
if (isKey())
{
return true;
}
final DocumentFieldWidgetType widgetType = getWidgetType();
if (!widgetType.isSupportZoomInto())
{
return false;
}
final Class<?> valueClass = getValueClass();
if (StringLookupValue.class.isAssignableFrom(valueClass))
{
return false;
}
final String lookupTableName = getLookupTableName().orElse(null);
return !WindowConstants.TABLENAME_AD_Ref_List.equals(lookupTableName);
}
public Builder setDefaultFilterInfo(@Nullable DocumentFieldDefaultFilterDescriptor defaultFilterInfo)
{
this.defaultFilterInfo = defaultFilterInfo;
return this;
}
/**
* Setting this to a non-{@code null} value means that this field is a tooltip field,
* i.e. it represents a tooltip that is attached to some other field.
*/
public Builder setTooltipIconName(@Nullable final String tooltipIconName)
{
this.tooltipIconName = tooltipIconName;
return this;
}
/**
* @return true if this field has ORDER BY instructions
*/
public boolean isDefaultOrderBy()
{
final DocumentFieldDataBindingDescriptor dataBinding = getDataBinding().orElse(null);
return dataBinding != null && dataBinding.isDefaultOrderBy();
}
|
public int getDefaultOrderByPriority()
{
// we assume isDefaultOrderBy() was checked before calling this method
//noinspection OptionalGetWithoutIsPresent
return getDataBinding().get().getDefaultOrderByPriority();
}
public boolean isDefaultOrderByAscending()
{
// we assume isDefaultOrderBy() was checked before calling this method
//noinspection OptionalGetWithoutIsPresent
return getDataBinding().get().isDefaultOrderByAscending();
}
public Builder deviceDescriptorsProvider(@NonNull final DeviceDescriptorsProvider deviceDescriptorsProvider)
{
this.deviceDescriptorsProvider = deviceDescriptorsProvider;
return this;
}
private DeviceDescriptorsProvider getDeviceDescriptorsProvider()
{
return deviceDescriptorsProvider;
}
public Builder mainAdFieldId(@Nullable final AdFieldId mainAdFieldId)
{
this.mainAdFieldId = mainAdFieldId;
return this;
}
@Nullable
public AdFieldId getMainAdFieldId() {return mainAdFieldId;}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentFieldDescriptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public File getSingleAttachment(String apiKey, String id) throws ApiException {
ApiResponse<File> resp = getSingleAttachmentWithHttpInfo(apiKey, id);
return resp.getData();
}
/**
* Einzelne Anlage abrufen
* Szenario - das WaWi ruft ein bestimmte Anlage als PDF ab
* @param apiKey (required)
* @param id (required)
* @return ApiResponse<File>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<File> getSingleAttachmentWithHttpInfo(String apiKey, String id) throws ApiException {
com.squareup.okhttp.Call call = getSingleAttachmentValidateBeforeCall(apiKey, id, null, null);
Type localVarReturnType = new TypeToken<File>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Einzelne Anlage abrufen (asynchronously)
* Szenario - das WaWi ruft ein bestimmte Anlage als PDF ab
* @param apiKey (required)
* @param id (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call getSingleAttachmentAsync(String apiKey, String id, final ApiCallback<File> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
|
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = getSingleAttachmentValidateBeforeCall(apiKey, id, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<File>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\api\AttachmentApi.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
|
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public String toString() {
return "ExceptionMessage [timestamp=" + timestamp + ", status=" + status + ", error=" + error + ", message=" + message + ", path=" + path + "]";
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-openfeign-2\src\main\java\com\baeldung\cloud\openfeign\fileupload\config\ExceptionMessage.java
| 2
|
请完成以下Java代码
|
private JSONIncludedTabInfo getIncludedTabInfo(final DetailId tabId)
{
return getIncludedTabsInfo().computeIfAbsent(tabId.toJson(), k -> JSONIncludedTabInfo.newInstance(tabId));
}
void addIncludedTabInfo(@NonNull final JSONIncludedTabInfo tabInfo)
{
getIncludedTabsInfo().compute(tabInfo.getTabId().toJson(), (tabId, existingTabInfo) -> {
if (existingTabInfo == null)
{
return tabInfo.copy();
}
else
{
existingTabInfo.mergeFrom(tabInfo);
return existingTabInfo;
}
});
}
@Override
@JsonIgnore
public WebsocketTopicName getWebsocketEndpoint()
{
return WebsocketTopicNames.buildDocumentTopicName(windowId, id);
}
public void staleTabs(@NonNull final Collection<DetailId> tabIds)
{
tabIds.stream().map(this::getIncludedTabInfo).forEach(JSONIncludedTabInfo::markAllRowsStaled);
}
public void staleIncludedRows(@NonNull final DetailId tabId, @NonNull final DocumentIdsSelection rowIds)
{
getIncludedTabInfo(tabId).staleRows(rowIds);
}
void mergeFrom(@NonNull final JSONDocumentChangedWebSocketEvent from)
{
|
if (!Objects.equals(windowId, from.windowId)
|| !Objects.equals(id, from.id))
{
throw new AdempiereException("Cannot merge events because they are not matching")
.setParameter("from", from)
.setParameter("to", this)
.appendParametersToMessage();
}
if (from.stale != null && from.stale)
{
stale = from.stale;
}
from.getIncludedTabsInfo().values().forEach(this::addIncludedTabInfo);
if (from.activeTabStaled != null && from.activeTabStaled)
{
activeTabStaled = from.activeTabStaled;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\events\JSONDocumentChangedWebSocketEvent.java
| 1
|
请完成以下Java代码
|
public BigDecimal getESR_Control_Trx_Qty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ESR_Control_Trx_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setESR_Import_ID (final int ESR_Import_ID)
{
if (ESR_Import_ID < 1)
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, ESR_Import_ID);
}
@Override
public int getESR_Import_ID()
{
return get_ValueAsInt(COLUMNNAME_ESR_Import_ID);
}
@Override
public void setESR_Trx_Qty (final @Nullable BigDecimal ESR_Trx_Qty)
{
throw new IllegalArgumentException ("ESR_Trx_Qty is virtual column"); }
@Override
public BigDecimal getESR_Trx_Qty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ESR_Trx_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setHash (final @Nullable java.lang.String Hash)
{
set_Value (COLUMNNAME_Hash, Hash);
}
@Override
public java.lang.String getHash()
{
return get_ValueAsString(COLUMNNAME_Hash);
}
@Override
public void setIsArchiveFile (final boolean IsArchiveFile)
{
set_Value (COLUMNNAME_IsArchiveFile, IsArchiveFile);
}
@Override
public boolean isArchiveFile()
{
return get_ValueAsBoolean(COLUMNNAME_IsArchiveFile);
}
@Override
public void setIsReceipt (final boolean IsReceipt)
{
set_Value (COLUMNNAME_IsReceipt, IsReceipt);
}
@Override
public boolean isReceipt()
{
return get_ValueAsBoolean(COLUMNNAME_IsReceipt);
}
@Override
public void setIsReconciled (final boolean IsReconciled)
{
set_Value (COLUMNNAME_IsReconciled, IsReconciled);
}
|
@Override
public boolean isReconciled()
{
return get_ValueAsBoolean(COLUMNNAME_IsReconciled);
}
@Override
public void setIsValid (final boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, IsValid);
}
@Override
public boolean isValid()
{
return get_ValueAsBoolean(COLUMNNAME_IsValid);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
throw new IllegalArgumentException ("Processing is virtual column"); }
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_Import.java
| 1
|
请完成以下Java代码
|
private String getLongestCommonPrefix(String str1, String str2) {
int compareLength = Math.min(str1.length(), str2.length());
for (int i = 0; i < compareLength; i++) {
if (str1.charAt(i) != str2.charAt(i)) {
return str1.substring(0, i);
}
}
return str1.substring(0, compareLength);
}
private List<Node> getAllNodesInTraversePath(String pattern, Node startNode, boolean isAllowPartialMatch) {
List<Node> nodes = new ArrayList<>();
for (int i = 0; i < startNode.getChildren()
.size(); i++) {
Node currentNode = startNode.getChildren()
.get(i);
String nodeText = currentNode.getText();
if (pattern.charAt(0) == nodeText.charAt(0)) {
if (isAllowPartialMatch && pattern.length() <= nodeText.length()) {
nodes.add(currentNode);
return nodes;
}
int compareLength = Math.min(nodeText.length(), pattern.length());
for (int j = 1; j < compareLength; j++) {
if (pattern.charAt(j) != nodeText.charAt(j)) {
if (isAllowPartialMatch) {
nodes.add(currentNode);
}
|
return nodes;
}
}
nodes.add(currentNode);
if (pattern.length() > compareLength) {
List<Node> nodes2 = getAllNodesInTraversePath(pattern.substring(compareLength), currentNode, isAllowPartialMatch);
if (nodes2.size() > 0) {
nodes.addAll(nodes2);
} else if (!isAllowPartialMatch) {
nodes.add(null);
}
}
return nodes;
}
}
return nodes;
}
public String printTree() {
return root.printTree("");
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\suffixtree\SuffixTree.java
| 1
|
请完成以下Java代码
|
public RetryConfig addSeries(HttpStatus.Series... series) {
this.series.addAll(Arrays.asList(series));
return this;
}
public Set<Class<? extends Throwable>> getExceptions() {
return exceptions;
}
public RetryConfig setExceptions(Set<Class<? extends Throwable>> exceptions) {
this.exceptions = exceptions;
return this;
}
public RetryConfig addExceptions(Class<? extends Throwable>... exceptions) {
this.exceptions.addAll(Arrays.asList(exceptions));
return this;
}
public Set<HttpMethod> getMethods() {
return methods;
}
public RetryConfig setMethods(Set<HttpMethod> methods) {
this.methods = methods;
return this;
}
public RetryConfig addMethods(HttpMethod... methods) {
this.methods.addAll(Arrays.asList(methods));
return this;
}
public boolean isCacheBody() {
return cacheBody;
|
}
public RetryConfig setCacheBody(boolean cacheBody) {
this.cacheBody = cacheBody;
return this;
}
}
public static class RetryException extends NestedRuntimeException {
private final ServerRequest request;
private final ServerResponse response;
RetryException(ServerRequest request, ServerResponse response) {
super(null);
this.request = request;
this.response = response;
}
public ServerRequest getRequest() {
return request;
}
public ServerResponse getResponse() {
return response;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\RetryFilterFunctions.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String sayHello(){
return "Hello Appleyk's Controller !";
}
/**
* 写一个shp文件
* @param shpInfo
* @return
* @throws Exception
*/
@PostMapping("/write")
public ResponseResult write(@RequestBody ShpInfo shpInfo) throws Exception{
return shpService.writeShp(shpInfo);
}
/**
* 查询一个shp文件
* @param shpFilePath 文件绝对路径
* @param limit 指定显示多少条shp特征【features】
* @return
* @throws Exception
*/
@GetMapping("/query")
public ResponseResult query(@RequestParam(value = "path",required = true) String shpFilePath,
@RequestParam(value = "limit",required = false,defaultValue = "10") Integer limit ) throws Exception{
return shpService.getShpDatas(shpFilePath,limit);
}
/**
|
* 将shp文件转换成png图片,图片或写入文件或通过response输出到界面【比如,客户端浏览器】
* @param path shp文件路径
* @param imagePath 如果imagePath不等于空,则shp文件转成图片文件存储进行存
* @param color 渲染颜色
*/
@GetMapping("/show")
public void show(@RequestParam(value = "path",required = true) String path,
@RequestParam(value = "imagePath",required = false) String imagePath,
@RequestParam(value = "color",required = false) String color,
HttpServletResponse response) throws Exception{
// 设置响应消息的类型
response.setContentType("image/png");
// 设置页面不缓存
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
shpService.showShp(path, imagePath,color ,response);
}
}
|
repos\springboot-demo-master\GeoTools\src\main\java\com\et\geotools\controller\ShpController.java
| 2
|
请完成以下Java代码
|
public ProviderConfig getProvider() {
return this.provider;
}
public void setProvider(ProviderConfig provider) {
this.provider = provider;
}
public ConsumerConfig getConsumer() {
return this.consumer;
}
public void setConsumer(ConsumerConfig consumer) {
this.consumer = consumer;
}
public Map<String, ApplicationConfig> getApplications() {
return this.applications;
}
public void setApplications(Map<String, ApplicationConfig> applications) {
this.applications = applications;
}
public Map<String, ModuleConfig> getModules() {
return this.modules;
}
public void setModules(Map<String, ModuleConfig> modules) {
this.modules = modules;
}
public Map<String, RegistryConfig> getRegistries() {
return this.registries;
}
public void setRegistries(Map<String, RegistryConfig> registries) {
this.registries = registries;
}
public Map<String, ProtocolConfig> getProtocols() {
return this.protocols;
}
public void setProtocols(Map<String, ProtocolConfig> protocols) {
this.protocols = protocols;
|
}
public Map<String, MonitorConfig> getMonitors() {
return this.monitors;
}
public void setMonitors(Map<String, MonitorConfig> monitors) {
this.monitors = monitors;
}
public Map<String, ProviderConfig> getProviders() {
return this.providers;
}
public void setProviders(Map<String, ProviderConfig> providers) {
this.providers = providers;
}
public Map<String, ConsumerConfig> getConsumers() {
return this.consumers;
}
public void setConsumers(Map<String, ConsumerConfig> consumers) {
this.consumers = consumers;
}
@Override
public String toString() {
return "DubboProperties [server=" + this.server + ", application=" + this.application
+ ", module=" + this.module + ", registry=" + this.registry + ", protocol=" + this.protocol
+ ", monitor=" + this.monitor + ", provider=" + this.provider + ", consumer="
+ this.consumer + ", applications=" + this.applications + ", modules=" + this.modules
+ ", registries=" + this.registries + ", protocols=" + this.protocols + ", monitors="
+ this.monitors + ", providers=" + this.providers + ", consumers=" + this.consumers + "]";
}
}
|
repos\dubbo-spring-boot-starter-master\src\main\java\com\alibaba\dubbo\spring\boot\DubboProperties.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public RuntimeService runtimeService(ProcessEngine processEngine) {
return processEngine.getRuntimeService();
}
@Bean
public TaskService taskService(ProcessEngine processEngine) {
return processEngine.getTaskService();
}
@Bean
public HistoryService historyService(ProcessEngine processEngine) {
return processEngine.getHistoryService();
}
@Bean
public ManagementService managementService(ProcessEngine processEngine) {
|
return processEngine.getManagementService();
}
@Bean
public IdentityService identityService(ProcessEngine processEngine) {
return processEngine.getIdentityService();
}
@Bean
public FormService formService(ProcessEngine processEngine) {
return processEngine.getFormService();
}
}
|
repos\spring-boot-quick-master\quick-flowable\src\main\java\com\quick\flowable\config\FlowableConfig.java
| 2
|
请完成以下Java代码
|
private void decrementHUCount()
{
final BigDecimal count = item.getQty();
final BigDecimal countNew = count.subtract(BigDecimal.ONE);
item.setQty(countNew);
dao.save(item);
}
@Override
public int getHUCount()
{
final int count = item.getQty().intValueExact();
return count;
}
@Override
public int getHUCapacity()
{
if (X_M_HU_Item.ITEMTYPE_HUAggregate.equals(item.getItemType()))
{
return Quantity.QTY_INFINITE.intValue();
}
return Services.get(IHandlingUnitsBL.class).getPIItem(item).getQty().intValueExact();
}
@Override
public IProductStorage getProductStorage(final ProductId productId, final I_C_UOM uom, final ZonedDateTime date)
{
return new HUItemProductStorage(this, productId, uom, date);
}
@Override
public List<IProductStorage> getProductStorages(final ZonedDateTime date)
{
final List<I_M_HU_Item_Storage> storages = dao.retrieveItemStorages(item);
final List<IProductStorage> result = new ArrayList<>(storages.size());
for (final I_M_HU_Item_Storage storage : storages)
{
final ProductId productId = ProductId.ofRepoId(storage.getM_Product_ID());
final I_C_UOM uom = extractUOM(storage);
final HUItemProductStorage productStorage = new HUItemProductStorage(this, productId, uom, date);
result.add(productStorage);
}
return result;
}
private I_C_UOM extractUOM(final I_M_HU_Item_Storage storage)
{
return Services.get(IUOMDAO.class).getById(storage.getC_UOM_ID());
}
@Override
public boolean isEmpty()
{
final List<I_M_HU_Item_Storage> storages = dao.retrieveItemStorages(item);
for (final I_M_HU_Item_Storage storage : storages)
{
if (!isEmpty(storage))
|
{
return false;
}
}
return true;
}
private boolean isEmpty(final I_M_HU_Item_Storage storage)
{
final BigDecimal qty = storage.getQty();
if (qty.signum() != 0)
{
return false;
}
return true;
}
@Override
public boolean isEmpty(final ProductId productId)
{
final I_M_HU_Item_Storage storage = dao.retrieveItemStorage(item, productId);
if (storage == null)
{
return true;
}
return isEmpty(storage);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUItemStorage.java
| 1
|
请完成以下Java代码
|
private boolean isAggregateHU(final HUEditorRow huRow)
{
final I_M_HU hu = huRow.getM_HU();
return handlingUnitsBL.isAggregateHU(hu);
}
private final void updateViewFromResult(final WebuiHUTransformCommandResult result)
{
final HUEditorView view = getView();
view.addHUIds(result.getHuIdsToAddToView());
view.removeHUIds(result.getHuIdsToRemoveFromView());
if (!result.getHuIdsChanged().isEmpty())
{
removeHUsIfDestroyed(result.getHuIdsChanged());
}
}
/** @return true if view was changed and needs invalidation */
private final boolean removeSelectedRowsIfHUDestoyed()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isEmpty())
{
return false;
}
else if (selectedRowIds.isAll())
{
return false;
}
final HUEditorView view = getView();
final ImmutableSet<HuId> selectedHUIds = view.streamByIds(selectedRowIds)
.map(HUEditorRow::getHuId)
.filter(Objects::nonNull)
|
.collect(ImmutableSet.toImmutableSet());
return removeHUsIfDestroyed(selectedHUIds);
}
/**
* @return true if at least one HU was removed
*/
private boolean removeHUsIfDestroyed(final Collection<HuId> huIds)
{
final ImmutableSet<HuId> destroyedHUIds = huIds.stream()
.distinct()
.map(huId -> load(huId, I_M_HU.class))
.filter(Services.get(IHandlingUnitsBL.class)::isDestroyed)
.map(I_M_HU::getM_HU_ID)
.map(HuId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
if (destroyedHUIds.isEmpty())
{
return false;
}
final HUEditorView view = getView();
final boolean changes = view.removeHUIds(destroyedHUIds);
return changes;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_Add_Batch_SerialNo_To_CUs.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractAccessDecisionManager
implements AccessDecisionManager, InitializingBean, MessageSourceAware {
protected final Log logger = LogFactory.getLog(getClass());
private List<AccessDecisionVoter<?>> decisionVoters;
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private boolean allowIfAllAbstainDecisions = false;
protected AbstractAccessDecisionManager(List<AccessDecisionVoter<?>> decisionVoters) {
Assert.notEmpty(decisionVoters, "A list of AccessDecisionVoters is required");
this.decisionVoters = decisionVoters;
}
@Override
public void afterPropertiesSet() {
Assert.notEmpty(this.decisionVoters, "A list of AccessDecisionVoters is required");
Assert.notNull(this.messages, "A message source must be set");
}
protected final void checkAllowIfAllAbstainDecisions() {
if (!this.isAllowIfAllAbstainDecisions()) {
throw new AccessDeniedException(
this.messages.getMessage("AbstractAccessDecisionManager.accessDenied", "Access is denied"));
}
}
public List<AccessDecisionVoter<?>> getDecisionVoters() {
return this.decisionVoters;
}
public boolean isAllowIfAllAbstainDecisions() {
return this.allowIfAllAbstainDecisions;
}
public void setAllowIfAllAbstainDecisions(boolean allowIfAllAbstainDecisions) {
this.allowIfAllAbstainDecisions = allowIfAllAbstainDecisions;
}
@Override
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
@Override
public boolean supports(ConfigAttribute attribute) {
for (AccessDecisionVoter<?> voter : this.decisionVoters) {
if (voter.supports(attribute)) {
return true;
}
|
}
return false;
}
/**
* Iterates through all <code>AccessDecisionVoter</code>s and ensures each can support
* the presented class.
* <p>
* If one or more voters cannot support the presented class, <code>false</code> is
* returned.
* @param clazz the type of secured object being presented
* @return true if this type is supported
*/
@Override
public boolean supports(Class<?> clazz) {
for (AccessDecisionVoter<?> voter : this.decisionVoters) {
if (!voter.supports(clazz)) {
return false;
}
}
return true;
}
@Override
public String toString() {
return this.getClass().getSimpleName() + " [DecisionVoters=" + this.decisionVoters
+ ", AllowIfAllAbstainDecisions=" + this.allowIfAllAbstainDecisions + "]";
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\access\vote\AbstractAccessDecisionManager.java
| 1
|
请完成以下Java代码
|
private ZonedDateTime computePurchaseDateOrderedOrNull(@NonNull final ZonedDateTime datePromised, @Nullable final ProductPlanningId productPlanningId)
{
if (productPlanningId == null)
{
return null;
}
final int leadTimeDays = productPlanningDAO.getById(productPlanningId).getLeadTimeDays();
return datePromised.minusDays(leadTimeDays);
}
private void saveCandidateAndPostCreatedEvent(
@NonNull final PurchaseCandidateRequestedEvent requestedEvent,
@NonNull final PurchaseCandidate newPurchaseCandidate)
{
try
{
INTERCEPTOR_SHALL_POST_EVENT_FOR_PURCHASE_CANDIDATE_RECORD.set(false);
final PurchaseCandidateId newPurchaseCandidateId = purchaseCandidateRepository.save(newPurchaseCandidate);
final PurchaseCandidateCreatedEvent purchaseCandidateCreatedEvent = createCandidateCreatedEvent(requestedEvent,
newPurchaseCandidate.getVendorId(),
newPurchaseCandidateId);
postMaterialEventService.enqueueEventAfterNextCommit(purchaseCandidateCreatedEvent);
|
}
finally
{
INTERCEPTOR_SHALL_POST_EVENT_FOR_PURCHASE_CANDIDATE_RECORD.set(true);
}
}
@VisibleForTesting
static PurchaseCandidateCreatedEvent createCandidateCreatedEvent(
@NonNull final PurchaseCandidateRequestedEvent requestedEvent,
@NonNull final BPartnerId vendorId,
@NonNull final PurchaseCandidateId newPurchaseCandidateId)
{
return PurchaseCandidateCreatedEvent.builder()
.eventDescriptor(requestedEvent.getEventDescriptor().withNewEventId())
.purchaseCandidateRepoId(newPurchaseCandidateId.getRepoId())
.vendorId(vendorId.getRepoId())
.purchaseMaterialDescriptor(requestedEvent.getPurchaseMaterialDescriptor())
.supplyCandidateRepoId(requestedEvent.getSupplyCandidateRepoId())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\material\event\PurchaseCandidateRequestedHandler.java
| 1
|
请完成以下Java代码
|
public class IgniteApp {
public static void main (String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(SpringDataConfig.class);
context.refresh();
EmployeeRepository repository = context.getBean(EmployeeRepository.class);
EmployeeDTO employeeDTO = new EmployeeDTO();
employeeDTO.setId(1);
employeeDTO.setName("John");
employeeDTO.setEmployed(true);
repository.save(employeeDTO.getId(), employeeDTO);
EmployeeDTO employee = repository.getEmployeeDTOById(employeeDTO.getId());
System.out.println(employee);
}
private void getUsingTheCache(Integer employeeId) {
|
Ignite ignite = Ignition.ignite();
IgniteCache<Integer, EmployeeDTO> cache = ignite.cache("baeldungCache");
EmployeeDTO employeeDTO = cache.get(employeeId);
System.out.println(employeeDTO);
SqlFieldsQuery sql = new SqlFieldsQuery(
"select * from EmployeeDTO where isEmployed = 'true'");
QueryCursor<List<?>> cursor = cache.query(sql);
}
}
|
repos\tutorials-master\libraries-data-3\src\main\java\com\baeldung\ignite\spring\IgniteApp.java
| 1
|
请完成以下Java代码
|
public Long getOverridingJobPriority() {
return jobPriority;
}
public void setJobPriority(Long jobPriority) {
this.jobPriority = jobPriority;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getDeploymentId() {
return deploymentId;
|
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<>();
return referenceIdAndClass;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\JobDefinitionEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class User {
@Id
@Column(name = "id")
private Long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "second_name")
private String secondName;
public User() {
}
public User(final Long id, final String firstName, final String secondName) {
this.id = id;
this.firstName = firstName;
this.secondName = secondName;
}
public void setId(final Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(final String secondName) {
this.secondName = secondName;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
|
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final User user = (User) o;
if (!Objects.equals(id, user.id)) {
return false;
}
if (!Objects.equals(firstName, user.firstName)) {
return false;
}
return Objects.equals(secondName, user.secondName);
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (secondName != null ? secondName.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", secondName='" + secondName + '\'' +
'}';
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-4\src\main\java\com\baeldung\spring\data\persistence\findvsget\entity\User.java
| 2
|
请完成以下Java代码
|
public class ProductBOMQtys
{
/**
* Calculates Qty + Scrap
*
* @param qty qty (without scrap)
* @param scrapPercent scrap percent (between 0..100)
* @return qty * (1 + qtyScrap/100)
*/
public static BigDecimal computeQtyWithScrap(final BigDecimal qty, @NonNull final Percent scrapPercent)
{
if (qty == null || qty.signum() == 0)
{
return BigDecimal.ZERO;
}
if (scrapPercent.isZero())
{
return qty;
}
final int precision = 8;
return scrapPercent.addToBase(qty, precision);
}
/**
* Calculates Qty + Scrap
|
*
* @param qty qty (without scrap)
* @param scrapPercent scrap percent (between 0..100)
* @return qty * (1 + qtyScrap/100)
*/
public static Quantity computeQtyWithScrap(@NonNull final Quantity qty, @NonNull final Percent scrapPercent)
{
if (qty.signum() == 0)
{
return qty;
}
if (scrapPercent.isZero())
{
return qty;
}
final int precision = 8;
return Quantity.of(
scrapPercent.addToBase(qty.toBigDecimal(), precision),
qty.getUOM());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\ProductBOMQtys.java
| 1
|
请完成以下Java代码
|
static void handleCarExceptionWithNamedVariables(Car<?> car) {
try {
someOperationThatFails(car);
} catch (IllegalStateException ex) {
System.out.println("Got an illegal state exception for: " + car.name());
} catch (RuntimeException ex) {
System.out.println("Got a runtime exception!");
}
}
static void handleCarExceptionWithUnnamedVariables(Car<?> car) {
try {
someOperationThatFails(car);
} catch (IllegalStateException | NumberFormatException _) {
System.out.println("Got an illegal state exception for: " + car.name());
} catch (RuntimeException _) {
System.out.println("Got a runtime exception!");
}
}
static void obtainTransactionAndUpdateCarWithNamedVariables(Car<?> car) {
try (var transaction = new Transaction()) {
updateCar(car);
}
}
static void obtainTransactionAndUpdateCarWithUnnamedVariables(Car<?> car) {
try (var _ = new Transaction()) {
updateCar(car);
}
}
|
static void updateCar(Car<?> car) {
// Some update logic
System.out.println("Car updated!");
}
static Map<String, List<Car<?>>> getCarsByFirstLetterWithNamedVariables(List<Car<?>> cars) {
Map<String, List<Car<?>>> carMap = new HashMap<>();
cars.forEach(car ->
carMap.computeIfAbsent(car.name().substring(0, 1), firstLetter -> new ArrayList<>()).add(car)
);
return carMap;
}
static Map<String, List<Car<?>>> getCarsByFirstLetterWithUnnamedVariables(List<Car<?>> cars) {
Map<String, List<Car<?>>> carMap = new HashMap<>();
cars.forEach(car ->
carMap.computeIfAbsent(car.name().substring(0, 1), _ -> new ArrayList<>()).add(car)
);
return carMap;
}
private static void someOperationThatFails(Car<?> car) {
throw new IllegalStateException("Triggered exception for: " + car.name());
}
}
|
repos\tutorials-master\core-java-modules\core-java-21\src\main\java\com\baeldung\unnamed\variables\UnnamedVariables.java
| 1
|
请完成以下Java代码
|
public static ZoneId getTimeZoneOrSystemDefault()
{
final UserSession userSession = getCurrentOrNull();
return userSession != null ? userSession.getTimeZone() : SystemTime.zoneId();
}
public boolean isWorkplacesEnabled()
{
return workplaceService.isAnyWorkplaceActive();
}
public @NonNull Optional<Workplace> getWorkplace()
{
if (!isWorkplacesEnabled())
{
return Optional.empty();
}
|
return getLoggedUserIdIfExists().flatMap(workplaceService::getWorkplaceByUserId);
}
/**
* Event fired when the user language was changed.
* Usually it is user triggered.
*
* @author metas-dev <dev@metasfresh.com>
*/
@lombok.Value
public static class LanguagedChangedEvent
{
@NonNull String adLanguage;
UserId adUserId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\UserSession.java
| 1
|
请完成以下Java代码
|
protected void prepare()
{
ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else
log.error("prepare - Unknown Parameter: " + name);
}
p_PA_SLA_Goal_ID = getRecord_ID();
} // prepare
/**
* Process
* @return info
* @throws Exception
*/
protected String doIt () throws Exception
{
log.info("PA_SLA_Goal_ID=" + p_PA_SLA_Goal_ID);
|
MSLAGoal goal = new MSLAGoal(getCtx(), p_PA_SLA_Goal_ID, get_TrxName());
if (goal.get_ID() == 0)
throw new AdempiereUserError("@PA_SLA_Goal_ID@ " + p_PA_SLA_Goal_ID);
MSLACriteria criteria = MSLACriteria.get(getCtx(), goal.getPA_SLA_Criteria_ID(), get_TrxName());
if (criteria.get_ID() == 0)
throw new AdempiereUserError("@PA_SLA_Criteria_ID@ " + goal.getPA_SLA_Criteria_ID());
SLACriteria pgm = criteria.newSLACriteriaInstance();
int no = pgm.createMeasures(goal);
//
goal.setMeasureActual(pgm.calculateMeasure(goal));
goal.setDateLastRun(new Timestamp(System.currentTimeMillis()));
goal.save();
//
return "@Created@ " + no + " - @MeasureActual@=" + goal.getMeasureActual();
} // doIt
} // SLAGoalProcess
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\sla\SLAGoalProcess.java
| 1
|
请完成以下Java代码
|
public void invalidateForModel(@NonNull final ICacheSourceModel model, @NonNull final ModelCacheInvalidationTiming timing)
{
final CacheInvalidateMultiRequest request = createRequestOrNull(model, timing);
if (request == null)
{
return;
}
invalidate(request, timing);
}
public void invalidate(@NonNull final CacheInvalidateMultiRequest request, @NonNull final ModelCacheInvalidationTiming timing)
{
//
// Reset model cache
// * only on AFTER event
// * only if it's not NEW event because in case of NEW, the model was not already in cache, for sure
if (timing.isAfter() && !timing.isNew())
{
modelCacheService.invalidate(request);
}
//
// Reset cache
// NOTE: we need to do it even for newly created records because there are some aggregates which are cached (e.g. all lines for a given document),
// so in case a new record pops in, those caches shall be reset..
CacheMgt.get().resetLocalNowAndBroadcastOnTrxCommit(ITrx.TRXNAME_ThreadInherited, request);
}
public CacheInvalidateMultiRequest createRequestOrNull(
@NonNull final ICacheSourceModel model,
@NonNull final ModelCacheInvalidationTiming timing)
{
final String tableName = model.getTableName();
final HashSet<CacheInvalidateRequest> requests = getRequestFactoriesByTableName(tableName, timing)
.stream()
.map(requestFactory -> requestFactory.createRequestsFromModel(model, timing))
.filter(Objects::nonNull)
.flatMap(List::stream)
.filter(Objects::nonNull)
.collect(Collectors.toCollection(HashSet::new));
//
final CacheInvalidateRequest request = createChildRecordInvalidateUsingRootRecordReference(model);
if (request != null)
|
{
requests.add(request);
}
//
if (requests.isEmpty())
{
return null;
}
return CacheInvalidateMultiRequest.of(requests);
}
private CacheInvalidateRequest createChildRecordInvalidateUsingRootRecordReference(final ICacheSourceModel model)
{
final TableRecordReference rootRecordReference = model.getRootRecordReferenceOrNull();
if (rootRecordReference == null)
{
return null;
}
final String modelTableName = model.getTableName();
final int modelRecordId = model.getRecordId();
return CacheInvalidateRequest.builder()
.rootRecord(rootRecordReference.getTableName(), rootRecordReference.getRecord_ID())
.childRecord(modelTableName, modelRecordId)
.build();
}
private Set<ModelCacheInvalidateRequestFactory> getRequestFactoriesByTableName(@NonNull final String tableName, @NonNull final ModelCacheInvalidationTiming timing)
{
final Set<ModelCacheInvalidateRequestFactory> factories = factoryGroups.stream()
.flatMap(factoryGroup -> factoryGroup.getFactoriesByTableName(tableName, timing).stream())
.collect(ImmutableSet.toImmutableSet());
return factories != null && !factories.isEmpty() ? factories : DEFAULT_REQUEST_FACTORIES;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\ModelCacheInvalidationService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToOne
@PrimaryKeyJoinColumn
private Department department;
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 Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\primarykeyjoincolumn\Person.java
| 2
|
请完成以下Java代码
|
public final class ConnectionFactoryConfigurationUtils {
private ConnectionFactoryConfigurationUtils() {
}
/**
* Parse the properties {@code key:value[,key:value]...} and add them to the
* underlying connection factory client properties.
* @param connectionFactory the connection factory.
* @param clientConnectionProperties the properties.
*/
public static void updateClientConnectionProperties(AbstractConnectionFactory connectionFactory,
@Nullable String clientConnectionProperties) {
if (clientConnectionProperties != null) {
String[] props = clientConnectionProperties.split(",");
if (props.length > 0) {
|
Map<String, Object> clientProps =
connectionFactory.getRabbitConnectionFactory()
.getClientProperties();
for (String prop : props) {
String[] aProp = prop.split(":");
if (aProp.length == 2) {
clientProps.put(aProp[0].trim(), aProp[1].trim());
}
}
}
}
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\ConnectionFactoryConfigurationUtils.java
| 1
|
请完成以下Java代码
|
public Object getPersistentState() {
return null;
}
@Override
public void setRevision(int revision) {}
@Override
public int getRevision() {
return 0;
}
@Override
public int getRevisionNext() {
return 0;
}
@Override
public void setName(String name) {}
@Override
public void setProcessInstanceId(String processInstanceId) {}
@Override
public void setExecutionId(String executionId) {}
@Override
public Object getValue() {
return variableValue;
}
@Override
public void setValue(Object value) {
variableValue = value;
}
@Override
public String getTypeName() {
return TYPE_TRANSIENT;
}
@Override
|
public void setTypeName(String typeName) {}
@Override
public String getProcessInstanceId() {
return null;
}
@Override
public String getTaskId() {
return null;
}
@Override
public void setTaskId(String taskId) {}
@Override
public String getExecutionId() {
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TransientVariableInstance.java
| 1
|
请完成以下Java代码
|
public List<I_M_HU> retrieveVhus(@NonNull final HuId huId)
{
return handlingUnitsBL.getVHUs(huId);
}
public List<I_M_HU> retrieveVhus(@NonNull final I_M_HU hu)
{
return handlingUnitsBL.getVHUs(hu);
}
/**
* @return the {@code M_HU_ID} of the given {@code hu}'s topmost parent (or grandparent etc),
* <b>or</b>{@code -1} if the given {@code hu} is not "physical".
*/
public int retrieveTopLevelHuId(@NonNull final I_M_HU hu)
{
if (huStatusBL.isPhysicalHU(hu) || huStatusBL.isStatusShipped(hu))
{
return handlingUnitsBL.getTopLevelParent(hu).getM_HU_ID();
}
return -1;
}
public Optional<IPair<ProductId, Quantity>> retrieveProductAndQty(@NonNull final I_M_HU vhu)
{
final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory();
final IHUStorage vhuStorage = storageFactory.getStorage(vhu);
if (vhuStorage == null)
{
return Optional.empty();
}
|
final ProductId vhuProductId = vhuStorage.getSingleProductIdOrNull();
if (vhuProductId == null)
{
return Optional.empty();
}
final I_C_UOM stockingUOM = productBL.getStockUOM(vhuProductId);
final Quantity qty = vhuStorage.getQuantity(vhuProductId, stockingUOM);
return Optional.of(ImmutablePair.of(vhuProductId, qty));
}
public Optional<Quantity> retrieveProductQty(final HuId huId, final ProductId productId)
{
return retrieveProductAndQty(handlingUnitsBL.getById(huId))
.filter(productAndQty -> ProductId.equals(productAndQty.getLeft(), productId))
.map(IPair::getRight);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\trace\HUAccessService.java
| 1
|
请完成以下Java代码
|
public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
return Flux.fromIterable(this.entryPoints)
.filterWhen((entry) -> isMatch(exchange, entry))
.next()
.map((entry) -> entry.getEntryPoint())
.doOnNext((entryPoint) -> logger.debug(LogMessage.format("Match found! Executing %s", entryPoint)))
.switchIfEmpty(Mono.just(this.defaultEntryPoint)
.doOnNext((entryPoint) -> logger
.debug(LogMessage.format("No match found. Using default entry point %s", this.defaultEntryPoint))))
.flatMap((entryPoint) -> entryPoint.commence(exchange, ex));
}
private Mono<Boolean> isMatch(ServerWebExchange exchange, DelegateEntry entry) {
ServerWebExchangeMatcher matcher = entry.getMatcher();
logger.debug(LogMessage.format("Trying to match using %s", matcher));
return matcher.matches(exchange).map(MatchResult::isMatch);
}
/**
* EntryPoint which is used when no RequestMatcher returned true
*/
public void setDefaultEntryPoint(ServerAuthenticationEntryPoint defaultEntryPoint) {
this.defaultEntryPoint = defaultEntryPoint;
}
public static class DelegateEntry {
private final ServerWebExchangeMatcher matcher;
|
private final ServerAuthenticationEntryPoint entryPoint;
public DelegateEntry(ServerWebExchangeMatcher matcher, ServerAuthenticationEntryPoint entryPoint) {
this.matcher = matcher;
this.entryPoint = entryPoint;
}
public ServerWebExchangeMatcher getMatcher() {
return this.matcher;
}
public ServerAuthenticationEntryPoint getEntryPoint() {
return this.entryPoint;
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\DelegatingServerAuthenticationEntryPoint.java
| 1
|
请完成以下Java代码
|
public static LockOwner newOwner(final String ownerNamePrefix, final Object ownerNameUniquePart)
{
Check.assumeNotNull(ownerNameUniquePart, "ownerNameUniquePart not null");
final String ownerNamePrefixToUse;
if (Check.isEmpty(ownerNamePrefix, true))
{
ownerNamePrefixToUse = "Unknown";
}
else
{
ownerNamePrefixToUse = ownerNamePrefix.trim();
}
final String ownerName = ownerNamePrefixToUse + "_" + ownerNameUniquePart;
return new LockOwner(ownerName, OwnerType.RealOwner);
}
/**
* Creates a new instance with "static" name.
*
* @param ownerName the name of the new owner. Other than with the <code>newOwner(...)</code> methods, nothing will be added to it.
* @return
*/
public static final LockOwner forOwnerName(final String ownerName)
{
Check.assumeNotEmpty(ownerName, "ownerName not empty");
return new LockOwner(ownerName, OwnerType.RealOwner);
}
private final String ownerName;
private final OwnerType ownerType;
|
private LockOwner(final String ownerName, final OwnerType ownerType)
{
Check.assumeNotNull(ownerName, "Param ownerName is not null");
this.ownerName = ownerName;
this.ownerType = ownerType;
}
public boolean isRealOwner()
{
return ownerType == OwnerType.RealOwner;
}
public boolean isRealOwnerOrNoOwner()
{
return isRealOwner()
|| isNoOwner();
}
public boolean isNoOwner()
{
return ownerType == OwnerType.None;
}
public boolean isAnyOwner()
{
return ownerType == OwnerType.Any;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\LockOwner.java
| 1
|
请完成以下Java代码
|
public boolean applies(@Nullable final BOMComponentIssueMethod issueMethod)
{
switch (this)
{
case DEFAULT:
return true;
case AssignedHUsOnly:
return issueMethod != null && issueMethod.isIssueOnlyForReceived();
default:
throw new AdempiereException("RawMaterialsIssueStrategy not supported!")
.appendParametersToMessage()
.setParameter("RawMaterialsIssueStrategy", this);
}
}
@Nullable
public static String toCode(@Nullable final RawMaterialsIssueStrategy strategy)
{
return strategy == null
? null
: strategy.getCode();
}
@NonNull
|
public static RawMaterialsIssueStrategy ofCode(@Nullable final String code)
{
return ofCodeOrDefault(code);
}
@NonNull
public static RawMaterialsIssueStrategy ofCodeOrDefault(@Nullable final String code)
{
if (AssignedHUsOnly.getCode().equals(code))
{
return AssignedHUsOnly;
}
return DEFAULT;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\RawMaterialsIssueStrategy.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Edge unassignEdgeFromCustomer(Edge edge, Customer customer, User user) throws ThingsboardException {
ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER;
TenantId tenantId = edge.getTenantId();
EdgeId edgeId = edge.getId();
CustomerId customerId = customer.getId();
try {
Edge savedEdge = checkNotNull(edgeService.unassignEdgeFromCustomer(tenantId, edgeId));
logEntityActionService.logEntityAction(tenantId, edgeId, savedEdge, customerId, actionType,
user, edgeId.toString(), customerId.toString(), customer.getName());
return savedEdge;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.EDGE),
ActionType.UNASSIGNED_FROM_CUSTOMER, user, e, edgeId.toString());
throw e;
}
}
@Override
public Edge assignEdgeToPublicCustomer(TenantId tenantId, EdgeId edgeId, User user) throws ThingsboardException {
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER;
Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId);
CustomerId customerId = publicCustomer.getId();
try {
Edge savedEdge = checkNotNull(edgeService.assignEdgeToCustomer(tenantId, edgeId, customerId));
logEntityActionService.logEntityAction(tenantId, edgeId, savedEdge, customerId, actionType, user,
edgeId.toString(), customerId.toString(), publicCustomer.getName());
return savedEdge;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.EDGE),
actionType, user, e, edgeId.toString());
throw e;
|
}
}
@Override
public Edge setEdgeRootRuleChain(Edge edge, RuleChainId ruleChainId, User user) throws Exception {
TenantId tenantId = edge.getTenantId();
EdgeId edgeId = edge.getId();
try {
Edge updatedEdge = edgeService.setEdgeRootRuleChain(tenantId, edge, ruleChainId);
logEntityActionService.logEntityAction(tenantId, edgeId, edge, null, ActionType.UPDATED, user);
return updatedEdge;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.EDGE),
ActionType.UPDATED, user, e, edgeId.toString());
throw e;
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\edge\DefaultTbEdgeService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void init(H http) {
this.loginPageGeneratingFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy());
this.loginPageGeneratingFilter.setResolveHiddenInputs(DefaultLoginPageConfigurer.this::hiddenInputs);
this.logoutPageGeneratingFilter.setResolveHiddenInputs(DefaultLoginPageConfigurer.this::hiddenInputs);
http.setSharedObject(DefaultLoginPageGeneratingFilter.class, this.loginPageGeneratingFilter);
}
private Map<String, String> hiddenInputs(HttpServletRequest request) {
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
return (token != null) ? Collections.singletonMap(token.getParameterName(), token.getToken())
: Collections.emptyMap();
}
@Override
@SuppressWarnings("unchecked")
public void configure(H http) {
|
AuthenticationEntryPoint authenticationEntryPoint = null;
ExceptionHandlingConfigurer<?> exceptionConf = http.getConfigurer(ExceptionHandlingConfigurer.class);
if (exceptionConf != null) {
authenticationEntryPoint = exceptionConf.getAuthenticationEntryPoint();
}
if (this.loginPageGeneratingFilter.isEnabled() && authenticationEntryPoint == null) {
this.loginPageGeneratingFilter = postProcess(this.loginPageGeneratingFilter);
http.addFilter(this.loginPageGeneratingFilter);
http.addFilter(DefaultResourcesFilter.css());
LogoutConfigurer<H> logoutConfigurer = http.getConfigurer(LogoutConfigurer.class);
if (logoutConfigurer != null) {
http.addFilter(this.logoutPageGeneratingFilter);
}
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\DefaultLoginPageConfigurer.java
| 2
|
请完成以下Java代码
|
private void jbInit() throws Exception
{
final String title = Adempiere.getName() + " - " + s_res.getString("Adempiere_License");
final JFrame dummyParentFrame = getOwner();
dummyParentFrame.setTitle(title);
dummyParentFrame.setIconImages(getIconImages());
setTitle(title);
southLabel.setText(s_res.getString("Do_you_accept"));
bReject.setText(s_res.getString("No"));
bAccept.setText(s_res.getString("Yes_I_Understand"));
//
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModal(true);
//
mainPanel.setLayout(mainLayout);
bReject.setForeground(Color.red);
bReject.addActionListener(this);
bAccept.addActionListener(this);
southPanel.setLayout(southLayout);
southLayout.setAlignment(FlowLayout.RIGHT);
licensePane.setEditable(false);
licensePane.setContentType("text/html");
scrollPane.setPreferredSize(new Dimension(700, 400));
southPanel.add(southLabel, null);
getContentPane().add(mainPanel);
mainPanel.add(scrollPane, BorderLayout.CENTER);
scrollPane.getViewport().add(licensePane, null);
mainPanel.add(southPanel, BorderLayout.SOUTH);
southPanel.add(bReject, null);
southPanel.add(bAccept, null);
} // jbInit
/**
* ActionListener
*
* @param e event
*/
@Override
public final void actionPerformed(ActionEvent e)
{
if (e.getSource() == bAccept)
m_accept = true;
dispose();
} // actionPerformed
/**
* Dispose
*/
@Override
public final void dispose()
{
if(_disposed)
{
return;
}
|
_disposed = true;
super.dispose();
if (!m_accept)
{
cmd_reject();
}
final JFrame dummyParentFrame = getOwner();
dummyParentFrame.dispose();
}
private boolean _disposed = false;
/**
* @return our dummy parent frame
* @see #createDummyParentFrame()
*/
@Override
public JFrame getOwner()
{
return (JFrame) super.getOwner();
}
/**
* Is Accepted
*
* @return true if accepted
*/
public final boolean isAccepted()
{
return m_accept;
} // isAccepted
/**
* Reject License
*/
public final void cmd_reject()
{
String info = "License rejected or expired";
try
{
info = s_res.getString("License_rejected");
}
catch (Exception e)
{
}
log.error(info);
System.exit(10);
} // cmd_reject
} // IniDialog
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\IniDialog.java
| 1
|
请完成以下Java代码
|
public void startProcessInstanceByKeyForm(String processDefinitionKey, String callbackUrl) {
this.url = callbackUrl;
this.processDefinitionKey = processDefinitionKey;
beginConversation();
}
/**
* Get processDefinitionKey and callbackUrl from request and start a conversation
* to start the form
*
*/
public void startProcessInstanceByKeyForm() {
if (FacesContext.getCurrentInstance().isPostback()) {
// if this is an AJAX request ignore it, since we will receive multiple calls to this bean if it is added
// as preRenderView event
// see http://stackoverflow.com/questions/2830834/jsf-fevent-prerenderview-is-triggered-by-fajax-calls-and-partial-renders-some
return;
}
Map<String, String> requestParameterMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String processDefinitionKey = requestParameterMap.get("processDefinitionKey");
String callbackUrl = requestParameterMap.get("callbackUrl");
this.url = callbackUrl;
this.processDefinitionKey = processDefinitionKey;
beginConversation();
}
public void completeProcessInstanceForm() throws IOException {
// start the process instance
if (processDefinitionId!=null) {
businessProcess.startProcessById(processDefinitionId);
processDefinitionId = null;
} else {
businessProcess.startProcessByKey(processDefinitionKey);
processDefinitionKey = null;
}
// End the conversation
|
conversationInstance.get().end();
// and redirect
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
}
public ProcessDefinition getProcessDefinition() {
// TODO cache result to avoid multiple queries within one page request
if (processDefinitionId!=null) {
return repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
} else {
return repositoryService.createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey).latestVersion().singleResult();
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\jsf\TaskForm.java
| 1
|
请完成以下Java代码
|
public EqualsBuilder append(final Map<String, Object> map1, final Map<String, Object> map2, final boolean handleEmptyAsNull)
{
if (!isEqual)
{
return this;
}
if (handleEmptyAsNull)
{
final Object value1 = map1 == null || map1.isEmpty() ? null : map1;
final Object value2 = map2 == null || map2.isEmpty() ? null : map2;
return append(value1, value2);
}
return append(map1, map2);
}
public boolean isEqual()
{
return isEqual;
}
/**
* Checks and casts <code>other</code> to same class as <code>obj</code>.
*
* This method shall be used as first statement in an {@link Object#equals(Object)} implementation. <br/>
* <br/>
* Example:
*
* <pre>
* public boolean equals(Object obj)
* {
* if (this == obj)
* {
* return true;
* }
* final MyClass other = EqualsBuilder.getOther(this, obj);
* if (other == null)
* {
* return false;
* }
*
* return new EqualsBuilder()
* .append(prop1, other.prop1)
* .append(prop2, other.prop2)
* .append(prop3, other.prop3)
* // ....
* .isEqual();
* }
|
* </pre>
*
* @param thisObj this object
* @param obj other object
* @return <code>other</code> casted to same class as <code>obj</code> or null if <code>other</code> is null or does not have the same class
*/
public static <T> T getOther(final T thisObj, final Object obj)
{
if (thisObj == null)
{
throw new IllegalArgumentException("obj is null");
}
if (thisObj == obj)
{
@SuppressWarnings("unchecked")
final T otherCasted = (T)obj;
return otherCasted;
}
if (obj == null)
{
return null;
}
if (thisObj.getClass() != obj.getClass())
{
return null;
}
@SuppressWarnings("unchecked")
final T otherCasted = (T)obj;
return otherCasted;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\EqualsBuilder.java
| 1
|
请完成以下Java代码
|
public class ELInputEntryExpressionPreParser {
protected static final String[] OPERATORS = new String[]{"==", "!=", "<", ">", ">=", "<="};
public static String parse(String expression, String inputVariable, String inputVariableType) {
expression = expression.replaceAll("fn_date", "date:toDate");
expression = expression.replaceAll("fn_subtractDate", "date:subtractDate");
expression = expression.replaceAll("fn_addDate", "date:addDate");
expression = expression.replaceAll("fn_now", "date:now");
if ((expression.contains("#{") || expression.contains("${")) && expression.contains("}")) {
return expression;
}
StringBuilder parsedExpressionBuilder = new StringBuilder();
parsedExpressionBuilder
.append("#{")
.append(inputVariable);
if ("date".equals(inputVariableType) || "number".equals(inputVariableType)) {
parsedExpressionBuilder.append(parseSegmentWithOperator(expression));
} else {
if (expression.startsWith(".")) {
parsedExpressionBuilder.append(expression);
} else {
parsedExpressionBuilder.append(parseSegmentWithOperator(expression));
|
}
}
parsedExpressionBuilder.append("}");
return parsedExpressionBuilder.toString();
}
protected static String parseSegmentWithOperator(String expression) {
String parsedExpressionSegment;
if (expression.length() < 2 || !StringUtils.startsWithAny(expression, OPERATORS)) {
parsedExpressionSegment = " == " + expression;
} else {
parsedExpressionSegment = " " + expression;
}
return parsedExpressionSegment;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\el\ELInputEntryExpressionPreParser.java
| 1
|
请完成以下Java代码
|
private static Optional<Object> generateDefaultValue(final Attribute attribute, final Evaluatee evalCtx)
{
try
{
if (attribute.getDefaultValueSQL() != null)
{
final String defaultValueSQL = attribute.getDefaultValueSQL().evaluate(evalCtx, IExpressionEvaluator.OnVariableNotFound.Fail);
final Object defaultValue = attribute.getValueType().map(new AttributeValueType.CaseMapper<Object>()
{
@Override
public Object string()
{
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited, defaultValueSQL);
}
@Override
public Object number()
{
return DB.getSQLValueBDEx(ITrx.TRXNAME_ThreadInherited, defaultValueSQL);
}
@Override
public Object date()
{
return DB.getSQLValueTSEx(ITrx.TRXNAME_ThreadInherited, defaultValueSQL);
}
@Override
public Object list()
{
|
// TODO: resolve the M_AttributeValue
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited, defaultValueSQL);
}
});
return Optional.of(Null.box(defaultValue));
}
else
{
return Optional.empty();
}
}
catch (Exception ex)
{
logger.warn("Failed generating default value for {}. Returning empty.", attribute, ex);
return Optional.empty();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeSetInstanceBL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public long executeCount(CommandContext commandContext) {
if (isCmmnEnabled(commandContext)) {
checkQueryOk();
return commandContext
.getCaseDefinitionManager()
.findCaseDefinitionCountByQueryCriteria(this);
}
return 0;
}
@Override
public List<CaseDefinition> executeList(CommandContext commandContext, Page page) {
if (isCmmnEnabled(commandContext)) {
checkQueryOk();
return commandContext
.getCaseDefinitionManager()
.findCaseDefinitionsByQueryCriteria(this, page);
}
return Collections.emptyList();
}
@Override
public void checkQueryOk() {
super.checkQueryOk();
// latest() makes only sense when used with key() or keyLike()
if (latest && ( (id != null) || (name != null) || (nameLike != null) || (version != null) || (deploymentId != null) ) ){
throw new NotValidException("Calling latest() can only be used in combination with key(String) and keyLike(String)");
}
}
private boolean isCmmnEnabled(CommandContext commandContext) {
return commandContext
.getProcessEngineConfiguration()
.isCmmnEnabled();
}
// getters ////////////////////////////////////////////
public String getId() {
return id;
}
public String[] getIds() {
return ids;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getName() {
return name;
}
public String getNameLike() {
|
return nameLike;
}
public String getDeploymentId() {
return deploymentId;
}
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public Integer getVersion() {
return version;
}
public boolean isLatest() {
return latest;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\repository\CaseDefinitionQueryImpl.java
| 2
|
请完成以下Java代码
|
protected Capacity retrieveTotalCapacity()
{
checkStaled();
final I_C_UOM uom = ppOrderBOMBL.getBOMLineUOM(orderBOMLine);
return Capacity.createInfiniteCapacity(productId, uom);
}
/**
* @return quantity that was already issued/received on this order BOM Line
*/
@Override
protected BigDecimal retrieveQtyInitial()
{
checkStaled();
final Quantity qtyCapacity;
final Quantity qtyToIssueOrReceive;
final BOMComponentType componentType = BOMComponentType.ofCode(orderBOMLine.getComponentType());
if (componentType.isReceipt())
{
qtyCapacity = ppOrderBOMBL.getQtyRequiredToReceive(orderBOMLine);
qtyToIssueOrReceive = ppOrderBOMBL.getQtyToReceive(orderBOMLine);
}
else
{
qtyCapacity = ppOrderBOMBL.getQtyRequiredToIssue(orderBOMLine);
qtyToIssueOrReceive = ppOrderBOMBL.getQtyToIssue(orderBOMLine);
}
final Quantity qtyIssued = qtyCapacity.subtract(qtyToIssueOrReceive);
return qtyIssued.toBigDecimal();
}
|
@Override
protected void beforeMarkingStalled()
{
staled = true;
}
/**
* refresh BOM line if staled
*/
private void checkStaled()
{
if (!staled)
{
return;
}
InterfaceWrapperHelper.refresh(orderBOMLine);
staled = false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\PPOrderBOMLineProductStorage.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getSingleKeyColumn(final String tableName)
{
if (Adempiere.isUnitTestMode())
{
return InterfaceWrapperHelper.getKeyColumnName(tableName);
}
final POInfo poInfo = POInfo.getPOInfo(tableName);
final List<String> keyColumnNames = poInfo.getKeyColumnNames();
if (keyColumnNames.size() != 1)
{
throw new NoSingleKeyColumnException(poInfo);
}
return keyColumnNames.get(0);
}
@Override
public boolean getDefaultAllowLoggingByColumnName(@NonNull final String columnName)
{
if (columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_Created)
|| columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_CreatedBy)
|| columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_Updated)
|| columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_UpdatedBy))
{
return false;
}
return true;
|
}
@Override
public boolean getDefaultIsCalculatedByColumnName(@NonNull final String columnName)
{
return columnName.equalsIgnoreCase("Value")
|| columnName.equalsIgnoreCase("DocumentNo")
|| columnName.equalsIgnoreCase("DocStatus")
|| columnName.equalsIgnoreCase("Docaction")
|| columnName.equalsIgnoreCase("Processed")
|| columnName.equalsIgnoreCase("Processing")
|| StringUtils.containsIgnoreCase(columnName, "ExternalID")
|| columnName.equalsIgnoreCase("ExternalHeaderId")
|| columnName.equalsIgnoreCase("ExternalLineId")
|| columnName.equalsIgnoreCase("IsReconciled")
;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\service\impl\ColumnBL.java
| 2
|
请完成以下Java代码
|
public class Attribute {
protected String name;
protected String value;
protected String uri;
public Attribute(String name, String value) {
this.name = name;
this.value = value;
}
public Attribute(String name, String value, String uri) {
this(name, value);
this.uri = uri;
}
public String getName() {
return name;
}
|
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\xml\Attribute.java
| 1
|
请完成以下Java代码
|
protected void initialize() {
ExecutionEntity processInstance = commandContext.getExecutionManager().findExecutionById(processInstanceId);
this.processDefinition = processInstance.getProcessDefinition();
List<ExecutionEntity> executions = fetchExecutionsForProcessInstance(processInstance);
executions.add(processInstance);
List<ExecutionEntity> leaves = findLeaves(executions);
assignExecutionsToActivities(leaves);
}
protected void assignExecutionsToActivities(List<ExecutionEntity> leaves) {
for (ExecutionEntity leaf : leaves) {
ScopeImpl activity = leaf.getActivity();
if (activity != null) {
if (leaf.getActivityInstanceId() != null) {
EnsureUtil.ensureNotNull("activity", activity);
submitExecution(leaf, activity);
}
mergeScopeExecutions(leaf);
}
else if (leaf.isProcessInstanceExecution()) {
submitExecution(leaf, leaf.getProcessDefinition());
}
}
}
protected void mergeScopeExecutions(ExecutionEntity leaf) {
Map<ScopeImpl, PvmExecutionImpl> mapping = leaf.createActivityExecutionMapping();
for (Map.Entry<ScopeImpl, PvmExecutionImpl> mappingEntry : mapping.entrySet()) {
ScopeImpl scope = mappingEntry.getKey();
ExecutionEntity scopeExecution = (ExecutionEntity) mappingEntry.getValue();
submitExecution(scopeExecution, scope);
}
}
protected List<ExecutionEntity> fetchExecutionsForProcessInstance(ExecutionEntity execution) {
List<ExecutionEntity> executions = new ArrayList<ExecutionEntity>();
executions.addAll(execution.getExecutions());
for (ExecutionEntity child : execution.getExecutions()) {
executions.addAll(fetchExecutionsForProcessInstance(child));
}
|
return executions;
}
protected List<ExecutionEntity> findLeaves(List<ExecutionEntity> executions) {
List<ExecutionEntity> leaves = new ArrayList<ExecutionEntity>();
for (ExecutionEntity execution : executions) {
if (isLeaf(execution)) {
leaves.add(execution);
}
}
return leaves;
}
/**
* event-scope executions are not considered in this mapping and must be ignored
*/
protected boolean isLeaf(ExecutionEntity execution) {
if (CompensationBehavior.isCompensationThrowing(execution)) {
return true;
}
else {
return !execution.isEventScope() && execution.getNonEventScopeExecutions().isEmpty();
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ActivityExecutionTreeMapping.java
| 1
|
请完成以下Java代码
|
public String getCategory() {
return activiti5Task.getCategory();
}
@Override
public String getParentTaskId() {
return activiti5Task.getParentTaskId();
}
@Override
public String getTenantId() {
return activiti5Task.getTenantId();
}
@Override
public String getFormKey() {
return activiti5Task.getFormKey();
}
@Override
public Map<String, Object> getTaskLocalVariables() {
return activiti5Task.getTaskLocalVariables();
}
@Override
public Map<String, Object> getProcessVariables() {
return activiti5Task.getProcessVariables();
}
@Override
public Map<String, Object> getCaseVariables() {
return null;
}
@Override
public List<? extends IdentityLinkInfo> getIdentityLinks() {
return null;
}
@Override
public Date getClaimTime() {
return null;
}
@Override
public void setName(String name) {
activiti5Task.setName(name);
}
@Override
public void setLocalizedName(String name) {
activiti5Task.setLocalizedName(name);
}
@Override
public void setDescription(String description) {
activiti5Task.setDescription(description);
}
@Override
public void setLocalizedDescription(String description) {
activiti5Task.setLocalizedDescription(description);
}
@Override
public void setPriority(int priority) {
activiti5Task.setPriority(priority);
}
|
@Override
public void setOwner(String owner) {
activiti5Task.setOwner(owner);
}
@Override
public void setAssignee(String assignee) {
activiti5Task.setAssignee(assignee);
}
@Override
public DelegationState getDelegationState() {
return activiti5Task.getDelegationState();
}
@Override
public void setDelegationState(DelegationState delegationState) {
activiti5Task.setDelegationState(delegationState);
}
@Override
public void setDueDate(Date dueDate) {
activiti5Task.setDueDate(dueDate);
}
@Override
public void setCategory(String category) {
activiti5Task.setCategory(category);
}
@Override
public void setParentTaskId(String parentTaskId) {
activiti5Task.setParentTaskId(parentTaskId);
}
@Override
public void setTenantId(String tenantId) {
activiti5Task.setTenantId(tenantId);
}
@Override
public void setFormKey(String formKey) {
activiti5Task.setFormKey(formKey);
}
@Override
public boolean isSuspended() {
return activiti5Task.isSuspended();
}
}
|
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5TaskWrapper.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the branchId
*/
public Long getBranchId() {
return branchId;
}
/**
* @param branchId the branchId to set
*/
public void setBranchId(Long branchId) {
this.branchId = branchId;
}
/**
* @return the customerId
*/
public Long getCustomerId() {
return customerId;
}
/**
* @param customerId the customerId to set
*/
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((branchId == null) ? 0 : branchId.hashCode());
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
|
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Account other = (Account) obj;
if (branchId == null) {
if (other.branchId != null)
return false;
} else if (!branchId.equals(other.branchId))
return false;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-vault\src\main\java\com\baeldung\spring\cloud\vaultsample\domain\Account.java
| 1
|
请完成以下Java代码
|
private void checkComponents (Container target)
{
int size = target.getComponentCount();
for (int i = 0; i < size; i++)
{
Component comp = target.getComponent(i);
if (!m_data.containsValue(comp))
m_data.put(null, comp);
}
} // checkComponents
/**
* Get Number of Rows
* @return no pf rows
*/
public int getRowCount()
{
return m_data.getMaxRow()+1;
} // getRowCount
/**
* Get Number of Columns
* @return no of cols
*/
public int getColCount()
{
return m_data.getMaxCol()+1;
} // getColCount
/**
* Set Horizontal Space (top, between rows, button)
* @param spaceH horizontal space (top, between rows, button)
*/
public void setSpaceH (int spaceH)
{
m_spaceH = spaceH;
} // setSpaceH
/**
* Get Horizontal Space (top, between rows, button)
* @return spaceH horizontal space (top, between rows, button)
*/
public int getSpaceH()
{
return m_spaceH;
|
} // getSpaceH
/**
* Set Vertical Space (left, between columns, right)
* @param spaceV vertical space (left, between columns, right)
*/
public void setSpaceV(int spaceV)
{
m_spaceV = spaceV;
} // setSpaceV
/**
* Get Vertical Space (left, between columns, right)
* @return spaceV vertical space (left, between columns, right)
*/
public int getSpaceV()
{
return m_spaceV;
} // getSpaceV
} // ALayout
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ALayout.java
| 1
|
请完成以下Java代码
|
public static String getRequestIp(HttpServletRequest request) {
//通过HTTP代理服务器转发时添加
String ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
// 从本地访问时根据网卡取本机配置的IP
if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getLocalHost();
|
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = inetAddress.getHostAddress();
}
}
// 通过多个代理转发的情况,第一个IP为客户端真实IP,多个IP会按照','分割
if (ipAddress != null && ipAddress.length() > 15) {
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
return ipAddress;
}
}
|
repos\mall-master\mall-common\src\main\java\com\macro\mall\common\util\RequestUtil.java
| 1
|
请完成以下Java代码
|
public ElementPermission noPermissions(final int elementId)
{
return ElementPermission.none(elementResource(elementId));
}
public static class Builder extends PermissionsBuilder<ElementPermission, ElementPermissions>
{
private String elementTableName;
@Override
protected ElementPermissions createPermissionsInstance()
{
return new ElementPermissions(this);
}
public Builder setElementTableName(final String elementTableName)
{
this.elementTableName = elementTableName;
return this;
}
|
public String getElementTableName()
{
Check.assumeNotEmpty(elementTableName, "elementTableName not empty");
return elementTableName;
}
@Override
protected void assertValidPermissionToAdd(final ElementPermission permission)
{
final String elementTableName = getElementTableName();
if (!Objects.equals(elementTableName, permission.getResource().getElementTableName()))
{
throw new IllegalArgumentException("Permission to add " + permission + " is not matching element table name '" + elementTableName + "'");
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\ElementPermissions.java
| 1
|
请完成以下Java代码
|
public Quantity roundToUOMPrecision()
{
final UOMPrecision precision = getUOMPrecision();
final BigDecimal qtyRounted = precision.roundIfNeeded(qty);
return qty.equals(qtyRounted)
? this
: new Quantity(qtyRounted, uom, sourceQty, sourceUom);
}
private UOMPrecision getUOMPrecision()
{
return UOMPrecision.ofInt(uom.getStdPrecision());
}
public Quantity setScale(@NonNull final UOMPrecision newScale)
{
return setScale(newScale, newScale.getRoundingMode());
}
public Quantity setScale(final UOMPrecision newScale, @NonNull final RoundingMode roundingMode)
{
final BigDecimal newQty = qty.setScale(newScale.toInt(), roundingMode);
return new Quantity(
newQty,
uom,
sourceQty != null ? sourceQty.setScale(newScale.toInt(), roundingMode) : newQty,
sourceUom != null ? sourceUom : uom);
}
public int intValueExact()
{
return toBigDecimal().intValueExact();
}
public boolean isWeightable()
{
return UOMType.ofNullableCodeOrOther(uom.getUOMType()).isWeight();
}
public Percent percentageOf(@NonNull final Quantity whole)
{
assertSameUOM(this, whole);
return Percent.of(toBigDecimal(), whole.toBigDecimal());
}
private void assertUOMOrSourceUOM(@NonNull final UomId uomId)
{
if (!getUomId().equals(uomId) && !getSourceUomId().equals(uomId))
{
|
throw new QuantitiesUOMNotMatchingExpection("UOMs are not compatible")
.appendParametersToMessage()
.setParameter("Qty.UOM", getUomId())
.setParameter("assertUOM", uomId);
}
}
@NonNull
public BigDecimal toBigDecimalAssumingUOM(@NonNull final UomId uomId)
{
assertUOMOrSourceUOM(uomId);
return getUomId().equals(uomId) ? toBigDecimal() : getSourceQty();
}
public List<Quantity> spreadEqually(final int count)
{
if (count <= 0)
{
throw new AdempiereException("count shall be greater than zero, but it was " + count);
}
else if (count == 1)
{
return ImmutableList.of(this);
}
else // count > 1
{
final ImmutableList.Builder<Quantity> result = ImmutableList.builder();
final Quantity qtyPerPart = divide(count);
Quantity qtyRemainingToSpread = this;
for (int i = 1; i <= count; i++)
{
final boolean isLast = i == count;
if (isLast)
{
result.add(qtyRemainingToSpread);
}
else
{
result.add(qtyPerPart);
qtyRemainingToSpread = qtyRemainingToSpread.subtract(qtyPerPart);
}
}
return result.build();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\Quantity.java
| 1
|
请完成以下Java代码
|
public final class TypedSqlQueryFilter<T> implements IQueryFilter<T>, ISqlQueryFilter
{
public static <T> TypedSqlQueryFilter<T> of(final String sql)
{
final List<Object> params = ImmutableList.of();
return new TypedSqlQueryFilter<>(sql, params);
}
public static <T> TypedSqlQueryFilter<T> of(final String sql, final List<Object> sqlParams)
{
return new TypedSqlQueryFilter<>(sql, sqlParams);
}
public static <T> TypedSqlQueryFilter<T> of(final String sql, final Object[] sqlParams)
{
return new TypedSqlQueryFilter<>(sql, sqlParams);
}
private final String sql;
private final List<Object> sqlParams;
private TypedSqlQueryFilter(final String sql, final Object[] sqlParams)
{
this(sql, sqlParams == null ? null : Arrays.asList(sqlParams));
}
private TypedSqlQueryFilter(@NonNull final String sql, @Nullable final List<Object> sqlParams)
{
Check.assumeNotEmpty(sql, "sql not empty");
this.sql = sql;
if (sqlParams == null || sqlParams.isEmpty())
{
this.sqlParams = Collections.emptyList();
}
else
{
// Take an immutable copy of given sqlParams
// NOTE: we cannot use ImmutableList because it might be that some parameters are null
this.sqlParams = Collections.unmodifiableList(new ArrayList<>(sqlParams));
}
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(sql)
.add("params", sqlParams)
.toString();
}
@Override
|
public int hashCode()
{
return Objects.hash(sql, sqlParams);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof TypedSqlQueryFilter)
{
final TypedSqlQueryFilter<?> other = (TypedSqlQueryFilter<?>)obj;
return Objects.equals(sql, other.sql)
&& Objects.equals(sqlParams, other.sqlParams);
}
else
{
return false;
}
}
@Override
public String getSql()
{
return sql;
}
@Override
public List<Object> getSqlParams(final Properties ctx_NOTUSED)
{
return sqlParams;
}
@Override
public boolean accept(final T model)
{
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\TypedSqlQueryFilter.java
| 1
|
请完成以下Java代码
|
public class LandedCostDistribute extends JavaProcess
{
/** Parameter */
private int p_C_LandedCost_ID = 0;
/** LC */
private MLandedCost m_lc = null;
/**
* Prepare
*/
protected void prepare ()
{
p_C_LandedCost_ID = getRecord_ID();
} // prepare
/**
* Process
* @return info
|
* @throws Exception
*/
protected String doIt () throws Exception
{
m_lc = new MLandedCost (getCtx(), p_C_LandedCost_ID, get_TrxName());
log.info(m_lc.toString());
if (m_lc.get_ID() == 0)
throw new AdempiereUserError("@NotFound@: @C_LandedCost_ID@ - " + p_C_LandedCost_ID);
String error = m_lc.allocateCosts();
if (error == null || error.length() == 0)
return "@OK@";
return error;
} // doIt
} // LandedCostDistribute
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\LandedCostDistribute.java
| 1
|
请完成以下Java代码
|
public static boolean isComplexObject(Object target) {
if (Objects.isNull(target)) {
return false;
}
if (target instanceof String) {
return true;
}
if (target instanceof Integer) {
return true;
}
if (target instanceof Long) {
return true;
}
if (target instanceof Boolean) {
return true;
}
if (target instanceof Float) {
return true;
}
if (target instanceof Double) {
return true;
}
|
if (target instanceof Byte) {
return true;
}
if (target instanceof Short) {
return true;
}
if (target instanceof Character) {
return true;
}
return false;
}
public static boolean isArray(Object obj) {
return (obj != null && obj.getClass().isArray());
}
}
|
repos\spring-boot-student-master\spring-boot-student-okhttp\src\main\java\com\xiaolyuh\util\ObjectUtils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public PropertySource<?> getPropertySource() {
return this.propertySource;
}
/**
* Return the {@link ConfigDataResource} of the property source or {@code null} if the
* source was not loaded from {@link ConfigData}.
* @return the config data location or {@code null}
*/
public @Nullable ConfigDataResource getLocation() {
return this.location;
}
/**
* Return the name of the property.
* @return the property name
*/
public String getPropertyName() {
return this.propertyName;
}
/**
* Return the origin or the property or {@code null}.
* @return the property origin
*/
public @Nullable Origin getOrigin() {
return this.origin;
}
|
/**
* Throw an {@link InactiveConfigDataAccessException} if the given
* {@link ConfigDataEnvironmentContributor} contains the property.
* @param contributor the contributor to check
* @param name the name to check
*/
static void throwIfPropertyFound(ConfigDataEnvironmentContributor contributor, ConfigurationPropertyName name) {
ConfigurationPropertySource source = contributor.getConfigurationPropertySource();
ConfigurationProperty property = (source != null) ? source.getConfigurationProperty(name) : null;
if (property != null) {
PropertySource<?> propertySource = contributor.getPropertySource();
ConfigDataResource location = contributor.getResource();
Assert.state(propertySource != null, "'propertySource' must not be null");
throw new InactiveConfigDataAccessException(propertySource, location, name.toString(),
property.getOrigin());
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\InactiveConfigDataAccessException.java
| 2
|
请完成以下Java代码
|
public abstract class UUIDBased implements HasUUID, Serializable {
private static final long serialVersionUID = 1L;
/** Cache the hash code */
private transient int hash; // Default to 0. The hash code calculated for this object likely never be zero
private final UUID id;
public UUIDBased() {
this(UUID.randomUUID());
}
public UUIDBased(UUID id) {
super();
this.id = id;
}
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "string", example = "784f394c-42b6-435a-983c-b7beff2784f9")
public UUID getId() {
return id;
}
@Override
public int hashCode() {
if (hash == 0) {
final int prime = 31;
int result = 1;
hash = prime * result + ((id == null) ? 0 : id.hashCode());
}
return hash;
}
@Override
public boolean equals(Object obj) {
|
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UUIDBased other = (UUIDBased) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return String.valueOf(id);
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\id\UUIDBased.java
| 1
|
请完成以下Java代码
|
public void setVariableLocal(String variableName, Object value) {
setVariableLocal(variableName, value, false);
}
@Override
public void removeVariable(String variableName) {
removeVariable(variableName, getSourceActivityVariableScope());
}
protected void removeVariable(String variableName, AbstractVariableScope sourceActivityExecution) {
if (getVariableStore().containsKey(variableName)) {
removeVariableLocal(variableName, sourceActivityExecution);
return;
}
AbstractVariableScope parentVariableScope = getParentVariableScope();
if (parentVariableScope!=null) {
if (sourceActivityExecution==null) {
parentVariableScope.removeVariable(variableName);
} else {
parentVariableScope.removeVariable(variableName, sourceActivityExecution);
}
}
}
@Override
public void removeVariableLocal(String variableName) {
removeVariableLocal(variableName, getSourceActivityVariableScope());
}
|
protected AbstractVariableScope getSourceActivityVariableScope() {
return this;
}
protected void removeVariableLocal(String variableName, AbstractVariableScope sourceActivityExecution) {
if (getVariableStore().containsKey(variableName)) {
CoreVariableInstance variableInstance = getVariableStore().getVariable(variableName);
invokeVariableLifecycleListenersDelete(variableInstance, sourceActivityExecution);
getVariableStore().removeVariable(variableName);
}
}
public ELContext getCachedElContext() {
return cachedElContext;
}
public void setCachedElContext(ELContext cachedElContext) {
this.cachedElContext = cachedElContext;
}
@Override
public void dispatchEvent(VariableEvent variableEvent) {
// default implementation does nothing
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\AbstractVariableScope.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.