instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | private boolean isString(Serializable object) {
return object.getClass().isAssignableFrom(String.class);
}
void setConversionService(ConversionService conversionService) {
Assert.notNull(conversionService, "conversionService must not be null");
this.conversionService = conversionService;
}
private static class StringToLongConverter implements Converter<String, Long> {
@Override
public Long convert(String identifierAsString) {
if (identifierAsString == null) {
throw new ConversionFailedException(TypeDescriptor.valueOf(String.class),
TypeDescriptor.valueOf(Long.class), null, null);
}
return Long.parseLong(identifierAsString); | }
}
private static class StringToUUIDConverter implements Converter<String, UUID> {
@Override
public UUID convert(String identifierAsString) {
if (identifierAsString == null) {
throw new ConversionFailedException(TypeDescriptor.valueOf(String.class),
TypeDescriptor.valueOf(UUID.class), null, null);
}
return UUID.fromString(identifierAsString);
}
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\jdbc\AclClassIdUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static PhonecallSchedule toPhonecallSchedule(final I_C_Phonecall_Schedule record)
{
final PhonecallSchemaVersionId schemaVersionId = PhonecallSchemaVersionId.ofRepoId(
record.getC_Phonecall_Schema_ID(),
record.getC_Phonecall_Schema_Version_ID());
return PhonecallSchedule.builder()
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.bpartnerAndLocationId(BPartnerLocationId.ofRepoId(record.getC_BPartner_ID(), record.getC_BPartner_Location_ID()))
.contactId(UserId.ofRepoId(record.getC_BP_Contact_ID()))
.date(TimeUtil.asLocalDate(record.getPhonecallDate()))
.startTime(TimeUtil.asZonedDateTime(record.getPhonecallTimeMin()))
.endTime(TimeUtil.asZonedDateTime(record.getPhonecallTimeMax()))
.id(PhonecallScheduleId.ofRepoId(record.getC_Phonecall_Schedule_ID()))
.schemaVersionLineId(PhonecallSchemaVersionLineId.ofRepoId(
schemaVersionId,
record.getC_Phonecall_Schema_Version_Line_ID()))
.isOrdered(record.isOrdered())
.isCalled(record.isCalled())
.salesRepId(UserId.ofRepoIdOrNull(record.getSalesRep_ID()))
.description(record.getDescription())
.build();
}
public void markAsOrdered(@NonNull final PhonecallSchedule schedule)
{
final I_C_Phonecall_Schedule scheduleRecord = load(schedule.getId(), I_C_Phonecall_Schedule.class); | scheduleRecord.setIsCalled(true);
scheduleRecord.setIsOrdered(true);
saveRecord(scheduleRecord);
}
public void markAsCalled(@NonNull final PhonecallSchedule schedule)
{
final I_C_Phonecall_Schedule scheduleRecord = load(schedule.getId(), I_C_Phonecall_Schedule.class);
scheduleRecord.setIsCalled(true);
saveRecord(scheduleRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\phonecall\service\PhonecallScheduleRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Mono<UserCacheObject> get(@RequestParam("id") Integer id) {
String key = genKey(id);
return commonRedisTemplate.opsForValue().get(key)
.map(o -> (UserCacheObject) o);
}
/**
* 设置指定用户的信息
*
* @param user 用户
* @return 是否成功
*/
@PostMapping("/set")
public Mono<Boolean> set(UserCacheObject user) {
String key = genKey(user.getId());
return commonRedisTemplate.opsForValue().set(key, user);
}
private static String genKey(Integer id) {
return "user::" + id;
}
// ========== 使用专属的 ReactiveRedisTemplate 的方式 =========
@Autowired
private ReactiveRedisTemplate<String, UserCacheObject> userRedisTemplate;
/**
* 获得指定用户编号的用户
*
* @param id 用户编号
* @return 用户
*/
@GetMapping("/v2/get")
public Mono<UserCacheObject> getV2(@RequestParam("id") Integer id) {
String key = genKeyV2(id);
return userRedisTemplate.opsForValue().get(key);
} | /**
* 设置指定用户的信息
*
* @param user 用户
* @return 是否成功
*/
@PostMapping("/v2/set")
public Mono<Boolean> setV2(UserCacheObject user) {
String key = genKeyV2(user.getId());
return userRedisTemplate.opsForValue().set(key, user);
}
private static String genKeyV2(Integer id) {
return "user::v2::" + id;
}
} | repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-redis\src\main\java\cn\iocoder\springboot\lab27\springwebflux\controller\UserController.java | 2 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if(obj == null) {
return false;
} | if (getClass() != obj.getClass()) {
return false;
}
BusinessKeyBook other = (BusinessKeyBook) obj;
return Objects.equals(isbn, other.getIsbn());
}
@Override
public int hashCode() {
return Objects.hash(isbn);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootLombokEqualsAndHashCode\src\main\java\com\app\BusinessKeyBook.java | 1 |
请完成以下Java代码 | public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair | */
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_Buyer.java | 1 |
请完成以下Java代码 | public class VariableScopeResolver implements Resolver {
protected VariableScope variableScope;
protected String variableScopeKey = "execution";
public VariableScopeResolver(VariableScope variableScope) {
if (variableScope == null) {
throw new ActivitiIllegalArgumentException("variableScope cannot be null");
}
if (variableScope instanceof ExecutionEntity) {
variableScopeKey = "execution";
} else if (variableScope instanceof TaskEntity) {
variableScopeKey = "task";
} else {
throw new ActivitiException("unsupported variable scope type: " + variableScope.getClass().getName());
}
this.variableScope = variableScope;
} | @Override
public boolean containsKey(Object key) {
return variableScopeKey.equals(key) || variableScope.hasVariable((String) key);
}
@Override
public Object get(Object key) {
if (variableScopeKey.equals(key)) {
return variableScope;
}
return variableScope.getVariable((String) key);
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\scripting\VariableScopeResolver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | Output decodeJpeg(Output contents, long channels) {
return g.opBuilder("DecodeJpeg", "DecodeJpeg", scope)
.addInput(contents)
.setAttr("channels", channels)
.build()
.output(0);
}
Output<? extends TType> constant(String name, Tensor t) {
return g.opBuilder("Const", name, scope)
.setAttr("dtype", t.dataType())
.setAttr("value", t)
.build()
.output(0);
}
private Output binaryOp(String type, Output in1, Output in2) {
return g.opBuilder(type, type, scope).addInput(in1).addInput(in2).build().output(0);
} | private final Graph g;
}
@PreDestroy
public void close() {
session.close();
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class LabelWithProbability {
private String label;
private float probability;
private long elapsed;
}
} | repos\springboot-demo-master\Tensorflow\src\main\java\com\et\tf\service\ClassifyImageService.java | 2 |
请完成以下Java代码 | public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Kleinunternehmer-Steuerbefreiung .
@param C_VAT_SmallBusiness_ID Kleinunternehmer-Steuerbefreiung */
@Override
public void setC_VAT_SmallBusiness_ID (int C_VAT_SmallBusiness_ID)
{
if (C_VAT_SmallBusiness_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_VAT_SmallBusiness_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_VAT_SmallBusiness_ID, Integer.valueOf(C_VAT_SmallBusiness_ID));
}
/** Get Kleinunternehmer-Steuerbefreiung .
@return Kleinunternehmer-Steuerbefreiung */
@Override
public int getC_VAT_SmallBusiness_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_VAT_SmallBusiness_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Notiz.
@param Note
Optional weitere Information für ein Dokument
*/
@Override
public void setNote (java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
/** Get Notiz.
@return Optional weitere Information für ein Dokument
*/
@Override
public java.lang.String getNote ()
{
return (java.lang.String)get_Value(COLUMNNAME_Note);
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom); | }
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
/** Set Umsatzsteuer-ID.
@param VATaxID Umsatzsteuer-ID */
@Override
public void setVATaxID (java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
/** Get Umsatzsteuer-ID.
@return Umsatzsteuer-ID */
@Override
public java.lang.String getVATaxID ()
{
return (java.lang.String)get_Value(COLUMNNAME_VATaxID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\tax\model\X_C_VAT_SmallBusiness.java | 1 |
请完成以下Java代码 | public void setQtyCalculated (final @Nullable BigDecimal QtyCalculated)
{
set_Value (COLUMNNAME_QtyCalculated, QtyCalculated);
}
@Override
public BigDecimal getQtyCalculated()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCalculated);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUOM (final java.lang.String UOM)
{
set_Value (COLUMNNAME_UOM, UOM);
}
@Override
public java.lang.String getUOM() | {
return get_ValueAsString(COLUMNNAME_UOM);
}
@Override
public void setWarehouseValue (final java.lang.String WarehouseValue)
{
set_Value (COLUMNNAME_WarehouseValue, WarehouseValue);
}
@Override
public java.lang.String getWarehouseValue()
{
return get_ValueAsString(COLUMNNAME_WarehouseValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Forecast.java | 1 |
请完成以下Java代码 | private void buildDetailsRecurse(
@NonNull final DocumentLayoutDetailDescriptor detail,
@NonNull final ImmutableMap.Builder<DetailId, DocumentLayoutDetailDescriptor> map)
{
putIfNotEmpty(detail, map);
for (final DocumentLayoutDetailDescriptor subDetail : detail.getSubTabLayouts())
{
buildDetailsRecurse(subDetail, map);
}
}
private void putIfNotEmpty(final DocumentLayoutDetailDescriptor detail, final ImmutableMap.Builder<DetailId, DocumentLayoutDetailDescriptor> map)
{
if (detail.isEmpty())
{
return;
}
map.put(detail.getDetailId(), detail);
}
public Builder setWindowId(final WindowId windowId)
{
this.windowId = windowId;
return this;
}
public Builder setCaption(final ITranslatableString caption)
{
this.caption = TranslatableStrings.nullToEmpty(caption);
return this;
}
public Builder setDocumentSummaryElement(@Nullable final DocumentLayoutElementDescriptor documentSummaryElement)
{
this.documentSummaryElement = documentSummaryElement;
return this;
}
public Builder setDocActionElement(@Nullable final DocumentLayoutElementDescriptor docActionElement)
{
this.docActionElement = docActionElement;
return this;
}
public Builder setGridView(final ViewLayout.Builder gridView)
{
this._gridView = gridView;
return this;
}
public Builder setSingleRowLayout(@NonNull final DocumentLayoutSingleRow.Builder singleRowLayout)
{
this.singleRowLayout = singleRowLayout;
return this;
}
private DocumentLayoutSingleRow.Builder getSingleRowLayout()
{
return singleRowLayout;
}
private ViewLayout.Builder getGridView()
{ | return _gridView;
}
public Builder addDetail(@Nullable final DocumentLayoutDetailDescriptor detail)
{
if (detail == null)
{
return this;
}
if (detail.isEmpty())
{
logger.trace("Skip adding detail to layout because it is empty; detail={}", detail);
return this;
}
details.add(detail);
return this;
}
public Builder setSideListView(final ViewLayout sideListViewLayout)
{
this._sideListView = sideListViewLayout;
return this;
}
private ViewLayout getSideList()
{
Preconditions.checkNotNull(_sideListView, "sideList");
return _sideListView;
}
public Builder putDebugProperty(final String name, final String value)
{
debugProperties.put(name, value);
return this;
}
public Builder setStopwatch(final Stopwatch stopwatch)
{
this.stopwatch = stopwatch;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutDescriptor.java | 1 |
请完成以下Java代码 | private IHUQueryBuilder newHUQuery()
{
return handlingUnitsDAO()
.createHUQueryBuilder()
.setContext(PlainContextAware.newOutOfTrx())
.setOnlyActiveHUs(false) // let other enforce this rule
.setOnlyTopLevelHUs(false); // let other enforce this rule
}
private SqlAndParams toSql(@NonNull final IHUQueryBuilder huQuery)
{
final ISqlQueryFilter sqlQueryFilter = ISqlQueryFilter.cast(huQuery.createQueryFilter());
return SqlAndParams.of(
sqlQueryFilter.getSql(),
sqlQueryFilter.getSqlParams(Env.getCtx()));
}
@Override
public FilterSql acceptAll() {return FilterSql.ALLOW_ALL;}
@Override
public FilterSql acceptAllBut(@NonNull final Set<HuId> alwaysIncludeHUIds, @NonNull final Set<HuId> excludeHUIds)
{
final SqlAndParams whereClause = !excludeHUIds.isEmpty()
? toSql(newHUQuery().addHUIdsToExclude(excludeHUIds))
: null;
return FilterSql.builder()
.whereClause(whereClause)
.alwaysIncludeSql(toAlwaysIncludeSql(alwaysIncludeHUIds))
.build();
}
@Override
public FilterSql acceptNone() {return FilterSql.ALLOW_NONE;}
@Override
public FilterSql acceptOnly(@NonNull final HuIdsFilterList fixedHUIds, @NonNull final Set<HuId> alwaysIncludeHUIds) | {
final SqlAndParams whereClause = fixedHUIds.isNone()
? FilterSql.ALLOW_NONE.getWhereClause()
: toSql(newHUQuery().addOnlyHUIds(fixedHUIds.toSet()));
return FilterSql.builder()
.whereClause(whereClause)
.alwaysIncludeSql(toAlwaysIncludeSql(alwaysIncludeHUIds))
.build();
}
@Override
public FilterSql huQuery(final @NonNull IHUQueryBuilder initialHUQueryCopy, final @NonNull Set<HuId> alwaysIncludeHUIds, final @NonNull Set<HuId> excludeHUIds)
{
initialHUQueryCopy.setContext(PlainContextAware.newOutOfTrx());
initialHUQueryCopy.addHUIdsToAlwaysInclude(alwaysIncludeHUIds);
initialHUQueryCopy.addHUIdsToExclude(excludeHUIds);
return FilterSql.builder()
.whereClause(toSql(initialHUQueryCopy))
.alwaysIncludeSql(toAlwaysIncludeSql(alwaysIncludeHUIds))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\filter\HUIdsFilterDataToSqlCaseConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MovieQuoteService implements Subject {
private static final Logger logger = LoggerFactory.getLogger(MovieQuoteService.class);
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private final List<Observer> observers = new ArrayList<>();
private final Faker faker = new Faker();
@Override
public void attach(Observer observer) {
logger.debug("Current number of subscribed users: {}", observers.size());
observers.add(observer);
}
@Override
public void detach(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
String quote = faker.movie().quote(); | logger.debug("New quote: {}", quote);
for (Observer observer : observers) {
logger.debug("Notifying user: {}", observer);
observer.update(quote);
}
}
public void start() {
scheduler.scheduleAtFixedRate(this::notifyObservers, 0, 1, TimeUnit.SECONDS);
}
public int numberOfSubscribers() {
return observers.size();
}
} | repos\tutorials-master\core-java-modules\core-java-perf-2\src\main\java\com\baeldung\lapsedlistener\MovieQuoteService.java | 2 |
请完成以下Java代码 | private Supplier<BucketConfiguration> getConfigSupplier() {
return () -> {
JHipsterProperties.Gateway.RateLimiting rateLimitingProperties =
jHipsterProperties.getGateway().getRateLimiting();
return Bucket4j.configurationBuilder()
.addLimit(Bandwidth.simple(rateLimitingProperties.getLimit(),
Duration.ofSeconds(rateLimitingProperties.getDurationInSeconds())))
.build();
};
}
/**
* Create a Zuul response error when the API limit is exceeded.
*/ | private void apiLimitExceeded() {
RequestContext ctx = RequestContext.getCurrentContext();
ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
if (ctx.getResponseBody() == null) {
ctx.setResponseBody("API rate limit exceeded");
ctx.setSendZuulResponse(false);
}
}
/**
* The ID that will identify the limit: the user login or the user IP address.
*/
private String getId(HttpServletRequest httpServletRequest) {
return SecurityUtils.getCurrentUserLogin().orElse(httpServletRequest.getRemoteAddr());
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\gateway\ratelimiting\RateLimitingFilter.java | 1 |
请完成以下Java代码 | public void validate(T query) {
if (!Context.getProcessEngineConfiguration().isEnableExpressionsInAdhocQueries() &&
!query.getExpressions().isEmpty()) {
throw new BadUserRequestException("Expressions are forbidden in adhoc queries. This behavior can be toggled"
+ " in the process engine configuration");
}
}
@SuppressWarnings("unchecked")
public static <T extends AbstractQuery<?, ?>> AdhocQueryValidator<T> get() {
return (AdhocQueryValidator<T>) INSTANCE;
}
}
public static class StoredQueryValidator<T extends AbstractQuery<?, ?>> implements Validator<T> {
@SuppressWarnings("rawtypes")
public static final StoredQueryValidator INSTANCE = new StoredQueryValidator();
private StoredQueryValidator() {
} | @Override
public void validate(T query) {
if (!Context.getProcessEngineConfiguration().isEnableExpressionsInStoredQueries() &&
!query.getExpressions().isEmpty()) {
throw new BadUserRequestException("Expressions are forbidden in stored queries. This behavior can be toggled"
+ " in the process engine configuration");
}
}
@SuppressWarnings("unchecked")
public static <T extends AbstractQuery<?, ?>> StoredQueryValidator<T> get() {
return (StoredQueryValidator<T>) INSTANCE;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\QueryValidators.java | 1 |
请完成以下Java代码 | public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
} | public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
} | repos\tutorials-master\aws-modules\aws-lambda-modules\lambda-function\src\main\java\com\baeldung\lambda\dynamodb\bean\PersonRequest.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String addItem(@RequestBody ItemRequest request, @SessionAttribute(GeneralConstants.ID_SESSION_SHOPPING_CART) List<Product> shoppingCart) {
Product newProduct = new Product();
Optional<Product> optional = getProductById(products.stream(), request.getId());
if (optional.isPresent()) {
Product product = optional.get();
newProduct.setId(product.getId());
newProduct.setName(product.getName());
newProduct.setPrice(product.getPrice());
newProduct.setQuantity(request.getQuantity());
Optional<Product> productInCart = getProductById(shoppingCart.stream(), product.getId());
String event;
if(productInCart.isPresent()) {
productInCart.get().setQuantity(request.getQuantity());
event = "itemUpdated";
} else {
shoppingCart.add(newProduct);
event = "itemAdded";
}
pusher.trigger(PusherConstants.CHANNEL_NAME, event, newProduct);
}
return "OK";
}
/**
* Method that deletes an item from the cart
*
* @param request Request object
* @param shoppingCart List of products injected by Spring MVC from the session
* @return Status string
*/
@RequestMapping(value = "/cart/item",
method = RequestMethod.DELETE,
consumes = "application/json")
public String deleteItem(@RequestBody ItemRequest request, @SessionAttribute(GeneralConstants.ID_SESSION_SHOPPING_CART) List<Product> shoppingCart) {
Optional<Product> optional = getProductById(products.stream(), request.getId());
if (optional.isPresent()) {
Product product = optional.get();
Optional<Product> productInCart = getProductById(shoppingCart.stream(), product.getId());
if(productInCart.isPresent()) { | shoppingCart.remove(productInCart.get());
pusher.trigger(PusherConstants.CHANNEL_NAME, "itemRemoved", product);
}
}
return "OK";
}
/**
* Method that empties the shopping cart
* @param model Object from Spring MVC
* @return Status string
*/
@RequestMapping(value = "/cart",
method = RequestMethod.DELETE)
public String emptyCart(Model model) {
model.addAttribute(GeneralConstants.ID_SESSION_SHOPPING_CART, new ArrayList<Product>());
pusher.trigger(PusherConstants.CHANNEL_NAME, "cartEmptied", "");
return "OK";
}
/**
* Gets a product by its id from a stream
* @param stream That contains the product to get
* @param id Of the product to get
* @return The product wrapped in an Optional object
*/
private Optional<Product> getProductById(Stream<Product> stream, Long id) {
return stream
.filter(product -> product.getId().equals(id))
.findFirst();
}
} | repos\Spring-Boot-Advanced-Projects-main\Springboot-ShoppingCard\fullstack\backend\src\main\java\com\urunov\controller\web\CartController.java | 2 |
请完成以下Java代码 | public boolean isEligibleForPacking()
{
return isEligibleForChangingPickStatus()
&& isApproved()
&& pickStatus != null
&& pickStatus.isEligibleForPacking();
}
public boolean isEligibleForReview()
{
return isEligibleForChangingPickStatus()
&& pickStatus != null
&& pickStatus.isEligibleForReview();
}
public boolean isEligibleForProcessing()
{ | return isEligibleForChangingPickStatus()
&& pickStatus != null
&& pickStatus.isEligibleForProcessing();
}
public String getLocatorName()
{
return locator != null ? locator.getDisplayName() : "";
}
@Override
public List<ProductsToPickRow> getIncludedRows()
{
return includedRows;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\ProductsToPickRow.java | 1 |
请完成以下Java代码 | public class LocalFileSystemClient implements FileClient {
@Value("${upload.path:/data/upload/}")
private String filePath;
public LocalFileSystemClient() {
// 初始化
this.initFileClient();
}
@Override
public void initFileClient() {
FileUtil.mkdir(filePath);
}
@Override
public String initTask(String filename) {
// 分块文件存储路径
String tempFilePath = filePath + filename + UUID.randomUUID();
FileUtil.mkdir(tempFilePath);
return tempFilePath;
}
@Override
public String chunk(Chunk chunk, String uploadId) {
String filename = chunk.getFilename();
String chunkFilePath = uploadId + "/" + chunk.getChunkNumber();
try (InputStream in = chunk.getFile().getInputStream();
OutputStream out = Files.newOutputStream(Paths.get(chunkFilePath))) {
FileCopyUtils.copy(in, out);
} catch (IOException e) {
log.error("File [{}] upload failed", filename, e);
throw new RuntimeException(e);
}
return chunkFilePath;
}
@Override
public void merge(ChunkProcess chunkProcess) {
String filename = chunkProcess.getFilename(); | // 需要合并的文件所在的文件夹
File chunkFolder = new File(chunkProcess.getUploadId());
// 合并后的文件
File mergeFile = new File(filePath + filename);
try (BufferedOutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(mergeFile.toPath()))) {
byte[] bytes = new byte[1024];
File[] fileArray = Optional.ofNullable(chunkFolder.listFiles())
.orElseThrow(() -> new IllegalArgumentException("Folder is empty"));
List<File> fileList = Arrays.stream(fileArray).sorted(Comparator.comparing(File::getName)).collect(Collectors.toList());
fileList.forEach(file -> {
try (BufferedInputStream inputStream = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
int len;
while ((len = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
} catch (IOException e) {
log.info("File [{}] chunk [{}] write failed", filename, file.getName(), e);
throw new RuntimeException(e);
}
});
} catch (IOException e) {
log.info("File [{}] merge failed", filename, e);
throw new RuntimeException(e);
} finally {
FileUtil.del(chunkProcess.getUploadId());
}
}
@Override
public Resource getFile(String filename) {
File file = new File(filePath + filename);
return new FileSystemResource(file);
}
} | repos\springboot-demo-master\file\src\main\java\com\et\service\impl\LocalFileSystemClient.java | 1 |
请完成以下Java代码 | private static final class IntegerValueConverter implements ValueConverter<Integer, IntegerStringExpression>
{
@Override
public Integer convertFrom(final Object valueObj, final ExpressionContext context)
{
if (valueObj == null)
{
return null;
}
else if (valueObj instanceof Integer)
{
return (Integer)valueObj;
}
else
{
String valueStr = valueObj.toString();
if (valueStr == null)
{
return null; // shall not happen
}
valueStr = valueStr.trim();
return new Integer(valueStr);
}
}
}
private static final class NullExpression extends NullExpressionTemplate<Integer, IntegerStringExpression>implements IntegerStringExpression
{
public NullExpression(final Compiler<Integer, IntegerStringExpression> compiler)
{
super(compiler);
}
}
private static final class ConstantExpression extends ConstantExpressionTemplate<Integer, IntegerStringExpression>implements IntegerStringExpression
{
public ConstantExpression(final Compiler<Integer, IntegerStringExpression> compiler, final String expressionStr, final Integer constantValue)
{
super(ExpressionContext.EMPTY, compiler, expressionStr, constantValue);
}
}
private static final class SingleParameterExpression extends SingleParameterExpressionTemplate<Integer, IntegerStringExpression>implements IntegerStringExpression | {
public SingleParameterExpression(final ExpressionContext context, final Compiler<Integer, IntegerStringExpression> compiler, final String expressionStr, final CtxName parameter)
{
super(context, compiler, expressionStr, parameter);
}
@Override
protected Integer extractParameterValue(final Evaluatee ctx)
{
return parameter.getValueAsInteger(ctx);
}
}
private static final class GeneralExpression extends GeneralExpressionTemplate<Integer, IntegerStringExpression>implements IntegerStringExpression
{
public GeneralExpression(final ExpressionContext context, final Compiler<Integer, IntegerStringExpression> compiler, final String expressionStr, final List<Object> expressionChunks)
{
super(context, compiler, expressionStr, expressionChunks);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\IntegerStringExpressionSupport.java | 1 |
请完成以下Java代码 | public class BinarySearch {
public int runBinarySearchIteratively(int[] sortedArray, int key, int low, int high) {
int index = Integer.MAX_VALUE;
while (low <= high) {
int mid = low + ((high - low) / 2);
if (sortedArray[mid] < key) {
low = mid + 1;
} else if (sortedArray[mid] > key) {
high = mid - 1;
} else if (sortedArray[mid] == key) {
index = mid;
break;
}
}
return index;
}
public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) {
int middle = low + ((high - low) / 2);
if (high < low) {
return -1;
}
if (key == sortedArray[middle]) {
return middle;
} else if (key < sortedArray[middle]) {
return runBinarySearchRecursively(sortedArray, key, low, middle - 1);
} else {
return runBinarySearchRecursively(sortedArray, key, middle + 1, high);
}
}
public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) {
int index = Arrays.binarySearch(sortedArray, key);
return index;
}
public int runBinarySearchUsingJavaCollections(List<Integer> sortedList, Integer key) {
int index = Collections.binarySearch(sortedList, key);
return index;
} | public List<Integer> runBinarySearchOnSortedArraysWithDuplicates(int[] sortedArray, Integer key) {
int startIndex = startIndexSearch(sortedArray, key);
int endIndex = endIndexSearch(sortedArray, key);
return IntStream.rangeClosed(startIndex, endIndex)
.boxed()
.collect(Collectors.toList());
}
private int endIndexSearch(int[] sortedArray, int target) {
int left = 0;
int right = sortedArray.length - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (sortedArray[mid] == target) {
result = mid;
left = mid + 1;
} else if (sortedArray[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
private int startIndexSearch(int[] sortedArray, int target) {
int left = 0;
int right = sortedArray.length - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (sortedArray[mid] == target) {
result = mid;
right = mid - 1;
} else if (sortedArray[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
} | repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\binarysearch\BinarySearch.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ResponseEntity<String> postToCondition(@RequestBody ConditionMessageRepresentation message ) throws FirebaseMessagingException {
Message msg = Message.builder()
.setCondition(message.getCondition())
.putData("body", message.getData())
.build();
String id = fcm.send(msg);
return ResponseEntity
.status(HttpStatus.ACCEPTED)
.body(id);
}
@PostMapping("/clients/{registrationToken}")
public ResponseEntity<String> postToClient(@RequestBody String message, @PathVariable("registrationToken") String registrationToken) throws FirebaseMessagingException {
Message msg = Message.builder()
.setToken(registrationToken)
.putData("body", message)
.build();
String id = fcm.send(msg);
return ResponseEntity
.status(HttpStatus.ACCEPTED)
.body(id);
}
@PostMapping("/clients")
public ResponseEntity<List<String>> postToClients(@RequestBody MulticastMessageRepresentation message) throws FirebaseMessagingException {
MulticastMessage msg = MulticastMessage.builder()
.addAllTokens(message.getRegistrationTokens())
.putData("body", message.getData()) | .build();
BatchResponse response = fcm.sendMulticast(msg);
List<String> ids = response.getResponses()
.stream()
.map(r->r.getMessageId())
.collect(Collectors.toList());
return ResponseEntity
.status(HttpStatus.ACCEPTED)
.body(ids);
}
@PostMapping("/subscriptions/{topic}")
public ResponseEntity<Void> createSubscription(@PathVariable("topic") String topic,@RequestBody List<String> registrationTokens) throws FirebaseMessagingException {
fcm.subscribeToTopic(registrationTokens, topic);
return ResponseEntity.ok().build();
}
@DeleteMapping("/subscriptions/{topic}/{registrationToken}")
public ResponseEntity<Void> deleteSubscription(@PathVariable String topic, @PathVariable String registrationToken) throws FirebaseMessagingException {
fcm.subscribeToTopic(Arrays.asList(registrationToken), topic);
return ResponseEntity.ok().build();
}
} | repos\tutorials-master\gcp-firebase\src\main\java\com\baeldung\gcp\firebase\publisher\controller\FirebasePublisherController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class FileEvidence
{
public static final String SERIALIZED_NAME_FILE_ID = "fileId";
@SerializedName(SERIALIZED_NAME_FILE_ID)
private String fileId;
public FileEvidence fileId(String fileId)
{
this.fileId = fileId;
return this;
}
/**
* If an uploadEvidenceFile call is successful, a unique identifier of this evidence file will be returned in the uploadEvidenceFile response payload. This unique fileId value is then used to either add this evidence file to a new evidence set using the addEvidence method, or to add this file to an existing evidence set using the updateEvidence method. Note that if an evidence set already
* exists for a payment dispute, the getPaymentDispute method will return both the evidenceId (unique identifier of evidence set) value, and the fileId (unique identifier of a file within that evidence set) value(s).
*
* @return fileId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "If an uploadEvidenceFile call is successful, a unique identifier of this evidence file will be returned in the uploadEvidenceFile response payload. This unique fileId value is then used to either add this evidence file to a new evidence set using the addEvidence method, or to add this file to an existing evidence set using the updateEvidence method. Note that if an evidence set already exists for a payment dispute, the getPaymentDispute method will return both the evidenceId (unique identifier of evidence set) value, and the fileId (unique identifier of a file within that evidence set) value(s).")
public String getFileId()
{
return fileId;
}
public void setFileId(String fileId)
{
this.fileId = fileId;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
FileEvidence fileEvidence = (FileEvidence)o;
return Objects.equals(this.fileId, fileEvidence.fileId);
}
@Override
public int hashCode() | {
return Objects.hash(fileId);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class FileEvidence {\n");
sb.append(" fileId: ").append(toIndentedString(fileId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\FileEvidence.java | 2 |
请完成以下Java代码 | public void handleCallOrderDetailUpsert(@NonNull final UpsertCallOrderDetailRequest request)
{
final FlatrateTermId flatrateTermId = request.getCallOrderContractId();
final Optional<CallOrderSummary> summaryOptional = summaryRepo.getByFlatrateTermId(flatrateTermId);
if (!summaryOptional.isPresent())
{
return;
}
final CallOrderSummary summary = summaryOptional.get();
if (request.getOrderLine() != null)
{
detailService.upsertOrderRelatedDetail(summary.getSummaryId(), request.getOrderLine());
}
else if (request.getShipmentLine() != null)
{
detailService.upsertShipmentRelatedDetail(summary.getSummaryId(), request.getShipmentLine());
}
else if (request.getInvoiceLine() != null)
{
detailService.upsertInvoiceRelatedDetail(summary.getSummaryId(), request.getInvoiceLine());
}
}
public void createCallOrderContractIfRequired(@NonNull final I_C_OrderLine ol)
{
if (!callContractService.isCallOrderContractLine(ol))
{
return;
}
if (flatrateBL.existsTermForOrderLine(ol))
{
return;
}
final I_C_Flatrate_Term newCallOrderTerm = callContractService.createCallOrderContract(ol); | summaryService.createSummaryForOrderLine(ol, newCallOrderTerm);
}
public boolean isCallOrder(@NonNull final OrderId orderId)
{
final I_C_Order order = orderBL.getById(orderId);
return isCallOrder(order);
}
public boolean isCallOrder(@NonNull final I_C_Order order)
{
final DocTypeId docTypeTargetId = DocTypeId.ofRepoIdOrNull(order.getC_DocTypeTarget_ID());
if (docTypeTargetId == null)
{
return false;
}
return docTypeBL.isCallOrder(docTypeTargetId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\CallOrderService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JwtTokenFilter authenticationTokenFilterBean() throws Exception {
return new JwtTokenFilter();
}
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure( AuthenticationManagerBuilder auth ) throws Exception {
auth.userDetailsService( userService ).passwordEncoder( new BCryptPasswordEncoder() );
}
@Override
protected void configure( HttpSecurity httpSecurity ) throws Exception { | httpSecurity.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.POST, "/authentication/**").permitAll()
.antMatchers(HttpMethod.POST).authenticated()
.antMatchers(HttpMethod.PUT).authenticated()
.antMatchers(HttpMethod.DELETE).authenticated()
.antMatchers(HttpMethod.GET).authenticated();
httpSecurity
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
httpSecurity.headers().cacheControl();
}
} | repos\Spring-Boot-In-Action-master\springbt_security_jwt\src\main\java\cn\codesheep\springbt_security_jwt\config\WebSecurityConfig.java | 2 |
请完成以下Java代码 | default boolean isMaterialReceiptOrCoProduct(final I_PP_Cost_Collector cc)
{
final CostCollectorType costCollectorType = CostCollectorType.ofCode(cc.getCostCollectorType());
return costCollectorType.isMaterialReceiptOrCoProduct();
}
default boolean isAnyComponentIssue(final I_PP_Cost_Collector cc)
{
final CostCollectorType costCollectorType = CostCollectorType.ofCode(cc.getCostCollectorType());
final PPOrderBOMLineId orderBOMLineId = PPOrderBOMLineId.ofRepoIdOrNull(cc.getPP_Order_BOMLine_ID());
return costCollectorType.isAnyComponentIssue(orderBOMLineId);
}
default boolean isAnyComponentIssueOrCoProduct(final I_PP_Cost_Collector cc)
{
final CostCollectorType costCollectorType = CostCollectorType.ofCode(cc.getCostCollectorType());
final PPOrderBOMLineId orderBOMLineId = PPOrderBOMLineId.ofRepoIdOrNull(cc.getPP_Order_BOMLine_ID());
return costCollectorType.isAnyComponentIssueOrCoProduct(orderBOMLineId);
}
/**
* Create and process material issue cost collector. The given qtys are converted to the UOM of the given <code>orderBOMLine</code>. The Cost collector's type is determined from the given
* <code>orderBOMLine</code> alone.
* <p>
* Note that this method is also used internally to handle the case of a "co-product receipt".
*
* @return processed cost collector
*/
I_PP_Cost_Collector createIssue(ComponentIssueCreateRequest request);
/**
* Create Receipt (finished good or co/by-products). If the given <code>candidate</code>'s {@link PP_Order_BOMLine} is not <code>!= null</code>, then a finished product receipt is created.
* Otherwise a co-product receipt is created. Note that under the hood a co-product receipt is a "negative issue".
*
* @param candidate the candidate to create the receipt from. | *
* @return processed cost collector
*/
I_PP_Cost_Collector createReceipt(ReceiptCostCollectorCandidate candidate);
void createActivityControl(ActivityControlCreateRequest request);
void createMaterialUsageVariance(I_PP_Order ppOrder, I_PP_Order_BOMLine line);
void createResourceUsageVariance(I_PP_Order ppOrder, PPOrderRoutingActivity activity);
/**
* Checks if given cost collector is a reversal.
*
* We consider given cost collector as a reversal if it's ID is bigger then the Reversal_ID.
*
* @param cc cost collector
* @return true if given cost collector is actually a reversal.
*/
boolean isReversal(I_PP_Cost_Collector cc);
boolean isFloorStock(I_PP_Cost_Collector cc);
void updateCostCollectorFromOrder(I_PP_Cost_Collector cc, I_PP_Order order);
List<I_PP_Cost_Collector> getByOrderId(PPOrderId ppOrderId);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\IPPCostCollectorBL.java | 1 |
请完成以下Java代码 | private static final int getOperatorStrength(final String operator)
{
if (operator == null)
{
return -100;
}
else if (LOGIC_OPERATOR_AND.equals(operator))
{
return 20;
}
else if (LOGIC_OPERATOR_OR.equals(operator))
{
return 10;
}
else
{
// unknown operator
throw ExpressionEvaluationException.newWithTranslatableMessage("Unknown operator: " + operator);
}
}
@Override
public Set<CtxName> getParameters()
{
if (_parameters == null)
{
if (isConstant())
{
_parameters = ImmutableSet.of();
}
else
{
final Set<CtxName> result = new LinkedHashSet<>(left.getParameters());
result.addAll(right.getParameters());
_parameters = ImmutableSet.copyOf(result);
}
}
return _parameters;
}
/**
* @return left expression; never null
*/
public ILogicExpression getLeft()
{
return left;
}
/**
* @return right expression; never null
*/
public ILogicExpression getRight()
{
return right;
}
/**
* @return logic operator; never null
*/ | public String getOperator()
{
return operator;
}
@Override
public String toString()
{
return getExpressionString();
}
@Override
public ILogicExpression evaluatePartial(final Evaluatee ctx)
{
if (isConstant())
{
return this;
}
final ILogicExpression leftExpression = getLeft();
final ILogicExpression newLeftExpression = leftExpression.evaluatePartial(ctx);
final ILogicExpression rightExpression = getRight();
final ILogicExpression newRightExpression = rightExpression.evaluatePartial(ctx);
final String logicOperator = getOperator();
if (newLeftExpression.isConstant() && newRightExpression.isConstant())
{
final BooleanEvaluator logicExprEvaluator = LogicExpressionEvaluator.getBooleanEvaluatorByOperator(logicOperator);
final boolean result = logicExprEvaluator.evaluateOrNull(newLeftExpression::constantValue, newRightExpression::constantValue);
return ConstantLogicExpression.of(result);
}
else if (Objects.equals(leftExpression, newLeftExpression)
&& Objects.equals(rightExpression, newRightExpression))
{
return this;
}
else
{
return LogicExpression.of(newLeftExpression, logicOperator, newRightExpression);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\LogicExpression.java | 1 |
请完成以下Java代码 | public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public org.compiere.model.I_M_DiscountSchema getM_DiscountSchema()
{
return get_ValueAsPO(COLUMNNAME_M_DiscountSchema_ID, org.compiere.model.I_M_DiscountSchema.class);
}
@Override
public void setM_DiscountSchema(final org.compiere.model.I_M_DiscountSchema M_DiscountSchema)
{
set_ValueFromPO(COLUMNNAME_M_DiscountSchema_ID, org.compiere.model.I_M_DiscountSchema.class, M_DiscountSchema);
}
@Override
public void setM_DiscountSchema_ID (final int M_DiscountSchema_ID)
{
if (M_DiscountSchema_ID < 1)
set_Value (COLUMNNAME_M_DiscountSchema_ID, null);
else
set_Value (COLUMNNAME_M_DiscountSchema_ID, M_DiscountSchema_ID);
}
@Override
public int getM_DiscountSchema_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_ID);
}
@Override
public void setM_PriceList_ID (final int M_PriceList_ID)
{
if (M_PriceList_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, M_PriceList_ID);
}
@Override
public int getM_PriceList_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_ID);
}
@Override
public void setM_Pricelist_Version_Base_ID (final int M_Pricelist_Version_Base_ID)
{
if (M_Pricelist_Version_Base_ID < 1)
set_Value (COLUMNNAME_M_Pricelist_Version_Base_ID, null);
else
set_Value (COLUMNNAME_M_Pricelist_Version_Base_ID, M_Pricelist_Version_Base_ID);
}
@Override
public int getM_Pricelist_Version_Base_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Pricelist_Version_Base_ID);
}
@Override
public void setM_PriceList_Version_ID (final int M_PriceList_Version_ID)
{
if (M_PriceList_Version_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PriceList_Version_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PriceList_Version_ID, M_PriceList_Version_ID);
}
@Override
public int getM_PriceList_Version_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_Version_ID);
}
@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 setProcCreate (final @Nullable java.lang.String ProcCreate)
{
set_Value (COLUMNNAME_ProcCreate, ProcCreate);
}
@Override
public java.lang.String getProcCreate()
{
return get_ValueAsString(COLUMNNAME_ProcCreate);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PriceList_Version.java | 1 |
请完成以下Java代码 | public static OptionalBoolean ofBoolean(final boolean value)
{
return value ? TRUE : FALSE;
}
@JsonCreator
public static OptionalBoolean ofNullableBoolean(@Nullable final Boolean value)
{
return value != null ? ofBoolean(value) : UNKNOWN;
}
public static OptionalBoolean ofNullableString(@Nullable final String value)
{
return ofNullableBoolean(StringUtils.toBooleanOrNull(value));
}
public boolean isTrue()
{
return this == TRUE;
}
public boolean isFalse()
{
return this == FALSE;
}
public boolean isPresent()
{
return this == TRUE || this == FALSE;
}
public boolean isUnknown()
{
return this == UNKNOWN;
}
public boolean orElseTrue() {return orElse(true);}
public boolean orElseFalse() {return orElse(false);}
public boolean orElse(final boolean other)
{
if (this == TRUE)
{
return true;
}
else if (this == FALSE)
{
return false;
}
else
{
return other;
}
}
@NonNull
public OptionalBoolean ifUnknown(@NonNull final OptionalBoolean other)
{
return isPresent() ? this : other;
}
@NonNull
public OptionalBoolean ifUnknown(@NonNull final Supplier<OptionalBoolean> otherSupplier)
{
return isPresent() ? this : otherSupplier.get();
}
@JsonValue
@Nullable
public Boolean toBooleanOrNull()
{
switch (this)
{
case TRUE:
return Boolean.TRUE;
case FALSE:
return Boolean.FALSE;
case UNKNOWN:
return null;
default: | throw new IllegalStateException("Type not handled: " + this);
}
}
@Nullable
public String toBooleanString()
{
return StringUtils.ofBoolean(toBooleanOrNull());
}
public void ifPresent(@NonNull final BooleanConsumer action)
{
if (this == TRUE)
{
action.accept(true);
}
else if (this == FALSE)
{
action.accept(false);
}
}
public void ifTrue(@NonNull final Runnable action)
{
if (this == TRUE)
{
action.run();
}
}
public <U> Optional<U> map(@NonNull final BooleanFunction<? extends U> mapper)
{
return isPresent() ? Optional.ofNullable(mapper.apply(isTrue())) : Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\OptionalBoolean.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProgressRequestBody extends RequestBody {
public interface ProgressRequestListener {
void onRequestProgress(long bytesWritten, long contentLength, boolean done);
}
private final RequestBody requestBody;
private final ProgressRequestListener progressListener;
public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) {
this.requestBody = requestBody;
this.progressListener = progressListener;
}
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() throws IOException {
return requestBody.contentLength();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSink bufferedSink = Okio.buffer(sink(sink));
requestBody.writeTo(bufferedSink); | bufferedSink.flush();
}
private Sink sink(Sink sink) {
return new ForwardingSink(sink) {
long bytesWritten = 0L;
long contentLength = 0L;
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
if (contentLength == 0) {
contentLength = contentLength();
}
bytesWritten += byteCount;
progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength);
}
};
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\ProgressRequestBody.java | 2 |
请完成以下Java代码 | public static RoleId ofRepoId(final int repoId)
{
final RoleId roleId = ofRepoIdOrNull(repoId);
return Check.assumeNotNull(roleId, "Unable to create a roleId for repoId={}", repoId);
}
public static RoleId ofRepoIdOrNull(final int repoId)
{
if (repoId == SYSTEM.getRepoId())
{
return SYSTEM;
}
else if (repoId == WEBUI.getRepoId())
{
return WEBUI;
}
else if (repoId == JSON_REPORTS.getRepoId())
{
return JSON_REPORTS;
}
else
{
return repoId > 0 ? new RoleId(repoId) : null;
}
}
public static int toRepoId(@Nullable final RoleId id)
{
return toRepoId(id, -1);
}
public static int toRepoId(@Nullable final RoleId id, final int defaultValue)
{
return id != null ? id.getRepoId() : defaultValue;
}
public static boolean equals(final RoleId id1, final RoleId id2)
{ | return Objects.equals(id1, id2);
}
int repoId;
private RoleId(final int repoId)
{
this.repoId = Check.assumeGreaterOrEqualToZero(repoId, "AD_Role_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public boolean isSystem() {return isSystem(repoId);}
public static boolean isSystem(final int repoId) {return repoId == SYSTEM.repoId;}
public boolean isRegular() {return isRegular(repoId);}
public static boolean isRegular(final int repoId) {return !isSystem(repoId);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\RoleId.java | 1 |
请完成以下Java代码 | public DocBaseType getDocBaseTypeById(@NonNull final DocTypeId docTypeId)
{
final I_C_DocType docTypeRecord = getById(docTypeId);
return DocBaseType.ofCode(docTypeRecord.getDocBaseType());
}
@NonNull
@Override
public DocBaseAndSubType getDocBaseAndSubTypeById(@NonNull final DocTypeId docTypeId)
{
final I_C_DocType docTypeRecord = getById(docTypeId);
return DocBaseAndSubType.of(docTypeRecord.getDocBaseType(), docTypeRecord.getDocSubType());
}
@NonNull
public ImmutableList<I_C_DocType> retrieveForSelection(@NonNull final PInstanceId pinstanceId)
{
return queryBL
.createQueryBuilder(I_C_DocType.class)
.setOnlySelection(pinstanceId)
.orderBy(I_C_DocType.COLUMNNAME_C_DocType_ID)
.create()
.listImmutable();
}
@EqualsAndHashCode
@ToString
private static class DocBaseTypeCountersMap
{
public static DocBaseTypeCountersMap ofMap(@NonNull final ImmutableMap<DocBaseType, DocBaseType> map)
{
return !map.isEmpty() | ? new DocBaseTypeCountersMap(map)
: EMPTY;
}
private static final DocBaseTypeCountersMap EMPTY = new DocBaseTypeCountersMap(ImmutableMap.of());
private final ImmutableMap<DocBaseType, DocBaseType> counterDocBaseTypeByDocBaseType;
private DocBaseTypeCountersMap(@NonNull final ImmutableMap<DocBaseType, DocBaseType> map)
{
this.counterDocBaseTypeByDocBaseType = map;
}
public Optional<DocBaseType> getCounterDocBaseTypeByDocBaseType(@NonNull final DocBaseType docBaseType)
{
return Optional.ofNullable(counterDocBaseTypeByDocBaseType.get(docBaseType));
}
}
@NonNull
private ImmutableSet<DocTypeId> retrieveDocTypeIdsByInvoicingPoolId(@NonNull final DocTypeInvoicingPoolId docTypeInvoicingPoolId)
{
return queryBL.createQueryBuilder(I_C_DocType.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_DocType.COLUMNNAME_C_DocType_Invoicing_Pool_ID, docTypeInvoicingPoolId)
.create()
.idsAsSet(DocTypeId::ofRepoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\impl\DocTypeDAO.java | 1 |
请完成以下Java代码 | public Builder addElement(final DocumentFieldDescriptor processParaDescriptor)
{
Check.assumeNotNull(processParaDescriptor, "Parameter processParaDescriptor is not null");
final DocumentLayoutElementDescriptor element = DocumentLayoutElementDescriptor.builder()
.setCaption(processParaDescriptor.getCaption())
.setDescription(processParaDescriptor.getDescription())
.setWidgetType(processParaDescriptor.getWidgetType())
.setAllowShowPassword(processParaDescriptor.isAllowShowPassword())
.barcodeScannerType(processParaDescriptor.getBarcodeScannerType())
.addField(DocumentLayoutElementFieldDescriptor.builder(processParaDescriptor.getFieldName())
.setLookupInfos(processParaDescriptor.getLookupDescriptor().orElse(null))
.setPublicField(true)
.setSupportZoomInto(processParaDescriptor.isSupportZoomInto()))
.build();
addElement(element); | return this;
}
public Builder addElements(@Nullable final DocumentEntityDescriptor parametersDescriptor)
{
if (parametersDescriptor != null)
{
parametersDescriptor.getFields().forEach(this::addElement);
}
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\descriptor\ProcessLayout.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getErrorUrl() {
return errorUrl;
}
public void setErrorUrl(String errorUrl) {
this.errorUrl = errorUrl;
}
/**
* 表示是否允许访问 ,如果允许访问返回true,否则false;
*
* @param servletRequest
* @param servletResponse
* @param o 表示写在拦截器中括号里面的字符串 mappedValue 就是 [urls] 配置中拦截器参数部分
* @return
* @throws Exception
*/
@Override
protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
Subject subject = getSubject(servletRequest, servletResponse);
String url = getPathWithinApplication(servletRequest);
log.info("当前用户正在访问的 url => " + url);
return subject.isPermitted(url);
} | /**
* onAccessDenied:表示当访问拒绝时是否已经处理了; 如果返回 true 表示需要继续处理; 如果返回 false
* 表示该拦截器实例已经处理了,将直接返回即可。
*
* @param servletRequest
* @param servletResponse
* @return
* @throws Exception
*/
@Override
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
log.info("当 isAccessAllowed 返回 false 的时候,才会执行 method onAccessDenied ");
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.sendRedirect(request.getContextPath() + this.errorUrl);
// 返回 false 表示已经处理,例如页面跳转啥的,表示不在走以下的拦截器了(如果还有配置的话)
return false;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\shiro\filters\ResourceCheckFilter.java | 2 |
请完成以下Java代码 | public class ReactiveSecurityDataFetcherExceptionResolver implements DataFetcherExceptionResolver {
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
/**
* Set the resolver to use to check if an authentication is anonymous that
* in turn determines whether {@code AccessDeniedException} is classified
* as "unauthorized" or "forbidden".
* @param trustResolver the resolver to use
*/
public void setAuthenticationTrustResolver(AuthenticationTrustResolver trustResolver) {
this.trustResolver = trustResolver;
}
@Override
public Mono<List<GraphQLError>> resolveException(Throwable ex, DataFetchingEnvironment environment) { | if (ex instanceof AuthenticationException) {
GraphQLError error = SecurityExceptionResolverUtils.resolveUnauthorized(environment);
return Mono.just(Collections.singletonList(error));
}
if (ex instanceof AccessDeniedException) {
return ReactiveSecurityContextHolder.getContext()
.map((context) -> Collections.singletonList(
SecurityExceptionResolverUtils.resolveAccessDenied(environment, this.trustResolver, context)))
.switchIfEmpty(Mono.fromCallable(() -> Collections.singletonList(
SecurityExceptionResolverUtils.resolveUnauthorized(environment))));
}
return Mono.empty();
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\ReactiveSecurityDataFetcherExceptionResolver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | ServerHttpSecurity httpSecurity() {
ContextAwareServerHttpSecurity http = new ContextAwareServerHttpSecurity();
// @formatter:off
return http.authenticationManager(authenticationManager())
.headers(withDefaults())
.logout(withDefaults());
// @formatter:on
}
private ReactiveAuthenticationManager authenticationManager() {
if (this.authenticationManager != null) {
return this.authenticationManager;
}
if (this.reactiveUserDetailsService != null) {
UserDetailsRepositoryReactiveAuthenticationManager manager = new UserDetailsRepositoryReactiveAuthenticationManager(
this.reactiveUserDetailsService);
if (this.passwordEncoder != null) {
manager.setPasswordEncoder(this.passwordEncoder);
}
manager.setUserDetailsPasswordService(this.userDetailsPasswordService); | manager.setCompromisedPasswordChecker(this.compromisedPasswordChecker);
return this.postProcessor.postProcess(manager);
}
return null;
}
private static class ContextAwareServerHttpSecurity extends ServerHttpSecurity implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
super.setApplicationContext(applicationContext);
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\reactive\ServerHttpSecurityConfiguration.java | 2 |
请完成以下Java代码 | public DmnDecision getDecision() {
return decision;
}
public void setDecision(DmnDecision decision) {
this.decision = decision;
}
public String getOutputName() {
return outputName;
}
public void setOutputName(String outputName) {
this.outputName = outputName;
}
public TypedValue getOutputValue() {
return outputValue;
}
public void setOutputValue(TypedValue outputValue) {
this.outputValue = outputValue;
}
public long getExecutedDecisionElements() {
return executedDecisionElements;
}
public void setExecutedDecisionElements(long executedDecisionElements) {
this.executedDecisionElements = executedDecisionElements;
} | @Override
public String toString() {
return "DmnDecisionLiteralExpressionEvaluationEventImpl [" +
" key="+ decision.getKey() +
", name="+ decision.getName() +
", decisionLogic=" + decision.getDecisionLogic() +
", outputName=" + outputName +
", outputValue=" + outputValue +
", executedDecisionElements=" + executedDecisionElements +
"]";
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\delegate\DmnDecisionLiteralExpressionEvaluationEventImpl.java | 1 |
请完成以下Java代码 | public class IOParameter extends BaseElement {
protected String source;
protected String sourceExpression;
protected String target;
protected String targetExpression;
protected boolean isTransient;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getSourceExpression() {
return sourceExpression;
}
public void setSourceExpression(String sourceExpression) {
this.sourceExpression = sourceExpression;
}
public String getTargetExpression() {
return targetExpression; | }
public void setTargetExpression(String targetExpression) {
this.targetExpression = targetExpression;
}
public boolean isTransient() {
return isTransient;
}
public void setTransient(boolean isTransient) {
this.isTransient = isTransient;
}
@Override
public IOParameter clone() {
IOParameter clone = new IOParameter();
clone.setValues(this);
return clone;
}
public void setValues(IOParameter otherElement) {
super.setValues(otherElement);
setSource(otherElement.getSource());
setSourceExpression(otherElement.getSourceExpression());
setTarget(otherElement.getTarget());
setTargetExpression(otherElement.getTargetExpression());
setTransient(otherElement.isTransient());
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\IOParameter.java | 1 |
请完成以下Java代码 | public class X_M_HazardSymbol extends org.compiere.model.PO implements I_M_HazardSymbol, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 147033401L;
/** Standard Constructor */
public X_M_HazardSymbol (final Properties ctx, final int M_HazardSymbol_ID, @Nullable final String trxName)
{
super (ctx, M_HazardSymbol_ID, trxName);
}
/** Load Constructor */
public X_M_HazardSymbol (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_AD_Image getAD_Image()
{
return get_ValueAsPO(COLUMNNAME_AD_Image_ID, org.compiere.model.I_AD_Image.class);
}
@Override
public void setAD_Image(final org.compiere.model.I_AD_Image AD_Image)
{
set_ValueFromPO(COLUMNNAME_AD_Image_ID, org.compiere.model.I_AD_Image.class, AD_Image);
}
@Override
public void setAD_Image_ID (final int AD_Image_ID)
{
if (AD_Image_ID < 1)
set_Value (COLUMNNAME_AD_Image_ID, null);
else
set_Value (COLUMNNAME_AD_Image_ID, AD_Image_ID);
}
@Override
public int getAD_Image_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Image_ID);
}
@Override
public void setM_HazardSymbol_ID (final int M_HazardSymbol_ID)
{
if (M_HazardSymbol_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, M_HazardSymbol_ID);
}
@Override | public int getM_HazardSymbol_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HazardSymbol_ID);
}
@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 setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_HazardSymbol.java | 1 |
请完成以下Java代码 | public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
@Override
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
@Override
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getLimitApp() {
return limitApp;
} | public void setLimitApp(String limitApp) {
this.limitApp = limitApp;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
@Override
public Rule toRule() {
ParamFlowRule rule = new ParamFlowRule();
return rule;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\ParamFlowRuleCorrectEntity.java | 1 |
请完成以下Java代码 | public class SuspendProcessDefinitionCmd extends AbstractSetProcessDefinitionStateCmd {
public SuspendProcessDefinitionCmd(UpdateProcessDefinitionSuspensionStateBuilderImpl builder) {
super(builder);
}
@Override
protected SuspensionState getNewSuspensionState() {
return SuspensionState.SUSPENDED;
}
@Override
protected String getDelayedExecutionJobHandlerType() {
return TimerSuspendProcessDefinitionHandler.TYPE;
}
@Override | protected AbstractSetJobDefinitionStateCmd getSetJobDefinitionStateCmd(UpdateJobDefinitionSuspensionStateBuilderImpl jobDefinitionSuspensionStateBuilder) {
return new SuspendJobDefinitionCmd(jobDefinitionSuspensionStateBuilder);
}
@Override
protected SuspendProcessInstanceCmd getNextCommand(UpdateProcessInstanceSuspensionStateBuilderImpl processInstanceCommandBuilder) {
return new SuspendProcessInstanceCmd(processInstanceCommandBuilder);
}
@Override
protected String getLogEntryOperation() {
return UserOperationLogEntry.OPERATION_TYPE_SUSPEND_PROCESS_DEFINITION;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SuspendProcessDefinitionCmd.java | 1 |
请完成以下Java代码 | public CacheIntrospectionException setMethod(final Method method)
{
this.method = method;
resetMessageBuilt();
return this;
}
public CacheIntrospectionException setParameter(final int parameterIndex, final Class<?> parameterType)
{
this.parameterIndex = parameterIndex;
this.parameterType = parameterType;
this.parameterSet = true;
resetMessageBuilt();
return this;
}
public CacheIntrospectionException addHintToFix(final String hintToFix)
{
if (Check.isEmpty(hintToFix, true))
{
return this;
}
if (this.hintsToFix == null)
{
this.hintsToFix = new HashSet<>();
}
this.hintsToFix.add(hintToFix);
resetMessageBuilt();
return this;
} | @Override
protected ITranslatableString buildMessage()
{
final TranslatableStringBuilder message = TranslatableStrings.builder();
message.append(super.buildMessage());
if (method != null)
{
message.append("\n Method: ").appendObj(method);
}
if (parameterSet)
{
message.append("\n Invalid parameter at index ").append(parameterIndex).append(": ").appendObj(parameterType);
}
if (!Check.isEmpty(hintsToFix))
{
for (final String hint : hintsToFix)
{
message.append("\n Hint to fix: ").append(hint);
}
}
return message.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CacheIntrospectionException.java | 1 |
请完成以下Java代码 | public void add(@NonNull final PurchaseCandidate purchaseCandidate)
{
final PurchaseCandidateAggregateKey purchaseCandidateAggKey = PurchaseCandidateAggregateKey.fromPurchaseCandidate(purchaseCandidate);
if (!aggregationKey.equals(purchaseCandidateAggKey))
{
throw new AdempiereException("" + purchaseCandidate + " does not have the expected aggregation key: " + aggregationKey);
}
purchaseCandidates.add(purchaseCandidate);
//
purchaseDatePromised = TimeUtil.min(purchaseDatePromised, purchaseCandidate.getPurchaseDatePromised());
final OrderAndLineId orderAndLineId = purchaseCandidate.getSalesOrderAndLineIdOrNull();
if (orderAndLineId != null)
{
salesOrderAndLineIds.add(orderAndLineId);
}
}
public OrgId getOrgId()
{
return aggregationKey.getOrgId();
}
public WarehouseId getWarehouseId()
{
return aggregationKey.getWarehouseId();
}
public ProductId getProductId()
{
return aggregationKey.getProductId();
}
public AttributeSetInstanceId getAttributeSetInstanceId()
{
return aggregationKey.getAttributeSetInstanceId();
}
public Quantity getQtyToDeliver()
{
return qtyToDeliver;
}
void setQtyToDeliver(final Quantity qtyToDeliver)
{
this.qtyToDeliver = qtyToDeliver;
}
public ZonedDateTime getDatePromised()
{
return purchaseDatePromised;
}
public List<PurchaseCandidateId> getPurchaseCandidateIds()
{
return purchaseCandidates | .stream()
.map(PurchaseCandidate::getId)
.collect(ImmutableList.toImmutableList());
}
public Set<OrderAndLineId> getSalesOrderAndLineIds()
{
return ImmutableSet.copyOf(salesOrderAndLineIds);
}
public void calculateAndSetQtyToDeliver()
{
if (purchaseCandidates.isEmpty())
{
return;
}
final Quantity qtyToPurchase = purchaseCandidates.get(0).getQtyToPurchase();
final Quantity sum = purchaseCandidates
.stream()
.map(PurchaseCandidate::getQtyToPurchase)
.reduce(qtyToPurchase.toZero(), Quantity::add);
setQtyToDeliver(sum);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\localorder\PurchaseCandidateAggregate.java | 1 |
请完成以下Java代码 | public void updateProcessInstanceLockTime(String processInstanceId) {
Date expirationTime = getClock().getCurrentTime();
int lockMillis = getAsyncExecutor().getAsyncJobLockTimeInMillis();
GregorianCalendar lockCal = new GregorianCalendar();
lockCal.setTime(expirationTime);
lockCal.add(Calendar.MILLISECOND, lockMillis);
Date lockDate = lockCal.getTime();
executionDataManager.updateProcessInstanceLockTime(processInstanceId, lockDate, expirationTime);
}
@Override
public void clearProcessInstanceLockTime(String processInstanceId) {
executionDataManager.clearProcessInstanceLockTime(processInstanceId);
}
@Override
public String updateProcessInstanceBusinessKey(ExecutionEntity executionEntity, String businessKey) {
if (executionEntity.isProcessInstanceType() && businessKey != null) {
executionEntity.setBusinessKey(businessKey);
getHistoryManager().updateProcessBusinessKeyInHistory(executionEntity);
if (getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_UPDATED, executionEntity)
); | }
return businessKey;
}
return null;
}
public ExecutionDataManager getExecutionDataManager() {
return executionDataManager;
}
public void setExecutionDataManager(ExecutionDataManager executionDataManager) {
this.executionDataManager = executionDataManager;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntityManagerImpl.java | 1 |
请完成以下Java代码 | static class VocabWordComparator implements Comparator<VocabWord>
{
@Override
public int compare(VocabWord o1, VocabWord o2)
{
return o2.cn - o1.cn;
}
}
void initUnigramTable(Corpus corpus)
{
final int vocabSize = corpus.getVocabSize();
final VocabWord[] vocab = corpus.getVocab();
long trainWordsPow = 0;
double d1, power = 0.75;
table = new int[TABLE_SIZE];
for (int i = 0; i < vocabSize; i++)
{
trainWordsPow += Math.pow(vocab[i].cn, power);
}
int i = 0;
d1 = Math.pow(vocab[i].cn, power) / (double) trainWordsPow;
for (int j = 0; j < TABLE_SIZE; j++)
{
table[j] = i;
if ((double) j / (double) TABLE_SIZE > d1)
{
i++;
d1 += Math.pow(vocab[i].cn, power) / (double) trainWordsPow;
}
if (i >= vocabSize)
i = vocabSize - 1;
}
}
void initNet(Corpus corpus)
{
final int layer1Size = config.getLayer1Size();
final int vocabSize = corpus.getVocabSize();
syn0 = posixMemAlign128(vocabSize * layer1Size);
if (config.useHierarchicalSoftmax())
{
syn1 = posixMemAlign128(vocabSize * layer1Size);
for (int i = 0; i < vocabSize; i++)
{
for (int j = 0; j < layer1Size; j++)
{
syn1[i * layer1Size + j] = 0;
}
}
}
if (config.getNegative() > 0) | {
syn1neg = posixMemAlign128(vocabSize * layer1Size);
for (int i = 0; i < vocabSize; i++)
{
for (int j = 0; j < layer1Size; j++)
{
syn1neg[i * layer1Size + j] = 0;
}
}
}
long nextRandom = 1;
for (int i = 0; i < vocabSize; i++)
{
for (int j = 0; j < layer1Size; j++)
{
nextRandom = nextRandom(nextRandom);
syn0[i * layer1Size + j] = (((nextRandom & 0xFFFF) / (double) 65536) - 0.5) / layer1Size;
}
}
corpus.createBinaryTree();
}
static double[] posixMemAlign128(int size)
{
final int surplus = size % 128;
if (surplus > 0)
{
int div = size / 128;
return new double[(div + 1) * 128];
}
return new double[size];
}
static long nextRandom(long nextRandom)
{
return nextRandom * 25214903917L + 11;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Word2VecTraining.java | 1 |
请完成以下Java代码 | public void setLevel(Integer level) {
this.level = level;
}
public Integer getProductCount() {
return productCount;
}
public void setProductCount(Integer productCount) {
this.productCount = productCount;
}
public String getProductUnit() {
return productUnit;
}
public void setProductUnit(String productUnit) {
this.productUnit = productUnit;
}
public Integer getNavStatus() {
return navStatus;
}
public void setNavStatus(Integer navStatus) {
this.navStatus = navStatus;
}
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) { | this.keywords = keywords;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", parentId=").append(parentId);
sb.append(", name=").append(name);
sb.append(", level=").append(level);
sb.append(", productCount=").append(productCount);
sb.append(", productUnit=").append(productUnit);
sb.append(", navStatus=").append(navStatus);
sb.append(", showStatus=").append(showStatus);
sb.append(", sort=").append(sort);
sb.append(", icon=").append(icon);
sb.append(", keywords=").append(keywords);
sb.append(", description=").append(description);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductCategory.java | 1 |
请完成以下Java代码 | ReadTsKvQueryResult findAllAsyncWithLimit(EntityId entityId, ReadTsKvQuery query) {
Integer keyId = keyDictionaryDao.getOrSaveKeyId(query.getKey());
List<TsKvEntity> tsKvEntities = tsKvRepository.findAllWithLimit(
entityId.getId(),
keyId,
query.getStartTs(),
query.getEndTs(),
PageRequest.ofSize(query.getLimit()).withSort(Direction.fromString(query.getOrder()), "ts"));
tsKvEntities.forEach(tsKvEntity -> tsKvEntity.setStrKey(query.getKey()));
List<TsKvEntry> tsKvEntries = DaoUtil.convertDataList(tsKvEntities);
long lastTs = tsKvEntries.stream().map(TsKvEntry::getTs).max(Long::compare).orElse(query.getStartTs());
return new ReadTsKvQueryResult(query.getId(), tsKvEntries, lastTs);
}
ListenableFuture<Optional<TsKvEntity>> findAndAggregateAsync(EntityId entityId, String key, long startTs, long endTs, long ts, Aggregation aggregation) {
return service.submit(() -> {
TsKvEntity entity = switchAggregation(entityId, key, startTs, endTs, aggregation);
if (entity != null && entity.isNotEmpty()) {
entity.setEntityId(entityId.getId());
entity.setStrKey(key);
entity.setTs(ts);
return Optional.of(entity);
} else {
return Optional.empty();
}
});
}
protected TsKvEntity switchAggregation(EntityId entityId, String key, long startTs, long endTs, Aggregation aggregation) {
var keyId = keyDictionaryDao.getOrSaveKeyId(key);
switch (aggregation) {
case AVG:
return tsKvRepository.findAvg(entityId.getId(), keyId, startTs, endTs); | case MAX:
var max = tsKvRepository.findNumericMax(entityId.getId(), keyId, startTs, endTs);
if (max.isNotEmpty()) {
return max;
} else {
return tsKvRepository.findStringMax(entityId.getId(), keyId, startTs, endTs);
}
case MIN:
var min = tsKvRepository.findNumericMin(entityId.getId(), keyId, startTs, endTs);
if (min.isNotEmpty()) {
return min;
} else {
return tsKvRepository.findStringMin(entityId.getId(), keyId, startTs, endTs);
}
case SUM:
return tsKvRepository.findSum(entityId.getId(), keyId, startTs, endTs);
case COUNT:
return tsKvRepository.findCount(entityId.getId(), keyId, startTs, endTs);
default:
throw new IllegalArgumentException("Not supported aggregation type: " + aggregation);
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\AbstractChunkedAggregationTimeseriesDao.java | 1 |
请完成以下Java代码 | private final boolean checkValid(final DocumentLayoutElementDescriptor.Builder elementBuilder)
{
if (elementBuilder.isConsumed())
{
logger.trace("Skip adding {} to {} because it's already consumed", elementBuilder, this);
return false;
}
if (elementBuilder.isEmpty())
{
logger.trace("Skip adding {} to {} because it's empty", elementBuilder, this);
return false;
}
return true;
}
private final boolean checkValid(final DocumentLayoutElementDescriptor element)
{
if (element.isEmpty())
{
logger.trace("Skip adding {} to {} because it does not have fields", element, this);
return false;
}
return true; | }
public Builder setInternalName(final String internalName)
{
this.internalName = internalName;
return this;
}
public Builder addElement(final DocumentLayoutElementDescriptor.Builder elementBuilder)
{
elementsBuilders.add(elementBuilder);
return this;
}
public boolean hasElements()
{
return !elementsBuilders.isEmpty();
}
public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders()
{
return elementsBuilders.stream();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementLineDescriptor.java | 1 |
请完成以下Java代码 | public SqlViewCustomizer getOrNull(
@NonNull final WindowId windowId,
@Nullable final ViewProfileId profileId)
{
if (ViewProfileId.isNull(profileId))
{
return null;
}
final ImmutableMap<ViewProfileId, SqlViewCustomizer> viewCustomizersByProfileId = map.get(windowId);
if (viewCustomizersByProfileId == null)
{
return null;
}
return viewCustomizersByProfileId.get(profileId);
}
public void forEachWindowIdAndProfileId(@NonNull final BiConsumer<WindowId, ViewProfileId> consumer)
{ | viewCustomizers.forEach(viewCustomizer -> consumer.accept(viewCustomizer.getWindowId(), viewCustomizer.getProfile().getProfileId()));
}
public ImmutableListMultimap<WindowId, ViewProfile> getViewProfilesIndexedByWindowId()
{
return viewCustomizers
.stream()
.collect(ImmutableListMultimap.toImmutableListMultimap(viewCustomizer -> viewCustomizer.getWindowId(), viewCustomizer -> viewCustomizer.getProfile()));
}
public List<ViewProfile> getViewProfilesByWindowId(WindowId windowId)
{
return viewProfilesByWindowId.get(windowId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewCustomizerMap.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDueDate() {
return dueDate;
}
public void setDueDate(String dueDate) {
this.dueDate = dueDate;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
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;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\interceptor\CreateHumanTaskBeforeContext.java | 1 |
请完成以下Java代码 | public void setLastSyncStatus (java.lang.String LastSyncStatus)
{
set_Value (COLUMNNAME_LastSyncStatus, LastSyncStatus);
}
/** Get Letzter Synchronisierungsstatus.
@return Letzter Synchronisierungsstatus */
@Override
public java.lang.String getLastSyncStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_LastSyncStatus);
}
/** Set MKTG_ContactPerson.
@param MKTG_ContactPerson_ID MKTG_ContactPerson */
@Override
public void setMKTG_ContactPerson_ID (int MKTG_ContactPerson_ID)
{
if (MKTG_ContactPerson_ID < 1)
set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, Integer.valueOf(MKTG_ContactPerson_ID));
}
/** Get MKTG_ContactPerson.
@return MKTG_ContactPerson */
@Override
public int getMKTG_ContactPerson_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.marketing.base.model.I_MKTG_Platform getMKTG_Platform() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_MKTG_Platform_ID, de.metas.marketing.base.model.I_MKTG_Platform.class);
}
@Override
public void setMKTG_Platform(de.metas.marketing.base.model.I_MKTG_Platform MKTG_Platform)
{
set_ValueFromPO(COLUMNNAME_MKTG_Platform_ID, de.metas.marketing.base.model.I_MKTG_Platform.class, MKTG_Platform);
}
/** Set MKTG_Platform.
@param MKTG_Platform_ID MKTG_Platform */
@Override
public void setMKTG_Platform_ID (int MKTG_Platform_ID)
{
if (MKTG_Platform_ID < 1) | set_Value (COLUMNNAME_MKTG_Platform_ID, null);
else
set_Value (COLUMNNAME_MKTG_Platform_ID, Integer.valueOf(MKTG_Platform_ID));
}
/** Get MKTG_Platform.
@return MKTG_Platform */
@Override
public int getMKTG_Platform_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Platform_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Externe Datensatz-ID.
@param RemoteRecordId Externe Datensatz-ID */
@Override
public void setRemoteRecordId (java.lang.String RemoteRecordId)
{
set_Value (COLUMNNAME_RemoteRecordId, RemoteRecordId);
}
/** Get Externe Datensatz-ID.
@return Externe Datensatz-ID */
@Override
public java.lang.String getRemoteRecordId ()
{
return (java.lang.String)get_Value(COLUMNNAME_RemoteRecordId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_ContactPerson.java | 1 |
请完成以下Java代码 | private static void fastutilMap() {
Int2BooleanMap int2BooleanMap = new Int2BooleanOpenHashMap();
int2BooleanMap.put(1, true);
int2BooleanMap.put(7, false);
int2BooleanMap.put(4, true);
boolean value = int2BooleanMap.get(1);
//Lambda style iteration
Int2BooleanMaps.fastForEach(int2BooleanMap, entry -> {
System.out.println(String.format("Key: %d, Value: %b",entry.getIntKey(),entry.getBooleanValue()));
});
//Iterator based loop
ObjectIterator<Int2BooleanMap.Entry> iterator = Int2BooleanMaps.fastIterator(int2BooleanMap);
while(iterator.hasNext()) {
Int2BooleanMap.Entry entry = iterator.next();
System.out.println(String.format("Key: %d, Value: %b",entry.getIntKey(),entry.getBooleanValue()));
} | }
private static void eclipseCollectionsMap() {
MutableIntIntMap mutableIntIntMap = IntIntMaps.mutable.empty();
mutableIntIntMap.addToValue(1, 1);
ImmutableIntIntMap immutableIntIntMap = IntIntMaps.immutable.empty();
MutableObjectDoubleMap<String> dObject = ObjectDoubleMaps.mutable.empty();
dObject.addToValue("price", 150.5);
dObject.addToValue("quality", 4.4);
dObject.addToValue("stability", 0.8);
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps-9\src\main\java\com\baeldung\map\primitives\PrimitiveMaps.java | 1 |
请完成以下Java代码 | public Builder issuedAt(Instant issuedAt) {
return claim(JwtClaimNames.IAT, issuedAt);
}
/**
* Sets the JWT ID {@code (jti)} claim, which provides a unique identifier for the
* JWT.
* @param jti the unique identifier for the JWT
* @return the {@link Builder}
*/
public Builder id(String jti) {
return claim(JwtClaimNames.JTI, jti);
}
/**
* Sets the claim.
* @param name the claim name
* @param value the claim value
* @return the {@link Builder}
*/
public Builder claim(String name, Object value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
this.claims.put(name, value);
return this;
}
/**
* A {@code Consumer} to be provided access to the claims allowing the ability to
* add, replace, or remove.
* @param claimsConsumer a {@code Consumer} of the claims
*/
public Builder claims(Consumer<Map<String, Object>> claimsConsumer) { | claimsConsumer.accept(this.claims);
return this;
}
/**
* Builds a new {@link JwtClaimsSet}.
* @return a {@link JwtClaimsSet}
*/
public JwtClaimsSet build() {
Assert.notEmpty(this.claims, "claims cannot be empty");
// The value of the 'iss' claim is a String or URL (StringOrURI).
// Attempt to convert to URL.
Object issuer = this.claims.get(JwtClaimNames.ISS);
if (issuer != null) {
URL convertedValue = ClaimConversionService.getSharedInstance().convert(issuer, URL.class);
if (convertedValue != null) {
this.claims.put(JwtClaimNames.ISS, convertedValue);
}
}
return new JwtClaimsSet(this.claims);
}
}
} | repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtClaimsSet.java | 1 |
请完成以下Java代码 | private ProcessPreconditionsResolution verifySelectedDocuments()
{
final DocumentIdsSelection selectedRowIds = getSelectedRootDocumentIds();
if (selectedRowIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
final long selectionSize = getSelectionSize(selectedRowIds);
if (selectionSize > MAX_ROWS_ALLOWED)
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_TOO_MANY_PACKAGEABLES_1P, MAX_ROWS_ALLOWED));
}
// Make sure that they all have the same C_BPartner and location.
if (selectionSize > 1)
{
final Set<Integer> bpartnerLocationIds = getView().streamByIds(selectedRowIds)
.flatMap(selectedRow -> selectedRow.getIncludedRows().stream())
.map(WEBUI_Picking_Launcher::getBPartnerLocationId)
.collect(Collectors.toSet());
if (bpartnerLocationIds.size() > 1)
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_DIVERGING_LOCATIONS));
}
}
return ProcessPreconditionsResolution.accept();
}
private static int getBPartnerLocationId(@NonNull final IViewRow row)
{
return row.getFieldValueAsInt(I_M_Packageable_V.COLUMNNAME_C_BPartner_Location_ID, -1);
}
private long getSelectionSize(final DocumentIdsSelection rowIds)
{
if (rowIds.isAll())
{
return getView().size();
}
else
{ | return rowIds.size();
}
}
private DocumentIdsSelection getSelectedRootDocumentIds()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isAll())
{
return selectedRowIds;
}
else if (selectedRowIds.isEmpty())
{
return selectedRowIds;
}
else
{
return selectedRowIds.stream().filter(DocumentId::isInt).collect(DocumentIdsSelection.toDocumentIdsSelection());
}
}
private Optional<ProductBarcodeFilterData> getProductBarcodeFilterData()
{
return PackageableFilterDescriptorProvider.extractProductBarcodeFilterData(getView());
}
private List<ShipmentScheduleId> getShipmentScheduleIds()
{
final DocumentIdsSelection selectedRowIds = getSelectedRootDocumentIds();
return getView().streamByIds(selectedRowIds)
.flatMap(selectedRow -> selectedRow.getIncludedRows().stream())
.map(IViewRow::getId)
.distinct()
.map(DocumentId::removeDocumentPrefixAndConvertToInt)
.map(ShipmentScheduleId::ofRepoIdOrNull)
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\process\WEBUI_Picking_Launcher.java | 1 |
请完成以下Java代码 | public class DocumentDTO {
private int id;
private String title;
private String text;
private List<String> comments;
private String author;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
} | public List<String> getComments() {
return comments;
}
public void setComments(List<String> comments) {
this.comments = comments;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
} | repos\tutorials-master\mapstruct\src\main\java\com\baeldung\unmappedproperties\dto\DocumentDTO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultTbTelemetryService implements TbTelemetryService {
private final TimeseriesService tsService;
private final AccessValidator accessValidator;
@Override
public ListenableFuture<List<TsKvEntry>> getTimeseries(EntityId entityId, List<String> keys, Long startTs, Long endTs, IntervalType intervalType,
Long interval, String timeZone, Integer limit, Aggregation agg, String orderBy,
Boolean useStrictDataTypes, SecurityUser currentUser) {
SettableFuture<List<TsKvEntry>> future = SettableFuture.create();
accessValidator.validate(currentUser, Operation.READ_TELEMETRY, entityId, new FutureCallback<>() {
@Override
public void onSuccess(ValidationResult validationResult) {
try {
AggregationParams params;
if (Aggregation.NONE.equals(agg)) {
params = AggregationParams.none();
} else if (intervalType == null || IntervalType.MILLISECONDS.equals(intervalType)) {
params = interval == 0L ? AggregationParams.none() : AggregationParams.milliseconds(agg, interval);
} else {
params = AggregationParams.calendar(agg, intervalType, timeZone);
}
List<ReadTsKvQuery> queries = keys.stream().map(key -> new BaseReadTsKvQuery(key, startTs, endTs, params, limit, orderBy)).collect(Collectors.toList());
Futures.addCallback(tsService.findAll(currentUser.getTenantId(), entityId, queries), new FutureCallback<>() {
@Override | public void onSuccess(List<TsKvEntry> result) {
future.set(result);
}
@Override
public void onFailure(Throwable t) {
future.setException(t);
}
}, MoreExecutors.directExecutor());
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable t) {
future.setException(t);
}
});
return future;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\telemetry\DefaultTbTelemetryService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class MainApplication {
private final BookstoreService bookstoreService;
public MainApplication(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
System.out.println("\nQuery entity history ...");
System.out.println("------------------------");
bookstoreService.queryEntityHistory();
System.out.println("\nRegister new author ..."); | System.out.println("-----------------------");
bookstoreService.registerAuthor();
Thread.sleep(5000);
System.out.println("\nUpdate an author ...");
System.out.println("--------------------");
bookstoreService.updateAuthor();
Thread.sleep(5000);
System.out.println("\nUpdate books of an author ...");
System.out.println("-----------------------------");
bookstoreService.updateBooks();
System.out.println("\nQuery entity history ...");
System.out.println("------------------------");
bookstoreService.queryEntityHistory();
};
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootEnvers\src\main\java\com\bookstore\MainApplication.java | 2 |
请完成以下Java代码 | private String getAsyncBatchDesc()
{
return asyncBatchDesc;
}
public ESRImportEnqueuer pinstanceId(@Nullable final PInstanceId pinstanceId)
{
this.pinstanceId = pinstanceId;
return this;
}
private PInstanceId getPinstanceId()
{
return pinstanceId;
}
public ESRImportEnqueuer fromDataSource(final ESRImportEnqueuerDataSource fromDataSource)
{
this.fromDataSource = fromDataSource;
return this;
}
@NonNull
private ESRImportEnqueuerDataSource getFromDataSource()
{
return fromDataSource;
}
public ESRImportEnqueuer loggable(@NonNull final ILoggable loggable)
{
this.loggable = loggable;
return this;
}
private void addLog(final String msg, final Object... msgParameters)
{
loggable.addLog(msg, msgParameters);
}
private static class ZipFileResource extends AbstractResource
{
private final byte[] data;
private final String filename;
@Builder
private ZipFileResource( | @NonNull final byte[] data,
@NonNull final String filename)
{
this.data = data;
this.filename = filename;
}
@Override
public String getFilename()
{
return filename;
}
@Override
public String getDescription()
{
return null;
}
@Override
public InputStream getInputStream()
{
return new ByteArrayInputStream(data);
}
public byte[] getData()
{
return data;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\dataimporter\ESRImportEnqueuer.java | 1 |
请完成以下Java代码 | public class PP_Order_BOMLine
{
private final IPPOrderBOMBL orderBOMBL = Services.get(IPPOrderBOMBL.class);
private final IUOMDAO uomDAO = Services.get(IUOMDAO.class);
/**
* Calculates and sets QtyRequired from QtyEntered and C_UOM_ID
*/
@CalloutMethod(columnNames = {
I_PP_Order_BOMLine.COLUMNNAME_M_Product_ID,
I_PP_Order_BOMLine.COLUMNNAME_QtyEntered,
I_PP_Order_BOMLine.COLUMNNAME_C_UOM_ID })
private void updateQtyRequired(final I_PP_Order_BOMLine bomLine)
{
final ProductId productId = ProductId.ofRepoIdOrNull(bomLine.getM_Product_ID());
if (productId == null) | {
return;
}
final UomId uomId = UomId.ofRepoIdOrNull(bomLine.getC_UOM_ID());
if (uomId == null)
{
return;
}
final I_C_UOM uom = uomDAO.getById(uomId);
final Quantity qtyEntered = Quantity.of(bomLine.getQtyEntered(), uom);
orderBOMBL.setQtyRequiredToIssueOrReceive(bomLine, qtyEntered);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\callout\PP_Order_BOMLine.java | 1 |
请完成以下Java代码 | private void logDependents(final IMigrationLoggerContext migrationCtx, final IMigrationLogger migrationLogger, final PO record)
{
final String tableName = InterfaceWrapperHelper.getModelTableName(record);
if (I_AD_Column.Table_Name.equals(tableName))
{
final I_AD_Column adColumn = InterfaceWrapperHelper.create(record, I_AD_Column.class);
final I_AD_Element adElement = adColumn.getAD_Element();
if (!Check.equals(adElement.getEntityType(), entityType))
{
adElement.setEntityType("D"); // do NOT save, NEVER save!
final PO adElementPO = InterfaceWrapperHelper.getPO(adElement);
final POInfo adElementPOInfo = adElementPO.getPOInfo();
migrationLogger.logMigration(migrationCtx, adElementPO, adElementPOInfo, X_AD_MigrationStep.ACTION_Insert);
}
}
else if (I_AD_Menu.Table_Name.equals(tableName))
{
final I_AD_Menu menu = InterfaceWrapperHelper.create(record, I_AD_Menu.class);
final POInfo poInfo = POInfo.getPOInfo(I_AD_TreeNodeMM.Table_Name);
for (final I_AD_TreeNodeMM nodeMM : retrieveADTreeNodeMM(menu))
{
final PO po = InterfaceWrapperHelper.getPO(nodeMM);
migrationLogger.logMigration(migrationCtx, po, poInfo, X_AD_MigrationStep.ACTION_Insert);
}
}
}
private List<I_AD_TreeNodeMM> retrieveADTreeNodeMM(final I_AD_Menu menu)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(menu);
final String trxName = InterfaceWrapperHelper.getTrxName(menu);
final StringBuilder whereClause = new StringBuilder();
final List<Object> params = new ArrayList<Object>();
whereClause.append(I_AD_TreeNodeMM.COLUMNNAME_Node_ID).append("=?");
params.add(menu.getAD_Menu_ID());
return new TypedSqlQuery<I_AD_TreeNodeMM>(ctx, I_AD_TreeNodeMM.class, whereClause.toString(), trxName) | .setParameters(params)
.list();
}
private Iterator<I_AD_Table> retrieveTablesWithEntityType()
{
final StringBuilder whereClause = new StringBuilder();
final List<Object> params = new ArrayList<Object>();
whereClause.append(" EXISTS (select 1 from AD_Column c where c.AD_Table_ID=AD_Table.AD_Table_ID and c.ColumnName=?)");
params.add("EntityType");
whereClause.append(" AND ").append(I_AD_Table.COLUMNNAME_IsView).append("=?");
params.add(false);
// whereClause.append(" AND ").append(I_AD_Table.COLUMNNAME_TableName).append("='AD_Menu'");
return new TypedSqlQuery<I_AD_Table>(getCtx(), I_AD_Table.class, whereClause.toString(), ITrx.TRXNAME_None)
.setParameters(params)
.setOrderBy(I_AD_Table.Table_Name)
.list(I_AD_Table.class)
.iterator();
}
private Iterator<PO> retrieveRecordsForEntityType(final I_AD_Table table, final String entityType)
{
final String whereClause = "EntityType=?";
final Iterator<PO> records = new Query(getCtx(), table.getTableName(), whereClause, ITrx.TRXNAME_None)
.setParameters(entityType)
.setOrderBy("Created")
.iterate(null, false);
return records;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\process\AD_Migration_CreateFromEntityType.java | 1 |
请完成以下Java代码 | public String[] sortingCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final CriteriaBuilder cb = session.getCriteriaBuilder();
final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
final Root<Item> root = cr.from(Item.class);
cr.select(root);
cr.orderBy(cb.asc(root.get("itemName")), cb.desc(root.get("itemPrice")));
// cr.addOrder(Order.asc("itemName"));
// cr.addOrder(Order.desc("itemPrice")).list();
Query<Item> query = session.createQuery(cr);
final List<Item> sortedItemsList = query.getResultList();
final String sortedItems[] = new String[sortedItemsList.size()];
for (int i = 0; i < sortedItemsList.size(); i++) {
sortedItems[i] = sortedItemsList.get(i)
.getItemName();
}
session.close();
return sortedItems;
}
// Set projections Row Count
public Long[] projectionRowCount() {
final Session session = HibernateUtil.getHibernateSession();
final CriteriaBuilder cb = session.getCriteriaBuilder();
final CriteriaQuery<Long> cr = cb.createQuery(Long.class);
final Root<Item> root = cr.from(Item.class);
cr.select(cb.count(root));
Query<Long> query = session.createQuery(cr);
final List<Long> itemProjected = query.getResultList();
// session.createCriteria(Item.class).setProjection(Projections.rowCount()).list(); | final Long projectedRowCount[] = new Long[itemProjected.size()];
for (int i = 0; i < itemProjected.size(); i++) {
projectedRowCount[i] = itemProjected.get(i);
}
session.close();
return projectedRowCount;
}
// Set projections average of itemPrice
public Double[] projectionAverage() {
final Session session = HibernateUtil.getHibernateSession();
final CriteriaBuilder cb = session.getCriteriaBuilder();
final CriteriaQuery<Double> cr = cb.createQuery(Double.class);
final Root<Item> root = cr.from(Item.class);
cr.select(cb.avg(root.get("itemPrice")));
Query<Double> query = session.createQuery(cr);
final List avgItemPriceList = query.getResultList();
// session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list();
final Double avgItemPrice[] = new Double[avgItemPriceList.size()];
for (int i = 0; i < avgItemPriceList.size(); i++) {
avgItemPrice[i] = (Double) avgItemPriceList.get(i);
}
session.close();
return avgItemPrice;
}
} | repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\criteria\view\ApplicationView.java | 1 |
请完成以下Java代码 | public static boolean isNonAlphanumeric(String str) {
// Pattern pattern = Pattern.compile("\\W"); //same as [^a-zA-Z0-9]+
// Pattern pattern = Pattern.compile("[^a-zA-Z0-9||\\s]+"); //ignores space
Matcher matcher = PATTERN_NON_ALPHNUM_USASCII.matcher(str);
return matcher.find();
}
/**
* Checks for non-alphanumeric characters from all language scripts
*
* @param input - String to check for special character
* @return true if special character found else false
*/
public static boolean containsNonAlphanumeric(String input) {
// Pattern pattern = Pattern.compile("[^\\p{Alnum}]", Pattern.UNICODE_CHARACTER_CLASS); //Binary properties
Matcher matcher = PATTERN_NON_ALPHNUM_ANYLANG.matcher(input);
return matcher.find();
} | /**
* checks for non-alphanumeric character. it returns true if it detects any character other than the
* specified script argument. example of script - Character.UnicodeScript.GEORGIAN.name()
*
* @param input - String to check for special character
* @param script - language script
* @return true if special character found else false
*/
public static boolean containsNonAlphanumeric(String input, String script) {
String regexScriptClass = "\\p{" + "Is" + script + "}";
Pattern pattern = Pattern.compile("[^" + regexScriptClass + "\\p{IsDigit}]"); //Binary properties
Matcher matcher = pattern.matcher(input);
return matcher.find();
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations-6\src\main\java\com\baeldung\nonalphanumeric\NonAlphaNumRegexChecker.java | 1 |
请完成以下Java代码 | public String getTaskDefinitionKey() {
return taskDefinitionKey;
}
public int getPriority() {
return priority;
}
public Date getDue() {
return due;
}
public String getParentTaskId() {
return parentTaskId;
}
public Date getFollowUp() {
return followUp;
}
public String getTenantId() {
return tenantId;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
/**
* Returns task State of history tasks
*/
public String getTaskState() { return taskState; } | public static HistoricTaskInstanceDto fromHistoricTaskInstance(HistoricTaskInstance taskInstance) {
HistoricTaskInstanceDto dto = new HistoricTaskInstanceDto();
dto.id = taskInstance.getId();
dto.processDefinitionKey = taskInstance.getProcessDefinitionKey();
dto.processDefinitionId = taskInstance.getProcessDefinitionId();
dto.processInstanceId = taskInstance.getProcessInstanceId();
dto.executionId = taskInstance.getExecutionId();
dto.caseDefinitionKey = taskInstance.getCaseDefinitionKey();
dto.caseDefinitionId = taskInstance.getCaseDefinitionId();
dto.caseInstanceId = taskInstance.getCaseInstanceId();
dto.caseExecutionId = taskInstance.getCaseExecutionId();
dto.activityInstanceId = taskInstance.getActivityInstanceId();
dto.name = taskInstance.getName();
dto.description = taskInstance.getDescription();
dto.deleteReason = taskInstance.getDeleteReason();
dto.owner = taskInstance.getOwner();
dto.assignee = taskInstance.getAssignee();
dto.startTime = taskInstance.getStartTime();
dto.endTime = taskInstance.getEndTime();
dto.duration = taskInstance.getDurationInMillis();
dto.taskDefinitionKey = taskInstance.getTaskDefinitionKey();
dto.priority = taskInstance.getPriority();
dto.due = taskInstance.getDueDate();
dto.parentTaskId = taskInstance.getParentTaskId();
dto.followUp = taskInstance.getFollowUpDate();
dto.tenantId = taskInstance.getTenantId();
dto.removalTime = taskInstance.getRemovalTime();
dto.rootProcessInstanceId = taskInstance.getRootProcessInstanceId();
dto.taskState = taskInstance.getTaskState();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricTaskInstanceDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setBankAccountQualifer(String value) {
this.bankAccountQualifer = value;
}
/**
* Gets the value of the bankName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBankName() {
return bankName;
}
/**
* Sets the value of the bankName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBankName(String value) {
this.bankName = value;
}
/**
* Gets the value of the bankCode property.
*
* @return
* possible object is
* {@link BankCodeCType }
*
*/
public BankCodeCType getBankCode() {
return bankCode;
}
/**
* Sets the value of the bankCode property.
*
* @param value
* allowed object is
* {@link BankCodeCType }
*
*/
public void setBankCode(BankCodeCType value) {
this.bankCode = value;
}
/**
* Gets the value of the bic property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBIC() {
return bic;
}
/**
* Sets the value of the bic property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBIC(String value) {
this.bic = value;
}
/** | * Gets the value of the bankAccountNr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBankAccountNr() {
return bankAccountNr;
}
/**
* Sets the value of the bankAccountNr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBankAccountNr(String value) {
this.bankAccountNr = value;
}
/**
* Gets the value of the iban property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIBAN() {
return iban;
}
/**
* Sets the value of the iban property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIBAN(String value) {
this.iban = value;
}
/**
* Gets the value of the bankAccountOwner property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBankAccountOwner() {
return bankAccountOwner;
}
/**
* Sets the value of the bankAccountOwner property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBankAccountOwner(String value) {
this.bankAccountOwner = value;
}
} | 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\AdditionalBankAccountType.java | 2 |
请完成以下Java代码 | public static void countSolution() {
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection(testCollectionName);
System.out.println(collection.countDocuments());
}
public static void main(String args[]) {
//
// Connect to cluster (default is localhost:27017)
//
setUp();
//
// Check the db existence using DB class's method
//
collectionExistsSolution();
//
// Check the db existence using the createCollection method of MongoDatabase class | //
createCollectionSolution();
//
// Check the db existence using the listCollectionNames method of MongoDatabase class
//
listCollectionNamesSolution();
//
// Check the db existence using the count method of MongoDatabase class
//
countSolution();
}
} | repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\collectionexistence\CollectionExistence.java | 1 |
请完成以下Java代码 | protected @Nullable Object[] getMethodArgumentValues(
DataFetchingEnvironment environment, Object... providedArgs) throws Exception {
MethodParameter[] parameters = getMethodParameters();
if (ObjectUtils.isEmpty(parameters)) {
return EMPTY_ARGS;
}
@Nullable Object[] args = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
MethodParameter parameter = parameters[i];
parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
args[i] = findProvidedArgument(parameter, providedArgs);
if (args[i] != null) {
continue;
}
if (!this.resolvers.supportsParameter(parameter)) {
throw new IllegalStateException(formatArgumentError(parameter, "No suitable resolver"));
} | try {
args[i] = this.resolvers.resolveArgument(parameter, environment);
}
catch (Exception ex) {
// Leave stack trace for later, exception may actually be resolved and handled...
if (logger.isDebugEnabled()) {
String exMsg = ex.getMessage();
if (exMsg != null && !exMsg.contains(parameter.getExecutable().toGenericString())) {
logger.debug(formatArgumentError(parameter, exMsg));
}
}
throw ex;
}
}
return args;
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\method\annotation\support\DataFetcherHandlerMethodSupport.java | 1 |
请完成以下Java代码 | public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) {
this.historicProcessInstanceQuery = historicProcessInstanceQuery;
}
public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
public Batch updateSuspensionStateAsync(ProcessEngine engine) {
int params = parameterCount(processInstanceIds, processInstanceQuery, historicProcessInstanceQuery);
if (params == 0) {
String message = "Either processInstanceIds, processInstanceQuery or historicProcessInstanceQuery should be set to update the suspension state.";
throw new InvalidRequestException(Status.BAD_REQUEST, message);
}
UpdateProcessInstancesSuspensionStateBuilder updateSuspensionStateBuilder = createUpdateSuspensionStateGroupBuilder(engine);
if (getSuspended()) {
return updateSuspensionStateBuilder.suspendAsync();
} else {
return updateSuspensionStateBuilder.activateAsync();
}
}
protected UpdateProcessInstancesSuspensionStateBuilder createUpdateSuspensionStateGroupBuilder(ProcessEngine engine) {
UpdateProcessInstanceSuspensionStateSelectBuilder selectBuilder = engine.getRuntimeService().updateProcessInstanceSuspensionState();
UpdateProcessInstancesSuspensionStateBuilder groupBuilder = null;
if (processInstanceIds != null) {
groupBuilder = selectBuilder.byProcessInstanceIds(processInstanceIds);
} | if (processInstanceQuery != null) {
if (groupBuilder == null) {
groupBuilder = selectBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine));
} else {
groupBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine));
}
}
if (historicProcessInstanceQuery != null) {
if (groupBuilder == null) {
groupBuilder = selectBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine));
} else {
groupBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine));
}
}
return groupBuilder;
}
protected int parameterCount(Object... o) {
int count = 0;
for (Object o1 : o) {
count += (o1 != null ? 1 : 0);
}
return count;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\ProcessInstanceSuspensionStateAsyncDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void signalEventReceived(@RequestBody SignalEventReceivedRequest signalRequest, HttpServletResponse response) {
if (signalRequest.getSignalName() == null) {
throw new FlowableIllegalArgumentException("signalName is required");
}
if (restApiInterceptor != null) {
restApiInterceptor.sendSignal(signalRequest);
}
Map<String, Object> signalVariables = null;
if (signalRequest.getVariables() != null) {
signalVariables = new HashMap<>();
for (RestVariable variable : signalRequest.getVariables()) {
if (variable.getName() == null) {
throw new FlowableIllegalArgumentException("Variable name is required.");
}
signalVariables.put(variable.getName(), restResponseFactory.getVariableValue(variable));
}
}
if (signalRequest.isAsync()) {
if (signalVariables != null) {
throw new FlowableIllegalArgumentException("Async signals cannot take variables as payload");
}
if (signalRequest.isCustomTenantSet()) { | runtimeService.signalEventReceivedAsyncWithTenantId(signalRequest.getSignalName(), signalRequest.getTenantId());
} else {
runtimeService.signalEventReceivedAsync(signalRequest.getSignalName());
}
response.setStatus(HttpStatus.ACCEPTED.value());
} else {
if (signalRequest.isCustomTenantSet()) {
runtimeService.signalEventReceivedWithTenantId(signalRequest.getSignalName(), signalVariables, signalRequest.getTenantId());
} else {
runtimeService.signalEventReceived(signalRequest.getSignalName(), signalVariables);
}
response.setStatus(HttpStatus.NO_CONTENT.value());
}
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\SignalResource.java | 2 |
请完成以下Java代码 | public void setAccepted(AcceptedType value) {
this.accepted = value;
}
/**
* Gets the value of the rejected property.
*
* @return
* possible object is
* {@link RejectedType }
*
*/
public RejectedType getRejected() {
return rejected;
}
/**
* Sets the value of the rejected property.
*
* @param value
* allowed object is
* {@link RejectedType }
*
*/
public void setRejected(RejectedType value) {
this.rejected = value; | }
/**
* Gets the value of the documents property.
*
* @return
* possible object is
* {@link DocumentsType }
*
*/
public DocumentsType getDocuments() {
return documents;
}
/**
* Sets the value of the documents property.
*
* @param value
* allowed object is
* {@link DocumentsType }
*
*/
public void setDocuments(DocumentsType value) {
this.documents = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\response\BodyType.java | 1 |
请完成以下Java代码 | public void onAfterChanged(final I_C_BPartner_Product bpartnerProduct)
{
final I_C_BPartner_Product bpartnerProductOld = InterfaceWrapperHelper.createOld(bpartnerProduct, I_C_BPartner_Product.class);
final boolean wasExcludedFromSale = isExcludedFromSaleToCustomer(bpartnerProductOld);
final boolean isExcludedFromSale = isExcludedFromSaleToCustomer(bpartnerProduct);
if (!wasExcludedFromSale && !isExcludedFromSale)
{
return;
}
final MSV3StockAvailabilityService stockAvailabilityService = getStockAvailabilityService();
final ProductId productId = ProductId.ofRepoId(bpartnerProduct.getM_Product_ID());
final BPartnerId newBPartnerId = BPartnerId.ofRepoIdOrNull(bpartnerProduct.getC_BPartner_ID());
final BPartnerId oldBPartnerId = BPartnerId.ofRepoIdOrNull(bpartnerProductOld.getC_BPartner_ID());
if (isExcludedFromSale)
{
runAfterCommit(() -> stockAvailabilityService.publishProductExcludeAddedOrChanged(productId, newBPartnerId, oldBPartnerId));
}
else
{
runAfterCommit(() -> stockAvailabilityService.publishProductExcludeDeleted(productId, newBPartnerId, oldBPartnerId));
}
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_DELETE)
public void onAfterDeleted(final I_C_BPartner_Product bpartnerProduct)
{
final I_C_BPartner_Product bpartnerProductOld = InterfaceWrapperHelper.createOld(bpartnerProduct, I_C_BPartner_Product.class);
final MSV3StockAvailabilityService stockAvailabilityService = getStockAvailabilityService();
final ProductId productId = ProductId.ofRepoId(bpartnerProduct.getM_Product_ID());
final BPartnerId newBPartnerId = BPartnerId.ofRepoIdOrNull(bpartnerProduct.getC_BPartner_ID());
final BPartnerId oldBPartnerId = BPartnerId.ofRepoIdOrNull(bpartnerProductOld.getC_BPartner_ID());
runAfterCommit(() -> stockAvailabilityService.publishProductExcludeDeleted(productId, newBPartnerId, oldBPartnerId));
} | private static boolean isExcludedFromSaleToCustomer(final I_C_BPartner_Product bpartnerProduct)
{
return bpartnerProduct.isActive() && bpartnerProduct.isExcludedFromSale();
}
private MSV3StockAvailabilityService getStockAvailabilityService()
{
return Adempiere.getBean(MSV3StockAvailabilityService.class);
}
private void runAfterCommit(@NonNull final Runnable runnable)
{
Services.get(ITrxManager.class)
.getCurrentTrxListenerManagerOrAutoCommit()
.newEventListener(TrxEventTiming.AFTER_COMMIT)
.registerHandlingMethod(trx -> runnable.run());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\interceptor\C_BPartner_Product.java | 1 |
请完成以下Java代码 | public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
@Override
public void setExternalSystem_Service_ID (final int ExternalSystem_Service_ID)
{
if (ExternalSystem_Service_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_ID, ExternalSystem_Service_ID);
}
@Override
public int getExternalSystem_Service_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Service_ID);
}
@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 setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Service.java | 1 |
请完成以下Java代码 | public class SocketServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port) {
try {
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String msg = in.readLine();
if (msg.contains("hi"))
out.println("hi");
else
out.println("didn't understand");
close(); | stop();
} catch (IOException e) {
}
}
private void close() throws IOException {
in.close();
out.close();
}
private void stop() throws IOException {
clientSocket.close();
serverSocket.close();
}
} | repos\tutorials-master\core-java-modules\core-java-exceptions\src\main\java\com\baeldung\exceptions\socketexception\SocketServer.java | 1 |
请完成以下Java代码 | private Mono<SerializableGraphQlRequest> readRequest(ServerRequest serverRequest) {
if (this.codecDelegate != null) {
ServerRequest.Headers headers = serverRequest.headers();
MediaType contentType;
try {
contentType = headers.contentType().orElse(MediaType.APPLICATION_OCTET_STREAM);
}
catch (InvalidMediaTypeException ex) {
throw new UnsupportedMediaTypeStatusException("Could not parse " +
"Content-Type [" + headers.firstHeader(HttpHeaders.CONTENT_TYPE) + "]: " + ex.getMessage());
}
return this.codecDelegate.decode(serverRequest.bodyToFlux(DataBuffer.class), contentType);
}
else {
return serverRequest.bodyToMono(SerializableGraphQlRequest.class)
.onErrorResume(
UnsupportedMediaTypeStatusException.class,
(ex) -> applyApplicationGraphQlFallback(ex, serverRequest));
}
}
private static Mono<SerializableGraphQlRequest> applyApplicationGraphQlFallback(
UnsupportedMediaTypeStatusException ex, ServerRequest request) {
String contentTypeHeader = request.headers().firstHeader(HttpHeaders.CONTENT_TYPE);
if (StringUtils.hasText(contentTypeHeader)) {
MediaType contentType = MediaType.parseMediaType(contentTypeHeader);
// Spec requires application/json but some clients still use application/graphql
return APPLICATION_GRAPHQL.includes(contentType) ? ServerRequest.from(request)
.headers((headers) -> headers.setContentType(MediaType.APPLICATION_JSON))
.body(request.bodyToFlux(DataBuffer.class))
.build()
.bodyToMono(SerializableGraphQlRequest.class)
.log() : Mono.error(ex);
}
return Mono.error(ex);
}
/**
* Prepare the {@link ServerResponse} for the given GraphQL response.
* @param request the current request
* @param response the GraphQL response
* @return the server response
*/
protected abstract Mono<ServerResponse> prepareResponse(ServerRequest request, WebGraphQlResponse response); | /**
* Encode the GraphQL response if custom codecs were provided, or return the result map.
* @param response the GraphQL response
* @return the encoded response or the result map
*/
protected Object encodeResponseIfNecessary(WebGraphQlResponse response) {
Map<String, Object> resultMap = response.toMap();
return (this.codecDelegate != null) ? encode(resultMap) : resultMap;
}
/**
* Encode the result map.
* <p>This method assumes that a {@link CodecConfigurer} has been provided.
* @param resultMap the result to encode
* @return the encoded result map
*/
protected DataBuffer encode(Map<String, Object> resultMap) {
Assert.state(this.codecDelegate != null, "CodecConfigurer was not provided");
return this.codecDelegate.encode(resultMap);
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\webflux\AbstractGraphQlHttpHandler.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} | public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getPictureUrl() {
return pictureUrl;
}
public void setPictureUrl(String pictureUrl) {
this.pictureUrl = pictureUrl;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\model\Product.java | 1 |
请在Spring Boot框架中完成以下Java代码 | RequestMatcher getRequestMatcher() {
return this.requestMatcher;
}
private static List<AuthenticationConverter> createDefaultAuthenticationConverters() {
List<AuthenticationConverter> authenticationConverters = new ArrayList<>();
authenticationConverters.add(new JwtClientAssertionAuthenticationConverter());
authenticationConverters.add(new ClientSecretBasicAuthenticationConverter());
authenticationConverters.add(new ClientSecretPostAuthenticationConverter());
authenticationConverters.add(new PublicClientAuthenticationConverter());
authenticationConverters.add(new X509ClientCertificateAuthenticationConverter());
return authenticationConverters;
}
private static List<AuthenticationProvider> createDefaultAuthenticationProviders(HttpSecurity httpSecurity) {
List<AuthenticationProvider> authenticationProviders = new ArrayList<>();
RegisteredClientRepository registeredClientRepository = OAuth2ConfigurerUtils
.getRegisteredClientRepository(httpSecurity);
OAuth2AuthorizationService authorizationService = OAuth2ConfigurerUtils.getAuthorizationService(httpSecurity); | JwtClientAssertionAuthenticationProvider jwtClientAssertionAuthenticationProvider = new JwtClientAssertionAuthenticationProvider(
registeredClientRepository, authorizationService);
authenticationProviders.add(jwtClientAssertionAuthenticationProvider);
X509ClientCertificateAuthenticationProvider x509ClientCertificateAuthenticationProvider = new X509ClientCertificateAuthenticationProvider(
registeredClientRepository, authorizationService);
authenticationProviders.add(x509ClientCertificateAuthenticationProvider);
ClientSecretAuthenticationProvider clientSecretAuthenticationProvider = new ClientSecretAuthenticationProvider(
registeredClientRepository, authorizationService);
PasswordEncoder passwordEncoder = OAuth2ConfigurerUtils.getOptionalBean(httpSecurity, PasswordEncoder.class);
if (passwordEncoder != null) {
clientSecretAuthenticationProvider.setPasswordEncoder(passwordEncoder);
}
authenticationProviders.add(clientSecretAuthenticationProvider);
PublicClientAuthenticationProvider publicClientAuthenticationProvider = new PublicClientAuthenticationProvider(
registeredClientRepository, authorizationService);
authenticationProviders.add(publicClientAuthenticationProvider);
return authenticationProviders;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\OAuth2ClientAuthenticationConfigurer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public HistoricTaskLogEntryQuery caseDefinitionId(String caseDefinitionId) {
this.scopeDefinitionId = caseDefinitionId;
this.scopeType = ScopeTypes.CMMN;
return this;
}
@Override
public HistoricTaskLogEntryQuery subScopeId(String subScopeId) {
this.subScopeId = subScopeId;
return this;
}
@Override
public HistoricTaskLogEntryQuery scopeType(String scopeType) {
this.scopeType = scopeType;
return this;
}
@Override
public HistoricTaskLogEntryQuery from(Date fromDate) {
this.fromDate = fromDate;
return this;
}
@Override
public HistoricTaskLogEntryQuery to(Date toDate) {
this.toDate = toDate;
return this;
}
@Override
public HistoricTaskLogEntryQuery tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
@Override
public HistoricTaskLogEntryQuery fromLogNumber(long fromLogNumber) {
this.fromLogNumber = fromLogNumber;
return this;
}
@Override
public HistoricTaskLogEntryQuery toLogNumber(long toLogNumber) {
this.toLogNumber = toLogNumber;
return this;
}
public String getTaskId() {
return taskId;
}
public String getType() {
return type;
}
public String getUserId() {
return userId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getScopeId() {
return scopeId;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public String getSubScopeId() {
return subScopeId;
}
public String getScopeType() {
return scopeType; | }
public Date getFromDate() {
return fromDate;
}
public Date getToDate() {
return toDate;
}
public String getTenantId() {
return tenantId;
}
public long getFromLogNumber() {
return fromLogNumber;
}
public long getToLogNumber() {
return toLogNumber;
}
@Override
public long executeCount(CommandContext commandContext) {
return taskServiceConfiguration.getHistoricTaskLogEntryEntityManager().findHistoricTaskLogEntriesCountByQueryCriteria(this);
}
@Override
public List<HistoricTaskLogEntry> executeList(CommandContext commandContext) {
return taskServiceConfiguration.getHistoricTaskLogEntryEntityManager().findHistoricTaskLogEntriesByQueryCriteria(this);
}
@Override
public HistoricTaskLogEntryQuery orderByLogNumber() {
orderBy(HistoricTaskLogEntryQueryProperty.LOG_NUMBER);
return this;
}
@Override
public HistoricTaskLogEntryQuery orderByTimeStamp() {
orderBy(HistoricTaskLogEntryQueryProperty.TIME_STAMP);
return this;
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\HistoricTaskLogEntryQueryImpl.java | 2 |
请完成以下Java代码 | public Optional<AsyncBatchId> extractAsyncBatchFromItem(final WorkpackagesOnCommitSchedulerTemplate<Object>.Collector collector, final Object item)
{
return asyncBatchBL.getAsyncBatchId(item);
}
};
static
{
SCHEDULER.setCreateOneWorkpackagePerAsyncBatch(true);
}
// services
private final transient IQueueDAO queueDAO = Services.get(IQueueDAO.class);
private final transient IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class);
private final transient IInvoiceCandidateHandlerBL invoiceCandidateHandlerBL = Services.get(IInvoiceCandidateHandlerBL.class);
@Override
public Result processWorkPackage(@NonNull final I_C_Queue_WorkPackage workpackage, final String localTrxName)
{
try (final IAutoCloseable ignored = invoiceCandBL.setUpdateProcessInProgress())
{
final List<Object> models = queueDAO.retrieveAllItemsSkipMissing(workpackage, Object.class);
for (final Object model : models)
{ | try (final MDCCloseable ignored1 = TableRecordMDC.putTableRecordReference(model))
{
final List<I_C_Invoice_Candidate> invoiceCandidates = invoiceCandidateHandlerBL.createMissingCandidatesFor(model);
Loggables.addLog("Created {} invoice candidate for {}", invoiceCandidates.size(), model);
}
}
}
catch (final LockFailedException e)
{
// One of the models could not be locked => postpone processing this workpackage
throw WorkpackageSkipRequestException.createWithThrowable("Skip processing because: " + e.getLocalizedMessage(), e);
}
return Result.SUCCESS;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\async\spi\impl\CreateMissingInvoiceCandidatesWorkpackageProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setKey(String key) {
this.key = key;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public List<FormField> getFields() {
return fields;
}
public void setFields(List<FormField> fields) {
this.fields = fields;
}
public List<FormOutcome> getOutcomes() { | return outcomes;
}
public void setOutcomes(List<FormOutcome> outcomes) {
this.outcomes = outcomes;
}
public String getOutcomeVariableName() {
return outcomeVariableName;
}
public void setOutcomeVariableName(String outcomeVariableName) {
this.outcomeVariableName = outcomeVariableName;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\FormModelResponse.java | 2 |
请完成以下Java代码 | default ConfigurationPropertySource withAliases(ConfigurationPropertyNameAliases aliases) {
return new AliasedConfigurationPropertySource(this, aliases);
}
/**
* Return a variant of this source that supports a prefix.
* @param prefix the prefix for properties in the source
* @return a {@link ConfigurationPropertySource} instance supporting a prefix
* @since 2.5.0
*/
default ConfigurationPropertySource withPrefix(@Nullable String prefix) {
return (StringUtils.hasText(prefix)) ? new PrefixedConfigurationPropertySource(this, prefix) : this;
}
/**
* Return the underlying source that is actually providing the properties.
* @return the underlying property source or {@code null}.
*/
default @Nullable Object getUnderlyingSource() {
return null;
} | /**
* Return a single new {@link ConfigurationPropertySource} adapted from the given
* Spring {@link PropertySource} or {@code null} if the source cannot be adapted.
* @param source the Spring property source to adapt
* @return an adapted source or {@code null} {@link SpringConfigurationPropertySource}
* @since 2.4.0
*/
static @Nullable ConfigurationPropertySource from(PropertySource<?> source) {
if (source instanceof ConfigurationPropertySourcesPropertySource) {
return null;
}
return SpringConfigurationPropertySource.from(source);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\ConfigurationPropertySource.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void softDeleteBook() {
Author author = authorRepository.findById(4L).get();
Book book = author.getBooks().get(0);
author.removeBook(book);
}
@Transactional
public void softDeleteAuthor() {
Author author = authorRepository.findById(1L).get();
authorRepository.delete(author);
}
@Transactional
public void restoreBook() {
bookRepository.restoreById(1L);
}
@Transactional
public void restoreAuthor() {
authorRepository.restoreById(1L);
bookRepository.restoreByAuthorId(1L);
}
public void displayAllExceptDeletedAuthors() {
List<Author> authors = authorRepository.findAll();
System.out.println("\nAll authors except deleted:");
authors.forEach(a -> System.out.println("Author name: " + a.getName()));
System.out.println();
}
public void displayAllIncludeDeletedAuthors() {
List<Author> authors = authorRepository.findAllIncludingDeleted();
System.out.println("\nAll authors including deleted:");
authors.forEach(a -> System.out.println("Author name: " + a.getName())); | System.out.println();
}
public void displayAllOnlyDeletedAuthors() {
List<Author> authors = authorRepository.findAllOnlyDeleted();
System.out.println("\nAll deleted authors:");
authors.forEach(a -> System.out.println("Author name: " + a.getName()));
System.out.println();
}
public void displayAllExceptDeletedBooks() {
List<Book> books = bookRepository.findAll();
System.out.println("\nAll books except deleted:");
books.forEach(b -> System.out.println("Book title: " + b.getTitle()));
System.out.println();
}
public void displayAllIncludeDeletedBooks() {
List<Book> books = bookRepository.findAllIncludingDeleted();
System.out.println("\nAll books including deleted:");
books.forEach(b -> System.out.println("Book title: " + b.getTitle()));
System.out.println();
}
public void displayAllOnlyDeletedBooks() {
List<Book> books = bookRepository.findAllOnlyDeleted();
System.out.println("\nAll deleted books:");
books.forEach(b -> System.out.println("Book title: " + b.getTitle()));
System.out.println();
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootSoftDeletes\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
} | public Double addBalance(Double amount) {
if (balance == null)
balance = 0.0;
return balance += amount;
}
public boolean hasFunds(Double amount) {
if (balance == null || amount == null) {
return false;
}
return (balance - amount) >= 0;
}
} | repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\exceptionhandling\data\Wallet.java | 1 |
请完成以下Java代码 | public boolean isAllowed(String uri, @Nullable Authentication authentication) {
return isAllowed(null, uri, null, authentication);
}
@Override
public boolean isAllowed(@Nullable String contextPath, String uri, @Nullable String method,
@Nullable Authentication authentication) {
FilterInvocation filterInvocation = new FilterInvocation(contextPath, uri, method, this.servletContext);
HttpServletRequest httpRequest = this.requestTransformer.transform(filterInvocation.getHttpRequest());
AuthorizationResult result = this.authorizationManager.authorize(() -> authentication, httpRequest);
return result == null || result.isGranted();
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
/**
* Set a {@link HttpServletRequestTransformer} to be used prior to passing to the
* {@link AuthorizationManager}.
* @param requestTransformer the {@link HttpServletRequestTransformer} to use.
*/
public void setRequestTransformer(HttpServletRequestTransformer requestTransformer) { | Assert.notNull(requestTransformer, "requestTransformer cannot be null");
this.requestTransformer = requestTransformer;
}
/**
* Used to transform the {@link HttpServletRequest} prior to passing it into the
* {@link AuthorizationManager}.
*/
public interface HttpServletRequestTransformer {
HttpServletRequestTransformer IDENTITY = (request) -> request;
/**
* Return the {@link HttpServletRequest} that is passed into the
* {@link AuthorizationManager}
* @param request the {@link HttpServletRequest} created by the
* {@link WebInvocationPrivilegeEvaluator}
* @return the {@link HttpServletRequest} that is passed into the
* {@link AuthorizationManager}
*/
HttpServletRequest transform(HttpServletRequest request);
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\AuthorizationManagerWebInvocationPrivilegeEvaluator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Map<String, Object> producerConfig() {
Map<String, Object> config = new HashMap<>();
config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
return config;
}
private ReceiverOptions<String, String> receiverOptions() {
Map<String, Object> consumerConfig = consumerConfig();
ReceiverOptions<String, String> receiverOptions = ReceiverOptions.create(consumerConfig);
return receiverOptions.subscription(Collections.singletonList("test-topic"));
}
private SenderOptions<String, String> senderOptions() { | Map<String, Object> producerConfig = producerConfig();
return SenderOptions.create(producerConfig);
}
@Bean
public ReactiveKafkaProducerTemplate<String, String> reactiveKafkaProducerTemplate() {
return new ReactiveKafkaProducerTemplate<>(senderOptions());
}
@Bean
public ReactiveKafkaConsumerTemplate<String, String> reactiveKafkaConsumerTemplate() {
return new ReactiveKafkaConsumerTemplate<>(receiverOptions());
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive-kafka\src\main\java\com\baeldung\config\KafkaConfig.java | 2 |
请完成以下Java代码 | public void paint (Graphics2D g2D, int pageNo, Point2D pageStart,
Properties ctx, boolean isView)
{
if (m_item == null)
return;
//
g2D.setColor(m_color);
BasicStroke s = new BasicStroke(m_item.getLineWidth());
g2D.setStroke(s);
//
Point2D.Double location = getAbsoluteLocation(pageStart);
int x = (int)location.x;
int y = (int)location.y;
int width = m_item.getMaxWidth();
int height = m_item.getMaxHeight();
if (m_item.getPrintFormatType().equals(MPrintFormatItem.PRINTFORMATTYPE_Line))
g2D.drawLine(x, y, x+width, y+height);
else
{
String type = m_item.getShapeType();
if (type == null)
type = "";
if (m_item.isFilledRectangle())
{ | if (type.equals(MPrintFormatItem.SHAPETYPE_3DRectangle))
g2D.fill3DRect(x, y, width, height, true);
else if (type.equals(MPrintFormatItem.SHAPETYPE_Oval))
g2D.fillOval(x, y, width, height);
else if (type.equals(MPrintFormatItem.SHAPETYPE_RoundRectangle))
g2D.fillRoundRect(x, y, width, height, m_item.getArcDiameter(), m_item.getArcDiameter());
else
g2D.fillRect(x, y, width, height);
}
else
{
if (type.equals(MPrintFormatItem.SHAPETYPE_3DRectangle))
g2D.draw3DRect(x, y, width, height, true);
else if (type.equals(MPrintFormatItem.SHAPETYPE_Oval))
g2D.drawOval(x, y, width, height);
else if (type.equals(MPrintFormatItem.SHAPETYPE_RoundRectangle))
g2D.drawRoundRect(x, y, width, height, m_item.getArcDiameter(), m_item.getArcDiameter());
else
g2D.drawRect(x, y, width, height);
}
}
} // paint
} // BoxElement | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\BoxElement.java | 1 |
请完成以下Java代码 | Optional<AttributeConfig> findMatchingAttributeConfig(
final int orgId,
final I_M_Attribute m_Attribute)
{
final ImmutableList<AttributeConfig> attributeConfigs = getAttributeConfigs();
final Comparator<AttributeConfig> orgComparator = Comparator
.comparing(AttributeConfig::getOrgId)
.reversed();
final Optional<AttributeConfig> matchingConfigIfPresent = attributeConfigs
.stream()
.filter(c -> AttributeId.toRepoId(c.getAttributeId()) == m_Attribute.getM_Attribute_ID())
.sorted(orgComparator)
.findFirst();
final Optional<AttributeConfig> wildCardConfigIfPresent = attributeConfigs
.stream()
.filter(c -> c.getAttributeId() == null)
.sorted(orgComparator)
.findFirst();
final Optional<AttributeConfig> attributeConfigIfPresent = //
Stream.of(matchingConfigIfPresent, wildCardConfigIfPresent)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
return attributeConfigIfPresent;
} | /**
* Visible so that we can stub out the cache in tests.
*/
@VisibleForTesting
ImmutableList<AttributeConfig> getAttributeConfigs()
{
final ImmutableList<AttributeConfig> attributeConfigs = //
cache.getOrLoad(M_IolCandHandler_ID, () -> loadAttributeConfigs(M_IolCandHandler_ID));
return attributeConfigs;
}
public static <T extends ShipmentScheduleHandler> T createNewInstance(@NonNull final Class<T> handlerClass)
{
try
{
final T handler = handlerClass.newInstance();
return handler;
}
catch (InstantiationException | IllegalAccessException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\ShipmentScheduleHandler.java | 1 |
请完成以下Java代码 | private int getFallbackPreparationDateOffsetInHours() {return sysConfigBL.getIntValue(SYSCONFIG_Fallback_PreparationDate_Offset_Hours, 0);}
@VisibleForTesting
static ZonedDateTime computePreparationTime(final ZonedDateTime preparationTimeBase, final int offsetInHours)
{
ZonedDateTime preparationTime;
if (offsetInHours == 0)
{
preparationTime = preparationTimeBase;
}
else
{
final boolean add = offsetInHours >= 0;
int offset = Math.abs(offsetInHours);
TemporalUnit unit = ChronoUnit.HOURS; | // Avoid daylight saving errors in case we have to offset entire days
if (offset % 24 == 0)
{
offset /= 24;
unit = ChronoUnit.DAYS;
}
preparationTime = add
? preparationTimeBase.plus(offset, unit)
: preparationTimeBase.minus(offset, unit);
}
return preparationTime;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\OrderDeliveryDayBL.java | 1 |
请完成以下Java代码 | public Set<Entry<String, ClassLoaderFile>> getFilesEntrySet() {
return this.files.entrySet();
}
protected final void add(String name, ClassLoaderFile file) {
this.files.put(name, file);
}
protected final void remove(String name) {
this.files.remove(name);
}
protected final @Nullable ClassLoaderFile get(String name) {
return this.files.get(name);
}
/**
* Return the name of the source directory.
* @return the name of the source directory
*/ | public String getName() {
return this.name;
}
/**
* Return all {@link ClassLoaderFile ClassLoaderFiles} in the collection that are
* contained in this source directory.
* @return the files contained in the source directory
*/
public Collection<ClassLoaderFile> getFiles() {
return Collections.unmodifiableCollection(this.files.values());
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\classloader\ClassLoaderFiles.java | 1 |
请完成以下Java代码 | public class BpmPlatformRootDefinition extends PersistentResourceDefinition {
public static final BpmPlatformRootDefinition INSTANCE = new BpmPlatformRootDefinition();
private BpmPlatformRootDefinition() {
super(new Parameters(BpmPlatformExtension.SUBSYSTEM_PATH,
BpmPlatformExtension.getResourceDescriptionResolver())
.setAddHandler(BpmPlatformSubsystemAdd.INSTANCE)
.setRemoveHandler(BpmPlatformSubsystemRemove.INSTANCE));
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return Collections.emptyList();
} | @Override
protected List<? extends PersistentResourceDefinition> getChildren() {
List<PersistentResourceDefinition> children = new ArrayList<>();
children.add(JobExecutorDefinition.INSTANCE);
children.add(ProcessEngineDefinition.INSTANCE);
return children;
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
super.registerOperations(resourceRegistration);
resourceRegistration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\extension\resource\BpmPlatformRootDefinition.java | 1 |
请完成以下Java代码 | public void setM_HU_PI_Item(final de.metas.handlingunits.model.I_M_HU_PI_Item M_HU_PI_Item)
{
set_ValueFromPO(COLUMNNAME_M_HU_PI_Item_ID, de.metas.handlingunits.model.I_M_HU_PI_Item.class, M_HU_PI_Item);
}
@Override
public void setM_HU_PI_Item_ID (final int M_HU_PI_Item_ID)
{
if (M_HU_PI_Item_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, M_HU_PI_Item_ID);
}
@Override
public int getM_HU_PI_Item_ID()
{ | return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_ID);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class EnableTransactionManagementConfiguration {
@Configuration(proxyBeanMethods = false)
@EnableTransactionManagement(proxyTargetClass = false)
@ConditionalOnBooleanProperty(name = "spring.aop.proxy-target-class", havingValue = false)
static class JdkDynamicAutoProxyConfiguration {
}
@Configuration(proxyBeanMethods = false)
@EnableTransactionManagement(proxyTargetClass = true)
@ConditionalOnBooleanProperty(name = "spring.aop.proxy-target-class", matchIfMissing = true)
static class CglibAutoProxyConfiguration {
} | }
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(AbstractTransactionAspect.class)
static class AspectJTransactionManagementConfiguration {
@Bean
static LazyInitializationExcludeFilter eagerTransactionAspect() {
return LazyInitializationExcludeFilter.forBeanTypes(AbstractTransactionAspect.class);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-transaction\src\main\java\org\springframework\boot\transaction\autoconfigure\TransactionAutoConfiguration.java | 2 |
请完成以下Java代码 | public void setPayDate (java.sql.Timestamp PayDate)
{
set_Value (COLUMNNAME_PayDate, PayDate);
}
/** Get Zahldatum.
@return Date Payment made
*/
@Override
public java.sql.Timestamp getPayDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PayDate);
}
/** Set PaySelection_includedTab.
@param PaySelection_includedTab PaySelection_includedTab */
@Override
public void setPaySelection_includedTab (java.lang.String PaySelection_includedTab)
{
set_Value (COLUMNNAME_PaySelection_includedTab, PaySelection_includedTab);
}
/** Get PaySelection_includedTab.
@return PaySelection_includedTab */
@Override
public java.lang.String getPaySelection_includedTab ()
{
return (java.lang.String)get_Value(COLUMNNAME_PaySelection_includedTab);
}
/**
* PaySelectionTrxType AD_Reference_ID=541109
* Reference name: PaySelectionTrxType
*/
public static final int PAYSELECTIONTRXTYPE_AD_Reference_ID=541109;
/** Direct Debit = DD */
public static final String PAYSELECTIONTRXTYPE_DirectDebit = "DD";
/** Credit Transfer = CT */
public static final String PAYSELECTIONTRXTYPE_CreditTransfer = "CT";
/** Set Transaktionsart.
@param PaySelectionTrxType Transaktionsart */
@Override
public void setPaySelectionTrxType (java.lang.String PaySelectionTrxType)
{
set_Value (COLUMNNAME_PaySelectionTrxType, PaySelectionTrxType);
}
/** Get Transaktionsart.
@return Transaktionsart */
@Override
public java.lang.String getPaySelectionTrxType ()
{ | return (java.lang.String)get_Value(COLUMNNAME_PaySelectionTrxType);
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Datensatz verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Datensatz verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Gesamtbetrag.
@param TotalAmt Gesamtbetrag */
@Override
public void setTotalAmt (java.math.BigDecimal TotalAmt)
{
set_Value (COLUMNNAME_TotalAmt, TotalAmt);
}
/** Get Gesamtbetrag.
@return Gesamtbetrag */
@Override
public java.math.BigDecimal getTotalAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaySelection.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SpringContextUtils implements ApplicationContextAware {
/**
* 上下文对象实例
*/
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtils.applicationContext = applicationContext;
}
/**
* 获取applicationContext
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取HttpServletRequest
*/
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
/**
* 获取HttpServletResponse
*/
public static HttpServletResponse getHttpServletResponse() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
}
/**
* 获取项目根路径 basePath
*/
public static String getDomain(){
HttpServletRequest request = getHttpServletRequest();
StringBuffer url = request.getRequestURL();
//1.微服务情况下,获取gateway的basePath
String basePath = request.getHeader(ServiceNameConstants.X_GATEWAY_BASE_PATH);
if(oConvertUtils.isNotEmpty(basePath)){
return basePath;
}else{
String domain = url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
//2.【兼容】SSL认证之后,request.getScheme()获取不到https的问题
// https://blog.csdn.net/weixin_34376986/article/details/89767950
String scheme = request.getHeader(CommonConstant.X_FORWARDED_SCHEME);
if(scheme!=null && !request.getScheme().equals(scheme)){
domain = domain.replace(request.getScheme(),scheme);
}
return domain;
}
} | public static String getOrigin(){
HttpServletRequest request = getHttpServletRequest();
return request.getHeader("Origin");
}
/**
* 通过name获取 Bean.
*
* @param name
* @return
*/
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
/**
* 通过class获取Bean.
*
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
/**
* 通过name,以及Clazz返回指定的Bean
*
* @param name
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\SpringContextUtils.java | 2 |
请完成以下Java代码 | public boolean isTarget()
{
return getMeasureTarget().signum() != 0;
} // isTarget
/**
* String Representation
*
* @return info
*/
@Override
public String toString()
{
StringBuffer sb = new StringBuffer("MGoal[");
sb.append(get_ID())
.append("-").append(getName())
.append(",").append(getGoalPerformance())
.append("]");
return sb.toString();
} // toString
/**
* Before Save
*
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave(boolean newRecord)
{
// if (getMultiplier(this) == null) // error
// setMeasureDisplay(getMeasureScope());
// Measure required if nor Summary
if (!isSummary() && getPA_Measure_ID() == 0)
{
throw new FillMandatoryException("PA_Measure_ID");
}
if (isSummary() && getPA_Measure_ID() != 0)
setPA_Measure_ID(0);
// User/Role Check
if ((newRecord || is_ValueChanged("AD_User_ID") || is_ValueChanged("AD_Role_ID"))
&& getAD_User_ID() != 0)
{
final List<IUserRolePermissions> roles = Services.get(IUserRolePermissionsDAO.class)
.retrieveUserRolesPermissionsForUserWithOrgAccess(
ClientId.ofRepoId(getAD_Client_ID()),
OrgId.ofRepoId(getAD_Org_ID()),
UserId.ofRepoId(getAD_User_ID()),
Env.getLocalDate());
if (roles.isEmpty()) // No Role
{
setAD_Role_ID(0);
}
else if (roles.size() == 1) // One
{
setAD_Role_ID(roles.get(0).getRoleId().getRepoId());
}
else
{
int AD_Role_ID = getAD_Role_ID();
if (AD_Role_ID != 0) // validate
{
boolean found = false;
for (IUserRolePermissions role : roles)
{
if (AD_Role_ID == role.getRoleId().getRepoId())
{
found = true;
break;
}
}
if (!found) | AD_Role_ID = 0;
}
if (AD_Role_ID == 0) // set to first one
setAD_Role_ID(roles.get(0).getRoleId().getRepoId());
} // multiple roles
} // user check
return true;
} // beforeSave
/**
* After Save
*
* @param newRecord new
* @param success success
* @return true
*/
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
if (!success)
return success;
// Update Goal if Target / Scope Changed
if (newRecord
|| is_ValueChanged("MeasureTarget")
|| is_ValueChanged("MeasureScope"))
updateGoal(true);
return success;
}
} // MGoal | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MGoal.java | 1 |
请完成以下Java代码 | public void setIsSameCurrency (boolean IsSameCurrency)
{
set_Value (COLUMNNAME_IsSameCurrency, Boolean.valueOf(IsSameCurrency));
}
/** Get Same Currency.
@return Same Currency */
public boolean isSameCurrency ()
{
Object oo = get_Value(COLUMNNAME_IsSameCurrency);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Same Tax.
@param IsSameTax
Use the same tax as the main transaction
*/
public void setIsSameTax (boolean IsSameTax)
{
set_Value (COLUMNNAME_IsSameTax, Boolean.valueOf(IsSameTax));
}
/** Get Same Tax.
@return Use the same tax as the main transaction
*/
public boolean isSameTax ()
{
Object oo = get_Value(COLUMNNAME_IsSameTax);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Price includes Tax.
@param IsTaxIncluded
Tax is included in the price
*/
public void setIsTaxIncluded (boolean IsTaxIncluded)
{
set_Value (COLUMNNAME_IsTaxIncluded, Boolean.valueOf(IsTaxIncluded));
}
/** Get Price includes Tax.
@return Tax is included in the price
*/
public boolean isTaxIncluded () | {
Object oo = get_Value(COLUMNNAME_IsTaxIncluded);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Charge.java | 1 |
请完成以下Java代码 | public class AccessorComparator<OT, IT> implements Comparator<OT>
{
private final Comparator<IT> cmp;
private final TypedAccessor<IT> accessor;
/**
*
* @param cmp comparator to be used for comparing inner type values
* @param accessor accessor which will get the inner type from a given outer type object
*/
public AccessorComparator(
@NonNull final Comparator<IT> cmp,
@NonNull final TypedAccessor<IT> accessor)
{
this.cmp = cmp;
this.accessor = accessor;
}
@Override
public int compare(OT o1, OT o2)
{
if (o1 == o2)
{
return 0; | }
if (o1 == null)
{
return +1;
}
if (o2 == null)
{
return -1;
}
final IT value1 = accessor.getValue(o1);
final IT value2 = accessor.getValue(o2);
return cmp.compare(value1, value2);
}
@Override
public String toString()
{
return "AccessorComparator [cmp=" + cmp + ", accessor=" + accessor + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\comparator\AccessorComparator.java | 1 |
请完成以下Java代码 | public class UserWrapper<T> {
@JsonProperty("user")
T content;
@NoArgsConstructor
public static class UserViewWrapper extends UserWrapper<UserView> {
public UserViewWrapper(UserView userView) {
super(userView);
}
}
@NoArgsConstructor
public static class UserRegistrationRequestWrapper extends UserWrapper<UserRegistrationRequest> {
public UserRegistrationRequestWrapper(UserRegistrationRequest user) {
super(user);
} | }
@NoArgsConstructor
public static class UserAuthenticationRequestWrapper extends UserWrapper<UserAuthenticationRequest> {
public UserAuthenticationRequestWrapper(UserAuthenticationRequest user) {
super(user);
}
}
@NoArgsConstructor
public static class UpdateUserRequestWrapper extends UserWrapper<UpdateUserRequest> {
public UpdateUserRequestWrapper(UpdateUserRequest user) {
super(user);
}
}
} | repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\api\wrappers\UserWrapper.java | 1 |
请完成以下Java代码 | void setCapacity(int capacity)
{
Capacity = capacity;
}
int getCapacity()
{
return Capacity;
}
void setLoad(int load)
{
Load = load;
}
int getLoad()
{
return Load;
}
int getDifference()
{
return Capacity - Load;
}
void setSummary(int summary)
{
Summary = summary;
}
int getSummary()
{
return Summary;
}
void setFrom(String from) | {
From = from;
}
String getFrom()
{
return From;
}
void setTo(String to)
{
To = to;
}
String getTo()
{
return To;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\CRPSummary.java | 1 |
请完成以下Java代码 | public void checkRenewal(String token) {
// 判断是否续期token,计算token的过期时间
String loginKey = loginKey(token);
long time = redisUtils.getExpire(loginKey) * 1000;
Date expireDate = DateUtil.offset(new Date(), DateField.MILLISECOND, (int) time);
// 判断当前时间与过期时间的时间差
long differ = expireDate.getTime() - System.currentTimeMillis();
// 如果在续期检查的范围内,则续期
if (differ <= properties.getDetect()) {
long renew = time + properties.getRenew();
redisUtils.expire(loginKey, renew, TimeUnit.MILLISECONDS);
}
}
public String getToken(HttpServletRequest request) {
final String requestHeader = request.getHeader(properties.getHeader());
if (requestHeader != null && requestHeader.startsWith(properties.getTokenStartWith())) {
return requestHeader.substring(7);
}
return null;
}
/**
* 获取登录用户RedisKey
* @param token / | * @return key
*/
public String loginKey(String token) {
Claims claims = getClaims(token);
return properties.getOnlineKey() + claims.getSubject() + ":" + getId(token);
}
/**
* 获取登录用户TokenKey
* @param token /
* @return /
*/
public String getId(String token) {
Claims claims = getClaims(token);
return claims.get(AUTHORITIES_UUID_KEY).toString();
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\security\security\TokenProvider.java | 1 |
请完成以下Java代码 | public ImmutableMap<ProductId, String> getProductValues(final ImmutableSet<ProductId> productIds)
{
return productsService.getProductValues(productIds);
}
@NonNull
public String getProductValue(@NonNull final ProductId productId)
{
return productsService.getProductValue(productId);
}
// TODO move this method to de.metas.bpartner.service.IBPartnerDAO since it has nothing to do with price list
// TODO: IdentifierString must also be moved to the module containing IBPartnerDAO
public Optional<BPartnerId> getBPartnerId(final IdentifierString bpartnerIdentifier, final OrgId orgId)
{
final BPartnerQuery query = createBPartnerQuery(bpartnerIdentifier, orgId);
return bpartnersRepo.retrieveBPartnerIdBy(query);
}
private static BPartnerQuery createBPartnerQuery(@NonNull final IdentifierString bpartnerIdentifier, final OrgId orgId)
{
final Type type = bpartnerIdentifier.getType();
final BPartnerQuery.BPartnerQueryBuilder builder = BPartnerQuery.builder();
if (orgId != null)
{
builder.onlyOrgId(orgId);
}
if (Type.METASFRESH_ID.equals(type))
{
return builder
.bPartnerId(bpartnerIdentifier.asMetasfreshId(BPartnerId::ofRepoId))
.build();
}
else if (Type.EXTERNAL_ID.equals(type))
{
return builder
.externalId(bpartnerIdentifier.asExternalId())
.build();
} | else if (Type.VALUE.equals(type))
{
return builder
.bpartnerValue(bpartnerIdentifier.asValue())
.build();
}
else if (Type.GLN.equals(type))
{
return builder
.gln(bpartnerIdentifier.asGLN())
.build();
}
else
{
throw new AdempiereException("Invalid bpartnerIdentifier: " + bpartnerIdentifier);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\bpartner_pricelist\BpartnerPriceListServicesFacade.java | 1 |
请完成以下Java代码 | public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof TypedSqlQueryFilter)
{
final TypedSqlQueryFilter<?> other = (TypedSqlQueryFilter<?>)obj;
return Objects.equals(sql, other.sql)
&& Objects.equals(sqlParams, other.sqlParams);
}
else
{
return false;
}
} | @Override
public String getSql()
{
return sql;
}
@Override
public List<Object> getSqlParams(final Properties ctx_NOTUSED)
{
return sqlParams;
}
@Override
public boolean accept(final T model)
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\TypedSqlQueryFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class X_M_ShipmentSchedule_Carrier_Service extends org.compiere.model.PO implements I_M_ShipmentSchedule_Carrier_Service, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1460375029L;
/** Standard Constructor */
public X_M_ShipmentSchedule_Carrier_Service (final Properties ctx, final int M_ShipmentSchedule_Carrier_Service_ID, @Nullable final String trxName)
{
super (ctx, M_ShipmentSchedule_Carrier_Service_ID, trxName);
}
/** Load Constructor */
public X_M_ShipmentSchedule_Carrier_Service (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setCarrier_Service_ID (final int Carrier_Service_ID)
{
if (Carrier_Service_ID < 1)
set_Value (COLUMNNAME_Carrier_Service_ID, null);
else
set_Value (COLUMNNAME_Carrier_Service_ID, Carrier_Service_ID);
}
@Override
public int getCarrier_Service_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_Service_ID);
} | @Override
public void setM_ShipmentSchedule_Carrier_Service_ID (final int M_ShipmentSchedule_Carrier_Service_ID)
{
if (M_ShipmentSchedule_Carrier_Service_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_Carrier_Service_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_Carrier_Service_ID, M_ShipmentSchedule_Carrier_Service_ID);
}
@Override
public int getM_ShipmentSchedule_Carrier_Service_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_Carrier_Service_ID);
}
@Override
public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID);
}
@Override
public int getM_ShipmentSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ShipmentSchedule_Carrier_Service.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.