instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public class GroupEntity implements Group, Serializable, DbEntity, HasDbRevision {
private static final long serialVersionUID = 1L;
protected String id;
protected int revision;
protected String name;
protected String type;
public GroupEntity() {
}
public GroupEntity(String id) {
this.id = id;
}
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("name", name);
persistentState.put("type", type);
return persistentState;
}
public int getRevisionNext() {
return revision+1;
}
public String getId() {
return id;
}
public void setId(String id) {
|
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getRevision() {
return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", name=" + name
+ ", type=" + type
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\GroupEntity.java
| 1
|
请完成以下Java代码
|
public abstract class BaseNativeQuery<T extends NativeQuery<?, ?>, U> implements NativeQuery<T, U>, Serializable {
private static final long serialVersionUID = 1L;
protected enum ResultType {
LIST, LIST_PAGE, SINGLE_RESULT, COUNT
}
protected int maxResults = -1;
protected int firstResult = -1;
protected ResultType resultType;
protected Map<String, Object> parameters = new HashMap<>();
protected String sqlStatement;
@SuppressWarnings("unchecked")
@Override
public T sql(String sqlStatement) {
this.sqlStatement = sqlStatement;
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
public T parameter(String name, Object value) {
parameters.put(name, value);
return (T) this;
}
protected Map<String, Object> generateParameterMap() {
Map<String, Object> parameterMap = new HashMap<>(parameters);
parameterMap.put("sql", sqlStatement);
parameterMap.put("resultType", resultType.toString());
parameterMap.put("firstResult", firstResult);
parameterMap.put("maxResults", maxResults);
parameterMap.put("needsPaging", firstResult >= 0);
|
String orderBy = (String) parameterMap.get("orderBy");
if (orderBy != null && !"".equals(orderBy)) {
orderBy = "RES." + orderBy;
} else {
orderBy = "RES.ID_ asc";
}
parameterMap.put("orderBy", "order by " + orderBy);
parameterMap.put("orderByForWindow", "order by " + orderBy);
parameterMap.put("orderByColumns", orderBy);
int firstRow = firstResult + 1;
parameterMap.put("firstRow", firstRow);
int lastRow = 0;
if (maxResults == Integer.MAX_VALUE) {
lastRow = maxResults;
} else {
lastRow = firstResult + maxResults + 1;
}
parameterMap.put("lastRow", lastRow);
return parameterMap;
}
public Map<String, Object> getParameters() {
return parameters;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\query\BaseNativeQuery.java
| 1
|
请完成以下Java代码
|
public final class AdImageId implements RepoIdAware
{
@JsonCreator
@Nullable
public static AdImageId ofNullableObject(@Nullable final Object obj)
{
if (obj == null)
{
return null;
}
try
{
final int id = NumberUtils.asInt(obj, -1);
return ofRepoIdOrNull(id);
}
catch (final Exception ex)
{
throw new AdempiereException("Cannot convert `" + obj + "` from " + obj.getClass() + " to " + AdImageId.class, ex);
}
}
public static AdImageId ofRepoId(final int repoId)
{
return new AdImageId(repoId);
}
@Nullable
public static AdImageId ofRepoIdOrNull(final int repoId)
|
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
private final int repoId;
public AdImageId(final int repoId)
{
Check.assumeGreaterThanZero(repoId, "AD_Image_ID");
this.repoId = repoId;
}
@JsonValue
@Override
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\image\AdImageId.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Article implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "article_id")
private int articleId;
@Column(name = "title")
private String title;
@Column(name = "category")
private String category;
public int getArticleId() {
return articleId;
}
public void setArticleId(int articleId) {
this.articleId = articleId;
}
|
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
|
repos\SpringBootBucket-master\springboot-hibernate\src\main\java\com\xncoding\pos\dao\entity\Article.java
| 2
|
请完成以下Java代码
|
public IViewRowType getType()
{
return DefaultRowType.Row;
}
@Override
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代码
|
private String convertLessThanOneThousand(int number) {
String soFar;
// Below 20
if (number % 100 < 20) {
soFar = numNames[number % 100];
number /= 100;
} else {
soFar = numNames[number % 10];
number /= 10;
soFar = tensNames[number % 10] + " " + soFar;
number /= 10;
}
soFar = hundredNames[number % 10] + " "+ soFar;
number /= 10;
return soFar;
} // convertLessThanOneThousand
/**
* Convert
*
* @param number
* @return amt
*/
private String convert (long number)
{
/* special case */
if (number == 0)
{
return "zero";
}
String prefix = "";
if (number < 0)
{
number = -number;
prefix = "minus ";
}
String soFar = "";
int place = 0;
do
{
long n = number % 1000;
if (n != 0)
{
String s = convertLessThanOneThousand ((int)n);
int pos;
if(number%10==1){
pos=0;
}else if (number%10<5){
pos =1;
}else{
pos=2;
}
if(number>9 && number <20){
pos = 2;
}
soFar = s + " " + majorNames[place][pos] + " "+soFar;
}
place++;
number /= 1000;
}
while (number > 0);
return (prefix + soFar).trim ();
} // convert
/***************************************************************************
* Get Amount in Words
*
* @param amount
* numeric amount (352.80)
* @return amount in words (three*five*two 80/100)
*/
public String getAmtInWords(String amount) throws Exception {
if (amount == null)
return amount;
//
StringBuffer sb = new StringBuffer();
int pos = amount.lastIndexOf('.');
int pos2 = amount.lastIndexOf(',');
if (pos2 > pos)
pos = pos2;
String oldamt = amount;
amount = amount.replaceAll(",", "");
int newpos = amount.lastIndexOf('.');
|
long dollars = Long.parseLong(amount.substring(0, newpos));
sb.append(convert(dollars));
for (int i = 0; i < oldamt.length(); i++) {
if (pos == i) // we are done
{
String cents = oldamt.substring(i + 1);
sb.append(' ').append(cents).append("/100");
break;
}
}
return sb.toString();
} // getAmtInWords
/**
* Test Print
*
* @param amt
* amount
*/
private void print(String amt) {
try {
System.out.println(amt + " = " + getAmtInWords(amt));
} catch (Exception e) {
e.printStackTrace();
}
} // print
/**
* Test
*
* @param args
* ignored
*/
public static void main(String[] args) {
AmtInWords_PL aiw = new AmtInWords_PL();
// aiw.print (".23"); Error
aiw.print("0.23");
aiw.print("1.23");
aiw.print("12.345");
aiw.print("123.45");
aiw.print("1234.56");
aiw.print("12345.78");
aiw.print("10345.78");
aiw.print("123457.89");
aiw.print("323457.89");
aiw.print("23457.89");
aiw.print("1,234,578.90");
} // main
} // AmtInWords_EN
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\AmtInWords_PL.java
| 1
|
请完成以下Java代码
|
public class BPartnerProductStatsEventSender
{
public static final Topic TOPIC_InOut = Topic.distributed("de.metas.bpartner.product.stats.updates.inout");
public static final Topic TOPIC_Invoice = Topic.distributed("de.metas.bpartner.product.stats.updates.invoice");
private static final String EVENT_PROPERTY_Content = "content";
public void send(@NonNull final InOutChangedEvent event)
{
sendEventObj(TOPIC_InOut, event);
}
public void send(@NonNull final InvoiceChangedEvent event)
{
sendEventObj(TOPIC_Invoice, event);
}
private void sendEventObj(final Topic topic, final Object eventObj)
{
final Event event = toEvent(eventObj);
Services.get(ITrxManager.class)
.getCurrentTrxListenerManagerOrAutoCommit()
.newEventListener(TrxEventTiming.AFTER_COMMIT)
.invokeMethodJustOnce(true)
.registerHandlingMethod(trx -> sendEventNow(topic, event));
}
private void sendEventNow(final Topic topic, final Event event)
{
final IEventBus eventBus = Services.get(IEventBusFactory.class).getEventBus(topic);
eventBus.enqueueEvent(event);
}
private static Event toEvent(final Object event)
{
final SimpleObjectSerializer objectSerializer = SimpleObjectSerializer.get();
|
return Event.builder()
.putProperty(EVENT_PROPERTY_Content, objectSerializer.serialize(event))
.shallBeLogged()
.build();
}
public static InOutChangedEvent extractInOutChangedEvent(@NonNull final Event event)
{
return extractEvent(event, InOutChangedEvent.class);
}
public static InvoiceChangedEvent extractInvoiceChangedEvent(@NonNull final Event event)
{
return extractEvent(event, InvoiceChangedEvent.class);
}
public static <T> T extractEvent(@NonNull final Event event, @NonNull final Class<T> eventType)
{
final String json = event.getPropertyAsString(EVENT_PROPERTY_Content);
final SimpleObjectSerializer objectSerializer = SimpleObjectSerializer.get();
return objectSerializer.deserialize(json, eventType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\product\stats\BPartnerProductStatsEventSender.java
| 1
|
请完成以下Java代码
|
public static class StringCacheKey implements CacheKey{
private final String value;
public StringCacheKey(String value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StringCacheKey that = (StringCacheKey) o;
return value.equals(that.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
public static class LongCacheKey implements CacheKey {
private final Long value;
public LongCacheKey(Long value) {
this.value = value;
}
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LongCacheKey that = (LongCacheKey) o;
return value.equals(that.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-maps-5\src\main\java\com\baeldung\map\multikey\WrapperInterfaceUserCache.java
| 1
|
请完成以下Java代码
|
public void setQtyReserved (BigDecimal QtyReserved)
{
set_ValueNoCheck (COLUMNNAME_QtyReserved, QtyReserved);
}
/** Get Reserved Quantity.
@return Reserved Quantity
*/
public BigDecimal getQtyReserved ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReserved);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set SKU.
@param SKU
Stock Keeping Unit
*/
public void setSKU (String SKU)
{
set_ValueNoCheck (COLUMNNAME_SKU, SKU);
}
/** Get SKU.
@return Stock Keeping Unit
*/
public String getSKU ()
{
return (String)get_Value(COLUMNNAME_SKU);
}
/** Set Symbol.
@param UOMSymbol
Symbol for a Unit of Measure
*/
public void setUOMSymbol (String UOMSymbol)
{
set_ValueNoCheck (COLUMNNAME_UOMSymbol, UOMSymbol);
}
/** Get Symbol.
@return Symbol for a Unit of Measure
*/
public String getUOMSymbol ()
{
return (String)get_Value(COLUMNNAME_UOMSymbol);
}
/** Set UPC/EAN.
@param UPC
Bar Code (Universal Product Code or its superset European Article Number)
*/
public void setUPC (String UPC)
{
set_ValueNoCheck (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
|
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
public String getUPC ()
{
return (String)get_Value(COLUMNNAME_UPC);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Warehouse.
@param WarehouseName
Warehouse Name
*/
public void setWarehouseName (String WarehouseName)
{
set_ValueNoCheck (COLUMNNAME_WarehouseName, WarehouseName);
}
/** Get Warehouse.
@return Warehouse Name
*/
public String getWarehouseName ()
{
return (String)get_Value(COLUMNNAME_WarehouseName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_RV_WarehousePrice.java
| 1
|
请完成以下Java代码
|
public boolean isCollecting()
{
return params != null;
}
/**
* Directly append all sqlParams from the given {@code sqlQueryFilter}.
*
* @param sqlQueryFilter
*
*/
public void collectAll(@NonNull final ISqlQueryFilter sqlQueryFilter)
{
final List<Object> sqlParams = sqlQueryFilter.getSqlParams(Env.getCtx());
collectAll(sqlParams);
}
/**
* Directly append the given {@code sqlParams}. Please prefer using {@link #placeholder(Object)} instead.<br>
* "Package" scope because currently this method is needed only by {@link SqlDefaultDocumentFilterConverter}.
*
* Please avoid using it. It's used mainly to adapt with old code
*
* @param sqlParams
*/
public void collectAll(@Nullable final Collection<? extends Object> sqlParams)
{
if (sqlParams == null || sqlParams.isEmpty())
{
return;
}
if (params == null)
{
throw new IllegalStateException("Cannot append " + sqlParams + " to not collecting params");
}
params.addAll(sqlParams);
}
public void collect(@NonNull final SqlParamsCollector from)
{
collectAll(from.params);
}
|
/**
* Collects given SQL value and returns an SQL placeholder, i.e. "?"
*
* In case this is in non-collecting mode, the given SQL value will be converted to SQL code and it will be returned.
* The internal list won't be affected, because it does not exist.
*/
public String placeholder(@Nullable final Object sqlValue)
{
if (params == null)
{
return DB.TO_SQL(sqlValue);
}
else
{
params.add(sqlValue);
return "?";
}
}
/** @return readonly live list */
public List<Object> toList()
{
return paramsRO;
}
/** @return read/write live list */
public List<Object> toLiveList()
{
return params;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\SqlParamsCollector.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
default List<EntityLink> findEntityLinksByScopeIdAndType(String scopeId, String scopeType, String linkType) {
return createInternalEntityLinkQuery()
.scopeId(scopeId)
.scopeType(scopeType)
.linkType(linkType)
.list();
}
default List<EntityLink> findEntityLinksByRootScopeIdAndRootType(String scopeId, String scopeType) {
return createInternalEntityLinkQuery()
.rootScopeId(scopeId)
.rootScopeType(scopeType)
.list();
}
List<EntityLink> findEntityLinksWithSameRootScopeForScopeIdAndScopeType(String scopeId, String scopeType, String linkType);
default List<EntityLink> findEntityLinksByReferenceScopeIdAndType(String referenceScopeId, String scopeType, String linkType) {
return createInternalEntityLinkQuery()
|
.referenceScopeId(referenceScopeId)
.referenceScopeType(scopeType)
.linkType(linkType)
.list();
}
InternalEntityLinkQuery<EntityLink> createInternalEntityLinkQuery();
EntityLink createEntityLink();
void insertEntityLink(EntityLink entityLink);
void deleteEntityLinksByScopeIdAndType(String scopeId, String scopeType);
void deleteEntityLinksByRootScopeIdAndType(String scopeId, String scopeType);
}
|
repos\flowable-engine-main\modules\flowable-entitylink-service-api\src\main\java\org\flowable\entitylink\api\EntityLinkService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public static class ServletUiConfiguration {
@Configuration(proxyBeanMethods = false)
public static class AdminUiWebMvcConfig implements WebMvcConfigurer {
private final AdminServerUiProperties adminUi;
private final AdminServerProperties adminServer;
private final ApplicationContext applicationContext;
public AdminUiWebMvcConfig(AdminServerUiProperties adminUi, AdminServerProperties adminServer,
ApplicationContext applicationContext) {
this.adminUi = adminUi;
this.adminServer = adminServer;
this.applicationContext = applicationContext;
}
@Bean
public HomepageForwardingFilterConfig homepageForwardingFilterConfig() throws IOException {
String homepage = normalizeHomepageUrl(this.adminServer.path("/"));
List<String> extensionRoutes = new UiRoutesScanner(this.applicationContext)
.scan(this.adminUi.getExtensionResourceLocations());
List<String> routesIncludes = Stream
.concat(DEFAULT_UI_ROUTES.stream(), Stream.concat(extensionRoutes.stream(), Stream.of("/")))
.map(this.adminServer::path)
.toList();
List<String> routesExcludes = Stream
.concat(DEFAULT_UI_ROUTE_EXCLUDES.stream(), this.adminUi.getAdditionalRouteExcludes().stream())
.map(this.adminServer::path)
.toList();
return new HomepageForwardingFilterConfig(homepage, routesIncludes, routesExcludes);
}
|
@Override
public void addResourceHandlers(
org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry registry) {
registry.addResourceHandler(this.adminServer.path("/**"))
.addResourceLocations(this.adminUi.getResourceLocations())
.setCacheControl(this.adminUi.getCache().toCacheControl());
registry.addResourceHandler(this.adminServer.path("/extensions/**"))
.addResourceLocations(this.adminUi.getExtensionResourceLocations())
.setCacheControl(this.adminUi.getCache().toCacheControl());
}
@Bean
@ConditionalOnMissingBean
public de.codecentric.boot.admin.server.ui.web.servlet.HomepageForwardingFilter homepageForwardFilter(
HomepageForwardingFilterConfig homepageForwardingFilterConfig) {
return new de.codecentric.boot.admin.server.ui.web.servlet.HomepageForwardingFilter(
homepageForwardingFilterConfig);
}
}
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\config\AdminServerUiAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public int getZipode() {
return zipode;
}
public void setZipode(int zipode) {
this.zipode = zipode;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
|
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\mapsid\Address.java
| 1
|
请完成以下Java代码
|
default Instant getIssuedAt() {
return getClaimAsInstant(OAuth2TokenIntrospectionClaimNames.IAT);
}
/**
* Returns a timestamp {@code (nbf)} indicating when the token is not to be used
* before
* @return a timestamp indicating when the token is not to be used before
*/
@Nullable
default Instant getNotBefore() {
return getClaimAsInstant(OAuth2TokenIntrospectionClaimNames.NBF);
}
/**
* Returns usually a machine-readable identifier {@code (sub)} of the resource owner
* who authorized the token
* @return usually a machine-readable identifier of the resource owner who authorized
* the token
*/
@Nullable
default String getSubject() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.SUB);
}
/**
* Returns the intended audience {@code (aud)} for the token
* @return the intended audience for the token
|
*/
@Nullable
default List<String> getAudience() {
return getClaimAsStringList(OAuth2TokenIntrospectionClaimNames.AUD);
}
/**
* Returns the issuer {@code (iss)} of the token
* @return the issuer of the token
*/
@Nullable
default URL getIssuer() {
return getClaimAsURL(OAuth2TokenIntrospectionClaimNames.ISS);
}
/**
* Returns the identifier {@code (jti)} for the token
* @return the identifier for the token
*/
@Nullable
default String getId() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.JTI);
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\OAuth2TokenIntrospectionClaimAccessor.java
| 1
|
请完成以下Java代码
|
private String getAccessToken()
{
return getAuthResponse().getAccessToken();
}
private synchronized JsonAuthResponse getAuthResponse()
{
JsonAuthResponse authResponse = _authResponse;
if (authResponse == null
|| authResponse.isExpired())
{
authResponse = _authResponse = authenticate(config);
}
return authResponse;
}
public void authenticate()
{
getAuthResponse();
}
private static JsonAuthResponse authenticate(@NonNull final SecurPharmConfig config)
{
try
{
final SSLContext sslContext = createSSLContext(config);
final HttpClient client = HttpClients.custom()
.setSSLContext(sslContext)
.build();
final RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(client));
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add(AUTH_PARAM_GRANT_TYPE, AUTH_PARAM_GRANT_TYPE_VALUE);
params.add(AUTH_PARAM_CLIENT_ID, AUTH_PARAM_CLIENT_ID_VALUE);
final HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
final ResponseEntity<JsonAuthResponse> response = restTemplate.postForEntity(config.getAuthBaseUrl() + AUTH_RELATIVE_PATH, request, JsonAuthResponse.class);
final JsonAuthResponse authResponse = response.getBody();
if (response.getStatusCode() == HttpStatus.OK)
{
return authResponse;
}
else
{
throw new AdempiereException(MSG_AUTHORIZATION_FAILED)
.appendParametersToMessage()
.setParameter("HTTPStatus", response.getStatusCode())
.setParameter("error", authResponse.getError())
|
.setParameter("errorDescription", authResponse.getErrorDescription());
}
}
catch (final AdempiereException ex)
{
throw ex;
}
catch (final Exception ex)
{
final Throwable cause = AdempiereException.extractCause(ex);
throw new AdempiereException(MSG_AUTHORIZATION_FAILED, cause);
}
}
private static SSLContext createSSLContext(final SecurPharmConfig config)
{
try
{
final char[] password = config.getKeystorePassword().toCharArray();
final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
final File key = new File(config.getCertificatePath());
try (final InputStream in = new FileInputStream(key))
{
keyStore.load(in, password);
}
return SSLContextBuilder.create()
.loadKeyMaterial(keyStore, password)
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
}
catch (final Exception ex)
{
throw new AdempiereException("Failed creating SSL context " + ex.getLocalizedMessage(), ex)
.appendParametersToMessage()
.setParameter("config", config);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\client\SecurPharmClientAuthenticator.java
| 1
|
请完成以下Java代码
|
public Criteria andProductAttrNotBetween(String value1, String value2) {
addCriterion("product_attr not between", value1, value2, "productAttr");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
|
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsCartItemExample.java
| 1
|
请完成以下Java代码
|
class WebExpressionConfigAttribute implements ConfigAttribute, EvaluationContextPostProcessor<FilterInvocation> {
private final Expression authorizeExpression;
private final EvaluationContextPostProcessor<FilterInvocation> postProcessor;
WebExpressionConfigAttribute(Expression authorizeExpression,
EvaluationContextPostProcessor<FilterInvocation> postProcessor) {
this.authorizeExpression = authorizeExpression;
this.postProcessor = postProcessor;
}
Expression getAuthorizeExpression() {
return this.authorizeExpression;
}
@Override
|
public EvaluationContext postProcess(EvaluationContext context, FilterInvocation fi) {
return (this.postProcessor != null) ? this.postProcessor.postProcess(context, fi) : context;
}
@Override
public String getAttribute() {
return null;
}
@Override
public String toString() {
return this.authorizeExpression.getExpressionString();
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\expression\WebExpressionConfigAttribute.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void configure() throws Exception
{
//@formatter:off
errorHandler(defaultErrorHandler());
onException(Exception.class)
.to(direct(MF_ERROR_ROUTE_ID));
from(direct(PUSH_BOM_PRODUCTS_ROUTE_ID))
.routeId(PUSH_BOM_PRODUCTS_ROUTE_ID)
.log("Route invoked!")
.unmarshal(setupJacksonDataFormatFor(getContext(), JsonBOM.class))
.process(new PushProductProcessor()).id(PUSH_PRODUCT_ROUTE_PROCESSOR_ID)
.to(direct(MF_UPSERT_PRODUCT_V2_CAMEL_URI))
.process(new PushBOMProductsProcessor()).id(PUSH_BOM_PRODUCTS_ROUTE_PROCESSOR_ID)
.to(direct(MF_UPSERT_BOM_V2_CAMEL_URI))
.to(direct(ATTACH_FILE_TO_BOM_PRODUCT_ROUTE_ID));
from(direct(ATTACH_FILE_TO_BOM_PRODUCT_ROUTE_ID))
.routeId(ATTACH_FILE_TO_BOM_PRODUCT_ROUTE_ID)
.process(RetrieveExternalSystemRequestBuilder::buildAndAttachRetrieveExternalSystemRequest)
.to("{{" + ExternalSystemCamelConstants.MF_GET_EXTERNAL_SYSTEM_INFO + "}}")
.unmarshal(CamelRouteUtil.setupJacksonDataFormatFor(getContext(), JsonExternalSystemInfo.class))
.process(this::processExternalSystemInfo)
.process(new ProductsAttachFileProcessor()).id(ATTACH_FILE_TO_BOM_PRODUCTS_PROCESSOR_ID)
.choice()
.when(body().isNull())
.log("No attachments found!")
.otherwise()
.to(direct(ExternalSystemCamelConstants.MF_ATTACHMENT_ROUTE_ID))
.end();
//@formatter:on
|
}
private void processExternalSystemInfo(@NonNull final Exchange exchange)
{
final PushBOMsRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange,
GRSSignumConstants.ROUTE_PROPERTY_PUSH_BOMs_CONTEXT,
PushBOMsRouteContext.class);
final JsonExternalSystemInfo externalSystemInfo = exchange.getIn().getBody(JsonExternalSystemInfo.class);
if (externalSystemInfo == null)
{
throw new RuntimeException("Missing JsonExternalSystemInfo!");
}
context.setExportDirectoriesBasePath(externalSystemInfo.getParameters().get(PARAM_BasePathForExportDirectories));
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\bom\PushBOMProductsRouteBuilder.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public List<Person> findAll() {
personMapper.findAll();
personMapper.findAll();
personMapper.findAll();
personMapper.findAll();
personMapper.findAll();
personMapper.findAll();
personMapper.findAll();
personMapper.findAll();
personMapper.findAll();
return personMapper.findAll();
}
@Override
public Page<Person> findByPage(int pageNo, int pageSize) {
PageHelper.startPage(pageNo, pageSize);
return personMapper.findByPage();
}
@Override
@Transactional(rollbackFor = Exception.class)
|
public void insert(Person person) {
personMapper.insert(person);
}
@Override
@Transactional(rollbackFor = Exception.class)
public int updateAge(long id) {
int result = personMapper.updateAge(id);
int i = atomicInteger.getAndIncrement();
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return result;
}
}
|
repos\spring-boot-student-master\spring-boot-student-mybatis-plus\src\main\java\com\xiaolyuh\service\impl\PersonServiceImpl.java
| 2
|
请完成以下Java代码
|
private int getOnly_Product_ID()
{
if (!Env.isSOTrx(Env.getCtx(), m_WindowNo))
{
return 0; // No product restrictions for PO
}
//
String only_Product = Env.getContext(Env.getCtx(), m_WindowNo, "M_Product_ID", true);
int only_Product_ID = 0;
try
{
if (only_Product != null && only_Product.length() > 0)
{
only_Product_ID = Integer.parseInt(only_Product);
}
}
catch (Exception ex)
{
}
return only_Product_ID;
} // getOnly_Product_ID
/**
* Set the default locator if this field is mandatory
* and we have a warehouse restriction.
*
* @since 3.1.4
*/
private void setDefault_Locator_ID()
{
// teo_sarca, FR [ 1661546 ] Mandatory locator fields should use defaults
if (!isMandatory() || m_mLocator == null)
{
return;
}
final WarehouseId warehouseId = getOnly_Warehouse_ID();
if (warehouseId == null)
{
|
return;
}
final LocatorId locatorId = Services.get(IWarehouseBL.class).getOrCreateDefaultLocatorId(warehouseId);
if (locatorId == null)
{
return;
}
setValue(locatorId.getRepoId());
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VLocator
/*****************************************************************************/
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocator.java
| 1
|
请完成以下Java代码
|
private Object getCSRFTokenSession(HttpSession session) {
return session.getAttribute(CsrfConstants.CSRF_TOKEN_SESSION_ATTR_NAME);
}
private String getCSRFTokenHeader(HttpServletRequest request) {
return request.getHeader(CsrfConstants.CSRF_TOKEN_HEADER_NAME);
}
private Object getSessionMutex(HttpSession session) {
if (session == null) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "HttpSession is missing");
}
Object mutex = session.getAttribute(CsrfConstants.CSRF_SESSION_MUTEX);
if (mutex == null) {
mutex = session;
}
return mutex;
}
private boolean isBlank(String s) {
return s == null || s.trim().isEmpty();
}
private String getRequestedPath(HttpServletRequest request) {
String path = request.getServletPath();
|
if (request.getPathInfo() != null) {
path = path + request.getPathInfo();
}
return path;
}
private Set<String> parseURLs(String urlString) {
Set<String> urlSet = new HashSet<>();
if (urlString != null && !urlString.isEmpty()) {
String values[] = urlString.split(",");
for (String value : values) {
urlSet.add(value.trim());
}
}
return urlSet;
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\CsrfPreventionFilter.java
| 1
|
请完成以下Java代码
|
public void registerCallout()
{
Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this);
}
/**
* Note that because of C_Payment.C_Order_ID's validation rule we can one have only prepay orders in this field.
* Before the payment is made, the prepay-order is not even completed, so the payment's date is effectively also the order's date.
* So in case of a prepay order there is no need to take the term's DiscountDays into account.
*/
@CalloutMethod(columnNames = I_C_Payment.COLUMNNAME_C_Order_ID)
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW }, ifColumnsChanged = I_C_Payment.COLUMNNAME_C_Order_ID)
public void updateFromOrder(@NonNull final I_C_Payment record)
{
final OrderId orderId = OrderId.ofRepoIdOrNull(record.getC_Order_ID());
if (orderId == null)
{
return;
}
final OrderPayScheduleId orderPayScheduleId = OrderPayScheduleId.ofRepoIdOrNull(record.getC_OrderPaySchedule_ID());
if (orderPayScheduleId != null)
{
return; // do not update form order, since all amounts are calculated
}
final I_C_Order order = orderDAO.getById(orderId);
final PaymentTermId paymentTermId = PaymentTermId.ofRepoId(order.getC_PaymentTerm_ID());
final Percent paymentTermDiscountPercent = paymentTermService.getPaymentTermDiscount(paymentTermId);
final Currency currency = currencyRepository.getById(record.getC_Currency_ID());
final BigDecimal priceActual = paymentTermDiscountPercent.subtractFromBase(order.getGrandTotal(), currency.getPrecision().toInt());
final BigDecimal discountAmount = paymentTermDiscountPercent.computePercentageOf(order.getGrandTotal(), currency.getPrecision().toInt());
record.setC_BPartner_ID(firstGreaterThanZero(order.getBill_BPartner_ID(), order.getC_BPartner_ID()));
record.setC_Currency_ID(order.getC_Currency_ID());
record.setC_Invoice(null);
record.setC_Charge_ID(0);
|
record.setIsPrepayment(true);
record.setWriteOffAmt(BigDecimal.ZERO);
record.setIsOverUnderPayment(false);
record.setOverUnderAmt(BigDecimal.ZERO);
//
record.setPayAmt(priceActual);
record.setDiscountAmt(discountAmount);
paymentBL.validateDocTypeIsInSync(record);
}
@DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE })
public void updateOrderPayScheduleStatus(final I_C_Payment payment)
{
final OrderId orderId = OrderId.ofRepoIdOrNull(payment.getC_Order_ID());
final OrderPayScheduleId orderPayScheduleId = OrderPayScheduleId.ofRepoIdOrNull(payment.getC_OrderPaySchedule_ID());
if (orderId == null || orderPayScheduleId == null)
{
return;
}
orderPayScheduleService.markAsPaid(orderId, orderPayScheduleId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\C_Payment.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void addListener(TenantId tenantId, EntityId listenerId,
Consumer<DeviceProfile> profileListener,
BiConsumer<DeviceId, DeviceProfile> deviceListener) {
if (profileListener != null) {
profileListeners.computeIfAbsent(tenantId, id -> new ConcurrentHashMap<>()).put(listenerId, profileListener);
}
if (deviceListener != null) {
deviceProfileListeners.computeIfAbsent(tenantId, id -> new ConcurrentHashMap<>()).put(listenerId, deviceListener);
}
}
@Override
public DeviceProfile find(DeviceProfileId deviceProfileId) {
return deviceProfileService.findDeviceProfileById(TenantId.SYS_TENANT_ID, deviceProfileId);
}
@Override
public DeviceProfile findOrCreateDeviceProfile(TenantId tenantId, String profileName) {
return deviceProfileService.findOrCreateDeviceProfile(tenantId, profileName);
}
@Override
public void removeListener(TenantId tenantId, EntityId listenerId) {
ConcurrentMap<EntityId, Consumer<DeviceProfile>> tenantListeners = profileListeners.get(tenantId);
if (tenantListeners != null) {
tenantListeners.remove(listenerId);
}
ConcurrentMap<EntityId, BiConsumer<DeviceId, DeviceProfile>> deviceListeners = deviceProfileListeners.get(tenantId);
if (deviceListeners != null) {
deviceListeners.remove(listenerId);
}
}
private void notifyProfileListeners(DeviceProfile profile) {
|
ConcurrentMap<EntityId, Consumer<DeviceProfile>> tenantListeners = profileListeners.get(profile.getTenantId());
if (tenantListeners != null) {
tenantListeners.forEach((id, listener) -> listener.accept(profile));
}
}
private void notifyDeviceListeners(TenantId tenantId, DeviceId deviceId, DeviceProfile profile) {
if (profile != null) {
ConcurrentMap<EntityId, BiConsumer<DeviceId, DeviceProfile>> tenantListeners = deviceProfileListeners.get(tenantId);
if (tenantListeners != null) {
tenantListeners.forEach((id, listener) -> listener.accept(deviceId, profile));
}
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\profile\DefaultTbDeviceProfileCache.java
| 2
|
请完成以下Java代码
|
public void setC_LicenseFeeSettings_ID (final int C_LicenseFeeSettings_ID)
{
if (C_LicenseFeeSettings_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_LicenseFeeSettings_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_LicenseFeeSettings_ID, C_LicenseFeeSettings_ID);
}
@Override
public int getC_LicenseFeeSettings_ID()
{
return get_ValueAsInt(COLUMNNAME_C_LicenseFeeSettings_ID);
}
@Override
public void setCommission_Product_ID (final int Commission_Product_ID)
{
if (Commission_Product_ID < 1)
set_Value (COLUMNNAME_Commission_Product_ID, null);
else
set_Value (COLUMNNAME_Commission_Product_ID, Commission_Product_ID);
}
@Override
public int getCommission_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Commission_Product_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setName (final java.lang.String Name)
{
|
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPointsPrecision (final int PointsPrecision)
{
set_Value (COLUMNNAME_PointsPrecision, PointsPrecision);
}
@Override
public int getPointsPrecision()
{
return get_ValueAsInt(COLUMNNAME_PointsPrecision);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_LicenseFeeSettings.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CityRepository {
private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>();
private static final AtomicLong idGenerator = new AtomicLong(0);
public Long save(City city) {
Long id = idGenerator.incrementAndGet();
city.setId(id);
repository.put(id, city);
return id;
}
public Collection<City> findAll() {
return repository.values();
}
|
public City findCityById(Long id) {
return repository.get(id);
}
public Long updateCity(City city) {
repository.put(city.getId(), city);
return city.getId();
}
public Long deleteCity(Long id) {
repository.remove(id);
return id;
}
}
|
repos\springboot-learning-example-master\springboot-webflux-2-restful\src\main\java\org\spring\springboot\dao\CityRepository.java
| 2
|
请完成以下Java代码
|
private void assertRestAPIColumnNames(final String tableName, final Collection<String> columnNames)
{
if (columnNames.isEmpty())
{
return;
}
final RESTApiTableInfo tableInfo = repository.getByTableNameOrNull(tableName);
final Collection<String> notValidColumnNames;
if (tableInfo == null)
{
notValidColumnNames = columnNames;
}
else
{
notValidColumnNames = columnNames.stream()
.filter(columnName -> !tableInfo.isCustomRestAPIColumn(columnName))
.collect(Collectors.toList());
}
if (!notValidColumnNames.isEmpty())
{
final String notValidColumnNamesStr = notValidColumnNames.stream()
.map(columnName -> tableName + "." + columnName)
.collect(Collectors.joining(", "));
throw new AdempiereException(MSG_CUSTOM_REST_API_COLUMN, notValidColumnNamesStr)
.markAsUserValidationError();
}
}
@NonNull
public CustomColumnsJsonValues getCustomColumnsJsonValues(@NonNull final PO record)
{
final ZoneId zoneId = extractZoneId(record);
return convertToJsonValues(record, zoneId);
}
@NonNull
|
private CustomColumnsJsonValues convertToJsonValues(final @NonNull PO record, final ZoneId zoneId)
{
final POInfo poInfo = record.getPOInfo();
final ImmutableMap.Builder<String, Object> map = ImmutableMap.builder();
streamCustomRestAPIColumns(poInfo)
.forEach(customColumn -> {
final String columnName = customColumn.getColumnName();
final Object poValue = record.get_Value(columnName);
final Object jsonValue = CustomColumnsConverters.convertToJsonValue(poValue, customColumn.getDisplayType(), zoneId);
if (jsonValue != null)
{
map.put(columnName, jsonValue);
}
});
return CustomColumnsJsonValues.ofJsonValuesMap(map.build());
}
private ZoneId extractZoneId(final @NonNull PO record) {return orgDAO.getTimeZone(OrgId.ofRepoId(record.getAD_Org_ID()));}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\custom_columns\CustomColumnService.java
| 1
|
请完成以下Java代码
|
public boolean contains(String id) {
return cache.containsKey(id);
}
@Override
public void add(String id, ProcessDefinitionInfoCacheObject obj) {
cache.put(id, obj);
}
@Override
public void remove(String id) {
cache.remove(id);
}
@Override
public void clear() {
cache.clear();
}
@Override
public Collection<ProcessDefinitionInfoCacheObject> getAll() {
return cache.values();
}
@Override
public int size() {
return cache.size();
}
protected ProcessDefinitionInfoCacheObject retrieveProcessDefinitionInfoCacheObject(String processDefinitionId, CommandContext commandContext) {
ProcessDefinitionInfoEntityManager infoEntityManager = CommandContextUtil.getProcessDefinitionInfoEntityManager(commandContext);
ObjectMapper objectMapper = CommandContextUtil.getProcessEngineConfiguration(commandContext).getObjectMapper();
ProcessDefinitionInfoCacheObject cacheObject = null;
|
if (cache.containsKey(processDefinitionId)) {
cacheObject = cache.get(processDefinitionId);
} else {
cacheObject = new ProcessDefinitionInfoCacheObject();
cacheObject.setRevision(0);
cacheObject.setInfoNode(objectMapper.createObjectNode());
}
ProcessDefinitionInfoEntity infoEntity = infoEntityManager.findProcessDefinitionInfoByProcessDefinitionId(processDefinitionId);
if (infoEntity != null && infoEntity.getRevision() != cacheObject.getRevision()) {
cacheObject.setRevision(infoEntity.getRevision());
if (infoEntity.getInfoJsonId() != null) {
byte[] infoBytes = infoEntityManager.findInfoJsonById(infoEntity.getInfoJsonId());
try {
ObjectNode infoNode = (ObjectNode) objectMapper.readTree(infoBytes);
cacheObject.setInfoNode(infoNode);
} catch (Exception e) {
throw new FlowableException("Error reading json info node for process definition " + processDefinitionId, e);
}
}
} else if (infoEntity == null) {
cacheObject.setRevision(0);
cacheObject.setInfoNode(objectMapper.createObjectNode());
}
return cacheObject;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\deploy\ProcessDefinitionInfoCache.java
| 1
|
请完成以下Java代码
|
public class ProductQty
{
private final int productId;
private final BigDecimal qty;
public ProductQty(int productId, BigDecimal qty)
{
super();
this.productId = productId;
this.qty = qty;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + productId;
result = prime * result + ((qty == null) ? 0 : qty.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProductQty other = (ProductQty)obj;
if (productId != other.productId)
return false;
if (qty == null)
{
if (other.qty != null)
return false;
}
else if (!qty.equals(other.qty))
return false;
return true;
|
}
@Override
public String toString()
{
return "ProductQty [productId=" + productId + ", qty=" + qty + "]";
}
public int getProductId()
{
return productId;
}
public BigDecimal getQty()
{
return qty;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\adempiere\model\ProductQty.java
| 1
|
请完成以下Java代码
|
public void deleteAttachmentsByTaskId(String taskId) {
checkHistoryEnabled();
List<AttachmentEntity> attachments = findAttachmentsByTaskId(taskId);
boolean dispatchEvents = getEventDispatcher().isEnabled();
String processInstanceId = null;
String processDefinitionId = null;
String executionId = null;
if (dispatchEvents && attachments != null && !attachments.isEmpty()) {
// Forced to fetch the task to get hold of the process definition
// for event-dispatching, if available
Task task = getTaskEntityManager().findById(taskId);
if (task != null) {
processDefinitionId = task.getProcessDefinitionId();
processInstanceId = task.getProcessInstanceId();
executionId = task.getExecutionId();
}
}
for (Attachment attachment : attachments) {
String contentId = attachment.getContentId();
if (contentId != null) {
getByteArrayEntityManager().deleteByteArrayById(contentId);
}
attachmentDataManager.delete((AttachmentEntity) attachment);
if (dispatchEvents) {
getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(
|
ActivitiEventType.ENTITY_DELETED,
attachment,
executionId,
processInstanceId,
processDefinitionId
)
);
}
}
}
protected void checkHistoryEnabled() {
if (!getHistoryManager().isHistoryEnabled()) {
throw new ActivitiException("In order to use attachments, history should be enabled");
}
}
public AttachmentDataManager getAttachmentDataManager() {
return attachmentDataManager;
}
public void setAttachmentDataManager(AttachmentDataManager attachmentDataManager) {
this.attachmentDataManager = attachmentDataManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AttachmentEntityManagerImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class Jedis {
/**
* Jedis pool configuration.
*/
private final Pool pool = new Pool();
public Pool getPool() {
return this.pool;
}
}
/**
* Lettuce client properties.
*/
public static class Lettuce {
/**
* Shutdown timeout.
*/
private Duration shutdownTimeout = Duration.ofMillis(100);
/**
* Defines from which Redis nodes data is read.
*/
private @Nullable String readFrom;
/**
* Lettuce pool configuration.
*/
private final Pool pool = new Pool();
private final Cluster cluster = new Cluster();
public Duration getShutdownTimeout() {
return this.shutdownTimeout;
}
public void setShutdownTimeout(Duration shutdownTimeout) {
this.shutdownTimeout = shutdownTimeout;
}
public @Nullable String getReadFrom() {
return this.readFrom;
}
public void setReadFrom(@Nullable String readFrom) {
this.readFrom = readFrom;
}
public Pool getPool() {
return this.pool;
}
public Cluster getCluster() {
return this.cluster;
}
public static class Cluster {
private final Refresh refresh = new Refresh();
public Refresh getRefresh() {
return this.refresh;
|
}
public static class Refresh {
/**
* Whether to discover and query all cluster nodes for obtaining the
* cluster topology. When set to false, only the initial seed nodes are
* used as sources for topology discovery.
*/
private boolean dynamicRefreshSources = true;
/**
* Cluster topology refresh period.
*/
private @Nullable Duration period;
/**
* Whether adaptive topology refreshing using all available refresh
* triggers should be used.
*/
private boolean adaptive;
public boolean isDynamicRefreshSources() {
return this.dynamicRefreshSources;
}
public void setDynamicRefreshSources(boolean dynamicRefreshSources) {
this.dynamicRefreshSources = dynamicRefreshSources;
}
public @Nullable Duration getPeriod() {
return this.period;
}
public void setPeriod(@Nullable Duration period) {
this.period = period;
}
public boolean isAdaptive() {
return this.adaptive;
}
public void setAdaptive(boolean adaptive) {
this.adaptive = adaptive;
}
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\DataRedisProperties.java
| 2
|
请完成以下Java代码
|
public static synchronized void destroy() {
if (isInitialized()) {
Map<String, ProcessEngine> engines = new HashMap<String, ProcessEngine>(processEngines);
processEngines = new HashMap<String, ProcessEngine>();
for (String processEngineName : engines.keySet()) {
ProcessEngine processEngine = engines.get(processEngineName);
try {
processEngine.close();
} catch (Exception e) {
log.error(
"exception while closing {}",
(processEngineName == null
? "the default process engine"
: "process engine " + processEngineName),
e
);
}
}
processEngineInfosByName.clear();
|
processEngineInfosByResourceUrl.clear();
processEngineInfos.clear();
setInitialized(false);
}
}
public static boolean isInitialized() {
return isInitialized;
}
public static void setInitialized(boolean isInitialized) {
ProcessEngines.isInitialized = isInitialized;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\ProcessEngines.java
| 1
|
请完成以下Java代码
|
public long iterateUsingKeySetAndEnhanceForLoop() {
return mapIteration.iterateUsingKeySetAndEnhanceForLoop(map);
}
@Benchmark
public long iterateUsingStreamAPIAndEntrySet() {
return mapIteration.iterateUsingStreamAPIAndEntrySet(map);
}
@Benchmark
public long iterateUsingStreamAPIAndKeySet() {
return mapIteration.iterateUsingStreamAPIAndKeySet(map);
}
@Benchmark
public long iterateKeysUsingKeySetAndEnhanceForLoop() {
return mapIteration.iterateKeysUsingKeySetAndEnhanceForLoop(map);
|
}
@Benchmark
public long iterateUsingMapIteratorApacheCollection() {
return mapIteration.iterateUsingMapIteratorApacheCollection(iterableMap);
}
@Benchmark
public long iterateEclipseMap() throws IOException {
return mapIteration.iterateEclipseMap(mutableMap);
}
@Benchmark
public long iterateMapUsingParallelStreamApi() throws IOException {
return mapIteration.iterateMapUsingParallelStreamApi(map);
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\iteration\MapIterationBenchmark.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PricingDAO implements IPricingDAO
{
private static final Logger logger = LogManager.getLogger(PricingDAO.class);
private final CCache<Integer, ImmutableList<PricingRuleDescriptor>> //
pricingRuleDescriptorsCache = CCache.<Integer, ImmutableList<PricingRuleDescriptor>> builder()
.cacheName("pricingRuleDescriptorsCache")
.additionalTableNameToResetFor(I_C_PricingRule.Table_Name)
.initialCapacity(1)
.build();
@Override
public List<PricingRuleDescriptor> getPricingRules()
{
return pricingRuleDescriptorsCache.getOrLoad(0, this::retrievePricingRules);
}
private ImmutableList<PricingRuleDescriptor> retrievePricingRules()
{
return Services.get(IQueryBL.class).createQueryBuilderOutOfTrx(I_C_PricingRule.class)
.addOnlyActiveRecordsFilter()
//
.orderBy(I_C_PricingRule.COLUMNNAME_SeqNo)
.orderBy(I_C_PricingRule.COLUMNNAME_C_PricingRule_ID)
//
.create()
.stream()
|
.map(this::toPricingRuleDescriptorNoFail)
.filter(Objects::nonNull)
.collect(GuavaCollectors.distinctBy(PricingRuleDescriptor::getPricingRuleClass))
.collect(ImmutableList.toImmutableList());
}
private PricingRuleDescriptor toPricingRuleDescriptorNoFail(final I_C_PricingRule record)
{
try
{
return toPricingRuleDescriptor(record);
}
catch (final Exception ex)
{
logger.warn("Skipping invalid pricing rule definition: {}", record, ex);
return null;
}
}
private PricingRuleDescriptor toPricingRuleDescriptor(final I_C_PricingRule record)
{
return PricingRuleDescriptor.builder()
.name(record.getName())
.pricingRuleClass(ClassReference.ofClassname(record.getClassname()))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PricingDAO.java
| 2
|
请完成以下Java代码
|
public class HUConsolidationJob
{
@NonNull HUConsolidationJobId id;
@NonNull BPartnerLocationId shipToBPLocationId;
@NonNull ImmutableSet<PickingSlotId> pickingSlotIds;
@NonNull @With HUConsolidationJobStatus docStatus;
@Nullable @With UserId responsibleId;
@Nullable @With HUConsolidationTarget currentTarget;
public static boolean equals(@Nullable HUConsolidationJob job1, @Nullable HUConsolidationJob job2) {return Objects.equals(job1, job2);}
public void assertUserCanEdit(final UserId callerId)
{
if (this.responsibleId != null && !UserId.equals(this.responsibleId, callerId))
{
throw new AdempiereException("User has no permissions");
}
}
|
public BPartnerId getCustomerId() {return shipToBPLocationId.getBpartnerId();}
@NonNull
public HUConsolidationTarget getCurrentTargetNotNull()
{
return Check.assumeNotNull(currentTarget, "job has a current target");
}
public boolean isProcessed() {return docStatus.isProcessed();}
public boolean containsPickingSlotId(@NonNull final PickingSlotId pickingSlotId)
{
return pickingSlotIds.contains(pickingSlotId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\HUConsolidationJob.java
| 1
|
请完成以下Java代码
|
public int getRevision() {
return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
public int getRevisionNext() {
return revision + 1;
}
@SuppressWarnings("unchecked")
public <T extends Query<?, ?>> Filter extend(T extendingQuery) {
ensureNotNull(NotValidException.class, "extendingQuery", extendingQuery);
if (!extendingQuery.getClass().equals(query.getClass())) {
throw LOG.queryExtensionException(query.getClass().getName(), extendingQuery.getClass().getName());
}
FilterEntity copy = copyFilter();
copy.setQuery(query.extend(extendingQuery));
return copy;
}
@SuppressWarnings("unchecked")
protected <T> JsonObjectConverter<T> getConverter() {
JsonObjectConverter<T> converter = (JsonObjectConverter<T>) queryConverter.get(resourceType);
if (converter != null) {
return converter;
}
else {
throw LOG.unsupportedResourceTypeException(resourceType);
}
}
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("name", this.name);
persistentState.put("owner", this.owner);
persistentState.put("query", this.query);
persistentState.put("properties", this.properties);
return persistentState;
|
}
protected FilterEntity copyFilter() {
FilterEntity copy = new FilterEntity(getResourceType());
copy.setName(getName());
copy.setOwner(getOwner());
copy.setQueryInternal(getQueryInternal());
copy.setPropertiesInternal(getPropertiesInternal());
return copy;
}
public void postLoad() {
if (query != null) {
query.addValidator(StoredQueryValidator.get());
}
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<String>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<String, Class>();
return referenceIdAndClass;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\FilterEntity.java
| 1
|
请完成以下Java代码
|
public CmmnExternalWorkerTransitionBuilder createCmmnExternalWorkerTransitionBuilder(String externalJobId, String workerId) {
return new CmmnExternalWorkerTransitionBuilderImpl(commandExecutor, externalJobId, workerId);
}
@Override
public void unacquireExternalWorkerJob(String jobId, String workerId) {
commandExecutor.execute(new UnacquireExternalWorkerJobCmd(jobId, workerId, configuration.getJobServiceConfiguration()));
}
@Override
public void unacquireAllExternalWorkerJobsForWorker(String workerId) {
commandExecutor.execute(new UnacquireAllExternalWorkerJobsForWorkerCmd(workerId, null, configuration.getJobServiceConfiguration()));
}
@Override
public void unacquireAllExternalWorkerJobsForWorker(String workerId, String tenantId) {
commandExecutor.execute(new UnacquireAllExternalWorkerJobsForWorkerCmd(workerId, tenantId, configuration.getJobServiceConfiguration()));
}
@Override
public ChangeTenantIdBuilder createChangeTenantIdBuilder(String fromTenantId, String toTenantId) {
return new ChangeTenantIdBuilderImpl(fromTenantId, toTenantId, configuration.getChangeTenantIdManager());
}
|
public <T> T executeCommand(Command<T> command) {
if (command == null) {
throw new FlowableIllegalArgumentException("The command is null");
}
return commandExecutor.execute(command);
}
public <T> T executeCommand(CommandConfig config, Command<T> command) {
if (config == null) {
throw new FlowableIllegalArgumentException("The config is null");
}
if (command == null) {
throw new FlowableIllegalArgumentException("The command is null");
}
return commandExecutor.execute(config, command);
}
@Override
public LockManager getLockManager(String lockName) {
return new LockManagerImpl(commandExecutor, lockName, getConfiguration().getLockPollRate(), configuration.getEngineCfgKey());
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnManagementServiceImpl.java
| 1
|
请完成以下Java代码
|
public class TbLwM2mRedisClientOtaInfoStore implements TbLwM2MClientOtaInfoStore {
private static final String OTA_EP = "OTA#EP#";
private final RedisConnectionFactory connectionFactory;
public TbLwM2mRedisClientOtaInfoStore(RedisConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
private void put(OtaPackageType type, LwM2MClientOtaInfo<?, ?, ?> info) {
try (var connection = connectionFactory.getConnection()) {
connection.set((OTA_EP + type + info.getEndpoint()).getBytes(), JacksonUtil.toString(info).getBytes());
}
}
@Override
public LwM2MClientFwOtaInfo getFw(String endpoint) {
return getLwM2MClientOtaInfo(OtaPackageType.FIRMWARE, endpoint, LwM2MClientFwOtaInfo.class);
}
@Override
public void putFw(LwM2MClientFwOtaInfo info) {
|
put(OtaPackageType.FIRMWARE, info);
}
@Override
public LwM2MClientSwOtaInfo getSw(String endpoint) {
return getLwM2MClientOtaInfo(OtaPackageType.SOFTWARE, endpoint, LwM2MClientSwOtaInfo.class);
}
@Override
public void putSw(LwM2MClientSwOtaInfo info) {
put(OtaPackageType.SOFTWARE, info);
}
private <T extends LwM2MClientOtaInfo<?, ?, ?>> T getLwM2MClientOtaInfo(OtaPackageType type, String endpoint, Class<T> clazz) {
try (var connection = connectionFactory.getConnection()) {
byte[] data = connection.get((OTA_EP + type + endpoint).getBytes());
return JacksonUtil.fromBytes(data, clazz);
}
}
}
|
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbLwM2mRedisClientOtaInfoStore.java
| 1
|
请完成以下Java代码
|
public <I, O> O put(
@NonNull final I requestBody,
@NonNull final ParameterizedTypeReference<O> returnType,
@NonNull final String url)
{
try (final MDCCloseable ignored = MDC.putCloseable("httpMethod", "PUT");
final MDCCloseable ignored1 = MDC.putCloseable("url", url);
final MDCCloseable ignored2 = MDC.putCloseable("requestBody", requestBody.toString()))
{
final RestTemplate restTemplate = createRestTemplate();
final HttpEntity<I> entity = new HttpEntity<>(requestBody, createHeaders());
final ResponseEntity<O> groups = restTemplate.exchange(
url,
HttpMethod.PUT,
entity,
returnType,
ImmutableMap.of());
return groups.getBody();
}
catch (final RuntimeException e)
{
throw convertException(e)
.setParameter("httpMethod", "PUT")
.setParameter("url", url)
.setParameter("requestBody", requestBody);
}
}
public void delete(@NonNull final String url)
{
try (final MDCCloseable ignored = MDC.putCloseable("httpMethod", "DELETE");
final MDCCloseable ignored1 = MDC.putCloseable("url", url))
{
final RestTemplate restTemplate = createRestTemplate();
final HttpEntity<?> entity = new HttpEntity<>(createHeaders());
restTemplate.exchange(url, HttpMethod.DELETE, entity, String.class);
}
catch (final RuntimeException e)
{
throw convertException(e)
.setParameter("httpMethod", "DELETE")
|
.setParameter("url", url);
}
}
private RestTemplate createRestTemplate()
{
return new RestTemplateBuilder().rootUri(BASE_URL).build();
}
private HttpHeaders createHeaders()
{
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(ImmutableList.of(MediaType.APPLICATION_JSON));
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.set(HttpHeaders.AUTHORIZATION, "Bearer " + authToken);
return httpHeaders;
}
private static AdempiereException convertException(@NonNull final RuntimeException rte)
{
if (rte instanceof HttpClientErrorException)
{
final HttpClientErrorException hcee = (HttpClientErrorException)rte;
final JSONObjectMapper<ErrorResponse> mapper = JSONObjectMapper.forClass(ErrorResponse.class);
final ErrorResponse errorResponse = mapper.readValue(hcee.getResponseBodyAsString());
return new AdempiereException(errorResponse.getError().getMessage(), hcee)
.markAsUserValidationError()
.appendParametersToMessage()
.setParameter("code", errorResponse.getError().getCode())
.setParameter("message", errorResponse.getError().getMessage());
}
return AdempiereException.wrapIfNeeded(rte)
.appendParametersToMessage();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\cleverreach\src\main\java\de\metas\marketing\gateway\cleverreach\CleverReachLowLevelClient.java
| 1
|
请完成以下Java代码
|
public class WEBUI_SalesOrder_PricingConditionsView_Launcher extends JavaProcess implements IProcessPrecondition
{
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("one and only one order shall be selected");
}
final I_C_Order salesOrder = context.getSelectedModel(I_C_Order.class);
// NOTE: we allow sales and purchase orders too; see https://github.com/metasfresh/metasfresh/issues/4017
final DocStatus docStatus = DocStatus.ofCode(salesOrder.getDocStatus());
if (!docStatus.isDrafted())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("only draft orders are allowed");
}
// Make sure only one line is selected
final Set<TableRecordReference> selectedOrderLineRefs = context.getSelectedIncludedRecords();
if (selectedOrderLineRefs.isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (selectedOrderLineRefs.size() > 1)
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
|
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final Set<TableRecordReference> salesOrderLineRefs = getSelectedIncludedRecordIds(I_C_OrderLine.class)
.stream()
.map(recordId -> TableRecordReference.of(I_C_OrderLine.Table_Name, recordId))
.collect(ImmutableSet.toImmutableSet());
CollectionUtils.singleElement(salesOrderLineRefs);
getResult().setRecordsToOpen(salesOrderLineRefs, OrderLinePricingConditionsViewFactory.WINDOW_ID_STRING);
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\process\WEBUI_SalesOrder_PricingConditionsView_Launcher.java
| 1
|
请完成以下Java代码
|
public String getFeeNameForProducedProduct(final I_M_Product product)
{
Check.assumeNotNull(product, "product not null");
// TODO: configure some where
// e.g. for product "Futterkarotten" return "Zusätzliche Sortierkosten"
//return product.getName();
return "Zus\u00e4tzliche Sortierkosten";
}
@Override
public List<QualityInvoiceLineGroupType> getQualityInvoiceLineGroupTypes()
{
return QualityInvoiceLineGroupType_ForInvoicing;
}
@Override
public int getC_DocTypeInvoice_DownPayment_ID()
{
if (_invoiceDocTypeDownPaymentId == null)
{
final String docSubType = IMaterialTrackingBL.C_DocType_INVOICE_DOCSUBTYPE_QI_DownPayment;
_invoiceDocTypeDownPaymentId = loadDocType(DocSubType.ofCode(docSubType));
}
return _invoiceDocTypeDownPaymentId.getRepoId();
}
@Override
public int getC_DocTypeInvoice_FinalSettlement_ID()
{
if (_invoiceDocTypeFinalSettlementId == null)
{
final String docSubType = IMaterialTrackingBL.C_DocType_INVOICE_DOCSUBTYPE_QI_FinalSettlement;
_invoiceDocTypeFinalSettlementId = loadDocType(DocSubType.ofCode(docSubType));
}
return _invoiceDocTypeFinalSettlementId.getRepoId();
}
/**
* Returns true if the scrap percentage treshold is less than 100.
*/
|
@Override
public boolean isFeeForScrap()
{
return getScrapPercentageTreshold().compareTo(new BigDecimal("100")) < 0;
}
private DocTypeId loadDocType(final DocSubType docSubType)
{
final IContextAware context = getContext();
final Properties ctx = context.getCtx();
final int adClientId = Env.getAD_Client_ID(ctx);
final int adOrgId = Env.getAD_Org_ID(ctx); // FIXME: not sure if it's ok
return Services.get(IDocTypeDAO.class).getDocTypeId(
DocTypeQuery.builder()
.docBaseType(X_C_DocType.DOCBASETYPE_APInvoice)
.docSubType(docSubType)
.adClientId(adClientId)
.adOrgId(adOrgId)
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\ch\lagerkonf\impl\AbstractQualityBasedConfig.java
| 1
|
请完成以下Java代码
|
default int getAD_User_InCharge_ID(final I_C_Invoice_Candidate ic)
{
return getHandlerRecord().getAD_User_InCharge_ID();
}
boolean isUserInChargeUserEditable();
/**
* Set NetAmtToInvoice = PriceActual * QtyToInvoice - DiscountAmt, rounded to currency precision.<br>
* (i.e. method responsible for setting {@link I_C_Invoice_Candidate#setNetAmtToInvoice(java.math.BigDecimal)}).
*/
void setNetAmtToInvoice(I_C_Invoice_Candidate ic);
/**
* Set the "full" open invoicable amount, no matter what the invoice rule is.
*/
void setLineNetAmt(I_C_Invoice_Candidate ic);
/**
* Method responsible for setting
* <ul>
* <li>C_Order_ID
* <li>DateOrderd
* <li>QtyOrdered
* <li>QtyEntered
* <li>C_UOM_ID
* </ul>
* of the given invoice candidate.
* <p>
* Implementors can assume that this method is called before {@link #setDeliveredData(I_C_Invoice_Candidate)}.
*/
void setOrderedData(I_C_Invoice_Candidate ic);
/**
* Method responsible for setting
* <ul>
* <li>{@code M_InOut_ID}
* <li>{@code DeliveryDate}
* <li>{@code QtyDelivered}
* <li>{@code QtyDeliveredInUOM}
* </ul>
* of the given invoice candidate.
* <p>
* Implementors can assume that when this method is called then {@link #setOrderedData(I_C_Invoice_Candidate)} was already called.
*/
void setDeliveredData(I_C_Invoice_Candidate ic);
default PriceAndTax calculatePriceAndTax(final I_C_Invoice_Candidate ic)
{
return PriceAndTax.NONE;
}
default void setShipmentSchedule(final I_C_Invoice_Candidate ic) { /* do nothing */ };
/**
* * Method responsible for setting
|
* <ul>
* <li>Bill_BPartner_ID
* <li>Bill_Location_ID
* <li>Bill_User_ID
* </ul>
* of the given invoice candidate.
*/
void setBPartnerData(I_C_Invoice_Candidate ic);
default void setInvoiceScheduleAndDateToInvoice(@NonNull final I_C_Invoice_Candidate ic)
{
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class);
ic.setC_InvoiceSchedule_ID(bpartnerDAO.getById(ic.getBill_BPartner_ID()).getC_InvoiceSchedule_ID());
invoiceCandBL.set_DateToInvoice_DefaultImpl(ic);
}
/**
* Price and tax info calculation result.
* <p>
* All fields are optional and only those filled will be set back to invoice candidate.
*/
@lombok.Value
@lombok.Builder
class PriceAndTax
{
public static final PriceAndTax NONE = builder().build();
PricingSystemId pricingSystemId;
PriceListVersionId priceListVersionId;
CurrencyId currencyId;
BigDecimal priceEntered;
BigDecimal priceActual;
UomId priceUOMId;
Percent discount;
InvoicableQtyBasedOn invoicableQtyBasedOn;
Boolean taxIncluded;
TaxId taxId;
TaxCategoryId taxCategoryId;
BigDecimal compensationGroupBaseAmt;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\IInvoiceCandidateHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void addCacheResetListener(@NonNull final DocOutboundConfigChangedListener listener)
{
final ICacheResetListener cacheResetListener = (request) -> {
listener.onConfigChanged();
return 1L;
};
final CacheMgt cacheMgt = CacheMgt.get();
cacheMgt.addCacheResetListener(I_C_Doc_Outbound_Config.Table_Name, cacheResetListener);
}
@Nullable
public DocOutboundConfig getByQuery(@NonNull final DocOutboundConfigQuery query)
{
return getDocOutboundConfigMap().getByQuery(query);
}
@NonNull
private DocOutboundConfigMap getDocOutboundConfigMap()
{
return cache.getOrLoadNonNull(0, this::retrieveDocOutboundConfigMap);
}
@NotNull
private DocOutboundConfigMap retrieveDocOutboundConfigMap()
{
final ImmutableList<DocOutboundConfig> docOutboundConfig = queryBL.createQueryBuilder(I_C_Doc_Outbound_Config.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(DocOutboundConfigRepository::ofRecord)
.collect(ImmutableList.toImmutableList());
return new DocOutboundConfigMap(docOutboundConfig);
}
private static DocOutboundConfig ofRecord(@NotNull final I_C_Doc_Outbound_Config record)
{
|
return DocOutboundConfig.builder()
.id(DocOutboundConfigId.ofRepoId(record.getC_Doc_Outbound_Config_ID()))
.tableId(AdTableId.ofRepoId(record.getAD_Table_ID()))
.docBaseType(DocBaseType.ofNullableCode(record.getDocBaseType()))
.printFormatId(PrintFormatId.ofRepoIdOrNull(record.getAD_PrintFormat_ID()))
.ccPath(record.getCCPath())
.isDirectProcessQueueItem(record.isDirectProcessQueueItem())
.isDirectEnqueue(record.isDirectEnqueue())
.isAutoSendDocument(record.isAutoSendDocument())
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.build();
}
@NonNull
public ImmutableSet<AdTableId> getDistinctConfigTableIds()
{
return getDocOutboundConfigMap().getTableIds();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\config\DocOutboundConfigRepository.java
| 2
|
请完成以下Java代码
|
public DmnDeploymentBuilder execute(CommandContext commandContext) {
return new DmnDeploymentBuilderImpl();
}
});
}
public DmnDeployment deploy(DmnDeploymentBuilderImpl deploymentBuilder) {
return commandExecutor.execute(new DeployCmd<DmnDeployment>(deploymentBuilder));
}
@Override
public void deleteDeployment(String deploymentId) {
commandExecutor.execute(new DeleteDeploymentCmd(deploymentId));
}
@Override
public DmnDecisionQuery createDecisionQuery() {
return new DecisionQueryImpl(commandExecutor);
}
@Override
public NativeDecisionQuery createNativeDecisionQuery() {
return new NativeDecisionTableQueryImpl(commandExecutor);
}
@Override
public List<String> getDeploymentResourceNames(String deploymentId) {
return commandExecutor.execute(new GetDeploymentResourceNamesCmd(deploymentId));
}
@Override
public InputStream getResourceAsStream(String deploymentId, String resourceName) {
return commandExecutor.execute(new GetDeploymentResourceCmd(deploymentId, resourceName));
}
@Override
public void setDeploymentCategory(String deploymentId, String category) {
commandExecutor.execute(new SetDeploymentCategoryCmd(deploymentId, category));
}
@Override
public void setDeploymentTenantId(String deploymentId, String newTenantId) {
commandExecutor.execute(new SetDeploymentTenantIdCmd(deploymentId, newTenantId));
}
@Override
public void changeDeploymentParentDeploymentId(String deploymentId, String newParentDeploymentId) {
commandExecutor.execute(new SetDeploymentParentDeploymentIdCmd(deploymentId, newParentDeploymentId));
}
|
@Override
public DmnDeploymentQuery createDeploymentQuery() {
return new DmnDeploymentQueryImpl(commandExecutor);
}
@Override
public NativeDmnDeploymentQuery createNativeDeploymentQuery() {
return new NativeDmnDeploymentQueryImpl(commandExecutor);
}
@Override
public DmnDecision getDecision(String decisionId) {
return commandExecutor.execute(new GetDeploymentDecisionCmd(decisionId));
}
@Override
public DmnDefinition getDmnDefinition(String decisionId) {
return commandExecutor.execute(new GetDmnDefinitionCmd(decisionId));
}
@Override
public InputStream getDmnResource(String decisionId) {
return commandExecutor.execute(new GetDeploymentDmnResourceCmd(decisionId));
}
@Override
public void setDecisionCategory(String decisionId, String category) {
commandExecutor.execute(new SetDecisionTableCategoryCmd(decisionId, category));
}
@Override
public InputStream getDecisionRequirementsDiagram(String decisionId) {
return commandExecutor.execute(new GetDeploymentDecisionRequirementsDiagramCmd(decisionId));
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\DmnRepositoryServiceImpl.java
| 1
|
请完成以下Java代码
|
public String getCharge() {
return charge;
}
/**
* Sets the value of the charge property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCharge(String value) {
this.charge = value;
}
/**
* Gets the value of the verfalldatum property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
|
*/
public XMLGregorianCalendar getVerfalldatum() {
return verfalldatum;
}
/**
* Sets the value of the verfalldatum property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setVerfalldatum(XMLGregorianCalendar value) {
this.verfalldatum = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourePositionType.java
| 1
|
请完成以下Java代码
|
public class CasePageTask extends Task {
public static final String TYPE = "casePage";
protected String type;
protected String formKey;
protected boolean sameDeployment = true;
protected String label;
protected String icon;
protected String assignee;
protected String owner;
protected List<String> candidateUsers = new ArrayList<>();
protected List<String> candidateGroups = new ArrayList<>();
public CasePageTask() {
type = TYPE;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public boolean isSameDeployment() {
return sameDeployment;
}
public void setSameDeployment(boolean sameDeployment) {
this.sameDeployment = sameDeployment;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getOwner() {
return owner;
}
|
public void setOwner(String owner) {
this.owner = owner;
}
public List<String> getCandidateUsers() {
return candidateUsers;
}
public void setCandidateUsers(List<String> candidateUsers) {
this.candidateUsers = candidateUsers;
}
public List<String> getCandidateGroups() {
return candidateGroups;
}
public void setCandidateGroups(List<String> candidateGroups) {
this.candidateGroups = candidateGroups;
}
@Override
public CasePageTask clone() {
CasePageTask clone = new CasePageTask();
clone.setValues(this);
return clone;
}
public void setValues(CasePageTask otherElement) {
super.setValues(otherElement);
setType(otherElement.getType());
setFormKey(otherElement.getFormKey());
setSameDeployment(otherElement.isSameDeployment());
setLabel(otherElement.getLabel());
setIcon(otherElement.getIcon());
setAssignee(otherElement.getAssignee());
setOwner(otherElement.getOwner());
setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups()));
setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers()));
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\CasePageTask.java
| 1
|
请完成以下Java代码
|
protected String doIt() throws Exception
{
updateFlatrateTermsPartner();
return MSG_OK;
}
private void updateFlatrateTermsPartner()
{
final List<I_C_Flatrate_Term> flatrateTermsToChange = getFlatrateTermsToChange();
flatrateTermsToChange.forEach(this::updateFlatrateTermPartner);
}
private void updateFlatrateTermPartner(final I_C_Flatrate_Term term)
{
final ImmutableList<I_C_Flatrate_Term> nextTerms = flatrateBL.retrieveNextFlatrateTerms(term);
updateFlatrateTermBillBPartner(term);
nextTerms.forEach(this::updateFlatrateTermBillBPartner);
}
|
private void updateFlatrateTermBillBPartner(final I_C_Flatrate_Term term)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoId(p_billBPartnerId);
final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoId(p_billBPartnerId, p_billLocationId);
final BPartnerContactId bPartnerContactId = BPartnerContactId.ofRepoIdOrNull(p_billBPartnerId, p_billUserId);
final boolean termHasInvoices = C_Flatrate_Term_Change_ProcessHelper.termHasInvoices(term);
final FlatrateTermBillPartnerRequest request = FlatrateTermBillPartnerRequest.builder()
.flatrateTermId(FlatrateTermId.ofRepoId(term.getC_Flatrate_Term_ID()))
.billBPartnerId(bPartnerId)
.billLocationId(bPartnerLocationId)
.billUserId(bPartnerContactId)
.termHasInvoices(termHasInvoices)
.build();
flatrateBL.updateFlatrateTermBillBPartner(request);
}
protected abstract ImmutableList<I_C_Flatrate_Term> getFlatrateTermsToChange();
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_Change_BillPartner_Base.java
| 1
|
请完成以下Java代码
|
public class ProcessEngineFactoryBean implements FactoryBean<ProcessEngine>, DisposableBean, ApplicationContextAware {
protected ProcessEngineConfigurationImpl processEngineConfiguration;
protected ApplicationContext applicationContext;
protected ProcessEngineImpl processEngine;
public void destroy() throws Exception {
if (processEngine != null) {
processEngine.close();
}
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public ProcessEngine getObject() throws Exception {
if (processEngine == null) {
initializeExpressionManager();
initializeTransactionExternallyManaged();
processEngine = (ProcessEngineImpl) processEngineConfiguration.buildProcessEngine();
}
return processEngine;
}
protected void initializeExpressionManager() {
if (processEngineConfiguration.getExpressionManager() == null && applicationContext != null) {
processEngineConfiguration.setExpressionManager(
new SpringExpressionManager(applicationContext, processEngineConfiguration.getBeans()));
}
}
protected void initializeTransactionExternallyManaged() {
if (processEngineConfiguration instanceof SpringProcessEngineConfiguration) { // remark: any config can be injected, so we cannot have SpringConfiguration as member
SpringProcessEngineConfiguration engineConfiguration = (SpringProcessEngineConfiguration) processEngineConfiguration;
if (engineConfiguration.getTransactionManager() != null) {
processEngineConfiguration.setTransactionsExternallyManaged(true);
}
}
|
}
public Class<ProcessEngine> getObjectType() {
return ProcessEngine.class;
}
public boolean isSingleton() {
return true;
}
// getters and setters //////////////////////////////////////////////////////
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
}
}
|
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\ProcessEngineFactoryBean.java
| 1
|
请完成以下Java代码
|
public final Message toMessage(Object object, MessageProperties messageProperties)
throws MessageConversionException {
return toMessage(object, messageProperties, null);
}
@Override
public final Message toMessage(Object object, @Nullable MessageProperties messagePropertiesArg,
@Nullable Type genericType)
throws MessageConversionException {
MessageProperties messageProperties = messagePropertiesArg;
if (messageProperties == null) {
messageProperties = new MessageProperties();
}
Message message = createMessage(object, messageProperties, genericType);
messageProperties = message.getMessageProperties();
if (this.createMessageIds && messageProperties.getMessageId() == null) {
messageProperties.setMessageId(UUID.randomUUID().toString());
}
return message;
}
/**
* Crate a message from the payload object and message properties provided. The message id will be added to the
* properties if necessary later.
* @param object the payload
|
* @param messageProperties the message properties (headers)
* @param genericType the type to convert from - used to populate type headers.
* @return a message
* @since 2.1
*/
protected Message createMessage(Object object, MessageProperties messageProperties, @Nullable Type genericType) {
return createMessage(object, messageProperties);
}
/**
* Crate a message from the payload object and message properties provided. The message id will be added to the
* properties if necessary later.
* @param object the payload.
* @param messageProperties the message properties (headers).
* @return a message.
*/
protected abstract Message createMessage(Object object, MessageProperties messageProperties);
}
|
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\converter\AbstractMessageConverter.java
| 1
|
请完成以下Java代码
|
public Criteria andReducePriceNotIn(List<BigDecimal> values) {
addCriterion("reduce_price not in", values, "reducePrice");
return (Criteria) this;
}
public Criteria andReducePriceBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("reduce_price between", value1, value2, "reducePrice");
return (Criteria) this;
}
public Criteria andReducePriceNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("reduce_price not between", value1, value2, "reducePrice");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
|
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductFullReductionExample.java
| 1
|
请完成以下Java代码
|
public final class AuthorizationGrantType implements Serializable {
private static final long serialVersionUID = 620L;
public static final AuthorizationGrantType AUTHORIZATION_CODE = new AuthorizationGrantType("authorization_code");
public static final AuthorizationGrantType REFRESH_TOKEN = new AuthorizationGrantType("refresh_token");
public static final AuthorizationGrantType CLIENT_CREDENTIALS = new AuthorizationGrantType("client_credentials");
/**
* @since 5.5
*/
public static final AuthorizationGrantType JWT_BEARER = new AuthorizationGrantType(
"urn:ietf:params:oauth:grant-type:jwt-bearer");
/**
* @since 6.1
*/
public static final AuthorizationGrantType DEVICE_CODE = new AuthorizationGrantType(
"urn:ietf:params:oauth:grant-type:device_code");
/**
* @since 6.3
*/
public static final AuthorizationGrantType TOKEN_EXCHANGE = new AuthorizationGrantType(
"urn:ietf:params:oauth:grant-type:token-exchange");
private final String value;
/**
* Constructs an {@code AuthorizationGrantType} using the provided value.
* @param value the value of the authorization grant type
*/
public AuthorizationGrantType(String value) {
Assert.hasText(value, "value cannot be empty");
this.value = value;
}
/**
* Returns the value of the authorization grant type.
* @return the value of the authorization grant type
*/
public String getValue() {
return this.value;
}
@Override
|
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
AuthorizationGrantType that = (AuthorizationGrantType) obj;
return this.getValue().equals(that.getValue());
}
@Override
public int hashCode() {
return this.getValue().hashCode();
}
@Override
public String toString() {
return "AuthorizationGrantType{" + "value='" + this.value + '\'' + '}';
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\AuthorizationGrantType.java
| 1
|
请完成以下Java代码
|
public void setCostDistributionMethod (final String CostDistributionMethod)
{
set_Value (COLUMNNAME_CostDistributionMethod, CostDistributionMethod);
}
@Override
public String getCostDistributionMethod()
{
return get_ValueAsString(COLUMNNAME_CostDistributionMethod);
}
@Override
public I_C_OrderLine getCreated_OrderLine()
{
return get_ValueAsPO(COLUMNNAME_Created_OrderLine_ID, I_C_OrderLine.class);
}
@Override
public void setCreated_OrderLine(final I_C_OrderLine Created_OrderLine)
{
set_ValueFromPO(COLUMNNAME_Created_OrderLine_ID, I_C_OrderLine.class, Created_OrderLine);
}
@Override
public void setCreated_OrderLine_ID (final int Created_OrderLine_ID)
{
if (Created_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_Created_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Created_OrderLine_ID, Created_OrderLine_ID);
}
@Override
public int getCreated_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_Created_OrderLine_ID);
}
@Override
public void setIsSOTrx (final boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public boolean isSOTrx()
{
return get_ValueAsBoolean(COLUMNNAME_IsSOTrx);
}
@Override
public I_M_CostElement getM_CostElement()
{
|
return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, I_M_CostElement.class);
}
@Override
public void setM_CostElement(final I_M_CostElement M_CostElement)
{
set_ValueFromPO(COLUMNNAME_M_CostElement_ID, I_M_CostElement.class, M_CostElement);
}
@Override
public void setM_CostElement_ID (final int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, M_CostElement_ID);
}
@Override
public int getM_CostElement_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostElement_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_Cost.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class VoidSubscriptionRelatedToOrderHandler implements VoidOrderAndRelatedDocsHandler
{
@Override
public RecordsToHandleKey getRecordsToHandleKey()
{
return RecordsToHandleKey.of(I_C_Flatrate_Term.Table_Name);
}
@Override
public void handleOrderVoided(@NonNull final VoidOrderAndRelatedDocsRequest request)
{
final ContractChangeParameters contractChangeParameters = ContractChangeParameters.builder()
.changeDate(SystemTime.asTimestamp())
.isCloseInvoiceCandidate(true)
.terminationReason(X_C_Flatrate_Term.TERMINATIONREASON_IncorrectlyRecorded)
.isCreditOpenInvoices(false) // leave all existing invoices alone! there is another handler to deal with them, open or not
.action(IContractChangeBL.ChangeTerm_ACTION_VoidSingleContract)
|
.build();
final IPair<RecordsToHandleKey, List<ITableRecordReference>> recordsToHandle = request.getRecordsToHandle();
final IContractChangeBL contractChangeBL = Services.get(IContractChangeBL.class);
for (final ITableRecordReference currentRecordToHandle : recordsToHandle.getRight())
{
// note: that we need to (re)load the flatrate term that we void before their respective successor was voided.
// if we loaded them all at once before voiding their successor,, they still had C_FlatrateTerm_Next_ID > 0
final I_C_Flatrate_Term currentTerm = currentRecordToHandle.getModel(I_C_Flatrate_Term.class);
contractChangeBL.cancelContract(currentTerm, contractChangeParameters);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\order\restart\VoidSubscriptionRelatedToOrderHandler.java
| 2
|
请完成以下Java代码
|
public class InvoicePaidInspector implements IRecordInspector
{
public static InvoicePaidInspector INSTANCE = new InvoicePaidInspector();
private InvoicePaidInspector()
{
}
@Override
public int inspectRecord(Object model)
{
final I_C_Invoice invoice = InterfaceWrapperHelper.create(model, I_C_Invoice.class);
if (!invoice.isProcessed())
{
return IMigratorService.DLM_Level_LIVE;
}
if (!invoice.isPaid())
|
{
return IMigratorService.DLM_Level_LIVE;
}
return IMigratorService.DLM_Level_ARCHIVE;
}
/**
* Returns <code>true</code> if the given model has an <code>Updated</code> column.
*/
@Override
public boolean isApplicableFor(Object model)
{
return I_C_Invoice.Table_Name.equals(InterfaceWrapperHelper.getModelTableName(model));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\dlm\InvoicePaidInspector.java
| 1
|
请完成以下Java代码
|
public void handleHttpRequest(VariableContainer execution, HttpRequest httpRequest, FlowableHttpClient client) {
HttpRequestHandler httpRequestHandler = getHttpRequestHandlerInstance();
CommandContextUtil.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(new HttpRequestHandlerInvocation(httpRequestHandler, execution, httpRequest, client));
}
@Override
public void handleHttpResponse(VariableContainer execution, HttpResponse httpResponse) {
HttpResponseHandler httpResponseHandler = getHttpResponseHandlerInstance();
CommandContextUtil.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(new HttpResponseHandlerInvocation(httpResponseHandler, execution, httpResponse));
}
protected HttpRequestHandler getHttpRequestHandlerInstance() {
Object delegateInstance = instantiateDelegate(className, fieldDeclarations);
if (delegateInstance instanceof HttpRequestHandler) {
return (HttpRequestHandler) delegateInstance;
|
} else {
throw new FlowableIllegalArgumentException(delegateInstance.getClass().getName() + " doesn't implement " + HttpRequestHandler.class);
}
}
protected HttpResponseHandler getHttpResponseHandlerInstance() {
Object delegateInstance = instantiateDelegate(className, fieldDeclarations);
if (delegateInstance instanceof HttpResponseHandler) {
return (HttpResponseHandler) delegateInstance;
} else {
throw new FlowableIllegalArgumentException(delegateInstance.getClass().getName() + " doesn't implement " + HttpResponseHandler.class);
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\http\handler\ClassDelegateHttpHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setInvoiceReference(DocumentReferenceType value) {
this.invoiceReference = value;
}
/**
* Gets the value of the stockEntryReference property.
*
* @return
* possible object is
* {@link DocumentReferenceType }
*
*/
public DocumentReferenceType getStockEntryReference() {
return stockEntryReference;
}
/**
* Sets the value of the stockEntryReference property.
*
* @param value
* allowed object is
* {@link DocumentReferenceType }
*
*/
public void setStockEntryReference(DocumentReferenceType value) {
this.stockEntryReference = value;
}
/**
* Gets the value of the additionalReferences property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the additionalReferences property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAdditionalReferences().add(newItem);
* </pre>
*
|
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DocumentReferenceType }
*
*
*/
public List<DocumentReferenceType> getAdditionalReferences() {
if (additionalReferences == null) {
additionalReferences = new ArrayList<DocumentReferenceType>();
}
return this.additionalReferences;
}
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\INVRPTListLineItemExtensionType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public static class Exposure {
/**
* Endpoint IDs that should be included or '*' for all.
*/
private Set<String> include = new LinkedHashSet<>();
/**
* Endpoint IDs that should be excluded or '*' for all.
*/
private Set<String> exclude = new LinkedHashSet<>();
public Set<String> getInclude() {
return this.include;
}
|
public void setInclude(Set<String> include) {
this.include = include;
}
public Set<String> getExclude() {
return this.exclude;
}
public void setExclude(Set<String> exclude) {
this.exclude = exclude;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\jmx\JmxEndpointProperties.java
| 2
|
请完成以下Java代码
|
protected Date getOrCalculateRemovalTime(SetRemovalTimeBatchConfiguration batchConfiguration, HistoricBatchEntity instance, CommandContext commandContext) {
if (batchConfiguration.hasRemovalTime()) {
return batchConfiguration.getRemovalTime();
} else if (hasBaseTime(instance, commandContext)) {
return calculateRemovalTime(instance, commandContext);
} else {
return null;
}
}
protected void addRemovalTime(String instanceId, Date removalTime, CommandContext commandContext) {
commandContext.getHistoricBatchManager()
.addRemovalTimeById(instanceId, removalTime);
}
protected boolean hasBaseTime(HistoricBatchEntity instance, CommandContext commandContext) {
return isStrategyStart(commandContext) || (isStrategyEnd(commandContext) && isEnded(instance));
}
protected boolean isEnded(HistoricBatchEntity instance) {
return instance.getEndTime() != null;
}
protected boolean isStrategyStart(CommandContext commandContext) {
return HISTORY_REMOVAL_TIME_STRATEGY_START.equals(getHistoryRemovalTimeStrategy(commandContext));
}
protected boolean isStrategyEnd(CommandContext commandContext) {
return HISTORY_REMOVAL_TIME_STRATEGY_END.equals(getHistoryRemovalTimeStrategy(commandContext));
}
protected String getHistoryRemovalTimeStrategy(CommandContext commandContext) {
return commandContext.getProcessEngineConfiguration()
.getHistoryRemovalTimeStrategy();
}
protected boolean isDmnEnabled(CommandContext commandContext) {
return commandContext.getProcessEngineConfiguration().isDmnEnabled();
}
protected Date calculateRemovalTime(HistoricBatchEntity batch, CommandContext commandContext) {
return commandContext.getProcessEngineConfiguration()
.getHistoryRemovalTimeProvider()
.calculateRemovalTime(batch);
}
protected ByteArrayEntity findByteArrayById(String byteArrayId, CommandContext commandContext) {
return commandContext.getDbEntityManager()
|
.selectById(ByteArrayEntity.class, byteArrayId);
}
protected HistoricBatchEntity findBatchById(String instanceId, CommandContext commandContext) {
return commandContext.getHistoricBatchManager()
.findHistoricBatchById(instanceId);
}
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() {
return JOB_DECLARATION;
}
protected SetRemovalTimeBatchConfiguration createJobConfiguration(SetRemovalTimeBatchConfiguration configuration, List<String> batchIds) {
return new SetRemovalTimeBatchConfiguration(batchIds)
.setRemovalTime(configuration.getRemovalTime())
.setHasRemovalTime(configuration.hasRemovalTime());
}
protected SetRemovalTimeJsonConverter getJsonConverterInstance() {
return SetRemovalTimeJsonConverter.INSTANCE;
}
public String getType() {
return Batch.TYPE_BATCH_SET_REMOVAL_TIME;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\removaltime\BatchSetRemovalTimeJobHandler.java
| 1
|
请完成以下Java代码
|
void rewriteLocation(ServerWebExchange exchange, Config config) {
final String location = exchange.getResponse().getHeaders().getFirst(config.getLocationHeaderName());
final String host = config.getHostValue() != null ? config.getHostValue()
: exchange.getRequest().getHeaders().getFirst(HttpHeaders.HOST);
final String path = exchange.getRequest().getURI().getPath();
if (location != null && host != null) {
final String fixedLocation = fixedLocation(location, host, path, config.getStripVersion(),
config.getHostPortPattern(), config.getHostPortVersionPattern());
exchange.getResponse().getHeaders().set(config.getLocationHeaderName(), fixedLocation);
}
}
String fixedLocation(String location, String host, String path, StripVersion stripVersion, Pattern hostPortPattern,
Pattern hostPortVersionPattern) {
final boolean doStrip = StripVersion.ALWAYS_STRIP.equals(stripVersion)
|| (StripVersion.AS_IN_REQUEST.equals(stripVersion) && !VERSIONED_PATH.matcher(path).matches());
final Pattern pattern = doStrip ? hostPortVersionPattern : hostPortPattern;
return pattern.matcher(location).replaceFirst(host);
}
public enum StripVersion {
/**
* Version will not be stripped, even if the original request path contains no
* version.
*/
NEVER_STRIP,
/**
* Version will be stripped only if the original request path contains no version.
* This is the Default.
*/
AS_IN_REQUEST,
/**
* Version will be stripped, even if the original request path contains version.
*/
ALWAYS_STRIP
}
public static class Config {
private StripVersion stripVersion = StripVersion.AS_IN_REQUEST;
private String locationHeaderName = HttpHeaders.LOCATION;
private @Nullable String hostValue;
private String protocols = DEFAULT_PROTOCOLS;
private Pattern hostPortPattern = DEFAULT_HOST_PORT;
private Pattern hostPortVersionPattern = DEFAULT_HOST_PORT_VERSION;
public StripVersion getStripVersion() {
return stripVersion;
}
public Config setStripVersion(StripVersion stripVersion) {
|
this.stripVersion = stripVersion;
return this;
}
public String getLocationHeaderName() {
return locationHeaderName;
}
public Config setLocationHeaderName(String locationHeaderName) {
this.locationHeaderName = locationHeaderName;
return this;
}
public @Nullable String getHostValue() {
return hostValue;
}
public Config setHostValue(String hostValue) {
this.hostValue = hostValue;
return this;
}
public String getProtocols() {
return protocols;
}
public Config setProtocols(String protocols) {
this.protocols = protocols;
this.hostPortPattern = compileHostPortPattern(protocols);
this.hostPortVersionPattern = compileHostPortVersionPattern(protocols);
return this;
}
public Pattern getHostPortPattern() {
return hostPortPattern;
}
public Pattern getHostPortVersionPattern() {
return hostPortVersionPattern;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RewriteLocationResponseHeaderGatewayFilterFactory.java
| 1
|
请完成以下Java代码
|
public boolean isToleranceExceeded()
{
return get_ValueAsBoolean(COLUMNNAME_IsToleranceExceeded);
}
@Override
public void setLine (final int Line)
{
set_Value (COLUMNNAME_Line, Line);
}
@Override
public int getLine()
{
return get_ValueAsInt(COLUMNNAME_Line);
}
@Override
public void setPP_Order_Weighting_RunCheck_ID (final int PP_Order_Weighting_RunCheck_ID)
{
if (PP_Order_Weighting_RunCheck_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_RunCheck_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_RunCheck_ID, PP_Order_Weighting_RunCheck_ID);
}
@Override
public int getPP_Order_Weighting_RunCheck_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Weighting_RunCheck_ID);
}
@Override
public org.eevolution.model.I_PP_Order_Weighting_Run getPP_Order_Weighting_Run()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_Weighting_Run_ID, org.eevolution.model.I_PP_Order_Weighting_Run.class);
}
@Override
public void setPP_Order_Weighting_Run(final org.eevolution.model.I_PP_Order_Weighting_Run PP_Order_Weighting_Run)
{
set_ValueFromPO(COLUMNNAME_PP_Order_Weighting_Run_ID, org.eevolution.model.I_PP_Order_Weighting_Run.class, PP_Order_Weighting_Run);
}
@Override
public void setPP_Order_Weighting_Run_ID (final int PP_Order_Weighting_Run_ID)
{
if (PP_Order_Weighting_Run_ID < 1)
|
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_Run_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_Run_ID, PP_Order_Weighting_Run_ID);
}
@Override
public int getPP_Order_Weighting_Run_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Weighting_Run_ID);
}
@Override
public void setWeight (final BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Weighting_RunCheck.java
| 1
|
请完成以下Java代码
|
class AdWindowIdSelection implements Iterable<AdWindowId>
{
private static final ImmutableSet<AdWindowId> SKIP_WINDOW_IDS = ImmutableSet.of(
AdWindowId.ofRepoId(540371), // Picking Tray Clearing - placeholder window
AdWindowId.ofRepoId(540674), // Shipment Schedule Editor - placeholder window
AdWindowId.ofRepoId(540759), // Payment Allocation - placeholder window
AdWindowId.ofRepoId(540485) // Picking Terminal (v2) - placeholder window
);
@NonNull private final ImmutableSet<AdWindowId> allAdWidowIds;
//@NonNull private final ImmutableSet<AdWindowId> onlyAdWindowIds;
@NonNull private final ImmutableSet<AdWindowId> selectedWindowIds;
@Builder
private AdWindowIdSelection(
@NonNull final ImmutableSet<AdWindowId> allAdWidowIds,
@NonNull final ImmutableSet<AdWindowId> onlyAdWindowIds)
{
this.allAdWidowIds = allAdWidowIds;
//this.onlyAdWindowIds = onlyAdWindowIds;
final LinkedHashSet<AdWindowId> selectedWindowIds = new LinkedHashSet<>(onlyAdWindowIds.isEmpty() ? allAdWidowIds : onlyAdWindowIds);
selectedWindowIds.removeAll(SKIP_WINDOW_IDS);
this.selectedWindowIds = ImmutableSet.copyOf(selectedWindowIds);
}
public int size()
{
return selectedWindowIds.size();
}
@Override
|
public @NotNull Iterator<AdWindowId> iterator()
{
return selectedWindowIds.iterator();
}
public boolean contains(@NonNull final AdWindowId adWindowId)
{
return selectedWindowIds.contains(adWindowId);
}
public boolean contains(final ContextPath path)
{
return contains(path.getAdWindowId());
}
public boolean isExistingActiveWindow(@NonNull final AdWindowId adWindowId)
{
return allAdWidowIds.contains(adWindowId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\AdWindowIdSelection.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WebSecurityConfig {
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers("/js/**", "/css/**");
}
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(request -> request.requestMatchers("/")
.permitAll()
.anyRequest()
.authenticated())
|
.formLogin(form -> form.defaultSuccessUrl("/welcome"))
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("User")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-core-2\src\main\java\com\baeldung\springsecuritymigration\configuration\WebSecurityConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class PricingSystemId implements RepoIdAware
{
@JsonCreator
public static PricingSystemId ofRepoId(final int repoId)
{
if (repoId == NONE.repoId)
{
return NONE;
}
return new PricingSystemId(repoId);
}
@Nullable
public static PricingSystemId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static final PricingSystemId NULL = null;
public static final PricingSystemId NONE = new PricingSystemId(100);
int repoId;
private PricingSystemId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "repoId");
}
|
public boolean isNone()
{
return repoId == NONE.repoId;
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static int toRepoId(@Nullable final PricingSystemId id)
{
return id != null ? id.getRepoId() : -1;
}
public static boolean equals(@Nullable final PricingSystemId o1, @Nullable final PricingSystemId o2)
{
return Objects.equals(o1, o2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\pricing\PricingSystemId.java
| 2
|
请完成以下Java代码
|
private boolean initDesktopWorkbenches()
{
String sql = "SELECT AD_Workbench_ID "
+ "FROM AD_DesktopWorkbench "
+ "WHERE AD_Desktop_ID=? AND IsActive='Y' "
+ "ORDER BY SeqNo";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_Desktop_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
int AD_Workbench_ID = rs.getInt(1);
m_workbenches.add (new Integer(AD_Workbench_ID));
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.error("MWorkbench.initDesktopWorkbenches", e);
return false;
}
return true;
} // initDesktopWorkbenches
/**
* Get Window Count
* @return no of windows
*/
public int getWindowCount()
{
return m_workbenches.size();
} // getWindowCount
|
/**
* Get AD_Workbench_ID of index
* @param index index
* @return -1 if not valid
*/
public int getAD_Workbench_ID (int index)
{
if (index < 0 || index > m_workbenches.size())
return -1;
Integer id = (Integer)m_workbenches.get(index);
return id.intValue();
} // getAD_Workbench_ID
} // MDesktop
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MDesktop.java
| 1
|
请完成以下Java代码
|
public class GitInfoContributor extends InfoPropertiesInfoContributor<GitProperties> {
public GitInfoContributor(GitProperties properties) {
this(properties, Mode.SIMPLE);
}
public GitInfoContributor(GitProperties properties, Mode mode) {
super(properties, mode);
}
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("git", generateContent());
}
@Override
protected PropertySource<?> toSimplePropertySource() {
Properties props = new Properties();
copyIfSet(props, "branch");
String commitId = getProperties().getShortCommitId();
if (commitId != null) {
props.put("commit.id", commitId);
}
copyIfSet(props, "commit.time");
return new PropertiesPropertySource("git", props);
}
/**
* Post-process the content to expose. By default, well known keys representing dates
* are converted to {@link Instant} instances.
* @param content the content to expose
*/
|
@Override
protected void postProcessContent(Map<String, Object> content) {
replaceValue(getNestedMap(content, "commit"), "time", getProperties().getCommitTime());
replaceValue(getNestedMap(content, "build"), "time", getProperties().getInstant("build.time"));
}
static class GitInfoContributorRuntimeHints implements RuntimeHintsRegistrar {
private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
this.bindingRegistrar.registerReflectionHints(hints.reflection(), GitProperties.class);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\info\GitInfoContributor.java
| 1
|
请完成以下Java代码
|
public I_C_UOM getC_UOM()
{
return uom;
}
@Override
public BigDecimal getQtyFree()
{
final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
final Capacity capacityAvailable = capacityTotal.subtractQuantity(getQty(), uomConversionBL);
if (capacityAvailable.isInfiniteCapacity())
{
return Quantity.QTY_INFINITE;
}
return capacityAvailable.toBigDecimal();
}
@Override
public Quantity getQty()
{
return huStorage.getQuantity(getProductId(), getC_UOM());
}
@Override
public final Quantity getQty(final I_C_UOM uom)
{
final UOMConversionContext conversionCtx = UOMConversionContext.of(getProductId());
final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
return uomConversionBL.convertQuantityTo(getQty(), conversionCtx, uom);
}
@Override
public final Quantity getQtyInStockingUOM()
{
final I_C_UOM productUOM = Services.get(IProductBL.class).getStockUOM(getProductId());
return getQty(productUOM);
}
@Override
public BigDecimal getQtyCapacity()
{
return capacityTotal.toBigDecimal();
}
@Override
public IAllocationRequest addQty(final IAllocationRequest request)
|
{
throw new AdempiereException("Adding Qty is not supported on this level");
}
@Override
public IAllocationRequest removeQty(final IAllocationRequest request)
{
throw new AdempiereException("Removing Qty is not supported on this level");
}
/**
* Returns always false because negative storages are not supported (see {@link #removeQty(IAllocationRequest)})
*
* @return false
*/
@Override
public boolean isAllowNegativeStorage()
{
return false;
}
@Override
public void markStaled()
{
// nothing, so far, itemStorage is always database coupled, no in memory values
}
@Override
public boolean isEmpty()
{
return huStorage.isEmpty(getProductId());
}
@Override
public I_M_HU getM_HU()
{
return huStorage.getM_HU();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUProductStorage.java
| 1
|
请完成以下Java代码
|
public UpdateJobDefinitionSuspensionStateBuilderImpl processDefinitionWithoutTenantId() {
this.processDefinitionTenantId = null;
this.isProcessDefinitionTenantIdSet = true;
return this;
}
@Override
public UpdateJobDefinitionSuspensionStateBuilderImpl processDefinitionTenantId(String tenantId) {
ensureNotNull("tenantId", tenantId);
this.processDefinitionTenantId = tenantId;
this.isProcessDefinitionTenantIdSet = true;
return this;
}
@Override
public UpdateJobDefinitionSuspensionStateBuilderImpl includeJobs(boolean includeJobs) {
this.includeJobs = includeJobs;
return this;
}
@Override
public UpdateJobDefinitionSuspensionStateBuilderImpl executionDate(Date executionDate) {
this.executionDate = executionDate;
return this;
}
@Override
public void activate() {
validateParameters();
ActivateJobDefinitionCmd command = new ActivateJobDefinitionCmd(this);
commandExecutor.execute(command);
}
@Override
public void suspend() {
validateParameters();
SuspendJobDefinitionCmd command = new SuspendJobDefinitionCmd(this);
commandExecutor.execute(command);
}
protected void validateParameters() {
ensureOnlyOneNotNull("Need to specify either a job definition id, a process definition id or a process definition key.",
jobDefinitionId, processDefinitionId, processDefinitionKey);
if (isProcessDefinitionTenantIdSet && (jobDefinitionId != null || processDefinitionId != null)) {
throw LOG.exceptionUpdateSuspensionStateForTenantOnlyByProcessDefinitionKey();
}
ensureNotNull("commandExecutor", commandExecutor);
}
|
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionTenantId() {
return processDefinitionTenantId;
}
public boolean isProcessDefinitionTenantIdSet() {
return isProcessDefinitionTenantIdSet;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public boolean isIncludeJobs() {
return includeJobs;
}
public Date getExecutionDate() {
return executionDate;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\management\UpdateJobDefinitionSuspensionStateBuilderImpl.java
| 1
|
请完成以下Java代码
|
private Document convertObjectToDocument(final Object xmlObj)
{
try
{
return convertObjectToDocument0(xmlObj);
}
catch (final Exception e)
{
throw new AdempiereException("Error while converting object '" + xmlObj + "' to XML document", e);
}
}
private Document convertObjectToDocument0(final Object xmlObj) throws JAXBException, ParserConfigurationException, SAXException, IOException
{
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setValidating(false);
final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
final Document document = documentBuilder.newDocument();
final JAXBElement<Object> jaxbElement = ObjectFactoryHelper.createJAXBElement(new ObjectFactory(), xmlObj);
jaxbMarshaller.marshal(jaxbElement, document);
|
return document;
}
private String createTransactionId()
{
final String transactionId = UUID.randomUUID().toString();
return transactionId;
}
@Override
public LoginResponse login(final LoginRequest loginRequest)
{
throw new UnsupportedOperationException();
// final PRTLoginRequestType xmlLoginRequest = LoginRequestConverter.instance.convert(loginRequest);
// final PRTLoginRequestType xmlLoginResponse = sendXmlObject(xmlLoginRequest);
// final LoginResponse loginResponse = LoginResponseConverter.instance.convert(xmlLoginResponse);
// return loginResponse;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.embedded-client\src\main\java\de\metas\printing\client\endpoint\LoopbackPrintConnectionEndpoint.java
| 1
|
请完成以下Java代码
|
public static FieldExtension getListenerField(DelegatePlanItemInstance planItemInstance, String fieldName) {
List<FieldExtension> fieldExtensions = getListenerFields(planItemInstance);
if (fieldExtensions == null || fieldExtensions.size() == 0) {
return null;
}
for (FieldExtension fieldExtension : fieldExtensions) {
if (fieldExtension.getFieldName() != null && fieldExtension.getFieldName().equals(fieldName)) {
return fieldExtension;
}
}
return null;
}
public static Expression createExpressionForField(FieldExtension fieldExtension) {
if (StringUtils.isNotEmpty(fieldExtension.getExpression())) {
ExpressionManager expressionManager = CommandContextUtil.getCmmnEngineConfiguration().getExpressionManager();
return expressionManager.createExpression(fieldExtension.getExpression());
} else {
return new FixedValue(fieldExtension.getStringValue());
}
}
public static Expression getFieldExpression(DelegatePlanItemInstance planItemInstance, String fieldName) {
if (isExecutingLifecycleListener(planItemInstance)) {
|
return getListenerFieldExpression(planItemInstance, fieldName);
} else {
return getCmmnElementFieldExpression(planItemInstance, fieldName);
}
}
public static Expression getCmmnElementFieldExpression(DelegatePlanItemInstance planItemInstance, String fieldName) {
FieldExtension fieldExtension = getCmmnElementField(planItemInstance, fieldName);
if (fieldExtension != null) {
return createExpressionForField(fieldExtension);
}
return null;
}
public static Expression getListenerFieldExpression(DelegatePlanItemInstance planItemInstance, String fieldName) {
FieldExtension fieldExtension = getListenerField(planItemInstance, fieldName);
if (fieldExtension != null) {
return createExpressionForField(fieldExtension);
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\CmmnDelegateHelper.java
| 1
|
请完成以下Java代码
|
public class PropertiesHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler {
@Override
public boolean supportsReturnType(MethodParameter returnType) {
return Properties.class.equals(returnType.getMethod().getReturnType());
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
Properties properties = (Properties) returnValue;
ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
HttpServletResponse response = servletWebRequest.getResponse();
ServletServerHttpResponse servletServerHttpResponse = new ServletServerHttpResponse(response);
// 获取请求头
HttpHeaders headers = servletServerHttpResponse.getHeaders();
MediaType contentType = headers.getContentType();
// 获取编码
Charset charset = null;
if (contentType != null) {
|
charset = contentType.getCharset();
}
charset = charset == null ? Charset.forName("UTF-8") : charset;
// 获取请求体
OutputStream body = servletServerHttpResponse.getBody();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(body, charset);
properties.store(outputStreamWriter, "Serialized by PropertiesHandlerMethodReturnValueHandler#handleReturnValue");
// 告诉 Spring MVC 请求已经处理完毕
mavContainer.setRequestHandled(true);
}
}
|
repos\SpringAll-master\47.Spring-Boot-Content-Negotiation\src\main\java\com\example\demo\handler\PropertiesHandlerMethodReturnValueHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<DocumentReferenceType> getDocumentReference() {
if (documentReference == null) {
documentReference = new ArrayList<DocumentReferenceType>();
}
return this.documentReference;
}
/**
* Deprecated. Please supply the phone number in Contact/Phone
*
* @return
* possible object is
* {@link String }
*
*/
public String getPhone() {
return phone;
}
/**
* Sets the value of the phone property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPhone(String value) {
this.phone = value;
}
/**
* Deprecated. Please supply the email address in Contact/Email.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEmail() {
return email;
}
/**
* Sets the value of the email property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEmail(String value) {
this.email = value;
}
/**
* Global Location Number of the party.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGLN() {
return gln;
}
/**
* Sets the value of the gln property.
*
* @param value
* allowed object is
* {@link String }
|
*
*/
public void setGLN(String value) {
this.gln = value;
}
/**
* Further contact details.
*
* @return
* possible object is
* {@link ContactType }
*
*/
public ContactType getContact() {
return contact;
}
/**
* Sets the value of the contact property.
*
* @param value
* allowed object is
* {@link ContactType }
*
*/
public void setContact(ContactType value) {
this.contact = value;
}
/**
* Address details of the party.
*
* @return
* possible object is
* {@link AddressType }
*
*/
public AddressType getAddress() {
return address;
}
/**
* Sets the value of the address property.
*
* @param value
* allowed object is
* {@link AddressType }
*
*/
public void setAddress(AddressType value) {
this.address = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\BusinessEntityType.java
| 2
|
请完成以下Java代码
|
public void setVolume (final @Nullable BigDecimal Volume)
{
set_Value (COLUMNNAME_Volume, Volume);
}
@Override
public BigDecimal getVolume()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Volume);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public org.compiere.model.I_C_Location getWarehouse_Location()
{
return get_ValueAsPO(COLUMNNAME_Warehouse_Location_ID, org.compiere.model.I_C_Location.class);
}
@Override
public void setWarehouse_Location(final org.compiere.model.I_C_Location Warehouse_Location)
{
set_ValueFromPO(COLUMNNAME_Warehouse_Location_ID, org.compiere.model.I_C_Location.class, Warehouse_Location);
}
@Override
public void setWarehouse_Location_ID (final int Warehouse_Location_ID)
{
if (Warehouse_Location_ID < 1)
|
set_Value (COLUMNNAME_Warehouse_Location_ID, null);
else
set_Value (COLUMNNAME_Warehouse_Location_ID, Warehouse_Location_ID);
}
@Override
public int getWarehouse_Location_ID()
{
return get_ValueAsInt(COLUMNNAME_Warehouse_Location_ID);
}
@Override
public void setWeight (final @Nullable BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_Order_Header_v.java
| 1
|
请完成以下Java代码
|
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected EventSubscriptionQuery createNewQuery(ProcessEngine engine) {
return engine.getRuntimeService().createEventSubscriptionQuery();
}
@Override
protected void applyFilters(EventSubscriptionQuery query) {
if (eventSubscriptionId != null) {
query.eventSubscriptionId(eventSubscriptionId);
}
if (eventName != null) {
query.eventName(eventName);
}
if (eventType != null) {
query.eventType(eventType);
}
if (executionId != null) {
query.executionId(executionId);
}
if (processInstanceId != null) {
query.processInstanceId(processInstanceId);
}
if (activityId != null) {
query.activityId(activityId);
}
if (tenantIdIn != null && !tenantIdIn.isEmpty()) {
query.tenantIdIn(tenantIdIn.toArray(new String[tenantIdIn.size()]));
}
|
if (TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (TRUE.equals(includeEventSubscriptionsWithoutTenantId)) {
query.includeEventSubscriptionsWithoutTenantId();
}
}
@Override
protected void applySortBy(EventSubscriptionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_CREATED)) {
query.orderByCreated();
} else if (sortBy.equals(SORT_BY_TENANT_ID)) {
query.orderByTenantId();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\EventSubscriptionQueryDto.java
| 1
|
请完成以下Java代码
|
public void alphanumericIteration(Blackhole blackhole) {
boolean result = true;
for (int i = 0; i < TEST_STRING.length(); ++i) {
final int codePoint = TEST_STRING.codePointAt(i);
if (!isAlphanumeric(codePoint)) {
result = false;
break;
}
}
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIterationWithCharacterChecks(Blackhole blackhole) {
boolean result = true;
for (int i = 0; i < TEST_STRING.length(); ++i) {
final int codePoint = TEST_STRING.codePointAt(i);
if (!Character.isAlphabetic(codePoint) || !Character.isDigit(codePoint)) {
result = false;
break;
}
}
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIterationWithCopy(Blackhole blackhole) {
boolean result = true;
|
for (final char c : TEST_STRING.toCharArray()) {
if (!isAlphanumeric(c)) {
result = false;
break;
}
}
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIterationWithStream(Blackhole blackhole) {
boolean result = TEST_STRING.chars().allMatch(this::isAlphanumeric);
blackhole.consume(result);
}
public boolean isAlphanumeric(final int codePoint) {
return (codePoint >= 65 && codePoint <= 90) ||
(codePoint >= 97 && codePoint <= 122) ||
(codePoint >= 48 && codePoint <= 57);
}
}
|
repos\tutorials-master\core-java-modules\core-java-regex\src\main\java\com\baeldung\alphanumeric\AlphanumericPerformanceBenchmark.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@ApiModelProperty(example = "http://localhost:8182/repository/models/5")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "2013-06-12T12:31:19.861+0000")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@ApiModelProperty(example = "2013-06-12T12:31:19.861+0000")
public Date getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
@ApiModelProperty(example = "http://localhost:8182/repository/deployments/2")
|
public String getDeploymentUrl() {
return deploymentUrl;
}
public void setDeploymentUrl(String deploymentUrl) {
this.deploymentUrl = deploymentUrl;
}
@ApiModelProperty(example = "null")
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getSourceUrl() {
return sourceUrl;
}
public void setSourceUrl(String sourceUrl) {
this.sourceUrl = sourceUrl;
}
public String getSourceExtraUrl() {
return sourceExtraUrl;
}
public void setSourceExtraUrl(String sourceExtraUrl) {
this.sourceExtraUrl = sourceExtraUrl;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ModelResponse.java
| 2
|
请完成以下Java代码
|
public Result enqueueSelection(@NonNull final EnqueuePPOrderCandidateRequest request)
{
final PInstanceId adPInstanceId = request.getAdPInstanceId();
final LockOwner lockOwner = LockOwner.newOwner(PPOrderCandidateEnqueuer.class.getSimpleName(), adPInstanceId.getRepoId());
final ILockCommand elementsLocker = lockManager
.lock()
.setOwner(lockOwner)
.setAutoCleanup(false)
.setFailIfAlreadyLocked(true)
.setRecordsBySelection(I_PP_Order_Candidate.class, adPInstanceId);
final IWorkPackageQueue queue = workPackageQueueFactory.getQueueForEnqueuing(request.getCtx(), GeneratePPOrderFromPPOrderCandidate.class);
final I_C_Queue_WorkPackage workPackage = queue
.newWorkPackage()
.parameter(WP_PINSTANCE_ID_PARAM, adPInstanceId)
.parameter(WP_COMPLETE_DOC_PARAM, request.getIsCompleteDocOverride())
.parameter(WP_AUTO_PROCESS_CANDIDATES_AFTER_PRODUCTION, request.isAutoProcessCandidatesAfterProduction())
.parameter(WP_AUTO_CLOSE_CANDIDATES_AFTER_PRODUCTION, request.isAutoCloseCandidatesAfterProduction())
.setElementsLocker(elementsLocker)
.buildAndEnqueue();
final Result result = new Result();
result.addEnqueuedWorkPackageId(QueueWorkPackageId.ofRepoId(workPackage.getC_Queue_WorkPackage_ID()));
return result;
}
|
public static class Result
{
private final List<QueueWorkPackageId> enqueuedWorkpackageIds = new ArrayList<>();
public int getEnqueuedPackagesCount()
{
return enqueuedWorkpackageIds.size();
}
public ImmutableList<QueueWorkPackageId> getEnqueuedPackageIds()
{
return ImmutableList.copyOf(enqueuedWorkpackageIds);
}
private void addEnqueuedWorkPackageId(@NonNull final QueueWorkPackageId workPackageId)
{
enqueuedWorkpackageIds.add(workPackageId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\async\PPOrderCandidateEnqueuer.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
public String getSubject() {
return subject;
}
public String getTeacher() {
return teacher;
}
public String getStudentGroup() {
return studentGroup;
}
|
public Timeslot getTimeslot() {
return timeslot;
}
public void setTimeslot(Timeslot timeslot) {
this.timeslot = timeslot;
}
public Room getRoom() {
return room;
}
public void setRoom(Room room) {
this.room = room;
}
}
|
repos\springboot-demo-master\Timefold Solver\src\main\java\org\acme\schooltimetabling\domain\Lesson.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SeparateFlowsExample {
@MessagingGateway
public interface NumbersClassifier {
@Gateway(requestChannel = "multipleOfThreeFlow.input")
void multipleofThree(Collection<Integer> numbers);
@Gateway(requestChannel = "remainderIsOneFlow.input")
void remainderIsOne(Collection<Integer> numbers);
@Gateway(requestChannel = "remainderIsTwoFlow.input")
void remainderIsTwo(Collection<Integer> numbers);
}
@Bean
QueueChannel multipleOfThreeChannel() {
return new QueueChannel();
}
@Bean
QueueChannel remainderIsOneChannel() {
return new QueueChannel();
}
@Bean
QueueChannel remainderIsTwoChannel() {
return new QueueChannel();
}
boolean isMultipleOfThree(Integer number) {
return number % 3 == 0;
}
boolean isRemainderOne(Integer number) {
return number % 3 == 1;
|
}
boolean isRemainderTwo(Integer number) {
return number % 3 == 2;
}
@Bean
public IntegrationFlow multipleOfThreeFlow() {
return flow -> flow.split()
.<Integer> filter(this::isMultipleOfThree)
.channel("multipleOfThreeChannel");
}
@Bean
public IntegrationFlow remainderIsOneFlow() {
return flow -> flow.split()
.<Integer> filter(this::isRemainderOne)
.channel("remainderIsOneChannel");
}
@Bean
public IntegrationFlow remainderIsTwoFlow() {
return flow -> flow.split()
.<Integer> filter(this::isRemainderTwo)
.channel("remainderIsTwoChannel");
}
}
|
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\subflows\separateflows\SeparateFlowsExample.java
| 2
|
请完成以下Java代码
|
public static BigDecimal roundToBigDecimal(@NonNull final BigDecimal argToRound, @NonNull final BigDecimal roundingArg)
{
BigDecimal actualRoundingArg = roundingArg;
BigDecimal actualArgToRound = argToRound;
BigDecimal decimalAdjustments = BigDecimal.ONE;
if (roundingArg.scale() > 0 || argToRound.scale() > 0)
{
final int scaleToConsider = Integer.max(roundingArg.scale(), argToRound.scale());
decimalAdjustments = new BigDecimal(String.valueOf(Math.pow(10, scaleToConsider)));
actualRoundingArg = roundingArg.multiply(decimalAdjustments);
actualArgToRound = argToRound.multiply(decimalAdjustments);
}
return actualArgToRound
.divide(actualRoundingArg, 0, RoundingMode.HALF_UP)
.multiply(actualRoundingArg)
.divide(decimalAdjustments, argToRound.scale(), RoundingMode.HALF_UP);
}
@Nullable
private static BigDecimal asBigDecimal(
@Nullable final Object value,
@Nullable final BigDecimal defaultValue,
final boolean failIfUnparsable)
{
if (value == null) //note that a zero-BigDecimal is also "empty" according to Check.IsEmpty()!
{
return defaultValue;
}
if (value instanceof BigDecimal)
{
return (BigDecimal)value;
}
else if (value instanceof Integer)
{
return BigDecimal.valueOf((int)value);
}
else if (value instanceof Long)
{
return BigDecimal.valueOf((long)value);
}
else
{
final String valueStr = value.toString();
if (Check.isBlank(valueStr))
{
return defaultValue;
}
try
{
return new BigDecimal(valueStr.trim());
}
catch (final NumberFormatException numberFormatException)
{
final String errorMsg = "Cannot convert `" + value + "` (" + value.getClass() + ") to BigDecimal";
if (failIfUnparsable)
{
final RuntimeException ex = Check.mkEx(errorMsg);
ex.initCause(numberFormatException);
throw ex;
}
else
{
System.err.println(errorMsg + ". Returning defaultValue=" + defaultValue);
numberFormatException.printStackTrace();
return defaultValue;
}
|
}
}
}
@Nullable
public static BigDecimal sumNullSafe(@Nullable final BigDecimal ag1, @Nullable final BigDecimal ag2)
{
if (ag1 == null && ag2 == null)
{
return null;
}
else if (ag1 == null)
{
return ag2;
}
else if (ag2 == null)
{
return ag1;
}
else
{
return ag1.add(ag2);
}
}
public static boolean isInteger(@NonNull final BigDecimal bd)
{
return bd.stripTrailingZeros().scale() <= 0;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\NumberUtils.java
| 1
|
请完成以下Java代码
|
public Long sumDataSizeByTenantId(TenantId tenantId) {
return resourceRepository.sumDataSizeByTenantId(tenantId.getId());
}
@Override
public TbResource findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(resourceRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public PageData<TbResource> findByTenantId(UUID tenantId, PageLink pageLink) {
return findAllByTenantId(TenantId.fromUUID(tenantId), pageLink);
}
@Override
|
public PageData<TbResourceId> findIdsByTenantId(UUID tenantId, PageLink pageLink) {
return DaoUtil.pageToPageData(resourceRepository.findIdsByTenantId(tenantId, DaoUtil.toPageable(pageLink))
.map(TbResourceId::new));
}
@Override
public TbResourceId getExternalIdByInternal(TbResourceId internalId) {
return DaoUtil.toEntityId(resourceRepository.getExternalIdByInternal(internalId.getId()), TbResourceId::new);
}
@Override
public EntityType getEntityType() {
return EntityType.TB_RESOURCE;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\resource\JpaTbResourceDao.java
| 1
|
请完成以下Java代码
|
public class UnzipFile {
public static void main(final String[] args) throws IOException {
final String fileZip = "src/main/resources/unzipTest/compressed.zip";
final File destDir = new File("src/main/resources/unzipTest");
final byte[] buffer = new byte[1024];
final ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
final File newFile = newFile(destDir, zipEntry);
if (zipEntry.isDirectory()) {
if (!newFile.isDirectory() && !newFile.mkdirs()) {
throw new IOException("Failed to create directory " + newFile);
}
} else {
File parent = newFile.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new IOException("Failed to create directory " + parent);
}
final FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
|
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
/**
* @see https://snyk.io/research/zip-slip-vulnerability
*/
public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
File destFile = new File(destinationDir, zipEntry.getName());
String destDirPath = destinationDir.getCanonicalPath();
String destFilePath = destFile.getCanonicalPath();
if (!destFilePath.startsWith(destDirPath + File.separator)) {
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
}
return destFile;
}
}
|
repos\tutorials-master\core-java-modules\core-java-io\src\main\java\com\baeldung\unzip\UnzipFile.java
| 1
|
请完成以下Java代码
|
private static IStringExpression toStringExpression(@NonNull final String sql, @Nullable final String joinTableName)
{
String sqlNorm = StringUtils.trimBlankToOptional(sql)
.orElseThrow(() -> new AdempiereException("sql shall not be empty"));
final String joinTableNameNorm = StringUtils.trimBlankToNull(joinTableName);
if (joinTableNameNorm != null)
{
sqlNorm = sqlNorm.replace(joinTableNameNorm + ".", CTX_JoinTableNameOrAliasIncludingDot.toStringWithMarkers());
}
return StringExpressionCompiler.instance.compile(sqlNorm); // throws exception if sql is invalid
}
public ColumnSql withJoinOnTableNameOrAlias(@Nullable final String joinTableNameOrAlias)
{
return !Objects.equals(this.joinTableNameOrAlias, joinTableNameOrAlias)
? new ColumnSql(joinTableNameOrAlias, sqlExpression)
: this;
}
@Override
@Deprecated
public String toString()
{
return toSqlString();
}
public String toSqlString()
{
|
String sqlBuilt = this._sqlBuilt;
if (sqlBuilt == null)
{
final String joinTableNameOrAliasIncludingDot = joinTableNameOrAlias != null ? joinTableNameOrAlias + "." : "";
final Evaluatee2 evalCtx = Evaluatees.ofSingleton(CTX_JoinTableNameOrAliasIncludingDot.toStringWithoutMarkers(), joinTableNameOrAliasIncludingDot);
sqlBuilt = this._sqlBuilt = sqlExpression.evaluate(evalCtx, IExpressionEvaluator.OnVariableNotFound.Preserve);
}
return sqlBuilt;
}
public String toSqlStringWrappedInBracketsIfNeeded()
{
final String sql = toSqlString();
if (sql.contains(" ") && !sql.startsWith("("))
{
return "(" + sql + ")";
}
else
{
return sql;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\column\ColumnSql.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Set<HuId> getFinishedGoodsReceivedHUIds(@NonNull final PPOrderId ppOrderId)
{
return huPPOrderQtyBL.getFinishedGoodsReceivedHUIds(ppOrderId);
}
@NonNull
public ManufacturingJob recomputeQtyToIssueForSteps(@NonNull final PPOrderId ppOrderId)
{
final ManufacturingJob job = getJobById(ppOrderId);
final ManufacturingJob changedJob = job.withChangedRawMaterialIssue(
rawMaterialsIssue -> rawMaterialsIssue.withChangedLines(this::recomputeQtyToIssueForSteps));
if (!changedJob.equals(job))
{
saveActivityStatuses(changedJob);
}
return changedJob;
}
@NonNull
private RawMaterialsIssueLine recomputeQtyToIssueForSteps(@NonNull final RawMaterialsIssueLine line)
{
Quantity qtyLeftToBeIssued = line.getQtyLeftToIssue().toZeroIfNegative();
final ImmutableList.Builder<RawMaterialsIssueStep> updatedStepsListBuilder = ImmutableList.builder();
for (final RawMaterialsIssueStep step : line.getSteps())
{
if (step.isIssued())
{
updatedStepsListBuilder.add(step);
}
else if (qtyLeftToBeIssued.isGreaterThan(step.getQtyToIssue()))
{
updatedStepsListBuilder.add(step);
qtyLeftToBeIssued = qtyLeftToBeIssued.subtract(step.getQtyToIssue());
}
else
{
ppOrderIssueScheduleService.updateQtyToIssue(step.getId(), qtyLeftToBeIssued);
updatedStepsListBuilder.add(step.withQtyToIssue(qtyLeftToBeIssued));
qtyLeftToBeIssued = qtyLeftToBeIssued.toZero();
}
}
return line.withSteps(updatedStepsListBuilder.build());
}
|
@NonNull
private Optional<Quantity> extractTargetCatchWeight(@NonNull final JsonManufacturingOrderEvent.ReceiveFrom receiveFrom)
{
if (receiveFrom.getCatchWeight() == null || Check.isBlank(receiveFrom.getCatchWeightUomSymbol()))
{
return Optional.empty();
}
return uomDAO.getBySymbol(receiveFrom.getCatchWeightUomSymbol())
.map(uom -> Quantity.of(receiveFrom.getCatchWeight(), uom));
}
public QueryLimit getLaunchersLimit()
{
final int limitInt = sysConfigBL.getIntValue(Constants.SYSCONFIG_LaunchersLimit, -100);
return limitInt == -100
? Constants.DEFAULT_LaunchersLimit
: QueryLimit.ofInt(limitInt);
}
public ManufacturingJob autoIssueWhatWasReceived(
@NonNull final ManufacturingJob job,
@NonNull final RawMaterialsIssueStrategy issueStrategy)
{
return newIssueWhatWasReceivedCommand()
.job(job)
.issueStrategy(issueStrategy)
.build().execute();
}
public IssueWhatWasReceivedCommandBuilder newIssueWhatWasReceivedCommand()
{
return IssueWhatWasReceivedCommand.builder()
.issueScheduleService(ppOrderIssueScheduleService)
.jobService(this)
.ppOrderSourceHUService(ppOrderSourceHUService)
.sourceHUsService(sourceHUsService);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\ManufacturingJobService.java
| 2
|
请完成以下Java代码
|
public boolean isInitialCare()
{
return get_ValueAsBoolean(COLUMNNAME_IsInitialCare);
}
@Override
public void setIsPrivateSale (final boolean IsPrivateSale)
{
set_Value (COLUMNNAME_IsPrivateSale, IsPrivateSale);
}
@Override
public boolean isPrivateSale()
{
return get_ValueAsBoolean(COLUMNNAME_IsPrivateSale);
}
@Override
public void setIsRentalEquipment (final boolean IsRentalEquipment)
{
set_Value (COLUMNNAME_IsRentalEquipment, IsRentalEquipment);
}
@Override
public boolean isRentalEquipment()
{
return get_ValueAsBoolean(COLUMNNAME_IsRentalEquipment);
}
@Override
public void setIsSeriesOrder (final boolean IsSeriesOrder)
{
set_Value (COLUMNNAME_IsSeriesOrder, IsSeriesOrder);
}
@Override
public boolean isSeriesOrder()
{
return get_ValueAsBoolean(COLUMNNAME_IsSeriesOrder);
}
@Override
public void setNextDelivery (final @Nullable java.sql.Timestamp NextDelivery)
{
set_Value (COLUMNNAME_NextDelivery, NextDelivery);
}
@Override
public java.sql.Timestamp getNextDelivery()
{
return get_ValueAsTimestamp(COLUMNNAME_NextDelivery);
}
@Override
public void setRootId (final @Nullable java.lang.String RootId)
{
set_Value (COLUMNNAME_RootId, RootId);
}
@Override
public java.lang.String getRootId()
{
return get_ValueAsString(COLUMNNAME_RootId);
}
@Override
public void setSalesLineId (final @Nullable java.lang.String SalesLineId)
{
set_Value (COLUMNNAME_SalesLineId, SalesLineId);
|
}
@Override
public java.lang.String getSalesLineId()
{
return get_ValueAsString(COLUMNNAME_SalesLineId);
}
@Override
public void setStartDate (final @Nullable java.sql.Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
@Override
public java.sql.Timestamp getStartDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StartDate);
}
@Override
public void setTimePeriod (final @Nullable BigDecimal TimePeriod)
{
set_Value (COLUMNNAME_TimePeriod, TimePeriod);
}
@Override
public BigDecimal getTimePeriod()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TimePeriod);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUnit (final @Nullable java.lang.String Unit)
{
set_Value (COLUMNNAME_Unit, Unit);
}
@Override
public java.lang.String getUnit()
{
return get_ValueAsString(COLUMNNAME_Unit);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_OLCand_AlbertaOrder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public StringToMapConverter stringToMapConverter(@Lazy ObjectMapper objectMapper) {
return new StringToMapConverter(objectMapper);
}
@Bean
public MapToStringConverter mapToStringConverter(@Lazy ObjectMapper objectMapper) {
return new MapToStringConverter(objectMapper);
}
@Bean
public StringToJsonNodeConverter stringToJsonNodeConverter(@Lazy ObjectMapper objectMapper) {
return new StringToJsonNodeConverter(objectMapper);
}
@Bean
public JsonNodeToStringConverter jsonNodeToStringConverter(@Lazy ObjectMapper objectMapper) {
return new JsonNodeToStringConverter(objectMapper);
}
@Bean
public StringToDateConverter stringToDateConverter() {
return new StringToDateConverter();
}
@Bean
public DateToStringConverter dateToStringConverter() {
return new DateToStringConverter();
}
@Bean
public StringToLocalDateTimeConverter stringToLocalDateTimeConverter() {
return new StringToLocalDateTimeConverter();
}
@Bean
public LocalDateTimeToStringConverter localDateTimeToStringConverter() {
return new LocalDateTimeToStringConverter();
}
@Bean
public StringToLocalDateConverter stringToLocalDateConverter() {
return new StringToLocalDateConverter();
}
|
@Bean
public LocalDateToStringConverter localDateToStringConverter() {
return new LocalDateToStringConverter();
}
@Bean
public StringToListConverter sringToListConverter(@Lazy ObjectMapper objectMapper) {
return new StringToListConverter(objectMapper);
}
@Bean
public ListToStringConverter listToStringConverter(@Lazy ObjectMapper objectMapper) {
return new ListToStringConverter(objectMapper);
}
@Bean
public StringToSetConverter stringToSetConverter(@Lazy ObjectMapper objectMapper) {
return new StringToSetConverter(objectMapper);
}
@Bean
public SetToStringConverter setToStringConverter(@Lazy ObjectMapper objectMapper) {
return new SetToStringConverter(objectMapper);
}
@Bean
public StringToObjectValueConverter stringToObjectValueConverter(@Lazy ObjectMapper objectMapper) {
return new StringToObjectValueConverter(objectMapper);
}
@Bean
public ObjectValueToStringConverter objectValueToStringConverter(@Lazy ObjectMapper objectMapper) {
return new ObjectValueToStringConverter(objectMapper);
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\conf\impl\ProcessModelAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void addLog(String logContent, Integer logType, Integer operatetype, LoginUser user) {
LogDTO sysLog = new LogDTO();
sysLog.setId(String.valueOf(IdWorker.getId()));
//注解上的描述,操作日志内容
sysLog.setLogContent(logContent);
sysLog.setLogType(logType);
sysLog.setOperateType(operatetype);
try {
//获取request
HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
//设置IP地址
sysLog.setIp(IpUtils.getIpAddr(request));
try {
//设置客户端
if(BrowserUtils.isDesktop(request)){
sysLog.setClientType(ClientTerminalTypeEnum.PC.getKey());
}else{
sysLog.setClientType(ClientTerminalTypeEnum.APP.getKey());
}
} catch (Exception e) {
//e.printStackTrace();
}
} catch (Exception e) {
sysLog.setIp("127.0.0.1");
}
//获取登录用户信息
if(user==null){
try {
user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
} catch (Exception e) {
//e.printStackTrace();
}
}
if(user!=null){
sysLog.setUserid(user.getUsername());
sysLog.setUsername(user.getRealname());
|
}
sysLog.setCreateTime(new Date());
//保存日志(异常捕获处理,防止数据太大存储失败,导致业务失败)JT-238
try {
baseCommonMapper.saveLog(sysLog);
} catch (Exception e) {
log.warn(" LogContent length : "+sysLog.getLogContent().length());
log.warn(e.getMessage());
}
}
@Override
public void addLog(String logContent, Integer logType, Integer operateType) {
addLog(logContent, logType, operateType, null);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\modules\base\service\impl\BaseCommonServiceImpl.java
| 2
|
请完成以下Java代码
|
public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {
byte[] buffer = IOUtils.toByteArray(context.getInputStream());
logger.info("The contents of request body is: \n" + new String(buffer, "UTF-8") + "\n");
context.setInputStream(new ByteArrayInputStream(buffer));
return context.proceed();
}
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
RestInterceptor.OutputStreamWrapper wrapper =
new RestInterceptor.OutputStreamWrapper(context.getOutputStream());
context.setOutputStream(wrapper);
context.proceed();
logger.info("The contents of response body is: \n" + new String(wrapper.getBytes(), "UTF-8") + "\n");
}
protected static class OutputStreamWrapper extends OutputStream {
private final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
private final OutputStream output;
private OutputStreamWrapper(OutputStream output) {
this.output = output;
}
@Override
public void write(int i) throws IOException {
buffer.write(i);
output.write(i);
|
}
@Override
public void write(byte[] b) throws IOException {
buffer.write(b);
output.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
buffer.write(b, off, len);
output.write(b, off, len);
}
@Override
public void flush() throws IOException {
output.flush();
}
@Override
public void close() throws IOException {
output.close();
}
public byte[] getBytes() {
return buffer.toByteArray();
}
}
}
|
repos\springBoot-master\springboot-dubbo\abel-user-provider\src\main\java\cn\abel\user\filter\RestInterceptor.java
| 1
|
请完成以下Java代码
|
public InputStream export()
{
final PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = null;
try
{
pipeIn = new PipedInputStream(pipeOut, 1024 * 16);
}
catch (IOException e)
{
throw new AdempiereException(e.getLocalizedMessage(), e);
}
executeAsync(pipeOut);
return pipeIn;
}
/**
* Prepare datasource first.
*
* This part will be run synchronously so we will make sure that we will get here the first error and also no InputStream will be sent to file downloaders or other streaming tools
*/
private void prepareDataSource()
{
IExportDataSource dataSource = exporter.getDataSource();
boolean dataSourcePrepared = false;
try
{
dataSource.prepare();
// Make sure we have something to export
final int size = dataSource.size();
if (size <= 0)
{
throw new AdempiereException("No data found");
}
dataSourcePrepared = true;
}
finally
{
if (!dataSourcePrepared)
{
try
{
dataSource.close();
}
catch (Exception e)
{
// do nothing;
}
}
}
}
public void executeAsync(final OutputStream out)
{
Check.assume(executorService == null, "No other execution started: {}", executorService);
prepareDataSource();
//
// Prepare & execute asynchronously
executorService = Executors.newFixedThreadPool(2);
final Runnable exportRunnable = new Runnable()
{
@Override
public void run()
{
exporter.export(out);
}
};
final Runnable exportMonitor = new Runnable()
{
@Override
public void run()
{
int prevRowCount = exporter.getExportedRowCount();
ExportStatus exportStatus = exporter.getExportStatus();
while (exportStatus != ExportStatus.Finished)
{
try
{
Thread.sleep(1000 * 10); // wait 10sec
}
catch (InterruptedException e)
{
// interruption required, just stop it
break;
}
exportStatus = exporter.getExportStatus();
final int rowCount = exporter.getExportedRowCount();
|
if (exportStatus == ExportStatus.Finished)
{
break;
}
if (prevRowCount >= rowCount)
{
// the export thread is stagnating... we will need to stop everything
break;
}
prevRowCount = rowCount;
}
executorService.shutdownNow();
}
};
futureExportResult = executorService.submit(exportRunnable);
executorService.submit(exportMonitor);
}
public void waitToFinish()
{
try
{
futureExportResult.get();
}
catch (InterruptedException e)
{
throw new AdempiereException(e.getLocalizedMessage(), e);
}
catch (ExecutionException e)
{
Throwable ex = e.getCause();
if (ex == null)
{
ex = e;
}
throw ex instanceof AdempiereException ? (AdempiereException)ex : new AdempiereException(ex.getLocalizedMessage(), ex); // NOPMD by tsa on 3/15/13 7:44 PM
}
finally
{
executorService.shutdownNow();
executorService = null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\ASyncExporterWrapper.java
| 1
|
请完成以下Java代码
|
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
@Override
public List<IOParameter> getOutParameters() {
return outParameters;
}
@Override
public void addOutParameter(IOParameter outParameter) {
this.outParameters.add(outParameter);
}
@Override
public void setOutParameters(List<IOParameter> outParameters) {
this.outParameters = outParameters;
}
public String getCaseInstanceIdVariableName() {
return caseInstanceIdVariableName;
}
public void setCaseInstanceIdVariableName(String caseInstanceIdVariableName) {
this.caseInstanceIdVariableName = caseInstanceIdVariableName;
}
@Override
public CaseServiceTask clone() {
CaseServiceTask clone = new CaseServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(CaseServiceTask otherElement) {
super.setValues(otherElement);
setCaseDefinitionKey(otherElement.getCaseDefinitionKey());
|
setCaseInstanceName(otherElement.getCaseInstanceName());
setBusinessKey(otherElement.getBusinessKey());
setInheritBusinessKey(otherElement.isInheritBusinessKey());
setSameDeployment(otherElement.isSameDeployment());
setFallbackToDefaultTenant(otherElement.isFallbackToDefaultTenant());
setCaseInstanceIdVariableName(otherElement.getCaseInstanceIdVariableName());
inParameters = new ArrayList<>();
if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getInParameters()) {
inParameters.add(parameter.clone());
}
}
outParameters = new ArrayList<>();
if (otherElement.getOutParameters() != null && !otherElement.getOutParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getOutParameters()) {
outParameters.add(parameter.clone());
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\CaseServiceTask.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void requestTaxiOrderStatus() throws Exception{
List<Orders> ordersList = orderRepository.findAllByStatusAndPaymentNumberIsNotNull(OrderStatus.awaitingPayment);
for(Orders orders: ordersList){
OrderStatus prevOrderStatus = orders.getStatus();
Map<String, String> mapResult = taxiOrderProcess.getTaxiOrderStatus(orders.getTaxiOrderId(), orders.getOrderDetailsList().get(0).getGood().getRetailer());
if(mapResult !=null){
switch (mapResult.get("get_order_state")) {
case "new_order":
ordersSave(orders, OrderStatus.courierSearch, mapResult);
break;
case "driver_assigned":
ordersSave(orders, OrderStatus.courierFound, mapResult);
break;
case "car_at_place":
ordersSave(orders, OrderStatus.courierFound, mapResult);
break;
case "client_inside":
ordersSave(orders, OrderStatus.deliveryInProgress, mapResult);
break;
case "finished":
ordersSave(orders, OrderStatus.awaitingConfirmation, mapResult);
break;
}
}
if(!prevOrderStatus.equals(orders.getStatus())){
producer.sendOrderRequest(orders);
|
}
}
}
private void ordersSave(Orders orders, OrderStatus status, Map<String, String> mapResult)
{
orders.setCarColor(mapResult.get("car_color"));
orders.setCarMark(mapResult.get("car_mark"));
orders.setCarModel(mapResult.get("car_model"));
orders.setCarNumber(mapResult.get("car_number"));
orders.setStatus(status);
orders.setNameDriver(mapResult.get("name"));
orders.setPhoneDriver(mapResult.get("phones"));
orderRepository.save(orders);
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\schedule\OrderStatusRequester.java
| 2
|
请完成以下Java代码
|
public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setMD_Available_For_Sales_ID (final int MD_Available_For_Sales_ID)
{
if (MD_Available_For_Sales_ID < 1)
set_ValueNoCheck (COLUMNNAME_MD_Available_For_Sales_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MD_Available_For_Sales_ID, MD_Available_For_Sales_ID);
}
@Override
public int getMD_Available_For_Sales_ID()
{
return get_ValueAsInt(COLUMNNAME_MD_Available_For_Sales_ID);
}
@Override
public void setQtyOnHandStock (final @Nullable BigDecimal QtyOnHandStock)
{
set_Value (COLUMNNAME_QtyOnHandStock, QtyOnHandStock);
}
@Override
public BigDecimal getQtyOnHandStock()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHandStock);
return bd != null ? bd : BigDecimal.ZERO;
|
}
@Override
public void setQtyToBeShipped (final @Nullable BigDecimal QtyToBeShipped)
{
set_Value (COLUMNNAME_QtyToBeShipped, QtyToBeShipped);
}
@Override
public BigDecimal getQtyToBeShipped()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToBeShipped);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setStorageAttributesKey (final java.lang.String StorageAttributesKey)
{
set_Value (COLUMNNAME_StorageAttributesKey, StorageAttributesKey);
}
@Override
public java.lang.String getStorageAttributesKey()
{
return get_ValueAsString(COLUMNNAME_StorageAttributesKey);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MD_Available_For_Sales.java
| 1
|
请完成以下Java代码
|
public class IntermediateThrowEscalationEventActivityBehavior extends AbstractBpmnActivityBehavior {
private static final long serialVersionUID = 1L;
protected final EscalationEventDefinition escalationEventDefinition;
protected String escalationCode;
protected String escalationName;
public IntermediateThrowEscalationEventActivityBehavior(ThrowEvent throwEvent, EscalationEventDefinition escalationEventDefinition,
Escalation escalation) {
if (escalation != null) {
escalationCode = escalation.getEscalationCode();
escalationName = escalation.getName();
|
} else {
escalationCode = escalationEventDefinition.getEscalationCode();
escalationName = escalationCode;
}
this.escalationEventDefinition = escalationEventDefinition;
}
@Override
public void execute(DelegateExecution execution) {
CommandContext commandContext = Context.getCommandContext();
EscalationPropagation.propagateEscalation(escalationCode, escalationName, execution);
CommandContextUtil.getAgenda(commandContext).planTakeOutgoingSequenceFlowsOperation((ExecutionEntity) execution, true);
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\IntermediateThrowEscalationEventActivityBehavior.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
sysCommentService.removeById(id);
return Result.OK("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
//@AutoLog(value = "系统评论回复表-批量删除")
@Operation(summary = "系统评论回复表-批量删除")
//@RequiresPermissions("org.jeecg.modules.demo:sys_comment:deleteBatch")
@DeleteMapping(value = "/deleteBatch")
public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.sysCommentService.removeByIds(Arrays.asList(ids.split(",")));
return Result.OK("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
//@AutoLog(value = "系统评论回复表-通过id查询")
@Operation(summary = "系统评论回复表-通过id查询")
@GetMapping(value = "/queryById")
public Result<SysComment> queryById(@RequestParam(name = "id", required = true) String id) {
SysComment sysComment = sysCommentService.getById(id);
if (sysComment == null) {
return Result.error("未找到对应数据");
}
|
return Result.OK(sysComment);
}
/**
* 导出excel
*
* @param request
* @param sysComment
*/
//@RequiresPermissions("org.jeecg.modules.demo:sys_comment:exportXls")
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, SysComment sysComment) {
return super.exportXls(request, sysComment, SysComment.class, "系统评论回复表");
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
//@RequiresPermissions("sys_comment:importExcel")
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, SysComment.class);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysCommentController.java
| 2
|
请完成以下Java代码
|
public void prohibitVoidAndClose(final I_C_Flatrate_Conditions cond)
{
throw new AdempiereException(MainValidator.MSG_FLATRATE_DOC_ACTION_NOT_SUPPORTED_0P);
}
@DocValidate(timings = { ModelValidator.TIMING_BEFORE_COMPLETE })
public void beforeComplete(final I_C_Flatrate_Conditions cond)
{
final IFlatrateDAO flatrateDB = Services.get(IFlatrateDAO.class);
final boolean matchingsAreRequired = X_C_Flatrate_Conditions.TYPE_CONDITIONS_HoldingFee.equals(cond.getType_Conditions())
|| X_C_Flatrate_Conditions.TYPE_CONDITIONS_Refundable.equals(cond.getType_Conditions())
|| X_C_Flatrate_Conditions.TYPE_CONDITIONS_FlatFee.equals(cond.getType_Conditions())
|| X_C_Flatrate_Conditions.TYPE_CONDITIONS_QualityBasedInvoicing.equals(cond.getType_Conditions());
if (matchingsAreRequired)
{
// 03660 for subscriptions, we don't strictly require mappings anymore,
// because it's simply impractical for multi-org-setups
final List<I_C_Flatrate_Matching> matchings = flatrateDB.retrieveFlatrateMatchings(cond);
if (matchings.isEmpty())
{
throw new AdempiereException(MSG_CONDITIONS_ERROR_MATCHING_MISSING_0P);
}
}
final boolean hasHoCompletedTransition = cond.getC_Flatrate_Transition_ID() <= 0 || !X_C_Flatrate_Transition.DOCSTATUS_Completed.equals(cond.getC_Flatrate_Transition().getDocStatus());
if (hasHoCompletedTransition)
{
throw new AdempiereException(MSG_CONDITIONS_ERROR_TRANSITION_NOT_CO_0P);
|
}
}
@DocValidate(timings = { ModelValidator.TIMING_BEFORE_REACTIVATE })
public void beforeReactivate(final I_C_Flatrate_Conditions cond)
{
// check if the conditions are already used somewhere
final IFlatrateDAO flatrateDB = Services.get(IFlatrateDAO.class);
final List<I_C_Flatrate_Term> terms = flatrateDB.retrieveTerms(cond);
if (!terms.isEmpty())
{
throw new AdempiereException(MSG_CONDITIONS_ERROR_ALREADY_IN_USE_0P);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_Flatrate_Conditions.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ProgramPayController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(ProgramPayController.class);
@Autowired
private RpTradePaymentManagerService tradePaymentManagerService;
@Autowired
private CnpPayService cnpPayService;
private static final String CONTENT_TYPE = "text/text;charset=UTF-8";
@RequestMapping("/doPay")
public void initPay(@ModelAttribute ProgramPayRequestBo programPayRequestBo, BindingResult bindingResult, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
String payResultJson = "";
try{
RpUserPayConfig rpUserPayConfig = cnpPayService.checkParamAndGetUserPayConfig(programPayRequestBo, bindingResult, httpServletRequest);
//发起支付
ProgramPayResultVo resultVo = tradePaymentManagerService.programPay( rpUserPayConfig, programPayRequestBo);
payResultJson = JSONObject.toJSONString(resultVo);
logger.debug("小程序--支付结果==>{}", payResultJson);
} catch (
BizException e) {
logger.error("业务异常:", e);
payResultJson = e.getMsg();
} catch (Exception e) {
|
logger.error("系统异常:", e);
payResultJson = "系统异常";
}
httpServletResponse.setContentType(CONTENT_TYPE);
write(httpServletResponse, payResultJson);
}
@RequestMapping("/authorize")
@ResponseBody
public String wxAuthorize(@RequestParam("code") String code) {
String authUrl = WeixinConfigUtil.xAuthUrl.replace("{APPID}", WeixinConfigUtil.xAppId).replace("{SECRET}", WeixinConfigUtil.xPartnerKey).replace("{JSCODE}", code).replace("{GRANTTYPE}", WeixinConfigUtil.xGrantType);
try {
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(authUrl);
httpClient.executeMethod(getMethod);
String result = getMethod.getResponseBodyAsString();
logger.info("小程序code换取结果:{}", result);
return result;
} catch (IOException e) {
logger.info("获取openId失败!");
return null;
}
}
}
|
repos\roncoo-pay-master\roncoo-pay-web-gateway\src\main\java\com\roncoo\pay\controller\ProgramPayController.java
| 2
|
请完成以下Java代码
|
public class SaveTaskCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected TaskEntity task;
public SaveTaskCmd(Task task) {
this.task = (TaskEntity) task;
}
@Override
public Void execute(CommandContext commandContext) {
if (task == null) {
throw new ActivitiIllegalArgumentException("task is null");
}
if (task.getRevision() == 0) {
task.insert(null, true);
// Need to to be done here, we can't make it generic for standalone tasks
// and tasks from a process, as the order of setting properties is
|
// completely different.
if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.TASK_CREATED, task),
EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);
if (task.getAssignee() != null) {
// The assignment event is normally fired when calling setAssignee. However, this
// doesn't work for standalone tasks as the commandcontext is not available.
Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.TASK_ASSIGNED, task),
EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);
}
}
} else {
task.update();
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\SaveTaskCmd.java
| 1
|
请完成以下Java代码
|
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public MultiplicityEnum getMultiplicity() {
return multiplicityAttribute.getValue(this);
}
public void setMultiplicity(MultiplicityEnum multiplicity) {
multiplicityAttribute.setValue(this, multiplicity);
}
public CaseFileItemDefinition getDefinitionRef() {
return definitionRefAttribute.getReferenceTargetElement(this);
}
public void setDefinitionRef(CaseFileItemDefinition caseFileItemDefinition) {
definitionRefAttribute.setReferenceTargetElement(this, caseFileItemDefinition);
}
public CaseFileItem getSourceRef() {
return sourceRefAttribute.getReferenceTargetElement(this);
}
public void setSourceRef(CaseFileItem sourceRef) {
sourceRefAttribute.setReferenceTargetElement(this, sourceRef);
}
public Collection<CaseFileItem> getSourceRefs() {
return sourceRefCollection.getReferenceTargetElements(this);
}
public Collection<CaseFileItem> getTargetRefs() {
return targetRefCollection.getReferenceTargetElements(this);
}
public Children getChildren() {
return childrenChild.getChild(this);
}
public void setChildren(Children children) {
childrenChild.setChild(this, children);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseFileItem.class, CMMN_ELEMENT_CASE_FILE_ITEM)
.namespaceUri(CMMN11_NS)
.extendsType(CmmnElement.class)
|
.instanceProvider(new ModelTypeInstanceProvider<CaseFileItem>() {
public CaseFileItem newInstance(ModelTypeInstanceContext instanceContext) {
return new CaseFileItemImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
multiplicityAttribute = typeBuilder.enumAttribute(CMMN_ATTRIBUTE_MULTIPLICITY, MultiplicityEnum.class)
.defaultValue(MultiplicityEnum.Unspecified)
.build();
definitionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DEFINITION_REF)
.qNameAttributeReference(CaseFileItemDefinition.class)
.build();
sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF)
.namespace(CMMN10_NS)
.idAttributeReference(CaseFileItem.class)
.build();
sourceRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REFS)
.idAttributeReferenceCollection(CaseFileItem.class, CmmnAttributeElementReferenceCollection.class)
.build();
targetRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_REFS)
.idAttributeReferenceCollection(CaseFileItem.class, CmmnAttributeElementReferenceCollection.class)
.build();
SequenceBuilder sequence = typeBuilder.sequence();
childrenChild = sequence.element(Children.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseFileItemImpl.java
| 1
|
请完成以下Java代码
|
protected final <T extends IView> boolean isViewClass(@NonNull final Class<T> expectedViewClass)
{
final IView view = _view;
if (view == null)
{
return false;
}
return expectedViewClass.isAssignableFrom(view.getClass());
}
protected final void invalidateView(@NonNull final IView view)
{
viewsRepo.invalidateView(view);
}
protected final void invalidateView(@NonNull final ViewId viewId)
{
viewsRepo.invalidateView(viewId);
}
protected final void invalidateView()
{
final IView view = getView();
invalidateView(view.getViewId());
}
protected final void invalidateParentView()
{
final IView view = getView();
final ViewId parentViewId = view.getParentViewId();
if (parentViewId != null)
{
invalidateView(parentViewId);
}
}
protected final boolean isSingleSelectedRow()
{
return getSelectedRowIds().isSingleDocumentId();
}
protected final DocumentIdsSelection getSelectedRowIds()
{
final ViewRowIdsSelection viewRowIdsSelection = Check.assumeNotNull(_viewRowIdsSelection, "View loaded");
return viewRowIdsSelection.getRowIds();
}
protected final <ID extends RepoIdAware> ImmutableSet<ID> getSelectedIds(@NonNull final IntFunction<ID> idMapper, @NonNull final QueryLimit limit)
{
final DocumentIdsSelection selectedRowsIds = getSelectedRowIds();
if (selectedRowsIds.isAll())
{
return streamSelectedRows()
|
.limit(limit.toIntOr(Integer.MAX_VALUE))
.map(row -> row.getId().toId(idMapper))
.collect(ImmutableSet.toImmutableSet());
}
else
{
return selectedRowsIds.toIdsFromInt(idMapper);
}
}
@OverridingMethodsMustInvokeSuper
protected IViewRow getSingleSelectedRow()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
final DocumentId documentId = selectedRowIds.getSingleDocumentId();
return getView().getById(documentId);
}
@OverridingMethodsMustInvokeSuper
protected Stream<? extends IViewRow> streamSelectedRows()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
return getView().streamByIds(selectedRowIds);
}
protected final ViewRowIdsSelection getParentViewRowIdsSelection()
{
return _parentViewRowIdsSelection;
}
protected final ViewRowIdsSelection getChildViewRowIdsSelection()
{
return _childViewRowIdsSelection;
}
@SuppressWarnings("SameParameterValue")
protected final <T extends IView> T getChildView(@NonNull final Class<T> viewType)
{
final ViewRowIdsSelection childViewRowIdsSelection = getChildViewRowIdsSelection();
Check.assumeNotNull(childViewRowIdsSelection, "child view is set");
final IView childView = viewsRepo.getView(childViewRowIdsSelection.getViewId());
return viewType.cast(childView);
}
protected final DocumentIdsSelection getChildViewSelectedRowIds()
{
final ViewRowIdsSelection childViewRowIdsSelection = getChildViewRowIdsSelection();
return childViewRowIdsSelection != null ? childViewRowIdsSelection.getRowIds() : DocumentIdsSelection.EMPTY;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\ViewBasedProcessTemplate.java
| 1
|
请完成以下Java代码
|
public int getCB_Differences_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CB_Differences_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getCB_Expense_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getCB_Expense_Acct(), get_TrxName()); }
/** Set Cash Book Expense.
@param CB_Expense_Acct
Cash Book Expense Account
*/
public void setCB_Expense_Acct (int CB_Expense_Acct)
{
set_Value (COLUMNNAME_CB_Expense_Acct, Integer.valueOf(CB_Expense_Acct));
}
/** Get Cash Book Expense.
@return Cash Book Expense Account
*/
public int getCB_Expense_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CB_Expense_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getCB_Receipt_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getCB_Receipt_Acct(), get_TrxName()); }
/** Set Cash Book Receipt.
@param CB_Receipt_Acct
Cash Book Receipts Account
*/
public void setCB_Receipt_Acct (int CB_Receipt_Acct)
{
set_Value (COLUMNNAME_CB_Receipt_Acct, Integer.valueOf(CB_Receipt_Acct));
}
|
/** Get Cash Book Receipt.
@return Cash Book Receipts Account
*/
public int getCB_Receipt_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CB_Receipt_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_CashBook getC_CashBook() throws RuntimeException
{
return (I_C_CashBook)MTable.get(getCtx(), I_C_CashBook.Table_Name)
.getPO(getC_CashBook_ID(), get_TrxName()); }
/** Set Cash Book.
@param C_CashBook_ID
Cash Book for recording petty cash transactions
*/
public void setC_CashBook_ID (int C_CashBook_ID)
{
if (C_CashBook_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CashBook_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CashBook_ID, Integer.valueOf(C_CashBook_ID));
}
/** Get Cash Book.
@return Cash Book for recording petty cash transactions
*/
public int getC_CashBook_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CashBook_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashBook_Acct.java
| 1
|
请完成以下Java代码
|
public boolean isValidNumericStringResult() {
return validNumericStringResult;
}
public void setValidNumericStringResult(boolean validNumericStringResult) {
this.validNumericStringResult = validNumericStringResult;
}
public boolean isInvalidNumericStringResult() {
return invalidNumericStringResult;
}
public void setInvalidNumericStringResult(boolean invalidNumericStringResult) {
this.invalidNumericStringResult = invalidNumericStringResult;
}
public boolean isValidAlphabeticStringResult() {
return validAlphabeticStringResult;
}
public void setValidAlphabeticStringResult(boolean validAlphabeticStringResult) {
this.validAlphabeticStringResult = validAlphabeticStringResult;
}
public boolean isInvalidAlphabeticStringResult() {
return invalidAlphabeticStringResult;
}
public void setInvalidAlphabeticStringResult(boolean invalidAlphabeticStringResult) {
this.invalidAlphabeticStringResult = invalidAlphabeticStringResult;
|
}
public boolean isValidFormatOfHorsePower() {
return validFormatOfHorsePower;
}
public void setValidFormatOfHorsePower(boolean validFormatOfHorsePower) {
this.validFormatOfHorsePower = validFormatOfHorsePower;
}
@Override
public String toString() {
return "SpelRegex{" +
"validNumericStringResult=" + validNumericStringResult +
", invalidNumericStringResult=" + invalidNumericStringResult +
", validAlphabeticStringResult=" + validAlphabeticStringResult +
", invalidAlphabeticStringResult=" + invalidAlphabeticStringResult +
", validFormatOfHorsePower=" + validFormatOfHorsePower +
'}';
}
}
|
repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelRegex.java
| 1
|
请完成以下Java代码
|
public class InvocationDecoder extends ByteToMessageDecoder {
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
// 标记当前读取位置
in.markReaderIndex();
// 判断是否能够读取 length 长度
if (in.readableBytes() <= 4) {
return;
}
// 读取长度
int length = in.readInt();
if (length < 0) {
throw new CorruptedFrameException("negative length: " + length);
}
|
// 如果 message 不够可读,则退回到原读取位置
if (in.readableBytes() < length) {
in.resetReaderIndex();
return;
}
// 读取内容
byte[] content = new byte[length];
in.readBytes(content);
// 解析成 Invocation
Invocation invocation = JSON.parseObject(content, Invocation.class);
out.add(invocation);
logger.info("[decode][连接({}) 解析到一条消息({})]", ctx.channel().id(), invocation.toString());
}
}
|
repos\SpringBoot-Labs-master\lab-67\lab-67-netty-demo\lab-67-netty-demo-common\src\main\java\cn\iocoder\springboot\lab67\nettycommondemo\codec\InvocationDecoder.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.