instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public int add(MemberProductCollection productCollection) {
int count = 0;
if (productCollection.getProductId() == null) {
return 0;
}
UmsMember member = memberService.getCurrentMember();
productCollection.setMemberId(member.getId());
productCollection.setMemberNickname(member.getNickname());
productCollection.setMemberIcon(member.getIcon());
MemberProductCollection findCollection = productCollectionRepository.findByMemberIdAndProductId(productCollection.getMemberId(), productCollection.getProductId());
if (findCollection == null) {
if (sqlEnable) {
PmsProduct product = productMapper.selectByPrimaryKey(productCollection.getProductId());
if (product == null || product.getDeleteStatus() == 1) {
return 0;
}
productCollection.setProductName(product.getName());
productCollection.setProductSubTitle(product.getSubTitle());
productCollection.setProductPrice(product.getPrice() + "");
productCollection.setProductPic(product.getPic());
}
productCollectionRepository.save(productCollection);
count = 1;
}
return count;
}
@Override
public int delete(Long productId) { | UmsMember member = memberService.getCurrentMember();
return productCollectionRepository.deleteByMemberIdAndProductId(member.getId(), productId);
}
@Override
public Page<MemberProductCollection> list(Integer pageNum, Integer pageSize) {
UmsMember member = memberService.getCurrentMember();
Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
return productCollectionRepository.findByMemberId(member.getId(), pageable);
}
@Override
public MemberProductCollection detail(Long productId) {
UmsMember member = memberService.getCurrentMember();
return productCollectionRepository.findByMemberIdAndProductId(member.getId(), productId);
}
@Override
public void clear() {
UmsMember member = memberService.getCurrentMember();
productCollectionRepository.deleteAllByMemberId(member.getId());
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\MemberCollectionServiceImpl.java | 2 |
请完成以下Java代码 | private static void checkInput(int k, int[] list1, int[] list2) throws NoSuchElementException, IllegalArgumentException {
if(list1 == null || list2 == null || k < 1) {
throw new IllegalArgumentException();
}
if(list1.length == 0 || list2.length == 0) {
throw new IllegalArgumentException();
}
if(k > list1.length + list2.length) {
throw new NoSuchElementException();
}
}
public static int getKthElementSorted(int[] list1, int[] list2, int k) {
int length1 = list1.length, length2 = list2.length;
int[] combinedArray = new int[length1 + length2];
System.arraycopy(list1, 0, combinedArray, 0, list1.length);
System.arraycopy(list2, 0, combinedArray, list1.length, list2.length);
Arrays.sort(combinedArray);
return combinedArray[k-1];
}
public static int getKthElementMerge(int[] list1, int[] list2, int k) {
int i1 = 0, i2 = 0; | while(i1 < list1.length && i2 < list2.length && (i1 + i2) < k) {
if(list1[i1] < list2[i2]) {
i1++;
} else {
i2++;
}
}
if((i1 + i2) < k) {
return i1 < list1.length ? list1[k - i2 - 1] : list2[k - i1 - 1];
} else if(i1 > 0 && i2 > 0) {
return Math.max(list1[i1-1], list2[i2-1]);
} else {
return i1 == 0 ? list2[i2-1] : list1[i1-1];
}
}
} | repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\kthsmallest\KthSmallest.java | 1 |
请完成以下Java代码 | public boolean isPalindrome(String text) {
String clean = text.replaceAll("\\s+", "")
.toLowerCase();
int length = clean.length();
int forward = 0;
int backward = length - 1;
while (backward > forward) {
char forwardChar = clean.charAt(forward++);
char backwardChar = clean.charAt(backward--);
if (forwardChar != backwardChar)
return false;
}
return true;
}
public boolean isPalindromeReverseTheString(String text) {
StringBuilder reverse = new StringBuilder();
String clean = text.replaceAll("\\s+", "")
.toLowerCase();
char[] plain = clean.toCharArray();
for (int i = plain.length - 1; i >= 0; i--)
reverse.append(plain[i]);
return (reverse.toString()).equals(clean);
}
public boolean isPalindromeUsingStringBuilder(String text) {
String clean = text.replaceAll("\\s+", "")
.toLowerCase();
StringBuilder plain = new StringBuilder(clean);
StringBuilder reverse = plain.reverse();
return (reverse.toString()).equals(clean);
}
public boolean isPalindromeUsingStringBuffer(String text) {
String clean = text.replaceAll("\\s+", "")
.toLowerCase();
StringBuffer plain = new StringBuffer(clean);
StringBuffer reverse = plain.reverse();
return (reverse.toString()).equals(clean);
}
public boolean isPalindromeRecursive(String text) {
String clean = text.replaceAll("\\s+", "")
.toLowerCase(); | return recursivePalindrome(clean, 0, clean.length() - 1);
}
private boolean recursivePalindrome(String text, int forward, int backward) {
if (forward == backward)
return true;
if ((text.charAt(forward)) != (text.charAt(backward)))
return false;
if (forward < backward + 1) {
return recursivePalindrome(text, forward + 1, backward - 1);
}
return true;
}
public boolean isPalindromeUsingIntStream(String text) {
String temp = text.replaceAll("\\s+", "")
.toLowerCase();
return IntStream.range(0, temp.length() / 2)
.noneMatch(i -> temp.charAt(i) != temp.charAt(temp.length() - i - 1));
}
boolean hasPalindromePermutation(String text) {
long charsWithOddOccurrencesCount = text.chars()
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.values()
.stream()
.filter(count -> count % 2 != 0)
.count();
return charsWithOddOccurrencesCount <= 1;
}
} | repos\tutorials-master\core-java-modules\core-java-string-algorithms-2\src\main\java\com\baeldung\palindrom\Palindrome.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void verification(Set<DeptDto> deptDtos) {
Set<Long> deptIds = deptDtos.stream().map(DeptDto::getId).collect(Collectors.toSet());
if(userRepository.countByDepts(deptIds) > 0){
throw new BadRequestException("所选部门存在用户关联,请解除后再试!");
}
if(roleRepository.countByDepts(deptIds) > 0){
throw new BadRequestException("所选部门存在角色关联,请解除后再试!");
}
}
private void updateSubCnt(Long deptId){
if(deptId != null){
int count = deptRepository.countByPid(deptId);
deptRepository.updateSubCntById(count, deptId);
}
}
private List<DeptDto> deduplication(List<DeptDto> list) {
List<DeptDto> deptDtos = new ArrayList<>();
for (DeptDto deptDto : list) {
boolean flag = true;
for (DeptDto dto : list) {
if (dto.getId().equals(deptDto.getPid())) {
flag = false;
break; | }
}
if (flag){
deptDtos.add(deptDto);
}
}
return deptDtos;
}
/**
* 清理缓存
* @param id /
*/
public void delCaches(Long id){
List<User> users = userRepository.findByRoleDeptId(id);
// 删除数据权限
redisUtils.delByKeys(CacheKey.DATA_USER, users.stream().map(User::getId).collect(Collectors.toSet()));
redisUtils.del(CacheKey.DEPT_ID + id);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\DeptServiceImpl.java | 2 |
请完成以下Java代码 | public IMigrationExecutorContext createInitialContext(final Properties ctx)
{
return new MigrationExecutorContext(ctx, this);
}
@Override
public IMigrationExecutor newMigrationExecutor(final IMigrationExecutorContext migrationCtx, final int migrationId)
{
return new MigrationExecutor(migrationCtx, migrationId);
}
@Override
public void registerMigrationStepExecutor(final String stepType, final Class<? extends IMigrationStepExecutor> executorClass)
{
stepExecutorsByType.put(stepType, executorClass);
}
@Override
public IMigrationStepExecutor newMigrationStepExecutor(final IMigrationExecutorContext migrationCtx, final I_AD_MigrationStep step)
{
final String stepType = step.getStepType();
final Class<? extends IMigrationStepExecutor> executorClass = stepExecutorsByType.get(stepType); | if (executorClass == null)
{
throw new AdempiereException("Step type not supported: " + stepType);
}
try
{
return executorClass
.getConstructor(IMigrationExecutorContext.class, I_AD_MigrationStep.class)
.newInstance(migrationCtx, step);
}
catch (Exception e)
{
throw new AdempiereException("Cannot not load step executor for class " + executorClass, e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\MigrationExecutorProvider.java | 1 |
请完成以下Java代码 | private Container getContentPane()
{
final Window window = getWindow();
Check.assumeInstanceOf(window, RootPaneContainer.class, "RootPaneContainer (i.e JDialog, JFrame)");
final RootPaneContainer rootPaneContainer = (RootPaneContainer)window;
return rootPaneContainer.getContentPane();
}
protected String getSQLSelect()
{
return m_sqlMain;
}
protected void setKeyColumnIndex(final int keyColumnIndex)
{
m_keyColumnIndex = keyColumnIndex;
}
/**
* @param row
* @return true if given row is a data row (e.g. not a totals row)
*/
public boolean isDataRow(final int row)
{
if (row < 0)
{
return false;
}
final int rows = p_table.getRowCount();
// If this is the Totals row (last row), we need to skip it - teo_sarca [ 2860556 ]
if (p_table.getShowTotals() && row == rows - 1)
{
return false;
}
return row < rows;
}
public static final String PROP_SaveSelection = "SaveSelection";
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
@Override
public void addPropertyChangeListener(final PropertyChangeListener listener)
{
pcs.addPropertyChangeListener(listener);
}
@Override
public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener)
{ | pcs.addPropertyChangeListener(propertyName, listener);
}
public IInfoColumnController getInfoColumnController(final int index)
{
return p_layout[index].getColumnController();
}
public boolean isLoading()
{
if (m_worker == null)
{
return false;
}
// Check for override.
if (ignoreLoading)
{
return false;
}
return m_worker.isAlive();
}
// metas: end
public void setIgnoreLoading(final boolean ignoreLoading)
{
this.ignoreLoading = ignoreLoading;
}
private static final Properties getCtx()
{
return Env.getCtx();
}
private static final int getCtxAD_Client_ID()
{
return Env.getAD_Client_ID(getCtx());
}
} // Info | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\Info.java | 1 |
请完成以下Java代码 | public class RootCauseFinder {
public static Throwable findCauseUsingPlainJava(Throwable throwable) {
Objects.requireNonNull(throwable);
Throwable rootCause = throwable;
while (rootCause.getCause() != null) {
rootCause = rootCause.getCause();
}
return rootCause;
}
/**
* Calculates the age of a person from a given date.
*/
static class AgeCalculator {
private AgeCalculator() {
}
public static int calculateAge(String birthDate) throws CalculationException {
if (birthDate == null || birthDate.isEmpty()) {
throw new IllegalArgumentException();
}
try {
return Period
.between(parseDate(birthDate), LocalDate.now())
.getYears();
} catch (DateParseException ex) {
throw new CalculationException(ex);
}
}
private static LocalDate parseDate(String birthDateAsString) throws DateParseException {
LocalDate birthDate;
try {
birthDate = LocalDate.parse(birthDateAsString);
} catch (DateTimeParseException ex) {
throw new InvalidFormatException(birthDateAsString, ex);
}
if (birthDate.isAfter(LocalDate.now())) {
throw new DateOutOfRangeException(birthDateAsString);
}
return birthDate;
}
}
static class CalculationException extends Exception {
CalculationException(DateParseException ex) { | super(ex);
}
}
static class DateParseException extends Exception {
DateParseException(String input) {
super(input);
}
DateParseException(String input, Throwable thr) {
super(input, thr);
}
}
static class InvalidFormatException extends DateParseException {
InvalidFormatException(String input, Throwable thr) {
super("Invalid date format: " + input, thr);
}
}
static class DateOutOfRangeException extends DateParseException {
DateOutOfRangeException(String date) {
super("Date out of range: " + date);
}
}
} | repos\tutorials-master\core-java-modules\core-java-exceptions-2\src\main\java\com\baeldung\rootcausefinder\RootCauseFinder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private BigDecimal getPriceStd(
@NonNull final ImportProductsRouteContext context,
@NonNull final PriceListBasicInfo targetPriceListInfo)
{
final String productId = context.getJsonProduct().getId();
final List<JsonPrice> prices = context.getJsonProduct().getPrices();
if (prices == null || prices.isEmpty())
{
processLogger.logMessage("No price info present for productId: " + productId, context.getPInstanceId());
return BigDecimal.ZERO;
}
if (prices.size() > 1)
{
processLogger.logMessage("More than 1 price present for productId: " + productId, context.getPInstanceId());
}
final JsonPrice price = prices.get(0);
final String isoCode = context.getCurrencyInfoProvider().getIsoCodeByCurrencyIdNotNull(price.getCurrencyId());
if (!isoCode.equals(targetPriceListInfo.getCurrencyCode()))
{
processLogger.logMessage("Target price list currency code is different from product price currency code for productId: " + productId, context.getPInstanceId());
return BigDecimal.ZERO;
}
if (targetPriceListInfo.isTaxIncluded())
{
if (price.getGross() == null) | {
processLogger.logMessage("No gross price info present for productId: " + productId, context.getPInstanceId());
return BigDecimal.ZERO;
}
return price.getGross();
}
else
{
if (price.getNet() == null)
{
processLogger.logMessage("No net price info present for productId: " + productId, context.getPInstanceId());
return BigDecimal.ZERO;
}
return price.getNet();
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\product\processor\ProductPriceProcessor.java | 2 |
请完成以下Java代码 | public class JpaQueueDao extends JpaAbstractDao<QueueEntity, Queue> implements QueueDao, TenantEntityDao<Queue> {
@Autowired
private QueueRepository queueRepository;
@Override
protected Class<QueueEntity> getEntityClass() {
return QueueEntity.class;
}
@Override
protected JpaRepository<QueueEntity, UUID> getRepository() {
return queueRepository;
}
@Override
public Queue findQueueByTenantIdAndTopic(TenantId tenantId, String topic) {
return DaoUtil.getData(queueRepository.findByTenantIdAndTopic(tenantId.getId(), topic));
}
@Override
public Queue findQueueByTenantIdAndName(TenantId tenantId, String name) {
return DaoUtil.getData(queueRepository.findByTenantIdAndName(tenantId.getId(), name));
}
@Override
public List<Queue> findAllByTenantId(TenantId tenantId) {
List<QueueEntity> entities = queueRepository.findByTenantId(tenantId.getId());
return DaoUtil.convertDataList(entities);
}
@Override
public List<Queue> findAllMainQueues() {
List<QueueEntity> entities = Lists.newArrayList(queueRepository.findAllByName(DataConstants.MAIN_QUEUE_NAME)); | return DaoUtil.convertDataList(entities);
}
@Override
public List<Queue> findAllQueues() {
List<QueueEntity> entities = Lists.newArrayList(queueRepository.findAll());
return DaoUtil.convertDataList(entities);
}
@Override
public PageData<Queue> findQueuesByTenantId(TenantId tenantId, PageLink pageLink) {
return DaoUtil.toPageData(queueRepository
.findByTenantId(tenantId.getId(), pageLink.getTextSearch(), DaoUtil.toPageable(pageLink)));
}
@Override
public PageData<Queue> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findQueuesByTenantId(tenantId, pageLink);
}
@Override
public EntityType getEntityType() {
return EntityType.QUEUE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\queue\JpaQueueDao.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
NoticeTypeEnum(String name, String value) {
this.name = name;
this.value = value;
}
/**
* 获取聊天通知类型
*
* @param value
* @return
*/
public static String getChatNoticeType(String value){
return value + "Notice";
} | /**
* 获取通知名称
*
* @param value
* @return
*/
public static String getNoticeNameByValue(String value){
value = value.replace("Notice","");
for (NoticeTypeEnum e : NoticeTypeEnum.values()) {
if (e.getValue().equals(value)) {
return e.getName();
}
}
return "系统消息";
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\NoticeTypeEnum.java | 1 |
请完成以下Java代码 | public class Book {
@Id
private String isbn;
@Property("name")
private String title;
private Integer year;
@Relationship(type = "WRITTEN_BY", direction = Relationship.Direction.OUTGOING)
private Author author;
public Book(String isbn, String title, Integer year) {
this.isbn = isbn;
this.title = title;
this.year = year;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
} | public void setTitle(String title) {
this.title = title;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
} | repos\tutorials-master\persistence-modules\spring-data-neo4j\src\main\java\com\baeldung\spring\data\neo4j\domain\Book.java | 1 |
请完成以下Java代码 | public String period (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
String colName = mField.getColumnName();
if (value == null || isCalloutActive())
return "";
int AD_Client_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Client_ID");
Timestamp DateAcct = null;
if (colName.equals("DateAcct"))
DateAcct = (Timestamp)value;
else
DateAcct = (Timestamp)mTab.getValue("DateAcct");
int C_Period_ID = 0;
if (colName.equals("C_Period_ID"))
C_Period_ID = ((Integer)value).intValue();
// When DateDoc is changed, update DateAcct
if (colName.equals("DateDoc"))
{
mTab.setValue("DateAcct", value);
}
// When DateAcct is changed, set C_Period_ID
else if (colName.equals("DateAcct"))
{
String sql = "SELECT C_Period_ID "
+ "FROM C_Period "
+ "WHERE C_Year_ID IN "
+ " (SELECT C_Year_ID FROM C_Year WHERE C_Calendar_ID ="
+ " (SELECT C_Calendar_ID FROM AD_ClientInfo WHERE AD_Client_ID=?))"
+ " AND ? BETWEEN StartDate AND EndDate"
// globalqss - cruiz - Bug [ 1577712 ] Financial Period Bug
+ " AND IsActive='Y'"
+ " AND PeriodType='S'";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_Client_ID);
pstmt.setTimestamp(2, DateAcct);
rs = pstmt.executeQuery();
if (rs.next())
C_Period_ID = rs.getInt(1);
rs.close();
pstmt.close();
pstmt = null;
}
catch (SQLException e)
{
log.error(sql, e);
return e.getLocalizedMessage();
}
finally
{ | DB.close(rs, pstmt);
}
if (C_Period_ID != 0)
mTab.setValue("C_Period_ID", new Integer(C_Period_ID));
}
// When C_Period_ID is changed, check if in DateAcct range and set to end date if not
else
{
String sql = "SELECT PeriodType, StartDate, EndDate "
+ "FROM C_Period WHERE C_Period_ID=?";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_Period_ID);
rs = pstmt.executeQuery();
if (rs.next())
{
String PeriodType = rs.getString(1);
Timestamp StartDate = rs.getTimestamp(2);
Timestamp EndDate = rs.getTimestamp(3);
if (PeriodType.equals("S")) // Standard Periods
{
// out of range - set to last day
if (DateAcct == null
|| DateAcct.before(StartDate) || DateAcct.after(EndDate))
mTab.setValue("DateAcct", EndDate);
}
}
}
catch (SQLException e)
{
log.error(sql, e);
return e.getLocalizedMessage();
}
finally
{
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
}
return "";
} // Journal_Period
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\CalloutAsset.java | 1 |
请完成以下Java代码 | public void resolve() {
if (this.rel == null) {
throw new InvalidInitializrMetadataException("Invalid link " + this + ": rel attribute is mandatory");
}
if (this.href == null) {
throw new InvalidInitializrMetadataException("Invalid link " + this + ": href attribute is mandatory");
}
Matcher matcher = VARIABLE_REGEX.matcher(this.href);
while (matcher.find()) {
String variable = matcher.group(1);
this.templateVariables.add(variable);
}
this.templated = !this.templateVariables.isEmpty();
}
/**
* Expand the link using the specified parameters.
* @param parameters the parameters value
* @return an URI where all variables have been expanded
*/
public URI expand(Map<String, String> parameters) {
AtomicReference<String> result = new AtomicReference<>(this.href);
this.templateVariables.forEach((var) -> {
Object value = parameters.get(var);
if (value == null) {
throw new IllegalArgumentException(
"Could not expand " + this.href + ", missing value for '" + var + "'"); | }
result.set(result.get().replace("{" + var + "}", value.toString()));
});
try {
return new URI(result.get());
}
catch (URISyntaxException ex) {
throw new IllegalStateException("Invalid URL", ex);
}
}
public static Link create(String rel, String href) {
return new Link(rel, href);
}
public static Link create(String rel, String href, String description) {
return new Link(rel, href, description);
}
public static Link create(String rel, String href, boolean templated) {
return new Link(rel, href, templated);
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\Link.java | 1 |
请完成以下Java代码 | public class King extends Person implements Serializable {
/**
* 名字
*/
private String name;
/**
* 家系:家族关系
*/
private String clan;
/**
* 年号:生活的时代
*/
private String times;
/**
* 谥号:人死之后,后人给予评价
*/
private String posthumousTitle;
/**
* 庙号:君主于庙中被供奉时所称呼的名号
*/
private String TempleNumber;
/**
* 陵墓
*/
private String tomb;
/**
* 大事件
*/
private String remark;
@Relationship(type = "传位")
King successor;
/**
* 第二种保存关系的方式
*/
@Relationship
List<FatherAndSonRelation> sons;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClan() {
return clan;
}
public void setClan(String clan) {
this.clan = clan;
}
public String getTimes() {
return times;
}
public void setTimes(String times) {
this.times = times;
}
public String getPosthumousTitle() {
return posthumousTitle;
}
public void setPosthumousTitle(String posthumousTitle) {
this.posthumousTitle = posthumousTitle;
}
public String getTempleNumber() {
return TempleNumber;
}
public void setTempleNumber(String templeNumber) {
TempleNumber = templeNumber;
}
public String getTomb() {
return tomb;
}
public void setTomb(String tomb) {
this.tomb = tomb; | }
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public King getSuccessor() {
return successor;
}
public void setSuccessor(King successor) {
this.successor = successor;
}
public List<FatherAndSonRelation> getSons() {
return sons;
}
public void setSons(List<FatherAndSonRelation> sons) {
this.sons = sons;
}
/**
* 添加友谊的关系
* @param
*/
public void addRelation(FatherAndSonRelation fatherAndSonRelation){
if(this.sons == null){
this.sons = new ArrayList<>();
}
this.sons.add(fatherAndSonRelation);
}
} | repos\springBoot-master\springboot-neo4j\src\main\java\cn\abel\neo4j\bean\King.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<AuthorDtoNoSetters> fetchAuthorsNoSetters() {
Query query = entityManager
.createNativeQuery("SELECT name, age FROM author")
.unwrap(org.hibernate.query.NativeQuery.class)
.setResultTransformer(
new AliasToBeanConstructorResultTransformer(
AuthorDtoNoSetters.class.getConstructors()[0]
)
);
List<AuthorDtoNoSetters> authors = query.getResultList();
return authors;
}
@Override
@Transactional(readOnly = true) | public List<AuthorDtoWithSetters> fetchAuthorsWithSetters() {
Query query = entityManager
.createNativeQuery("SELECT name, age FROM author")
.unwrap(org.hibernate.query.NativeQuery.class)
.setResultTransformer(
Transformers.aliasToBean(AuthorDtoWithSetters.class)
);
List<AuthorDtoWithSetters> authors = query.getResultList();
return authors;
}
protected EntityManager getEntityManager() {
return entityManager;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoResultTransformer\src\main\java\com\bookstore\dao\Dao.java | 2 |
请完成以下Java代码 | public DeviceCredentialsType getCredentialsType() {
return credentialsType;
}
public void setCredentialsType(DeviceCredentialsType credentialsType) {
this.credentialsType = credentialsType;
}
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Unique Credentials Id per platform instance. " +
"Used to lookup credentials from the database. " +
"By default, new access token for your device. " +
"Depends on the type of the credentials."
, example = "Access token or other value that depends on the credentials type")
@Override
public String getCredentialsId() {
return credentialsId;
}
public void setCredentialsId(String credentialsId) {
this.credentialsId = credentialsId; | }
@Schema(description = "Value of the credentials. " +
"Null in case of ACCESS_TOKEN credentials type. Base64 value in case of X509_CERTIFICATE. " +
"Complex object in case of MQTT_BASIC and LWM2M_CREDENTIALS", example = "Null in case of ACCESS_TOKEN. See model definition.")
public String getCredentialsValue() {
return credentialsValue;
}
public void setCredentialsValue(String credentialsValue) {
this.credentialsValue = credentialsValue;
}
@Override
public String toString() {
return "DeviceCredentials [deviceId=" + deviceId + ", credentialsType=" + credentialsType + ", credentialsId="
+ credentialsId + ", credentialsValue=" + credentialsValue + ", createdTime=" + createdTime + ", id="
+ id + "]";
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\security\DeviceCredentials.java | 1 |
请完成以下Java代码 | public boolean isStandardHeaderFooter ()
{
Object oo = get_Value(COLUMNNAME_IsStandardHeaderFooter);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Table Based.
@param IsTableBased
Table based List Reporting
*/
@Override
public void setIsTableBased (boolean IsTableBased)
{
set_ValueNoCheck (COLUMNNAME_IsTableBased, Boolean.valueOf(IsTableBased));
}
/** Get Table Based.
@return Table based List Reporting
*/
@Override
public boolean isTableBased ()
{
Object oo = get_Value(COLUMNNAME_IsTableBased);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public org.compiere.model.I_AD_Process getJasperProcess() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_JasperProcess_ID, org.compiere.model.I_AD_Process.class);
}
@Override
public void setJasperProcess(org.compiere.model.I_AD_Process JasperProcess)
{
set_ValueFromPO(COLUMNNAME_JasperProcess_ID, org.compiere.model.I_AD_Process.class, JasperProcess);
}
/** Set Jasper Process.
@param JasperProcess_ID
The Jasper Process used by the printengine if any process defined
*/
@Override
public void setJasperProcess_ID (int JasperProcess_ID)
{
if (JasperProcess_ID < 1)
set_Value (COLUMNNAME_JasperProcess_ID, null);
else
set_Value (COLUMNNAME_JasperProcess_ID, Integer.valueOf(JasperProcess_ID));
}
/** Get Jasper Process.
@return The Jasper Process used by the printengine if any process defined
*/
@Override
public int getJasperProcess_ID () | {
Integer ii = (Integer)get_Value(COLUMNNAME_JasperProcess_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 Drucker.
@param PrinterName
Name of the Printer
*/
@Override
public void setPrinterName (java.lang.String PrinterName)
{
set_Value (COLUMNNAME_PrinterName, PrinterName);
}
/** Get Drucker.
@return Name of the Printer
*/
@Override
public java.lang.String getPrinterName ()
{
return (java.lang.String)get_Value(COLUMNNAME_PrinterName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintFormat.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigInteger getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setValue(BigInteger value) {
this.value = value;
}
/**
* Defines the type of bank code by providing the country from which the bank code is. In order to specify the country in this attribute, a code according to ISO 3166-1 must be used.
*
* @return
* possible object is | * {@link CountryCodeType }
*
*/
public CountryCodeType getBankCodeType() {
return bankCodeType;
}
/**
* Sets the value of the bankCodeType property.
*
* @param value
* allowed object is
* {@link CountryCodeType }
*
*/
public void setBankCodeType(CountryCodeType value) {
this.bankCodeType = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\BankCodeCType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class AuthenticationRestController {
@Value("${2fa.enabled}")
private boolean isTwoFaEnabled;
@Autowired
private UserService userService;
@Autowired
private TotpService totpService;
@PostMapping("{login}/{password}")
public AuthenticationStatus authenticate(@PathVariable String login, @PathVariable String password) {
Optional<User> user = userService.findUser(login, password);
if (!user.isPresent()) {
return AuthenticationStatus.FAILED;
}
if (!isTwoFaEnabled) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(login, password);
SecurityContextHolder.getContext().setAuthentication(authentication);
return AuthenticationStatus.AUTHENTICATED;
} else {
SecurityContextHolder.getContext().setAuthentication(null);
return AuthenticationStatus.REQUIRE_TOKEN_CHECK;
}
} | @GetMapping("token/{login}/{password}/{token}")
public AuthenticationStatus tokenCheck(@PathVariable String login, @PathVariable String password, @PathVariable String token) {
Optional<User> user = userService.findUser(login, password);
if (!user.isPresent()) {
return AuthenticationStatus.FAILED;
}
if (!totpService.verifyCode(token, user.get().getSecret())) {
return AuthenticationStatus.FAILED;
}
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user.get().getLogin(), user.get().getPassword(), new ArrayList<>());
SecurityContextHolder.getContext().setAuthentication(authentication);
return AuthenticationStatus.AUTHENTICATED;
}
@PostMapping("/logout")
public void logout() {
SecurityContextHolder.clearContext();
}
} | repos\springboot-demo-master\MFA\src\main\java\com\et\mfa\controller\AuthenticationRestController.java | 2 |
请完成以下Java代码 | private static Dataset<Row> combineDataframes(Dataset<Row> df1, Dataset<Row> df2) {
return df1.unionByName(df2);
}
private static Dataset<Row> normalizeCustomerDataFromEbay(Dataset<Row> rawDataset) {
Dataset<Row> transformedDF = rawDataset.withColumn("id", concat(rawDataset.col("zoneId"), lit("-"), rawDataset.col("customerId")))
.drop(column("customerId"))
.withColumn("source", lit("ebay"))
.withColumn("city", rawDataset.col("contact.customer_city"))
.drop(column("contact"))
.drop(column("zoneId"))
.withColumn("year", functions.year(col("transaction_date")))
.drop("transaction_date")
.withColumn("firstName", functions.split(column("name"), " ")
.getItem(0))
.withColumn("lastName", functions.split(column("name"), " ")
.getItem(1))
.drop(column("name"));
print(transformedDF);
return transformedDF;
}
private static Dataset<Row> normalizeCustomerDataFromAmazon(Dataset<Row> rawDataset) {
Dataset<Row> transformedDF = rawDataset.withColumn("id", concat(rawDataset.col("zoneId"), lit("-"), rawDataset.col("id")))
.withColumn("source", lit("amazon"))
.withColumnRenamed("CITY", "city")
.withColumnRenamed("PHONE_NO", "contactNo")
.withColumnRenamed("POSTCODE", "postCode")
.withColumnRenamed("FIRST_NAME", "firstName")
.drop(column("MIDDLE_NAME"))
.drop(column("zoneId"))
.withColumnRenamed("LAST_NAME", "lastName")
.withColumn("year", functions.year(col("transaction_date")))
.drop("transaction_date");
print(transformedDF);
return transformedDF;
}
private static Dataset<Row> aggregateYearlySalesByGender(Dataset<Row> dataset) { | Dataset<Row> aggDF = dataset.groupBy(column("year"), column("source"), column("gender"))
.sum("transaction_amount")
.withColumnRenamed("sum(transaction_amount)", "annual_spending")
.orderBy(col("year").asc(), col("annual_spending").desc());
print(aggDF);
return aggDF;
}
private static void print(Dataset<Row> aggDs) {
aggDs.show();
aggDs.printSchema();
}
private void exportData(Dataset<Row> dataset) {
String connectionURL = dbProperties.getProperty("connectionURL");
dataset.write()
.mode(SaveMode.Overwrite)
.jdbc(connectionURL, "customer", dbProperties);
}
} | repos\tutorials-master\apache-spark\src\main\java\com\baeldung\dataframes\CustomerDataAggregationPipeline.java | 1 |
请完成以下Java代码 | private Function<JsonNode, DynamicMessage> callGRPCServer() {
return jsonRequest -> {
try {
DynamicMessage.Builder builder = DynamicMessage.newBuilder(descriptor);
JsonFormat.parser().merge(jsonRequest.toString(), builder);
return ClientCalls.blockingUnaryCall(clientCall, builder.build());
}
catch (IOException e) {
throw new RuntimeException(e);
}
};
}
private Function<DynamicMessage, Object> serialiseGRPCResponse() {
return gRPCResponse -> {
try {
return objectReader
.readValue(JsonFormat.printer().omittingInsignificantWhitespace().print(gRPCResponse));
}
catch (IOException e) {
throw new RuntimeException(e);
}
};
}
private Flux<JsonNode> deserializeJSONRequest() {
return exchange.getRequest().getBody().mapNotNull(dataBufferBody -> {
if (dataBufferBody.capacity() == 0) {
return objectNode; | }
ResolvableType targetType = ResolvableType.forType(JsonNode.class);
return new JacksonJsonDecoder().decode(dataBufferBody, targetType, null, null);
}).cast(JsonNode.class);
}
private Function<Object, DataBuffer> wrapGRPCResponse() {
return jsonResponse -> new NettyDataBufferFactory(new PooledByteBufAllocator())
.wrap(Objects.requireNonNull(new ObjectMapper().writeValueAsBytes(jsonResponse)));
}
// We are creating this on every call, should optimize?
private ManagedChannel createChannelChannel(String host, int port) {
NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port);
try {
return grpcSslConfigurer.configureSsl(nettyChannelBuilder);
}
catch (SSLException e) {
throw new RuntimeException(e);
}
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\JsonToGrpcGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public void run(final String localTrxName) throws Exception
{
//
// Setup in-transaction context
final IHUContext huContext = getHUContext();
final IMutableHUContext huContextLocal = huContext.copyAsMutable();
huContextLocal.setTrxName(localTrxName);
setHUContext(huContextLocal);
try
{
//
// Iterate hus
for (final I_M_HU hu : hus)
{
//
// Make sure our HU has NULL transaction or same transaction as the one we are running in now
final String huTrxName = InterfaceWrapperHelper.getTrxName(hu);
if (!trxManager.isNull(huTrxName) && !trxManager.isSameTrxName(huTrxName, localTrxName))
{
throw new AdempiereException("" + hu + " shall have null transaction or local transaction(" + localTrxName + ") but not " + huTrxName);
}
//
// Set HU's transaction to our local transaction an iterate it
InterfaceWrapperHelper.setTrxName(hu, localTrxName);
try
{ | huNodeIterator.iterate(hu);
}
finally
{
// Restore HU's initial transaction
InterfaceWrapperHelper.setTrxName(hu, huTrxName);
}
}
}
finally
{
// restore initial context
setHUContext(huContext);
}
}
});
//
// If after running everything the status is still running, switch it to finished
if (getStatus() == HUIteratorStatus.Running)
{
setStatus(HUIteratorStatus.Finished);
}
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUIterator.java | 1 |
请完成以下Java代码 | private static class ValueConversionException extends AdempiereException
{
public static ValueConversionException wrapIfNeeded(final Throwable ex)
{
if (ex instanceof ValueConversionException)
{
return (ValueConversionException)ex;
}
final Throwable cause = extractCause(ex);
if (cause instanceof ValueConversionException)
{
return (ValueConversionException)cause;
}
else
{
return new ValueConversionException(cause);
}
}
public ValueConversionException()
{
this("no conversion rule defined to convert the value to target type");
}
public ValueConversionException(final String message)
{
super(message);
appendParametersToMessage();
}
public ValueConversionException(final Throwable cause)
{
super("Conversion failed because: " + cause.getLocalizedMessage(), cause);
appendParametersToMessage();
} | public ValueConversionException setFieldName(@Nullable final String fieldName)
{
setParameter("fieldName", fieldName);
return this;
}
public ValueConversionException setWidgetType(@Nullable final DocumentFieldWidgetType widgetType)
{
setParameter("widgetType", widgetType);
return this;
}
public ValueConversionException setFromValue(@Nullable final Object fromValue)
{
setParameter("value", fromValue);
setParameter("valueClass", fromValue != null ? fromValue.getClass() : null);
return this;
}
public ValueConversionException setTargetType(@Nullable final Class<?> targetType)
{
setParameter("targetType", targetType);
return this;
}
public ValueConversionException setLookupDataSource(@Nullable final LookupValueByIdSupplier lookupDataSource)
{
setParameter("lookupDataSource", lookupDataSource);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DataTypes.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonEnqueueForInvoicingRequest
{
@ApiModelProperty(position = 10, required = true, //
value = "Specifies the invoice candidates to be invoiced.")
List<JsonInvoiceCandidateReference> invoiceCandidates;
@ApiModelProperty(position = 20, value = "Optional invoices' document date", example = "2019-10-30")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
@JsonInclude(Include.NON_NULL)
LocalDate dateInvoiced;
@ApiModelProperty(position = 30, value = "Optional invoices' accounting date", example = "2019-10-30")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
@JsonInclude(Include.NON_NULL)
LocalDate dateAcct;
@ApiModelProperty(position = 40, value = "Optional customer's purchase order's documentno. POReference to be set to all invoice candidates, right before enqueueing them.")
String poReference;
@ApiModelProperty(position = 50, required = false, //
value = "This is needed when the user wants to invoice candidates that have their `DateToInvoice` sometime in the future.\n"
+ "If this is not set and the DateToInvoice is in the future then an error will occur \"no invoicable ICs selected\n"
+ "Default = `false`")
Boolean ignoreInvoiceSchedule;
@ApiModelProperty(position = 70, required = false,//
value = "If this parameter is activated, the invoices to be created receive the current users and locations of their business partners, regardless of the values in `Bill_Location_ID` and `Bill_User_ID` that are set in the queued billing candidates.\n"
+ "Default = `false`")
Boolean updateLocationAndContactForInvoice; | @ApiModelProperty(position = 80, required = false,//
value = "When this parameter is set on true, the newly generated invoices are directly completed.\n"
+ "Otherwise they are just prepared and left in the DocStatus IP (in progress). Default = `true`")
Boolean completeInvoices;
@JsonCreator
@Builder(toBuilder = true)
private JsonEnqueueForInvoicingRequest(
@JsonProperty("invoiceCandidates") @Singular final List<JsonInvoiceCandidateReference> invoiceCandidates,
@JsonProperty("dateInvoiced") @Nullable final LocalDate dateInvoiced,
@JsonProperty("dateAcct") @Nullable final LocalDate dateAcct,
@JsonProperty("poReference") @Nullable final String poReference,
@JsonProperty("ignoreInvoiceSchedule") @Nullable final Boolean ignoreInvoiceSchedule,
@JsonProperty("updateLocationAndContactForInvoice") @Nullable final Boolean updateLocationAndContactForInvoice,
@JsonProperty("completeInvoices") @Nullable final Boolean completeInvoices)
{
this.invoiceCandidates = ImmutableList.copyOf(invoiceCandidates);
this.poReference = poReference;
this.dateAcct = dateAcct;
this.dateInvoiced = dateInvoiced;
this.ignoreInvoiceSchedule = coalesce(ignoreInvoiceSchedule, false);
this.updateLocationAndContactForInvoice = coalesce(updateLocationAndContactForInvoice, false);
this.completeInvoices = coalesce(completeInvoices, true);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api\src\main\java\de\metas\rest_api\invoicecandidates\request\JsonEnqueueForInvoicingRequest.java | 2 |
请完成以下Java代码 | public Builder profile(String profile) {
return claim(StandardClaimNames.PROFILE, profile);
}
/**
* Use this subject in the resulting {@link OidcUserInfo}
* @param subject The subject to use
* @return the {@link Builder} for further configurations
*/
public Builder subject(String subject) {
return this.claim(StandardClaimNames.SUB, subject);
}
/**
* Use this updated-at {@link Instant} in the resulting {@link OidcUserInfo}
* @param updatedAt The updated-at {@link Instant} to use
* @return the {@link Builder} for further configurations
*/
public Builder updatedAt(String updatedAt) {
return this.claim(StandardClaimNames.UPDATED_AT, updatedAt);
}
/**
* Use this website in the resulting {@link OidcUserInfo}
* @param website The website to use
* @return the {@link Builder} for further configurations
*/
public Builder website(String website) {
return this.claim(StandardClaimNames.WEBSITE, website);
}
/** | * Use this zoneinfo in the resulting {@link OidcUserInfo}
* @param zoneinfo The zoneinfo to use
* @return the {@link Builder} for further configurations
*/
public Builder zoneinfo(String zoneinfo) {
return this.claim(StandardClaimNames.ZONEINFO, zoneinfo);
}
/**
* Build the {@link OidcUserInfo}
* @return The constructed {@link OidcUserInfo}
*/
public OidcUserInfo build() {
return new OidcUserInfo(this.claims);
}
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\OidcUserInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ResponseEntity<?> getPDF(HttpServletRequest request, HttpServletResponse response) throws IOException {
/* Do Business Logic*/
Order order = OrderHelper.getOrder();
/* Create HTML using Thymeleaf template Engine */
WebContext context = new WebContext(request, response, servletContext);
context.setVariable("orderEntry", order);
String orderHtml = templateEngine.process("order", context);
/* Setup Source and target I/O streams */
ByteArrayOutputStream target = new ByteArrayOutputStream();
ConverterProperties converterProperties = new ConverterProperties();
converterProperties.setBaseUri("http://localhost:8088"); | /* Call convert method */
HtmlConverter.convertToPdf(orderHtml, target, converterProperties);
/* extract output as bytes */
byte[] bytes = target.toByteArray();
/* Send the response as downloadable PDF */
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=order.pdf")
.contentType(MediaType.APPLICATION_PDF)
.body(bytes);
}
} | repos\springboot-demo-master\itextpdf\src\main\java\com\et\itextpdf\controller\PDFController.java | 2 |
请完成以下Java代码 | private boolean isCallOrderContract(@NonNull final I_C_Flatrate_Term contract)
{
return TypeConditions.CALL_ORDER.getCode().equals(contract.getType_Conditions());
}
private void validateSOTrx(
@NonNull final I_C_Flatrate_Term contract,
@NonNull final SOTrx documentSOTrx,
final int documentLineSeqNo)
{
final OrderId initiatingContractOrderId = OrderId.ofRepoIdOrNull(contract.getC_Order_Term_ID());
Check.assumeNotNull(initiatingContractOrderId, "C_Order_Term_ID cannot be null on CallOrder contracts!");
final I_C_Order initiatingContractOrder = orderBL.getById(initiatingContractOrderId);
if (initiatingContractOrder.isSOTrx() == documentSOTrx.toBoolean()) | {
return;
}
if (initiatingContractOrder.isSOTrx())
{
throw new AdempiereException(MSG_SALES_CALL_ORDER_CONTRACT_TRX_NOT_MATCH,
contract.getDocumentNo(),
documentLineSeqNo)
.markAsUserValidationError();
}
throw new AdempiereException(MSG_PURCHASE_CALL_ORDER_CONTRACT_TRX_NOT_MATCH,
contract.getDocumentNo(),
documentLineSeqNo)
.markAsUserValidationError();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\CallOrderContractService.java | 1 |
请完成以下Java代码 | public void setAttribute (String Attribute)
{
set_Value (COLUMNNAME_Attribute, Attribute);
}
/** Get Attribute.
@return Attribute */
public String getAttribute ()
{
return (String)get_Value(COLUMNNAME_Attribute);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getAttribute());
}
/** Set Search Key.
@param Value | Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Preference.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class GeodeGatewayReceiverConfiguration {
@Bean
GatewayReceiverFactoryBean gatewayReceiver(Cache cache) {
GatewayReceiverFactoryBean gatewayReceiver = new GatewayReceiverFactoryBean(cache);
gatewayReceiver.setHostnameForSenders(GATEWAY_RECEIVER_HOSTNAME_FOR_SENDERS);
gatewayReceiver.setStartPort(GATEWAY_RECEIVER_START_PORT);
gatewayReceiver.setEndPort(GATEWAY_RECEIVER_END_PORT);
return gatewayReceiver;
}
}
// end::gateway-receiver-configuration[]
// tag::gateway-sender-configuration[]
@Configuration
@Profile("gateway-sender")
static class GeodeGatewaySenderConfiguration {
@Bean
GatewaySenderFactoryBean customersByNameGatewaySender(Cache cache,
@Value("${geode.distributed-system.remote.id:1}") int remoteDistributedSystemId) {
GatewaySenderFactoryBean gatewaySender = new GatewaySenderFactoryBean(cache);
gatewaySender.setPersistent(PERSISTENT);
gatewaySender.setRemoteDistributedSystemId(remoteDistributedSystemId); | return gatewaySender;
}
@Bean
RegionConfigurer customersByNameConfigurer(GatewaySender gatewaySender) {
return new RegionConfigurer() {
@Override
public void configure(String beanName, PeerRegionFactoryBean<?, ?> regionBean) {
if (CUSTOMERS_BY_NAME_REGION.equals(beanName)) {
regionBean.setGatewaySenders(ArrayUtils.asArray(gatewaySender));
}
}
};
}
}
// end::gateway-sender-configuration[]
// end::gateway-configuration[]
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\caching\multi-site\src\main\java\example\app\caching\multisite\server\BootGeodeMultiSiteCachingServerApplication.java | 2 |
请完成以下Java代码 | private boolean hasPrintFormatAssigned()
{
final int cnt = Services.get(IQueryBL.class)
.createQueryBuilder(I_M_Product_PrintFormat.class)
.addInArrayFilter(I_M_Product_PrintFormat.COLUMNNAME_M_Product_ID, retrieveSelectedProductIDs())
.create()
.count();
return cnt > 0;
}
private Set<ProductId> retrieveSelectedProductIDs()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
final ImmutableList<PPOrderLineRow> selectedRows = getView()
.streamByIds(selectedRowIds)
.collect(ImmutableList.toImmutableList());
final Set<ProductId> productIds = new HashSet<>();
for (final PPOrderLineRow row : selectedRows)
{
productIds.add(row.getProductId());
}
return productIds;
}
private ReportResult printLabel()
{
final PInstanceRequest pinstanceRequest = createPInstanceRequest();
final PInstanceId pinstanceId = adPInstanceDAO.createADPinstanceAndADPInstancePara(pinstanceRequest);
final ProcessInfo jasperProcessInfo = ProcessInfo.builder()
.setCtx(getCtx())
.setProcessCalledFrom(ProcessCalledFrom.WebUI)
.setAD_Process_ID(getPrintFormat().getReportProcessId())
.setAD_PInstance(adPInstanceDAO.getById(pinstanceId))
.setReportLanguage(getProcessInfo().getReportLanguage())
.setJRDesiredOutputType(OutputType.PDF)
.build();
final ReportsClient reportsClient = ReportsClient.get();
return reportsClient.report(jasperProcessInfo);
}
private PInstanceRequest createPInstanceRequest()
{
return PInstanceRequest.builder()
.processId(getPrintFormat().getReportProcessId())
.processParams(ImmutableList.of(
ProcessInfoParameter.of("AD_PInstance_ID", getPinstanceId()),
ProcessInfoParameter.of("AD_PrintFormat_ID", printFormatId)))
.build(); | }
private String buildFilename()
{
final String instance = String.valueOf(getPinstanceId().getRepoId());
final String title = getProcessInfo().getTitle();
return Joiner.on("_").skipNulls().join(instance, title) + ".pdf";
}
private PrintFormat getPrintFormat()
{
return pfRepo.getById(PrintFormatId.ofRepoId(printFormatId));
}
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
if (Objects.equals(I_M_Product.COLUMNNAME_M_Product_ID, parameter.getColumnName()))
{
return retrieveSelectedProductIDs().stream().findFirst().orElse(null);
}
return DEFAULT_VALUE_NOTAVAILABLE;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_PrintLabel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookServiceImpl implements BookService {
@Autowired
BookRepository bookRepository;
@Override
public List<Book> findAll() {
return bookRepository.findAll();
}
@Override
public Book insertByBook(Book book) {
return bookRepository.save(book);
}
@Override | public Book update(Book book) {
return bookRepository.save(book);
}
@Override
public Book delete(Long id) {
Book book = bookRepository.findById(id).get();
bookRepository.delete(book);
return book;
}
@Override
public Book findById(Long id) {
return bookRepository.findById(id).get();
}
} | repos\springboot-learning-example-master\chapter-5-spring-boot-data-jpa\src\main\java\demo\springboot\service\impl\BookServiceImpl.java | 2 |
请完成以下Java代码 | private static Supplier<CurrencyId> extractDefaultCurrencyIdSupplier(final PartialPriceChange changes)
{
if (changes.getDefaultCurrencyId() != null)
{
return changes::getDefaultCurrencyId;
}
else
{
final ICurrencyBL currenciesService = Services.get(ICurrencyBL.class);
return () -> currenciesService.getBaseCurrencyId(Env.getClientId(), Env.getOrgId());
}
}
@NonNull
private static Money extractMoney(
@Nullable final BigDecimal amount,
@Nullable final CurrencyId currencyId,
@Nullable final Money fallback,
@NonNull final Supplier<CurrencyId> defaultCurrencyIdSupplier)
{
if (amount == null && currencyId == null && fallback != null)
{
return fallback;
} | final BigDecimal amountEffective = coalesce(
amount,
fallback != null ? fallback.toBigDecimal() : BigDecimal.ZERO);
final CurrencyId currencyIdEffective = coalesceSuppliers(
() -> currencyId,
() -> fallback != null ? fallback.getCurrencyId() : null,
defaultCurrencyIdSupplier);
if (currencyIdEffective == null)
{
// shall not happen
throw new AdempiereException("No currency set");
}
return Money.of(amountEffective, currencyIdEffective);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRowReducers.java | 1 |
请完成以下Java代码 | private ConfigurationPropertyName tryMap(String propertySourceName) {
try {
ConfigurationPropertyName convertedName = ConfigurationPropertyName.adapt(propertySourceName, '.');
if (!convertedName.isEmpty()) {
return convertedName;
}
}
catch (Exception ex) {
// Ignore
}
return ConfigurationPropertyName.EMPTY;
}
private static class LastMapping<T, M> {
private final T from;
private final M mapping; | LastMapping(T from, M mapping) {
this.from = from;
this.mapping = mapping;
}
boolean isFrom(T from) {
return ObjectUtils.nullSafeEquals(from, this.from);
}
M getMapping() {
return this.mapping;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\DefaultPropertyMapper.java | 1 |
请完成以下Java代码 | public int getM_ProductPrice_ID()
{
return olCandRecord.getM_ProductPrice_ID();
}
@Override
public boolean isExplicitProductPriceAttribute()
{
return olCandRecord.isExplicitProductPriceAttribute();
}
public int getFlatrateConditionsId()
{
return olCandRecord.getC_Flatrate_Conditions_ID();
}
public int getHUPIProductItemId()
{
final HUPIItemProductId packingInstructions = olCandEffectiveValuesBL.getEffectivePackingInstructions(olCandRecord);
return HUPIItemProductId.toRepoId(packingInstructions);
}
public InvoicableQtyBasedOn getInvoicableQtyBasedOn()
{
return InvoicableQtyBasedOn.ofNullableCodeOrNominal(olCandRecord.getInvoicableQtyBasedOn());
}
public BPartnerInfo getBPartnerInfo()
{
return bpartnerInfo; | }
public boolean isAssignToBatch(@NonNull final AsyncBatchId asyncBatchIdCandidate)
{
if (this.asyncBatchId == null)
{
return false;
}
return asyncBatchId.getRepoId() == asyncBatchIdCandidate.getRepoId();
}
public void setHeaderAggregationKey(@NonNull final String headerAggregationKey)
{
olCandRecord.setHeaderAggregationKey(headerAggregationKey);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCand.java | 1 |
请完成以下Java代码 | public class RequestAttributePrincipalResolver implements OAuth2ClientHttpRequestInterceptor.PrincipalResolver {
private static final String PRINCIPAL_ATTR_NAME = RequestAttributePrincipalResolver.class.getName()
.concat(".principal");
@Override
public Authentication resolve(HttpRequest request) {
return (Authentication) request.getAttributes().get(PRINCIPAL_ATTR_NAME);
}
/**
* Modifies the {@link ClientHttpRequest#getAttributes() attributes} to include the
* {@link Authentication principal} to be used to look up the
* {@link OAuth2AuthorizedClient}.
* @param principal the {@link Authentication principal} to be used to look up the
* {@link OAuth2AuthorizedClient}
* @return the {@link Consumer} to populate the attributes
*/
public static Consumer<Map<String, Object>> principal(Authentication principal) {
Assert.notNull(principal, "principal cannot be null");
return (attributes) -> attributes.put(PRINCIPAL_ATTR_NAME, principal);
}
/**
* Modifies the {@link ClientHttpRequest#getAttributes() attributes} to include the
* {@link Authentication principal} to be used to look up the | * {@link OAuth2AuthorizedClient}.
* @param principalName the {@code principalName} to be used to look up the
* {@link OAuth2AuthorizedClient}
* @return the {@link Consumer} to populate the attributes
*/
public static Consumer<Map<String, Object>> principal(String principalName) {
Assert.hasText(principalName, "principalName cannot be empty");
Authentication principal = createAuthentication(principalName);
return (attributes) -> attributes.put(PRINCIPAL_ATTR_NAME, principal);
}
private static Authentication createAuthentication(String principalName) {
return new AbstractAuthenticationToken(Collections.emptySet()) {
@Override
public Object getPrincipal() {
return principalName;
}
@Override
public Object getCredentials() {
return null;
}
};
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\client\RequestAttributePrincipalResolver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Boolean isArchived() {
return archived;
}
public void setArchived(Boolean archived) {
this.archived = archived;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AttachmentMetadata attachmentMetadata = (AttachmentMetadata) o;
return Objects.equals(this.type, attachmentMetadata.type) &&
Objects.equals(this.therapyId, attachmentMetadata.therapyId) &&
Objects.equals(this.therapyTypeId, attachmentMetadata.therapyTypeId) &&
Objects.equals(this.woundLocation, attachmentMetadata.woundLocation) &&
Objects.equals(this.patientId, attachmentMetadata.patientId) &&
Objects.equals(this.createdBy, attachmentMetadata.createdBy) &&
Objects.equals(this.createdAt, attachmentMetadata.createdAt) &&
Objects.equals(this.archived, attachmentMetadata.archived);
}
@Override
public int hashCode() {
return Objects.hash(type, therapyId, therapyTypeId, woundLocation, patientId, createdBy, createdAt, archived);
} | @Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class AttachmentMetadata {\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" therapyId: ").append(toIndentedString(therapyId)).append("\n");
sb.append(" therapyTypeId: ").append(toIndentedString(therapyTypeId)).append("\n");
sb.append(" woundLocation: ").append(toIndentedString(woundLocation)).append("\n");
sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n");
sb.append(" createdBy: ").append(toIndentedString(createdBy)).append("\n");
sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\model\AttachmentMetadata.java | 2 |
请完成以下Java代码 | public String getTaskId() {
return taskId;
}
@Override
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public String getCalledProcessInstanceId() {
return calledProcessInstanceId;
}
@Override
public void setCalledProcessInstanceId(String calledProcessInstanceId) {
this.calledProcessInstanceId = calledProcessInstanceId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public Date getTime() {
return getStartTime();
} | @Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ActivityInstanceEntity[id=").append(id)
.append(", activityId=").append(activityId);
if (activityName != null) {
sb.append(", activityName=").append(activityName);
}
sb.append(", executionId=").append(executionId)
.append(", definitionId=").append(processDefinitionId);
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ActivityInstanceEntityImpl.java | 1 |
请完成以下Java代码 | public class PersonWithEquals {
private String firstName;
private String lastName;
private LocalDate birthDate;
public PersonWithEquals(String firstName, String lastName) {
if (firstName == null || lastName == null) {
throw new NullPointerException("Names can't be null");
}
this.firstName = firstName;
this.lastName = lastName;
}
public PersonWithEquals(String firstName, String lastName, LocalDate birthDate) {
this(firstName, lastName);
this.birthDate = birthDate;
}
public String getFirstName() {
return firstName;
}
public String getLastName() { | return lastName;
}
public LocalDate getBirthDate() {
return birthDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PersonWithEquals that = (PersonWithEquals) o;
return firstName.equals(that.firstName) &&
lastName.equals(that.lastName) &&
Objects.equals(birthDate, that.birthDate);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
} | repos\tutorials-master\core-java-modules\core-java-lang\src\main\java\com\baeldung\comparing\PersonWithEquals.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_EXP_Processor getEXP_Processor() throws RuntimeException
{
return (org.compiere.model.I_EXP_Processor)MTable.get(getCtx(), org.compiere.model.I_EXP_Processor.Table_Name)
.getPO(getEXP_Processor_ID(), get_TrxName()); }
/** Set Export Processor.
@param EXP_Processor_ID Export Processor */
public void setEXP_Processor_ID (int EXP_Processor_ID)
{
if (EXP_Processor_ID < 1)
set_Value (COLUMNNAME_EXP_Processor_ID, null);
else
set_Value (COLUMNNAME_EXP_Processor_ID, Integer.valueOf(EXP_Processor_ID));
}
/** Get Export Processor.
@return Export Processor */
public int getEXP_Processor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_EXP_Processor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** 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 Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReplicationStrategy.java | 1 |
请完成以下Java代码 | public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public Date getFollowUpDate() {
return followUpDate;
}
public void setFollowUpDate(Date followUpDate) {
this.followUpDate = followUpDate;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public String getParentTaskId() {
return parentTaskId;
}
public void setParentTaskId(String parentTaskId) {
this.parentTaskId = parentTaskId;
}
public void setDeleteReason(final String deleteReason) {
this.deleteReason = deleteReason;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getTaskId() {
return taskId;
}
public String getTaskDefinitionKey() {
return taskDefinitionKey;
}
public void setTaskDefinitionKey(String taskDefinitionKey) {
this.taskDefinitionKey = taskDefinitionKey;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public void setActivityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId; | }
public String getTaskState() {
return taskState;
}
public void setTaskState(String taskState) {
this.taskState = taskState;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[taskId" + taskId
+ ", assignee=" + assignee
+ ", owner=" + owner
+ ", name=" + name
+ ", description=" + description
+ ", dueDate=" + dueDate
+ ", followUpDate=" + followUpDate
+ ", priority=" + priority
+ ", parentTaskId=" + parentTaskId
+ ", deleteReason=" + deleteReason
+ ", taskDefinitionKey=" + taskDefinitionKey
+ ", durationInMillis=" + durationInMillis
+ ", startTime=" + startTime
+ ", endTime=" + endTime
+ ", id=" + id
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", activityInstanceId=" + activityInstanceId
+ ", tenantId=" + tenantId
+ ", taskState=" + taskState
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricTaskInstanceEventEntity.java | 1 |
请完成以下Java代码 | public Void execute(CommandContext commandContext) {
if (processDefinitionId == null) {
throw new ActivitiIllegalArgumentException("Process definition id is null");
}
ProcessDefinitionEntity processDefinition = commandContext
.getProcessDefinitionEntityManager()
.findById(processDefinitionId);
if (processDefinition == null) {
throw new ActivitiObjectNotFoundException(
"No process definition found for id = '" + processDefinitionId + "'",
ProcessDefinition.class
);
}
executeInternal(commandContext, processDefinition);
return null;
}
protected void executeInternal(CommandContext commandContext, ProcessDefinitionEntity processDefinition) {
// Update category
processDefinition.setCategory(category);
// Remove process definition from cache, it will be refetched later
DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache = commandContext
.getProcessEngineConfiguration()
.getProcessDefinitionCache();
if (processDefinitionCache != null) {
processDefinitionCache.remove(processDefinitionId);
} | if (commandContext.getEventDispatcher().isEnabled()) {
commandContext
.getEventDispatcher()
.dispatchEvent(
ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_UPDATED, processDefinition)
);
}
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SetProcessDefinitionCategoryCmd.java | 1 |
请完成以下Java代码 | public static FormService getFormService(AbstractEngineConfiguration engineConfiguration) {
FormService formService = null;
FormEngineConfigurationApi formEngineConfiguration = getFormEngineConfiguration(engineConfiguration);
if (formEngineConfiguration != null) {
formService = formEngineConfiguration.getFormService();
}
return formService;
}
public static FormManagementService getFormManagementService(AbstractEngineConfiguration engineConfiguration) {
FormManagementService formManagementService = null;
FormEngineConfigurationApi formEngineConfiguration = getFormEngineConfiguration(engineConfiguration);
if (formEngineConfiguration != null) {
formManagementService = formEngineConfiguration.getFormManagementService();
}
return formManagementService;
} | // CONTENT ENGINE
public static ContentEngineConfigurationApi getContentEngineConfiguration(AbstractEngineConfiguration engineConfiguration) {
return (ContentEngineConfigurationApi) engineConfiguration.getEngineConfigurations().get(EngineConfigurationConstants.KEY_CONTENT_ENGINE_CONFIG);
}
public static ContentService getContentService(AbstractEngineConfiguration engineConfiguration) {
ContentService contentService = null;
ContentEngineConfigurationApi contentEngineConfiguration = getContentEngineConfiguration(engineConfiguration);
if (contentEngineConfiguration != null) {
contentService = contentEngineConfiguration.getContentService();
}
return contentService;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\EngineServiceUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public UUID getId() {
return _id;
}
public void setId(UUID _id) {
this._id = _id;
}
public DeviceMapping serialNumber(String serialNumber) {
this.serialNumber = serialNumber;
return this;
}
/**
* eindeutige Seriennumer aus WaWi
* @return serialNumber
**/
@Schema(example = "2005-F540053-EB-0430", required = true, description = "eindeutige Seriennumer aus WaWi")
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public DeviceMapping updated(OffsetDateTime updated) {
this.updated = updated;
return this;
}
/**
* Der Zeitstempel der letzten Änderung
* @return updated
**/
@Schema(example = "2020-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung")
public OffsetDateTime getUpdated() {
return updated;
}
public void setUpdated(OffsetDateTime updated) {
this.updated = updated;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
} | DeviceMapping deviceMapping = (DeviceMapping) o;
return Objects.equals(this._id, deviceMapping._id) &&
Objects.equals(this.serialNumber, deviceMapping.serialNumber) &&
Objects.equals(this.updated, deviceMapping.updated);
}
@Override
public int hashCode() {
return Objects.hash(_id, serialNumber, updated);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DeviceMapping {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" serialNumber: ").append(toIndentedString(serialNumber)).append("\n");
sb.append(" updated: ").append(toIndentedString(updated)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\DeviceMapping.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public abstract class AbstractFunctionExecutionAutoConfigurationExtension
extends FunctionExecutionBeanDefinitionRegistrar implements BeanFactoryAware {
private BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
protected BeanFactory getBeanFactory() {
Assert.state(this.beanFactory != null, "BeanFactory was not properly configured");
return this.beanFactory;
}
protected abstract Class<?> getConfiguration();
@SuppressWarnings("unused") | @Override
protected AbstractFunctionExecutionConfigurationSource newAnnotationBasedFunctionExecutionConfigurationSource(
AnnotationMetadata annotationMetadata) {
AnnotationMetadata metadata = AnnotationMetadata.introspect(getConfiguration());
return new AnnotationFunctionExecutionConfigurationSource(metadata) {
@Override
public Iterable<String> getBasePackages() {
return AutoConfigurationPackages.get(getBeanFactory());
}
};
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\function\config\AbstractFunctionExecutionAutoConfigurationExtension.java | 2 |
请完成以下Java代码 | public boolean isAddressLinesReverse ()
{
Object oo = get_Value(COLUMNNAME_IsAddressLinesReverse);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Media Size.
@param MediaSize
Java Media Size
*/
@Override
public void setMediaSize (java.lang.String MediaSize)
{
set_Value (COLUMNNAME_MediaSize, MediaSize);
}
/** Get Media Size.
@return Java Media Size
*/
@Override
public java.lang.String getMediaSize ()
{
return (java.lang.String)get_Value(COLUMNNAME_MediaSize);
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | /** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Region.
@param RegionName
Name of the Region
*/
@Override
public void setRegionName (java.lang.String RegionName)
{
set_Value (COLUMNNAME_RegionName, RegionName);
}
/** Get Region.
@return Name of the Region
*/
@Override
public java.lang.String getRegionName ()
{
return (java.lang.String)get_Value(COLUMNNAME_RegionName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Country.java | 1 |
请完成以下Java代码 | public void approveForInvoicingLinkedInvoiceCandidates(final I_M_InOut inOut)
{
Check.assumeNotNull(inOut, "InOut not null");
final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class);
final boolean isApprovedForInvoicing = inOut.isInOutApprovedForInvoicing();
if (!isApprovedForInvoicing)
{
// nothing to do
return;
}
// get all the inout lines of the given inout
final List<I_M_InOutLine> inoutLines = Services.get(IInOutDAO.class).retrieveLines(inOut);
for (final I_M_InOutLine line : inoutLines)
{
// for each line, get all the linked invoice candidates
final List<I_C_Invoice_Candidate> candidates = invoiceCandDAO.retrieveInvoiceCandidatesForInOutLine(line);
for (final I_C_Invoice_Candidate candidate : candidates)
{
// because we are not allowed to set an invoice candidate as approved for invoicing if not all the valid inoutlines linked to it are approved for invoicing,
// we have to get all the linked lines and check them one by one
final List<I_M_InOutLine> inOutLinesForCandidate = invoiceCandDAO.retrieveInOutLinesForCandidate(candidate, I_M_InOutLine.class);
boolean isAllowInvoicing = true;
for (final I_M_InOutLine inOutLineForCandidate : inOutLinesForCandidate)
{
if(inOutLineForCandidate.getM_InOut_ID() == inOut.getM_InOut_ID())
{
// skip the current inout | continue;
}
final I_M_InOut inoutForCandidate = InterfaceWrapperHelper.create(inOutLineForCandidate.getM_InOut(), I_M_InOut.class);
// in case the inout entry is active, completed or closed but it doesn't have the flag isInOutApprovedForInvoicing set on true
// we shall not approve the candidate for invoicing
if (Services.get(IInOutInvoiceCandidateBL.class).isApproveInOutForInvoicing(inoutForCandidate) && !inoutForCandidate.isInOutApprovedForInvoicing())
{
isAllowInvoicing = false;
break;
}
}
candidate.setIsInOutApprovedForInvoicing(isAllowInvoicing);
// also set the ApprovalForInvoicing flag with the calculated value
// note that this flag is editable so it can be modifyied by the user anytime
candidate.setApprovalForInvoicing(isAllowInvoicing);
InterfaceWrapperHelper.save(candidate);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\api\impl\InOutInvoiceCandidateBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static DeleteIndexRequest buildDeleteIndexRequest(String index) {
return new DeleteIndexRequest(index);
}
/**
* build IndexRequest
*
* @param index elasticsearch index name
* @param id request object id
* @param object request object
* @return {@link org.elasticsearch.action.index.IndexRequest}
* @author fxbin
*/
protected static IndexRequest buildIndexRequest(String index, String id, Object object) {
return new IndexRequest(index).id(id).source(BeanUtil.beanToMap(object), XContentType.JSON);
}
/**
* exec updateRequest
*
* @param index elasticsearch index name
* @param id Document id
* @param object request object
* @author fxbin
*/
protected void updateRequest(String index, String id, Object object) {
try {
UpdateRequest updateRequest = new UpdateRequest(index, id).doc(BeanUtil.beanToMap(object), XContentType.JSON);
client.update(updateRequest, COMMON_OPTIONS);
} catch (IOException e) {
throw new ElasticsearchException("更新索引 {" + index + "} 数据 {" + object + "} 失败");
}
}
/**
* exec deleteRequest
*
* @param index elasticsearch index name
* @param id Document id
* @author fxbin
*/
protected void deleteRequest(String index, String id) {
try { | DeleteRequest deleteRequest = new DeleteRequest(index, id);
client.delete(deleteRequest, COMMON_OPTIONS);
} catch (IOException e) {
throw new ElasticsearchException("删除索引 {" + index + "} 数据id {" + id + "} 失败");
}
}
/**
* search all
*
* @param index elasticsearch index name
* @return {@link SearchResponse}
* @author fxbin
*/
protected SearchResponse search(String index) {
SearchRequest searchRequest = new SearchRequest(index);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = null;
try {
searchResponse = client.search(searchRequest, COMMON_OPTIONS);
} catch (IOException e) {
e.printStackTrace();
}
return searchResponse;
}
} | repos\spring-boot-demo-master\demo-elasticsearch-rest-high-level-client\src\main\java\com\xkcoding\elasticsearch\service\base\BaseElasticsearchService.java | 2 |
请完成以下Java代码 | public static String getIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
String comma = ",";
String localhost = "127.0.0.1";
if (ip.contains(comma)) {
ip = ip.split(",")[0];
}
if (localhost.equals(ip)) {
// 获取本机真正的ip地址
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.error(e.getMessage(), e);
}
}
return ip;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
static class Log {
// 线程id
private String threadId;
// 线程名称
private String threadName;
// ip
private String ip;
// url
private String url; | // http方法 GET POST PUT DELETE PATCH
private String httpMethod;
// 类方法
private String classMethod;
// 请求参数
private Object requestParams;
// 返回参数
private Object result;
// 接口耗时
private Long timeCost;
// 操作系统
private String os;
// 浏览器
private String browser;
// user-agent
private String userAgent;
}
} | repos\spring-boot-demo-master\demo-log-aop\src\main\java\com\xkcoding\log\aop\aspectj\AopLog.java | 1 |
请完成以下Java代码 | public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getTaskId() {
return taskId;
}
public String getErrorMessage() {
return errorMessage;
}
public String getTenantId() {
return tenantId;
}
public String getState() {
return state;
}
public Date getCreateTime() {
return createTime;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
} | public static HistoricVariableInstanceDto fromHistoricVariableInstance(HistoricVariableInstance historicVariableInstance) {
HistoricVariableInstanceDto dto = new HistoricVariableInstanceDto();
dto.id = historicVariableInstance.getId();
dto.name = historicVariableInstance.getName();
dto.processDefinitionKey = historicVariableInstance.getProcessDefinitionKey();
dto.processDefinitionId = historicVariableInstance.getProcessDefinitionId();
dto.processInstanceId = historicVariableInstance.getProcessInstanceId();
dto.executionId = historicVariableInstance.getExecutionId();
dto.activityInstanceId = historicVariableInstance.getActivityInstanceId();
dto.caseDefinitionKey = historicVariableInstance.getCaseDefinitionKey();
dto.caseDefinitionId = historicVariableInstance.getCaseDefinitionId();
dto.caseInstanceId = historicVariableInstance.getCaseInstanceId();
dto.caseExecutionId = historicVariableInstance.getCaseExecutionId();
dto.taskId = historicVariableInstance.getTaskId();
dto.tenantId = historicVariableInstance.getTenantId();
dto.state = historicVariableInstance.getState();
dto.createTime = historicVariableInstance.getCreateTime();
dto.removalTime = historicVariableInstance.getRemovalTime();
dto.rootProcessInstanceId = historicVariableInstance.getRootProcessInstanceId();
if(historicVariableInstance.getErrorMessage() == null) {
VariableValueDto.fromTypedValue(dto, historicVariableInstance.getTypedValue());
}
else {
dto.errorMessage = historicVariableInstance.getErrorMessage();
dto.type = VariableValueDto.toRestApiTypeName(historicVariableInstance.getTypeName());
}
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricVariableInstanceDto.java | 1 |
请完成以下Spring Boot application配置 | # Custom properties to ease configuration overrides
# on command-line or IDE launch configurations
scheme: http
hostname: localhost
reverse-proxy-port: 7080
reverse-proxy-uri: ${scheme}://${hostname}:${reverse-proxy-port}
authorization-server-prefix: /auth
issuer: ${reverse-proxy-uri}${authorization-server-prefix}/realms/baeldung
client-id: baeldung-confidential
client-secret: secret
username-claim-json-path: $.preferred_username
authorities-json-path: $.realm_access.roles
bff-port: 7081
bff-prefix: /bff
resource-server-port: 7084
audience:
server:
port: ${bff-port}
ssl:
enabled: false
spring:
cloud:
gateway:
routes:
- id: bff
uri: ${scheme}://${hostname}:${resource-server-port}
predicates:
- Path=/api/**
filters:
- DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
- TokenRelay=
- SaveSession
- StripPrefix=1
security:
oauth2:
client:
provider:
baeldung:
issuer-uri: ${issuer}
registration:
baeldung:
provider: baeldung
authorization-grant-type: authorization_code
client-id: ${client-id}
client-secret: ${client-secret}
scope: openid,profile,email,offline_access
com:
c4-soft:
springaddons:
oidc:
ops:
- iss: ${issuer}
authorities:
- path: ${authorities-json-path}
aud: ${audience}
# SecurityFilterChain with oauth2Login() (sessions and CSRF protection enabled)
client:
client-uri: ${reverse-proxy-uri}${bff-prefix}
security-matchers:
- /api/**
- /login/**
- /oauth2/**
- /logout/**
permit-all:
- /api/**
- /login/**
- /oauth2/**
- /logout/connect/back-channel/baeldung
post-logout-redirect-host: ${hostname}
csrf: cookie-accessible-from-js
oauth2-redirections:
rp-initiated-logout: ACCEPTED
back-channel-logout:
enabled: true
# internal-logout-uri: ${reverse-proxy-uri}${bff-prefix}/logout
# should work too, but there is no reason to go through the reverse proxy for this internal call
internal-logout-uri: ${scheme}://localhost:${bff-port}/logout
# SecurityFilterChain with oauth2ResourceServer() (sessions and CSRF protection disabled)
resourceserver:
permit-all:
- /login-options
- /error
- /v3/api-docs/**
- /swagger-ui/**
- /actuator/health/readiness
- /actuator/health/liveness
management:
endpoint:
health:
probes:
enabled: true
endpoints:
web:
exposure:
include: '*'
health:
livenessstate:
enabled: true
readinessstate:
enabled: true
logging:
level:
root: INFO
org:
springframework:
boot: INFO
security: TRACE
web: INFO
---
spring:
| config:
activate:
on-profile: ssl
server:
ssl:
enabled: true
scheme: https
---
spring:
config:
activate:
on-profile: cognito
issuer: https://cognito-idp.us-west-2.amazonaws.com/us-west-2_RzhmgLwjl
client-id: 12olioff63qklfe9nio746es9f
client-secret: change-me
username-claim-json-path: username
authorities-json-path: $.cognito:groups
com:
c4-soft:
springaddons:
oidc:
client:
oauth2-logout:
baeldung:
uri: https://spring-addons.auth.us-west-2.amazoncognito.com/logout
client-id-request-param: client_id
post-logout-uri-request-param: logout_uri
---
spring:
config:
activate:
on-profile: auth0
issuer: https://dev-ch4mpy.eu.auth0.com/
client-id: yWgZDRJLAksXta8BoudYfkF5kus2zv2Q
client-secret: change-me
username-claim-json-path: $['https://c4-soft.com/user']['name']
authorities-json-path: $['https://c4-soft.com/user']['roles']
audience: bff.baeldung.com
com:
c4-soft:
springaddons:
oidc:
client:
authorization-params:
baeldung:
audience: ${audience}
oauth2-logout:
baeldung:
uri: ${issuer}v2/logout
client-id-request-param: client_id
post-logout-uri-request-param: returnTo | repos\tutorials-master\spring-security-modules\spring-security-oauth2-bff\backend\bff\src\main\resources\application.yml | 2 |
请完成以下Java代码 | private static ManufacturingOrderExportAuditItem createExportedAuditItem(@NonNull final I_PP_Order order)
{
return ManufacturingOrderExportAuditItem.builder()
.orderId(PPOrderId.ofRepoId(order.getPP_Order_ID()))
.orgId(OrgId.ofRepoIdOrAny(order.getAD_Org_ID()))
.exportStatus(APIExportStatus.Exported)
.build();
}
private static ManufacturingOrderExportAuditItem createExportErrorAuditItem(final I_PP_Order order, final AdIssueId adIssueId)
{
return ManufacturingOrderExportAuditItem.builder()
.orderId(PPOrderId.ofRepoId(order.getPP_Order_ID()))
.orgId(OrgId.ofRepoIdOrAny(order.getAD_Org_ID()))
.exportStatus(APIExportStatus.ExportError)
.issueId(adIssueId)
.build();
}
private AdIssueId createAdIssueId(final Throwable ex)
{
return errorManager.createIssue(IssueCreateRequest.builder()
.throwable(ex)
.loggerName(logger.getName())
.sourceClassname(ManufacturingOrderAPIService.class.getName())
.summary(ex.getMessage())
.build());
}
private List<I_PP_Order_BOMLine> getBOMLinesByOrderId(final PPOrderId orderId)
{
return getBOMLinesByOrderId().get(orderId);
}
private ImmutableListMultimap<PPOrderId, I_PP_Order_BOMLine> getBOMLinesByOrderId()
{
if (_bomLinesByOrderId != null)
{
return _bomLinesByOrderId;
}
final ImmutableSet<PPOrderId> orderIds = getOrders()
.stream()
.map(order -> PPOrderId.ofRepoId(order.getPP_Order_ID()))
.collect(ImmutableSet.toImmutableSet());
_bomLinesByOrderId = ppOrderBOMDAO.retrieveOrderBOMLines(orderIds, I_PP_Order_BOMLine.class)
.stream()
.collect(ImmutableListMultimap.toImmutableListMultimap(
bomLine -> PPOrderId.ofRepoId(bomLine.getPP_Order_ID()),
bomLine -> bomLine)); | return _bomLinesByOrderId;
}
private Product getProductById(@NonNull final ProductId productId)
{
if (_productsById == null)
{
final HashSet<ProductId> allProductIds = new HashSet<>();
allProductIds.add(productId);
getOrders().stream()
.map(order -> ProductId.ofRepoId(order.getM_Product_ID()))
.forEach(allProductIds::add);
getBOMLinesByOrderId()
.values()
.stream()
.map(bomLine -> ProductId.ofRepoId(bomLine.getM_Product_ID()))
.forEach(allProductIds::add);
_productsById = productRepo.getByIds(allProductIds)
.stream()
.collect(GuavaCollectors.toHashMapByKey(Product::getId));
}
return _productsById.computeIfAbsent(productId, productRepo::getById);
}
private List<I_PP_Order> getOrders()
{
if (_orders == null)
{
_orders = ppOrderDAO.retrieveManufacturingOrders(query);
}
return _orders;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\v1\ManufacturingOrdersExportCommand.java | 1 |
请完成以下Java代码 | private IExportDataSource createDataSource(@NonNull final DATEVExportFormat exportFormat, final int datevExportId)
{
Check.assume(datevExportId > 0, "datevExportId > 0");
final JdbcExporterBuilder builder = new JdbcExporterBuilder(I_DATEV_ExportLine.Table_Name)
.addEqualsWhereClause(I_DATEV_ExportLine.COLUMNNAME_DATEV_Export_ID, datevExportId)
.addEqualsWhereClause(I_DATEV_ExportLine.COLUMNNAME_IsActive, true)
.addOrderBy(I_DATEV_ExportLine.COLUMNNAME_DocumentNo)
.addOrderBy(I_DATEV_ExportLine.COLUMNNAME_DATEV_ExportLine_ID);
exportFormat
.getColumns()
.forEach(formatColumn -> builder.addField(formatColumn.getCsvHeaderName(), formatColumn.getColumnName()));
return builder.createDataSource();
} | private static String buildFilename(final I_DATEV_Export datevExport)
{
final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
final Timestamp dateAcctFrom = datevExport.getDateAcctFrom();
final Timestamp dateAcctTo = datevExport.getDateAcctTo();
return Joiner.on("_")
.skipNulls()
.join("datev",
dateAcctFrom != null ? dateFormatter.format(TimeUtil.asLocalDate(dateAcctFrom)) : null,
dateAcctTo != null ? dateFormatter.format(TimeUtil.asLocalDate(dateAcctTo)) : null)
+ ".csv";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java\de\metas\datev\process\DATEV_ExportFile.java | 1 |
请完成以下Java代码 | private Stream<CacheInterface> streamCaches()
{
return caches.values().stream().filter(Objects::nonNull);
}
private long invalidateAllNoFail()
{
return streamCaches()
.mapToLong(CachesGroup::invalidateNoFail)
.sum();
}
private long invalidateForRecordNoFail(final TableRecordReference recordRef)
{
return streamCaches()
.mapToLong(cache -> invalidateNoFail(cache, recordRef))
.sum();
}
private static long invalidateNoFail(@Nullable final CacheInterface cacheInstance)
{
try (final IAutoCloseable ignored = CacheMDC.putCache(cacheInstance))
{
if (cacheInstance == null)
{
return 0;
} | return cacheInstance.reset();
}
catch (final Exception ex)
{
// log but don't fail
logger.warn("Error while resetting {}. Ignored.", cacheInstance, ex);
return 0;
}
}
private static long invalidateNoFail(final CacheInterface cacheInstance, final TableRecordReference recordRef)
{
try (final IAutoCloseable ignored = CacheMDC.putCache(cacheInstance))
{
return cacheInstance.resetForRecordId(recordRef);
}
catch (final Exception ex)
{
// log but don't fail
logger.warn("Error while resetting {} for {}. Ignored.", cacheInstance, recordRef, ex);
return 0;
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CacheMgt.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public int getMinIdle() {
return minIdle; | }
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-7 课: Spring Boot 集成 Druid 监控数据源\spring-boot-multi-Jpa-druid\src\main\java\com\neo\config\druid\DruidOneConfig.java | 2 |
请完成以下Java代码 | public List<Series> getSeries() {
return series;
}
public RetryConfig setSeries(Series... series) {
this.series = Arrays.asList(series);
return this;
}
public List<HttpStatus> getStatuses() {
return statuses;
}
public RetryConfig setStatuses(HttpStatus... statuses) {
this.statuses = Arrays.asList(statuses);
return this;
}
public List<HttpMethod> getMethods() {
return methods;
}
public RetryConfig setMethods(HttpMethod... methods) {
this.methods = Arrays.asList(methods);
return this;
}
public List<Class<? extends Throwable>> getExceptions() {
return exceptions;
}
public RetryConfig setExceptions(Class<? extends Throwable>... exceptions) {
this.exceptions = Arrays.asList(exceptions);
return this;
}
}
public static class BackoffConfig {
private Duration firstBackoff = Duration.ofMillis(5);
private @Nullable Duration maxBackoff;
private int factor = 2;
private boolean basedOnPreviousValue = true;
public BackoffConfig() {
}
public BackoffConfig(Duration firstBackoff, Duration maxBackoff, int factor, boolean basedOnPreviousValue) {
this.firstBackoff = firstBackoff;
this.maxBackoff = maxBackoff;
this.factor = factor;
this.basedOnPreviousValue = basedOnPreviousValue;
}
public void validate() {
Objects.requireNonNull(this.firstBackoff, "firstBackoff must be present");
}
public Duration getFirstBackoff() {
return firstBackoff;
}
public void setFirstBackoff(Duration firstBackoff) {
this.firstBackoff = firstBackoff;
}
public @Nullable Duration getMaxBackoff() {
return maxBackoff;
}
public void setMaxBackoff(Duration maxBackoff) {
this.maxBackoff = maxBackoff;
}
public int getFactor() {
return factor;
} | public void setFactor(int factor) {
this.factor = factor;
}
public boolean isBasedOnPreviousValue() {
return basedOnPreviousValue;
}
public void setBasedOnPreviousValue(boolean basedOnPreviousValue) {
this.basedOnPreviousValue = basedOnPreviousValue;
}
@Override
public String toString() {
return new ToStringCreator(this).append("firstBackoff", firstBackoff)
.append("maxBackoff", maxBackoff)
.append("factor", factor)
.append("basedOnPreviousValue", basedOnPreviousValue)
.toString();
}
}
public static class JitterConfig {
private double randomFactor = 0.5;
public void validate() {
Assert.isTrue(randomFactor >= 0 && randomFactor <= 1,
"random factor must be between 0 and 1 (default 0.5)");
}
public JitterConfig() {
}
public JitterConfig(double randomFactor) {
this.randomFactor = randomFactor;
}
public double getRandomFactor() {
return randomFactor;
}
public void setRandomFactor(double randomFactor) {
this.randomFactor = randomFactor;
}
@Override
public String toString() {
return new ToStringCreator(this).append("randomFactor", randomFactor).toString();
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RetryGatewayFilterFactory.java | 1 |
请完成以下Java代码 | private static class ConfigAndEvents
{
@Getter
private final FTSConfig config;
@Getter
private final ImmutableSet<TableName> sourceTableNames;
private final ArrayList<ModelToIndex> events = new ArrayList<>();
private ConfigAndEvents(
@NonNull final FTSConfig config,
@NonNull final ImmutableSet<TableName> sourceTableNames)
{
this.config = config;
this.sourceTableNames = sourceTableNames;
} | public void addEvent(final ModelToIndex event)
{
if (!events.contains(event))
{
events.add(event);
}
}
public ImmutableList<ModelToIndex> getEvents()
{
return ImmutableList.copyOf(events);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\indexer\queue\ModelToIndexEnqueueProcessor.java | 1 |
请完成以下Java代码 | void collect(@NonNull final IAttributeSet from)
{
from.getAttributes()
.stream()
.filter(AttributeSetAggregator::isAggregable)
.forEach(attribute -> getAttributeAggregator(attribute).collect(from));
}
@NonNull
private AttributeAggregator getAttributeAggregator(@NonNull final I_M_Attribute attribute)
{
return attributeAggregators.computeIfAbsent(
AttributeCode.ofString(attribute.getValue()),
attributeCode -> new AttributeAggregator(attributeCode, AttributeValueType.ofCode(attribute.getAttributeValueType()))
);
}
void updateAggregatedValuesTo(@NonNull final IAttributeSet to)
{
attributeAggregators.values()
.forEach(attributeAggregator -> attributeAggregator.updateAggregatedValueTo(to));
}
private static boolean isAggregable(@NonNull final I_M_Attribute attribute)
{
return !Weightables.isWeightableAttribute(AttributeCode.ofString(attribute.getValue()));
}
//
//
//
@RequiredArgsConstructor
private static class AttributeAggregator
{
private final AttributeCode attributeCode;
private final AttributeValueType attributeValueType;
private final HashSet<Object> values = new HashSet<>();
void collect(@NonNull final IAttributeSet from)
{ | final Object value = attributeValueType.map(new AttributeValueType.CaseMapper<Object>()
{
@Nullable
@Override
public Object string()
{
return from.getValueAsString(attributeCode);
}
@Override
public Object number()
{
return from.getValueAsBigDecimal(attributeCode);
}
@Nullable
@Override
public Object date()
{
return from.getValueAsDate(attributeCode);
}
@Nullable
@Override
public Object list()
{
return from.getValueAsString(attributeCode);
}
});
values.add(value);
}
void updateAggregatedValueTo(@NonNull final IAttributeSet to)
{
if (values.size() == 1 && to.hasAttribute(attributeCode))
{
to.setValue(attributeCode, values.iterator().next());
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AttributeSetAggregator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ErrorController {
@RequestMapping(value = "500Error", method = RequestMethod.GET)
public void throwRuntimeException() {
throw new NullPointerException("Throwing a null pointer exception");
}
@RequestMapping(value = "errors", method = RequestMethod.GET)
public ModelAndView renderErrorPage(HttpServletRequest httpRequest) {
ModelAndView errorPage = new ModelAndView("errorPage");
String errorMsg = "";
int httpErrorCode = getErrorCode(httpRequest);
switch (httpErrorCode) {
case 400: {
errorMsg = "Http Error Code : 400 . Bad Request";
break;
}
case 401: {
errorMsg = "Http Error Code : 401. Unauthorized";
break;
}
case 404: { | errorMsg = "Http Error Code : 404. Resource not found";
break;
}
// Handle other 4xx error codes.
case 500: {
errorMsg = "Http Error Code : 500. Internal Server Error";
break;
}
// Handle other 5xx error codes.
}
errorPage.addObject("errorMsg", errorMsg);
return errorPage;
}
private int getErrorCode(HttpServletRequest httpRequest) {
return (Integer) httpRequest.getAttribute("jakarta.servlet.error.status_code");
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-xml-2\src\main\java\com\baeldung\spring\controller\ErrorController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors(Customizer.withDefaults()).csrf(AbstractHttpConfigurer::disable)
.sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterAfter(requestHeaderAuthenticationFilter(), HeaderWriterFilter.class)
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry
.requestMatchers(HttpMethod.GET, "/health").permitAll()
.requestMatchers("/api/**").authenticated())
.exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer
.authenticationEntryPoint((request, response, authException) ->
response.sendError(HttpServletResponse.SC_UNAUTHORIZED)));
return http.build();
}
@Bean | public RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter() {
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
filter.setPrincipalRequestHeader(apiAuthHeaderName);
filter.setExceptionIfHeaderMissing(false);
filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/api/**"));
filter.setAuthenticationManager(authenticationManager());
return filter;
}
@Bean
protected AuthenticationManager authenticationManager() {
return new ProviderManager(Collections.singletonList(requestHeaderAuthenticationProvider));
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-5\src\main\java\com\baeldung\customauth\configuration\SecurityConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public JwtSettings getJwtSettings() {
log.trace("Executing getJwtSettings");
return getJwtSettings(false);
}
public JwtSettings getJwtSettings(boolean forceReload) {
if (this.jwtSettings == null || forceReload) {
synchronized (this) {
if (this.jwtSettings == null || forceReload) {
jwtSettings = getJwtSettingsFromDb();
}
}
}
return this.jwtSettings;
}
private JwtSettings getJwtSettingsFromDb() {
AdminSettings adminJwtSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, ADMIN_SETTINGS_JWT_KEY);
return adminJwtSettings != null ? mapAdminToJwtSettings(adminJwtSettings) : null;
}
private JwtSettings mapAdminToJwtSettings(AdminSettings adminSettings) {
Objects.requireNonNull(adminSettings, "adminSettings for JWT is null");
return JacksonUtil.treeToValue(adminSettings.getJsonValue(), JwtSettings.class);
}
private AdminSettings mapJwtToAdminSettings(JwtSettings jwtSettings) {
Objects.requireNonNull(jwtSettings, "jwtSettings is null");
AdminSettings adminJwtSettings = new AdminSettings(); | adminJwtSettings.setTenantId(TenantId.SYS_TENANT_ID);
adminJwtSettings.setKey(ADMIN_SETTINGS_JWT_KEY);
adminJwtSettings.setJsonValue(JacksonUtil.valueToTree(jwtSettings));
return adminJwtSettings;
}
public static boolean isSigningKeyDefault(JwtSettings settings) {
return TOKEN_SIGNING_KEY_DEFAULT.equals(settings.getTokenSigningKey());
}
public static boolean validateKeyLength(String key) {
return Base64.getDecoder().decode(key).length * Byte.SIZE >= KEY_LENGTH;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\jwt\settings\DefaultJwtSettingsService.java | 2 |
请完成以下Java代码 | final class FixedConversionRateMap
{
public static final FixedConversionRateMap EMPTY = new FixedConversionRateMap(ImmutableMap.of());
private final ImmutableMap<FixedConversionRateKey, FixedConversionRate> rates;
private FixedConversionRateMap(final Map<FixedConversionRateMap.FixedConversionRateKey, FixedConversionRate> rates)
{
this.rates = ImmutableMap.copyOf(rates);
}
public FixedConversionRateMap addingConversionRate(@NonNull final FixedConversionRate rate)
{
final HashMap<FixedConversionRateMap.FixedConversionRateKey, FixedConversionRate> newRates = new HashMap<>(rates);
newRates.put(extractKey(rate), rate);
return new FixedConversionRateMap(newRates);
}
private static FixedConversionRateMap.FixedConversionRateKey extractKey(@NonNull final FixedConversionRate rate)
{
return FixedConversionRateKey.builder()
.fromCurrencyId(rate.getFromCurrencyId())
.toCurrencyId(rate.getToCurrencyId())
.build();
}
public BigDecimal getMultiplyRate(
@NonNull final CurrencyId fromCurrencyId,
@NonNull final CurrencyId toCurrencyId)
{
final BigDecimal multiplyRate = getMultiplyRateOrNull(fromCurrencyId, toCurrencyId);
if (multiplyRate == null)
{
throw new AdempiereException("No fixed conversion rate found from " + fromCurrencyId + " to " + toCurrencyId + "."
+ " Available rates are: " + rates.values());
}
return multiplyRate;
}
public boolean hasMultiplyRate(
@NonNull final CurrencyId fromCurrencyId,
@NonNull final CurrencyId toCurrencyId)
{ | return getMultiplyRateOrNull(fromCurrencyId, toCurrencyId) != null;
}
@Nullable
private BigDecimal getMultiplyRateOrNull(
@NonNull final CurrencyId fromCurrencyId,
@NonNull final CurrencyId toCurrencyId)
{
final FixedConversionRate rate = rates.get(FixedConversionRateKey.builder()
.fromCurrencyId(fromCurrencyId)
.toCurrencyId(toCurrencyId)
.build());
return rate != null ? rate.getMultiplyRate() : null;
}
@Value
@Builder
private static class FixedConversionRateKey
{
@NonNull
CurrencyId fromCurrencyId;
@NonNull
CurrencyId toCurrencyId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\FixedConversionRateMap.java | 1 |
请完成以下Java代码 | private ClassicHttpResponse execute(HttpUriRequest request, URI url, String description) {
try {
HttpHost host = HttpHost.create(url);
request.addHeader("User-Agent", "SpringBootCli/" + getClass().getPackage().getImplementationVersion());
return getHttp().executeOpen(host, request, null);
}
catch (IOException ex) {
throw new ReportableException(
"Failed to " + description + " from service at '" + url + "' (" + ex.getMessage() + ")");
}
}
private ReportableException createException(String url, ClassicHttpResponse httpResponse) {
StatusLine statusLine = new StatusLine(httpResponse);
String message = "Initializr service call failed using '" + url + "' - service returned "
+ statusLine.getReasonPhrase();
String error = extractMessage(httpResponse.getEntity());
if (StringUtils.hasText(error)) {
message += ": '" + error + "'";
}
else {
int statusCode = statusLine.getStatusCode();
message += " (unexpected " + statusCode + " error)";
}
throw new ReportableException(message);
}
private @Nullable String extractMessage(@Nullable HttpEntity entity) {
if (entity != null) {
try {
JSONObject error = getContentAsJson(entity);
if (error.has("message")) {
return error.getString("message");
}
}
catch (Exception ex) {
// Ignore | }
}
return null;
}
private JSONObject getContentAsJson(HttpEntity entity) throws IOException, JSONException {
return new JSONObject(getContent(entity));
}
private String getContent(HttpEntity entity) throws IOException {
ContentType contentType = ContentType.create(entity.getContentType());
Charset charset = contentType.getCharset();
charset = (charset != null) ? charset : StandardCharsets.UTF_8;
byte[] content = FileCopyUtils.copyToByteArray(entity.getContent());
return new String(content, charset);
}
private @Nullable String extractFileName(@Nullable Header header) {
if (header != null) {
String value = header.getValue();
int start = value.indexOf(FILENAME_HEADER_PREFIX);
if (start != -1) {
value = value.substring(start + FILENAME_HEADER_PREFIX.length());
int end = value.indexOf('\"');
if (end != -1) {
return value.substring(0, end);
}
}
}
return null;
}
} | repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\init\InitializrService.java | 1 |
请完成以下Java代码 | public void start() {
// Technically, the resolveImportLifecycle().isLazy() check is not strictly required since if the cache data
// import is "eager", then the regionsForImport Set will be empty anyway.
if (resolveImportLifecycle().isLazy()) {
getRegionsForImport().forEach(getCacheDataImporterExporter()::importInto);
}
}
/**
* An {@link Enum Enumeration} defining the different modes for the cache data import lifecycle.
*/
public enum ImportLifecycle {
EAGER("Imports cache data during Region bean post processing, after initialization"),
LAZY("Imports cache data during the appropriate phase on Lifecycle start");
private final String description;
ImportLifecycle(@NonNull String description) {
Assert.hasText(description, "The enumerated value must have a description");
this.description = description;
}
public static @NonNull ImportLifecycle getDefault() {
return LAZY;
} | public static @Nullable ImportLifecycle from(String name) {
for (ImportLifecycle importCycle : values()) {
if (importCycle.name().equalsIgnoreCase(name)) {
return importCycle;
}
}
return null;
}
public boolean isEager() {
return EAGER.equals(this);
}
public boolean isLazy() {
return LAZY.equals(this);
}
@Override
public String toString() {
return this.description;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\support\LifecycleAwareCacheDataImporterExporter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExchangeRatesContainer {
private LocalDate date = LocalDate.now();
private Currency base;
private Map<String, BigDecimal> rates;
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public Currency getBase() {
return base;
}
public void setBase(Currency base) {
this.base = base;
}
public Map<String, BigDecimal> getRates() {
return rates; | }
public void setRates(Map<String, BigDecimal> rates) {
this.rates = rates;
}
@Override
public String toString() {
return "RateList{" +
"date=" + date +
", base=" + base +
", rates=" + rates +
'}';
}
} | repos\piggymetrics-master\statistics-service\src\main\java\com\piggymetrics\statistics\domain\ExchangeRatesContainer.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Dimensionstyp.
@param DIM_Dimension_Type_ID Dimensionstyp */
@Override
public void setDIM_Dimension_Type_ID (int DIM_Dimension_Type_ID)
{
if (DIM_Dimension_Type_ID < 1)
set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Type_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Type_ID, Integer.valueOf(DIM_Dimension_Type_ID));
}
/** Get Dimensionstyp.
@return Dimensionstyp */
@Override
public int getDIM_Dimension_Type_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DIM_Dimension_Type_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Interner Name.
@param InternalName | Generally used to give records a name that can be safely referenced from code.
*/
@Override
public void setInternalName (java.lang.String InternalName)
{
set_ValueNoCheck (COLUMNNAME_InternalName, InternalName);
}
/** Get Interner Name.
@return Generally used to give records a name that can be safely referenced from code.
*/
@Override
public java.lang.String getInternalName ()
{
return (java.lang.String)get_Value(COLUMNNAME_InternalName);
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Type.java | 1 |
请完成以下Java代码 | private static long gcd(long a, long b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
public static String convertDecimalToFractionUsingGCD(double decimal) {
String decimalStr = String.valueOf(decimal);
int decimalPlaces = decimalStr.length() - decimalStr.indexOf('.') - 1;
long denominator = (long) Math.pow(10, decimalPlaces);
long numerator = (long) (decimal * denominator);
long gcd = gcd(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
return numerator + "/" + denominator;
}
public static String convertDecimalToFractionUsingApacheCommonsMath(double decimal) {
Fraction fraction = new Fraction(decimal);
return fraction.toString();
}
private static String extractRepeatingDecimal(String fractionalPart) {
int length = fractionalPart.length();
for (int i = 1; i <= length / 2; i++) {
String sub = fractionalPart.substring(0, i);
boolean repeating = true;
for (int j = i; j + i <= length; j += i) {
if (!fractionalPart.substring(j, j + i)
.equals(sub)) {
repeating = false;
break;
}
}
if (repeating) {
return sub;
}
}
return ""; | }
public static String convertDecimalToFractionUsingGCDRepeating(double decimal) {
String decimalStr = String.valueOf(decimal);
int indexOfDot = decimalStr.indexOf('.');
String afterDot = decimalStr.substring(indexOfDot + 1);
String repeatingNumber = extractRepeatingDecimal(afterDot);
if (repeatingNumber == "") {
return convertDecimalToFractionUsingGCD(decimal);
} else {
int n = repeatingNumber.length();
int repeatingValue = Integer.parseInt(repeatingNumber);
int integerPart = Integer.parseInt(decimalStr.substring(0, indexOfDot));
long denominator = (long) Math.pow(10, n) - 1;
long numerator = repeatingValue + (integerPart * denominator);
long gcd = gcd(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
return numerator + "/" + denominator;
}
}
} | repos\tutorials-master\core-java-modules\core-java-numbers-8\src\main\java\com\baeldung\decimaltofraction\DecimalToFraction.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BPartnerProductStatsEventListener implements IEventListener
{
private static final Logger logger = LogManager.getLogger(BPartnerProductStatsEventListener.class);
/**
* Introduce this lock to get rid of
* <pre>
* ERROR: duplicate key value violates unique constraint "c_bpartner_product_stats_uq"
* </pre>
* ..I suspect that the reason for the problem is that this listener is invoked concurrently, e.g. from async processors
*/
private final ReentrantLock statsRepoAccessLock = new ReentrantLock();
private final IEventBusFactory eventBusRegistry;
private final BPartnerProductStatsEventHandler statsEventHandler;
public BPartnerProductStatsEventListener(
@NonNull final IEventBusFactory eventBusRegistry,
@NonNull final BPartnerProductStatsEventHandler statsEventHandler)
{
this.eventBusRegistry = eventBusRegistry;
this.statsEventHandler = statsEventHandler;
}
@PostConstruct
public void registerListener()
{
eventBusRegistry.registerGlobalEventListener(BPartnerProductStatsEventSender.TOPIC_InOut, this);
eventBusRegistry.registerGlobalEventListener(BPartnerProductStatsEventSender.TOPIC_Invoice, this);
} | @Override
public void onEvent(final IEventBus eventBus, final Event event)
{
final String topicName = eventBus.getTopic().getName();
statsRepoAccessLock.lock();
try
{
if (BPartnerProductStatsEventSender.TOPIC_InOut.getName().equals(topicName))
{
statsEventHandler.handleInOutChangedEvent(BPartnerProductStatsEventSender.extractInOutChangedEvent(event));
}
else if (BPartnerProductStatsEventSender.TOPIC_Invoice.getName().equals(topicName))
{
statsEventHandler.handleInvoiceChangedEvent(BPartnerProductStatsEventSender.extractInvoiceChangedEvent(event));
}
else
{
logger.warn("Ignore unknown event {} got on topic={}", event, topicName);
}
}
finally
{
statsRepoAccessLock.unlock();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\product\stats\BPartnerProductStatsEventListener.java | 2 |
请完成以下Java代码 | public class GlobalExceptionHandler {
private Logger log = LoggerFactory.getLogger(this.getClass());
@ExceptionHandler(value = Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Response handleException(Exception e) {
log.error("系统内部异常,异常信息:", e);
return new Response().message("系统内部异常");
}
@ExceptionHandler(value = SystemException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Response handleParamsInvalidException(SystemException e) {
log.error("系统错误:{}", e.getMessage());
return new Response().message(e.getMessage());
}
/**
* 统一处理请求参数校验(实体对象传参)
*
* @param e BindException
* @return FebsResponse
*/
@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Response validExceptionHandler(BindException e) {
StringBuilder message = new StringBuilder();
List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
for (FieldError error : fieldErrors) {
message.append(error.getField()).append(error.getDefaultMessage()).append(",");
} | message = new StringBuilder(message.substring(0, message.length() - 1));
return new Response().message(message.toString());
}
/**
* 统一处理请求参数校验(普通传参)
*
* @param e ConstraintViolationException
* @return FebsResponse
*/
@ExceptionHandler(value = ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Response handleConstraintViolationException(ConstraintViolationException e) {
StringBuilder message = new StringBuilder();
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
for (ConstraintViolation<?> violation : violations) {
Path path = violation.getPropertyPath();
String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), ".");
message.append(pathArr[1]).append(violation.getMessage()).append(",");
}
message = new StringBuilder(message.substring(0, message.length() - 1));
return new Response().message(message.toString());
}
@ExceptionHandler(value = UnauthorizedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public void handleUnauthorizedException(Exception e) {
log.error("权限不足,{}", e.getMessage());
}
} | repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\handler\GlobalExceptionHandler.java | 1 |
请完成以下Java代码 | private boolean mayBeContainsProcessDefinitionResourceName(String resourceName) {
return (
!deploymentSettings.containsKey(RESOURCE_NAMES) ||
Optional.of(deploymentSettings.get(RESOURCE_NAMES))
.filter(List.class::isInstance)
.map(List.class::cast)
.filter(it -> it.contains(resourceName))
.isPresent()
);
}
protected BpmnParse createBpmnParseFromResource(ResourceEntity resource) {
String resourceName = resource.getName();
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(resource.getBytes())) {
BpmnParse bpmnParse = bpmnParser
.createParse()
.sourceInputStream(inputStream)
.setSourceSystemId(resourceName)
.deployment(deployment)
.name(resourceName);
if (deploymentSettings != null) {
// Schema validation if needed
if (deploymentSettings.containsKey(DeploymentSettings.IS_BPMN20_XSD_VALIDATION_ENABLED)) {
bpmnParse.setValidateSchema(
(Boolean) deploymentSettings.get(DeploymentSettings.IS_BPMN20_XSD_VALIDATION_ENABLED)
);
}
// Process validation if needed
if (deploymentSettings.containsKey(DeploymentSettings.IS_PROCESS_VALIDATION_ENABLED)) { | bpmnParse.setValidateProcess(
(Boolean) deploymentSettings.get(DeploymentSettings.IS_PROCESS_VALIDATION_ENABLED)
);
}
} else {
// On redeploy, we assume it is validated at the first deploy
bpmnParse.setValidateSchema(false);
bpmnParse.setValidateProcess(false);
}
bpmnParse.execute();
return bpmnParse;
} catch (IOException e) {
throw new ActivitiException(e.getMessage(), e);
}
}
protected boolean isBpmnResource(String resourceName) {
for (String suffix : ResourceNameUtil.BPMN_RESOURCE_SUFFIXES) {
if (resourceName.endsWith(suffix)) {
return true;
}
}
return false;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\ParsedDeploymentBuilder.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public String getName() {
return name;
}
public String getCorrelationKey() {
return correlationKey;
}
public Map<String, Object> getVariables() {
return variables;
}
@Override
public int hashCode() {
return Objects.hash(id, name, correlationKey, variables);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false; | ReceiveMessagePayload other = (ReceiveMessagePayload) obj;
return (
Objects.equals(correlationKey, other.correlationKey) &&
Objects.equals(id, other.id) &&
Objects.equals(name, other.name) &&
Objects.equals(variables, other.variables)
);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ReceiveMessagePayload [id=");
builder.append(id);
builder.append(", name=");
builder.append(name);
builder.append(", correlationKey=");
builder.append(correlationKey);
builder.append(", variables=");
builder.append(variables);
builder.append("]");
return builder.toString();
}
} | repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\ReceiveMessagePayload.java | 1 |
请完成以下Java代码 | public IHUContextProcessorExecutor createHUContextProcessorExecutor(final IHUContext huContext)
{
return new HUContextProcessorExecutor(huContext);
}
@Override
public IHUContextProcessorExecutor createHUContextProcessorExecutor(final IContextAware context)
{
final IHUContext huContext = Services.get(IHUContextFactory.class).createMutableHUContextForProcessing(context);
return new HUContextProcessorExecutor(huContext);
}
@Override
public List<IHUTransactionCandidate> aggregateTransactions(final List<IHUTransactionCandidate> transactions)
{
final Map<ArrayKey, IHUTransactionCandidate> transactionsAggregateMap = new HashMap<>();
final List<IHUTransactionCandidate> notAggregated = new ArrayList<>();
for (final IHUTransactionCandidate trx : transactions)
{
if (trx.getCounterpart() != null)
{
// we don't want to aggregate paired trxCandidates because we want to discard the trxCandidates this method was called with.
// unless we don't have to, we don't want to delve into those intricacies...
notAggregated.add(trx);
}
// note that we use the ID if we can, because we don't want this to fail e.g. because of two different versions of the "same" VHU-item
final ArrayKey key = Util.mkKey(
// trxCandidate.getCounterpart(),
trx.getDate(),
trx.getHUStatus(),
// trxCandidate.getM_HU(), just delegates to HU_Item
trx.getM_HU_Item() == null ? -1 : trx.getM_HU_Item().getM_HU_Item_ID(), | trx.getLocatorId(),
trx.getProductId() == null ? -1 : trx.getProductId().getRepoId(),
// trxCandidate.getQuantity(),
trx.getReferencedModel() == null ? -1 : TableRecordReference.of(trx.getReferencedModel()),
// trxCandidate.getVHU(), just delegates to VHU_Item
trx.getVHU_Item() == null ? -1 : trx.getVHU_Item().getM_HU_Item_ID(),
trx.isSkipProcessing());
transactionsAggregateMap.merge(key,
trx,
(existingCand, newCand) -> {
final HUTransactionCandidate mergedCandidate = new HUTransactionCandidate(existingCand.getReferencedModel(),
existingCand.getM_HU_Item(),
existingCand.getVHU_Item(),
existingCand.getProductId(),
existingCand.getQuantity().add(newCand.getQuantity()),
existingCand.getDate(),
existingCand.getLocatorId(),
existingCand.getHUStatus());
if (existingCand.isSkipProcessing())
{
mergedCandidate.setSkipProcessing();
}
return mergedCandidate;
});
}
return ImmutableList.<IHUTransactionCandidate>builder()
.addAll(notAggregated)
.addAll(transactionsAggregateMap.values())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTrxBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public float getDiskUsageCriticalPercentage() {
return this.diskUsageCriticalPercentage;
}
public void setDiskUsageCriticalPercentage(float diskUsageCriticalPercentage) {
this.diskUsageCriticalPercentage = diskUsageCriticalPercentage;
}
public float getDiskUsageWarningPercentage() {
return this.diskUsageWarningPercentage;
}
public void setDiskUsageWarningPercentage(float diskUsageWarningPercentage) {
this.diskUsageWarningPercentage = diskUsageWarningPercentage;
}
public long getMaxOplogSize() {
return this.maxOplogSize;
}
public void setMaxOplogSize(long maxOplogSize) {
this.maxOplogSize = maxOplogSize;
}
public int getQueueSize() { | return this.queueSize;
}
public void setQueueSize(int queueSize) {
this.queueSize = queueSize;
}
public long getTimeInterval() {
return this.timeInterval;
}
public void setTimeInterval(long timeInterval) {
this.timeInterval = timeInterval;
}
public int getWriteBufferSize() {
return this.writeBufferSize;
}
public void setWriteBufferSize(int writeBufferSize) {
this.writeBufferSize = writeBufferSize;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\DiskStoreProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public abstract class OnEndpointElementCondition extends SpringBootCondition {
private final String prefix;
private final Class<? extends Annotation> annotationType;
protected OnEndpointElementCondition(String prefix, Class<? extends Annotation> annotationType) {
this.prefix = prefix;
this.annotationType = annotationType;
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
AnnotationAttributes annotationAttributes = AnnotationAttributes
.fromMap(metadata.getAnnotationAttributes(this.annotationType.getName()));
Assert.state(annotationAttributes != null, "'annotationAttributes' must not be null");
String endpointName = annotationAttributes.getString("value");
ConditionOutcome outcome = getEndpointOutcome(context, endpointName);
if (outcome != null) {
return outcome;
}
return getDefaultOutcome(context, annotationAttributes);
}
protected @Nullable ConditionOutcome getEndpointOutcome(ConditionContext context, String endpointName) {
Environment environment = context.getEnvironment();
String enabledProperty = this.prefix + endpointName + ".enabled";
if (environment.containsProperty(enabledProperty)) {
boolean match = environment.getProperty(enabledProperty, Boolean.class, true); | return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType)
.because(this.prefix + endpointName + ".enabled is " + match));
}
return null;
}
/**
* Return the default outcome that should be used if property is not set. By default
* this method will use the {@code <prefix>.defaults.enabled} property, matching if it
* is {@code true} or if it is not configured.
* @param context the condition context
* @param annotationAttributes the annotation attributes
* @return the default outcome
* @since 2.6.0
*/
protected ConditionOutcome getDefaultOutcome(ConditionContext context, AnnotationAttributes annotationAttributes) {
boolean match = Boolean
.parseBoolean(context.getEnvironment().getProperty(this.prefix + "defaults.enabled", "true"));
return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType)
.because(this.prefix + "defaults.enabled is considered " + match));
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\OnEndpointElementCondition.java | 2 |
请完成以下Java代码 | public boolean isApplicable(@NonNull final Evaluatee context, @NonNull final DocumentSequenceInfo docSeqInfo)
{
final Date date = getDateOrNull(context, docSeqInfo);
final boolean result = date != null;
logger.debug("isApplicable - Given evaluatee-context contains {}={}; -> returning {}; context={}", docSeqInfo.getDateColumn(), date, result, context);
return result;
}
/**
* @return the given prefix + {@code context}'s {@code Date} value.
*/
@Override
public String provideSequenceNo(@NonNull final Evaluatee context, @NonNull final DocumentSequenceInfo docSeqInfo, @Nullable final String autoIncrementedSeqNumber)
{
final Date date = getDateOrNull(context, docSeqInfo);
Check.assumeNotNull(date, "The given context needs to have a non-empty Date value; context={}", context);
final String dateFormatToUse = sysConfigBL.getValue(SYSCONFIG_DATE_FORMAT);
Check.assumeNotEmpty(dateFormatToUse, "{} sysconfig has not been defined", SYSCONFIG_DATE_FORMAT);
final String result = TimeUtil.formatDate(TimeUtil.asTimestamp(date), dateFormatToUse);
if (Check.isNotBlank(autoIncrementedSeqNumber))
{
final String decimalPattern = docSeqInfo.getDecimalPattern();
final boolean stringCanBeParsedAsInt = autoIncrementedSeqNumber.matches("\\d+");
if (!Check.isEmpty(decimalPattern) && stringCanBeParsedAsInt)
{ | final int seqNoAsInt = Integer.parseInt(autoIncrementedSeqNumber);
final String formattedSeqNumber = new DecimalFormat(decimalPattern).format(seqNoAsInt);
logger.debug("provideSequenceNo - returning {};", result);
return result + formattedSeqNumber;
}
}
logger.debug("provideSequenceNo - returning {};", result);
return result;
}
@Nullable
private static Date getDateOrNull(@NonNull final Evaluatee context, final @NonNull DocumentSequenceInfo docSeqInfo)
{
return context.get_ValueAsDate(docSeqInfo.getDateColumn(), SystemTime.asDate());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequenceno\DateSequenceProvider.java | 1 |
请完成以下Java代码 | public Iterable<HierarchyNode> getUpStream(@NonNull final Beneficiary beneficiary)
{
final HierarchyNode node = beneficiary2Node.get(beneficiary);
if (node == null)
{
throw new AdempiereException("Beneficiary with C_BPartner_ID=" + beneficiary.getBPartnerId().getRepoId() + " is not part of this hierarchy")
.appendParametersToMessage()
.setParameter("this", this);
}
return () -> new ParentNodeIterator(child2Parent, node);
}
public static class ParentNodeIterator implements Iterator<HierarchyNode>
{
private final ImmutableMap<HierarchyNode, HierarchyNode> child2Parent;
private HierarchyNode next;
private HierarchyNode previous;
private ParentNodeIterator(
@NonNull final ImmutableMap<HierarchyNode, HierarchyNode> childAndParent,
@NonNull final HierarchyNode first)
{
this.child2Parent = childAndParent;
this.next = first;
} | @Override
public boolean hasNext()
{
return next != null;
}
@Override
public HierarchyNode next()
{
final HierarchyNode result = next;
if (result == null)
{
throw new NoSuchElementException("Previous HierarchyNode=" + previous + " had no parent");
}
previous = next;
next = child2Parent.get(next);
return result;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\hierarchy\Hierarchy.java | 1 |
请完成以下Java代码 | public void setC_Region_ID(final int regionId)
{
source.setC_Region_ID(regionId);
}
/**
* Source of {@link CityVO}s.
*
* @author metas-dev <dev@metasfresh.com>
*
*/
private final class CitiesSource implements ResultItemSource
{
private ArrayKey lastQueryKey = null;
private List<CityVO> lastResult = null;
private int countryId = -1;
private int regionId = -1;
@Override
public List<CityVO> query(String searchText, int limit)
{
final int adClientId = getAD_Client_ID();
final int countryId = getC_Country_ID();
final int regionId = getC_Region_ID();
final ArrayKey queryKey = Util.mkKey(adClientId, countryId, regionId);
if (lastQueryKey != null && lastQueryKey.equals(queryKey))
{
return lastResult;
}
final Iterator<CityVO> allCitiesIterator = retrieveAllCities(adClientId, countryId, regionId);
List<CityVO> result = null;
try
{
result = ImmutableList.copyOf(allCitiesIterator);
}
finally
{
IteratorUtils.close(allCitiesIterator);
}
this.lastResult = result;
this.lastQueryKey = queryKey;
return result;
}
private Iterator<CityVO> retrieveAllCities(final int adClientId, final int countryId, final int regionId)
{
if (countryId <= 0)
{
return Collections.emptyIterator();
}
final List<Object> sqlParams = new ArrayList<Object>();
final StringBuilder sql = new StringBuilder(
"SELECT cy.C_City_ID, cy.Name, cy.C_Region_ID, r.Name"
+ " FROM C_City cy"
+ " LEFT OUTER JOIN C_Region r ON (r.C_Region_ID=cy.C_Region_ID)"
+ " WHERE cy.AD_Client_ID IN (0,?)");
sqlParams.add(adClientId);
if (regionId > 0)
{
sql.append(" AND cy.C_Region_ID=?");
sqlParams.add(regionId);
}
if (countryId > 0)
{
sql.append(" AND COALESCE(cy.C_Country_ID, r.C_Country_ID)=?");
sqlParams.add(countryId);
}
sql.append(" ORDER BY cy.Name, r.Name");
return IteratorUtils.asIterator(new AbstractPreparedStatementBlindIterator<CityVO>()
{
@Override
protected PreparedStatement createPreparedStatement() throws SQLException | {
final PreparedStatement pstmt = DB.prepareStatement(sql.toString(), ITrx.TRXNAME_None);
DB.setParameters(pstmt, sqlParams);
return pstmt;
}
@Override
protected CityVO fetch(ResultSet rs) throws SQLException
{
final CityVO vo = new CityVO(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4));
return vo;
}
});
}
private int getAD_Client_ID()
{
return Env.getAD_Client_ID(Env.getCtx());
}
private int getC_Country_ID()
{
return countryId;
}
public void setC_Country_ID(final int countryId)
{
this.countryId = countryId > 0 ? countryId : -1;
}
public int getC_Region_ID()
{
return regionId;
}
public void setC_Region_ID(final int regionId)
{
this.regionId = regionId > 0 ? regionId : -1;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\CityAutoCompleter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static Collector<I_AD_Preference, UserValuePreferencesBuilder, IUserValuePreferences> collector()
{
return Collector.of(
UserValuePreferencesBuilder::new // supplier
, UserValuePreferencesBuilder::add // accumulator
, (l, r) -> l.addAll(r) // combiner
, UserValuePreferencesBuilder::build // finisher
, Collector.Characteristics.UNORDERED // characteristics
);
}
private static Optional<AdWindowId> extractAdWindowId(final I_AD_Preference adPreference)
{
return AdWindowId.optionalOfRepoId(adPreference.getAD_Window_ID());
}
private Optional<AdWindowId> adWindowIdOptional;
private final Map<String, IUserValuePreference> name2value = new HashMap<>();
private UserValuePreferencesBuilder()
{
super();
}
public UserValuePreferences build()
{
if (isEmpty())
{
return UserValuePreferences.EMPTY;
}
return new UserValuePreferences(this);
}
public boolean isEmpty()
{
return name2value.isEmpty();
}
public UserValuePreferencesBuilder add(final I_AD_Preference adPreference) | {
final Optional<AdWindowId> currentWindowId = extractAdWindowId(adPreference);
if (isEmpty())
{
adWindowIdOptional = currentWindowId;
}
else if (!adWindowIdOptional.equals(currentWindowId))
{
throw new IllegalArgumentException("Preference " + adPreference + "'s AD_Window_ID=" + currentWindowId + " is not matching builder's AD_Window_ID=" + adWindowIdOptional);
}
final String attributeName = adPreference.getAttribute();
final String attributeValue = adPreference.getValue();
name2value.put(attributeName, UserValuePreference.of(adWindowIdOptional, attributeName, attributeValue));
return this;
}
public UserValuePreferencesBuilder addAll(final UserValuePreferencesBuilder fromBuilder)
{
if (fromBuilder == null || fromBuilder.isEmpty())
{
return this;
}
if (!isEmpty() && !adWindowIdOptional.equals(fromBuilder.adWindowIdOptional))
{
throw new IllegalArgumentException("Builder " + fromBuilder + "'s AD_Window_ID=" + fromBuilder.adWindowIdOptional + " is not matching builder's AD_Window_ID=" + adWindowIdOptional);
}
name2value.putAll(fromBuilder.name2value);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\ValuePreferenceBL.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected boolean scheduleLongRunningWork(Runnable runnable) {
final ManagedQueueExecutorService managedQueueExecutorService = managedQueueInjector.getValue();
boolean rejected = false;
try {
// wait for 2 seconds for the job to be accepted by the pool.
managedQueueExecutorService.executeBlocking(runnable, 2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// the acquisition thread is interrupted, this probably means the app server is turning the lights off -> ignore
} catch (ExecutionTimedOutException e) {
rejected = true;
} catch (RejectedExecutionException e) {
rejected = true;
} catch (Exception e) {
// if it fails for some other reason, log a warning message
long now = System.currentTimeMillis();
// only log every 60 seconds to prevent log flooding | if((now-lastWarningLogged) >= (60*1000)) {
log.log(Level.WARNING, "Unexpected Exception while submitting job to executor pool.", e);
} else {
log.log(Level.FINE, "Unexpected Exception while submitting job to executor pool.", e);
}
}
return !rejected;
}
public InjectedValue<ManagedQueueExecutorService> getManagedQueueInjector() {
return managedQueueInjector;
}
} | repos\camunda-bpm-platform-master\distro\wildfly26\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscExecutorService.java | 2 |
请完成以下Java代码 | public Mono<GraphQlResponse> execute(GraphQlRequest request) {
return this.rsocketRequester.route(this.route).data(request.toMap())
.retrieveMono(MAP_TYPE)
.map(ResponseMapGraphQlResponse::new);
}
@Override
public Flux<GraphQlResponse> executeSubscription(GraphQlRequest request) {
return this.rsocketRequester.route(this.route).data(request.toMap())
.retrieveFlux(MAP_TYPE)
.onErrorResume(RejectedException.class, (ex) -> Flux.error(decodeErrors(request, ex)))
.map(ResponseMapGraphQlResponse::new);
}
@SuppressWarnings("unchecked") | private Exception decodeErrors(GraphQlRequest request, RejectedException ex) {
try {
String errorMessage = (ex.getMessage() != null) ? ex.getMessage() : "";
byte[] errorData = errorMessage.getBytes(StandardCharsets.UTF_8);
List<GraphQLError> errors = (List<GraphQLError>) this.jsonDecoder.decode(
DefaultDataBufferFactory.sharedInstance.wrap(errorData), LIST_TYPE, null, null);
GraphQlResponse response = new ResponseMapGraphQlResponse(Collections.singletonMap("errors", errors));
return new SubscriptionErrorException(request, response.getErrors());
}
catch (DecodingException ex2) {
return ex;
}
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\RSocketGraphQlTransport.java | 1 |
请完成以下Java代码 | /* package */final class DefaultContextMenuActionContext implements IContextMenuActionContext
{
private final VEditor editor;
private final VTable vtable;
private final int viewRow;
private final int viewColumn;
public DefaultContextMenuActionContext(final VEditor editor, final VTable vtable, final int viewRow, final int viewColumn)
{
super();
Check.assumeNotNull(editor, "editor not null");
this.editor = editor;
this.vtable = vtable;
this.viewRow = viewRow;
this.viewColumn = viewColumn;
}
@Override
public Properties getCtx()
{
return Env.getCtx();
}
@Override
public VEditor getEditor()
{ | return editor;
}
@Override
public VTable getVTable()
{
return vtable;
}
@Override
public int getViewRow()
{
return viewRow;
}
@Override
public int getViewColumn()
{
return viewColumn;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\impl\DefaultContextMenuActionContext.java | 1 |
请完成以下Java代码 | public br setClear(String clear_type)
{
addAttribute("clear",clear_type);
return this;
}
/**
Sets the lang="" and xml:lang="" attributes
@param lang the lang="" and xml:lang="" attributes
*/
public Element setLang(String lang)
{
addAttribute("lang",lang);
addAttribute("xml:lang",lang);
return this;
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public br addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public br addElement(String hashcode,String element)
{ | addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public br addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public br addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public br removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\br.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setISOCode(String value) {
this.isoCode = value;
}
/**
* Gets the value of the netdate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getNetdate() {
return netdate;
}
/**
* Sets the value of the netdate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setNetdate(XMLGregorianCalendar value) {
this.netdate = value;
}
/**
* Gets the value of the netDays property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getNetDays() {
return netDays;
}
/**
* Sets the value of the netDays property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setNetDays(BigInteger value) {
this.netDays = value;
}
/**
* Gets the value of the singlevat property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getSinglevat() {
return singlevat;
} | /**
* Sets the value of the singlevat property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setSinglevat(BigDecimal value) {
this.singlevat = value;
}
/**
* Gets the value of the taxfree property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTaxfree() {
return taxfree;
}
/**
* Sets the value of the taxfree property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTaxfree(String value) {
this.taxfree = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop120VType.java | 2 |
请完成以下Java代码 | void sendWebsocketViewChangedNotification(
final ViewId viewId,
final DocumentIdsSelection changedRowIds)
{
final ViewChanges viewChanges = new ViewChanges(viewId);
viewChanges.addChangedRowIds(changedRowIds);
JSONViewChanges jsonViewChanges = JSONViewChanges.of(viewChanges);
final WebsocketTopicName endpoint = WebsocketTopicNames.buildViewNotificationsTopicName(jsonViewChanges.getViewId());
try
{
websocketSender.convertAndSend(endpoint, jsonViewChanges);
}
catch (final Exception ex)
{
throw AdempiereException.wrapIfNeeded(ex)
.appendParametersToMessage()
.setParameter("json", jsonViewChanges);
}
}
@GetMapping("/logging/config")
public void setWebsocketLoggingConfig(
@RequestParam("enabled") final boolean enabled,
@RequestParam(value = "maxLoggedEvents", defaultValue = "500") final int maxLoggedEvents)
{
userSession.assertLoggedIn();
websocketSender.setLogEventsEnabled(enabled);
websocketSender.setLogEventsMaxSize(maxLoggedEvents);
} | @GetMapping("/logging/events")
public List<WebsocketEventLogRecord> getWebsocketLoggedEvents(
@RequestParam(value = "destinationFilter", required = false) final String destinationFilter)
{
userSession.assertLoggedIn();
return websocketSender.getLoggedEvents(destinationFilter);
}
@GetMapping("/activeSubscriptions")
public Map<String, ?> getActiveSubscriptions()
{
userSession.assertLoggedIn();
final ImmutableMap<WebsocketTopicName, Collection<WebsocketSubscriptionId>> map = websocketActiveSubscriptionsIndex.getSubscriptionIdsByTopicName().asMap();
final ImmutableMap<String, ImmutableList<String>> stringsMap = map.entrySet()
.stream()
.map(entry -> GuavaCollectors.entry(
entry.getKey().getAsString(), // topic
entry.getValue().stream()
.map(WebsocketSubscriptionId::getAsString)
.collect(ImmutableList.toImmutableList())))
.collect(GuavaCollectors.toImmutableMap());
return stringsMap;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\debug\DebugWebsocketRestController.java | 1 |
请完成以下Java代码 | public CreditorReferenceType1Choice getCdOrPrtry() {
return cdOrPrtry;
}
/**
* Sets the value of the cdOrPrtry property.
*
* @param value
* allowed object is
* {@link CreditorReferenceType1Choice }
*
*/
public void setCdOrPrtry(CreditorReferenceType1Choice value) {
this.cdOrPrtry = value;
}
/**
* Gets the value of the issr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIssr() { | return issr;
}
/**
* Sets the value of the issr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIssr(String value) {
this.issr = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CreditorReferenceType2.java | 1 |
请完成以下Java代码 | public class WrapperClassUserCache {
private Map<CacheKey, User> cache = new HashMap<>();
public User getById(CacheKey key) {
return cache.get(key);
}
public void storeById(CacheKey key, User user) {
cache.put(key, user);
}
public static class CacheKey {
private final Object value;
public CacheKey(String value) {
this.value = value;
} | public CacheKey(Long value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CacheKey cacheKey = (CacheKey) o;
return value.equals(cacheKey.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps-5\src\main\java\com\baeldung\map\multikey\WrapperClassUserCache.java | 1 |
请完成以下Java代码 | public abstract class TrxItemProcessorAdapter<IT, RT> implements ITrxItemProcessor<IT, RT>
{
private ITrxItemProcessorContext processorCtx;
@Override
public final void setTrxItemProcessorCtx(ITrxItemProcessorContext processorCtx)
{
this.processorCtx = processorCtx;
}
protected final ITrxItemProcessorContext getTrxItemProcessorCtx()
{
return processorCtx;
}
protected final Properties getCtx()
{
return getTrxItemProcessorCtx().getCtx();
}
protected final String getTrxName()
{
return getTrxItemProcessorCtx().getTrxName();
} | protected final IParams getParams()
{
return getTrxItemProcessorCtx().getParams();
}
@Override
public abstract void process(IT item) throws Exception;
@Override
public RT getResult()
{
// nothing at this level
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\spi\TrxItemProcessorAdapter.java | 1 |
请完成以下Java代码 | public Builder setSourceRoleDisplayName(final ITranslatableString sourceRoleDisplayName)
{
this.sourceRoleDisplayName = sourceRoleDisplayName;
return this;
}
public Builder setTarget_Reference_AD(final int targetReferenceId)
{
this.targetReferenceId = ReferenceId.ofRepoIdOrNull(targetReferenceId);
targetTableRefInfo = null; // lazy
return this;
}
private ReferenceId getTarget_Reference_ID()
{
return Check.assumeNotNull(targetReferenceId, "targetReferenceId is set");
}
private ADRefTable getTargetTableRefInfoOrNull()
{
if (targetTableRefInfo == null)
{
targetTableRefInfo = retrieveTableRefInfo(getTarget_Reference_ID());
}
return targetTableRefInfo;
} | public Builder setTargetRoleDisplayName(final ITranslatableString targetRoleDisplayName)
{
this.targetRoleDisplayName = targetRoleDisplayName;
return this;
}
public ITranslatableString getTargetRoleDisplayName()
{
return targetRoleDisplayName;
}
public Builder setIsTableRecordIdTarget(final boolean isReferenceTarget)
{
isTableRecordIDTarget = isReferenceTarget;
return this;
}
private boolean isTableRecordIdTarget()
{
return isTableRecordIDTarget;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\relation_type\SpecificRelationTypeRelatedDocumentsProvider.java | 1 |
请完成以下Java代码 | public InputDataItem getInputDataItem() {
return inputDataItemChild.getChild(this);
}
public void setInputDataItem(InputDataItem inputDataItem) {
inputDataItemChild.setChild(this, inputDataItem);
}
public OutputDataItem getOutputDataItem() {
return outputDataItemChild.getChild(this);
}
public void setOutputDataItem(OutputDataItem outputDataItem) {
outputDataItemChild.setChild(this, outputDataItem);
}
public Collection<ComplexBehaviorDefinition> getComplexBehaviorDefinitions() {
return complexBehaviorDefinitionCollection.get(this);
}
public CompletionCondition getCompletionCondition() {
return completionConditionChild.getChild(this);
}
public void setCompletionCondition(CompletionCondition completionCondition) {
completionConditionChild.setChild(this, completionCondition);
}
public boolean isSequential() {
return isSequentialAttribute.getValue(this);
}
public void setSequential(boolean sequential) {
isSequentialAttribute.setValue(this, sequential);
}
public MultiInstanceFlowCondition getBehavior() {
return behaviorAttribute.getValue(this);
}
public void setBehavior(MultiInstanceFlowCondition behavior) {
behaviorAttribute.setValue(this, behavior);
}
public EventDefinition getOneBehaviorEventRef() {
return oneBehaviorEventRefAttribute.getReferenceTargetElement(this);
}
public void setOneBehaviorEventRef(EventDefinition oneBehaviorEventRef) {
oneBehaviorEventRefAttribute.setReferenceTargetElement(this, oneBehaviorEventRef);
} | public EventDefinition getNoneBehaviorEventRef() {
return noneBehaviorEventRefAttribute.getReferenceTargetElement(this);
}
public void setNoneBehaviorEventRef(EventDefinition noneBehaviorEventRef) {
noneBehaviorEventRefAttribute.setReferenceTargetElement(this, noneBehaviorEventRef);
}
public boolean isCamundaAsyncBefore() {
return camundaAsyncBefore.getValue(this);
}
public void setCamundaAsyncBefore(boolean isCamundaAsyncBefore) {
camundaAsyncBefore.setValue(this, isCamundaAsyncBefore);
}
public boolean isCamundaAsyncAfter() {
return camundaAsyncAfter.getValue(this);
}
public void setCamundaAsyncAfter(boolean isCamundaAsyncAfter) {
camundaAsyncAfter.setValue(this, isCamundaAsyncAfter);
}
public boolean isCamundaExclusive() {
return camundaExclusive.getValue(this);
}
public void setCamundaExclusive(boolean isCamundaExclusive) {
camundaExclusive.setValue(this, isCamundaExclusive);
}
public String getCamundaCollection() {
return camundaCollection.getValue(this);
}
public void setCamundaCollection(String expression) {
camundaCollection.setValue(this, expression);
}
public String getCamundaElementVariable() {
return camundaElementVariable.getValue(this);
}
public void setCamundaElementVariable(String variableName) {
camundaElementVariable.setValue(this, variableName);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\MultiInstanceLoopCharacteristicsImpl.java | 1 |
请完成以下Java代码 | public String mineBlock(int prefix) {
String prefixString = new String(new char[prefix]).replace('\0', '0');
while (!hash.substring(0, prefix)
.equals(prefixString)) {
nonce++;
hash = calculateBlockHash();
}
return hash;
}
public String calculateBlockHash() {
String dataToHash = previousHash + Long.toString(timeStamp) + Integer.toString(nonce) + data;
MessageDigest digest = null;
byte[] bytes = null;
try {
digest = MessageDigest.getInstance("SHA-256");
bytes = digest.digest(dataToHash.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
logger.log(Level.SEVERE, ex.getMessage());
}
StringBuffer buffer = new StringBuffer(); | for (byte b : bytes) {
buffer.append(String.format("%02x", b));
}
return buffer.toString();
}
public String getHash() {
return this.hash;
}
public String getPreviousHash() {
return this.previousHash;
}
public void setData(String data) {
this.data = data;
}
} | repos\tutorials-master\java-blockchain\src\main\java\com\baeldung\blockchain\Block.java | 1 |
请完成以下Java代码 | public Builder expiresAt(Instant expiresAt) {
this.claim(JwtClaimNames.EXP, expiresAt);
return this;
}
/**
* Use this identifier in the resulting {@link Jwt}
* @param jti The identifier to use
* @return the {@link Builder} for further configurations
*/
public Builder jti(String jti) {
this.claim(JwtClaimNames.JTI, jti);
return this;
}
/**
* Use this issued-at timestamp in the resulting {@link Jwt}
* @param issuedAt The issued-at timestamp to use
* @return the {@link Builder} for further configurations
*/
public Builder issuedAt(Instant issuedAt) {
this.claim(JwtClaimNames.IAT, issuedAt);
return this;
}
/**
* Use this issuer in the resulting {@link Jwt}
* @param issuer The issuer to use
* @return the {@link Builder} for further configurations
*/
public Builder issuer(String issuer) {
this.claim(JwtClaimNames.ISS, issuer);
return this;
}
/**
* Use this not-before timestamp in the resulting {@link Jwt}
* @param notBefore The not-before timestamp to use
* @return the {@link Builder} for further configurations
*/
public Builder notBefore(Instant notBefore) {
this.claim(JwtClaimNames.NBF, notBefore); | return this;
}
/**
* Use this subject in the resulting {@link Jwt}
* @param subject The subject to use
* @return the {@link Builder} for further configurations
*/
public Builder subject(String subject) {
this.claim(JwtClaimNames.SUB, subject);
return this;
}
/**
* Build the {@link Jwt}
* @return The constructed {@link Jwt}
*/
public Jwt build() {
Instant iat = toInstant(this.claims.get(JwtClaimNames.IAT));
Instant exp = toInstant(this.claims.get(JwtClaimNames.EXP));
return new Jwt(this.tokenValue, iat, exp, this.headers, this.claims);
}
private Instant toInstant(Object timestamp) {
if (timestamp != null) {
Assert.isInstanceOf(Instant.class, timestamp, "timestamps must be of type Instant");
}
return (Instant) timestamp;
}
}
} | repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\Jwt.java | 1 |
请完成以下Java代码 | private void verifyReferenceObjectTrxName(final I_M_HU_Trx_Attribute huTrxAttribute, final Object referencedObject)
{
// final String refObjTrxName = InterfaceWrapperHelper.getTrxName(referencedObject);
// final String huTrxAttrTrxName = InterfaceWrapperHelper.getTrxName(huTrxAttribute);
// Check.errorUnless(Objects.equals(refObjTrxName, huTrxAttrTrxName),
// "The two objects have different trxNames: 'referencedObject'=>{}, 'huTrxAttribute'=>{}",
// refObjTrxName, huTrxAttrTrxName);
}
public void process(final I_M_HU_Trx_Attribute huTrxAttribute)
{
//
// Check if it was already processed
if (huTrxAttribute.isProcessed())
{
return;
}
//
// Actually process it
process0(huTrxAttribute);
//
// Flag it as Processed and save it
huTrxAttribute.setProcessed(true);
save(huTrxAttribute);
}
private final void save(final I_M_HU_Trx_Attribute huTrxAttribute)
{
if (!saveTrxAttributes)
{
return; // don't save it
}
InterfaceWrapperHelper.save(huTrxAttribute);
}
/**
* Process given {@link I_M_HU_Trx_Attribute} by calling the actual processor.
*
* @param huTrxAttribute
*/
private void process0(final I_M_HU_Trx_Attribute huTrxAttribute) | {
final Object referencedModel = getReferencedObject(huTrxAttribute);
final IHUTrxAttributeProcessor trxAttributeProcessor = getHUTrxAttributeProcessor(referencedModel);
final HUTransactionAttributeOperation operation = HUTransactionAttributeOperation.ofCode(huTrxAttribute.getOperation());
if (HUTransactionAttributeOperation.SAVE.equals(operation))
{
trxAttributeProcessor.processSave(huContext, huTrxAttribute, referencedModel);
}
else if (HUTransactionAttributeOperation.DROP.equals(operation))
{
trxAttributeProcessor.processDrop(huContext, huTrxAttribute, referencedModel);
}
else
{
throw new InvalidAttributeValueException("Invalid operation on trx attribute (" + operation + "): " + huTrxAttribute);
}
}
@Override
public void reverseTrxAttributes(final I_M_HU_Trx_Line reversalTrxLine, final I_M_HU_Trx_Line trxLine)
{
// TODO implement trx line attributes reversal
final AdempiereException ex = new AdempiereException("attribute transactions reversal not implemented");
logger.warn(ex.getLocalizedMessage() + ". Skip it for now", ex);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\HUTransactionAttributeProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int getMaxConnections() {
return this.maxConnections;
}
public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}
public int getMaxSessionsPerConnection() {
return this.maxSessionsPerConnection;
}
public void setMaxSessionsPerConnection(int maxSessionsPerConnection) {
this.maxSessionsPerConnection = maxSessionsPerConnection;
} | public Duration getTimeBetweenExpirationCheck() {
return this.timeBetweenExpirationCheck;
}
public void setTimeBetweenExpirationCheck(Duration timeBetweenExpirationCheck) {
this.timeBetweenExpirationCheck = timeBetweenExpirationCheck;
}
public boolean isUseAnonymousProducers() {
return this.useAnonymousProducers;
}
public void setUseAnonymousProducers(boolean useAnonymousProducers) {
this.useAnonymousProducers = useAnonymousProducers;
}
} | repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JmsPoolConnectionFactoryProperties.java | 2 |
请完成以下Java代码 | public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
/**
* Sets the convert to be used
* @param authenticationConverter
*/
public void setAuthenticationConverter(PayloadExchangeAuthenticationConverter authenticationConverter) {
Assert.notNull(authenticationConverter, "authenticationConverter cannot be null");
this.authenticationConverter = authenticationConverter; | }
@Override
public Mono<Void> intercept(PayloadExchange exchange, PayloadInterceptorChain chain) {
return this.authenticationConverter.convert(exchange)
.switchIfEmpty(chain.next(exchange).then(Mono.empty()))
.flatMap((a) -> this.authenticationManager.authenticate(a))
.flatMap((a) -> onAuthenticationSuccess(chain.next(exchange), a));
}
private Mono<Void> onAuthenticationSuccess(Mono<Void> payload, Authentication authentication) {
return payload.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication));
}
} | repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\authentication\AuthenticationPayloadInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WEBUI_PickingSlotsClearingView_TakeOutMultiHUsAndAddToNewHU extends PickingSlotsClearingViewBasedProcess implements IProcessPrecondition
{
// services
private final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
@Autowired
private PickingCandidateService pickingCandidateService;
//
// parameters
private static final String PARAM_M_HU_PI_ID = I_M_HU_PI.COLUMNNAME_M_HU_PI_ID;
@Param(parameterName = PARAM_M_HU_PI_ID, mandatory = true)
private I_M_HU_PI targetHUPI;
@Override
public final ProcessPreconditionsResolution checkPreconditionsApplicable()
{
final List<PickingSlotRow> pickingSlotRows = getSelectedPickingSlotRows();
if (pickingSlotRows.size() <= 1)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("select more than one HU");
}
final Set<PickingSlotRowId> rootRowIds = getRootRowIdsForSelectedPickingSlotRows();
if (rootRowIds.size() > 1)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("all selected HU rows shall be from one picking slot");
}
for (final PickingSlotRow pickingSlotRow : pickingSlotRows)
{
if (!pickingSlotRow.isPickedHURow())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("select an HU");
}
if (!pickingSlotRow.isTopLevelHU())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("select an top level HU");
}
}
//
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final List<I_M_HU> fromHUs = getSelectedPickingSlotTopLevelHUs();
final IAllocationSource source = HUListAllocationSourceDestination.of(fromHUs)
.setDestroyEmptyHUs(true);
final IHUProducerAllocationDestination destination = createHUProducer();
HULoader.of(source, destination) | .setAllowPartialUnloads(false)
.setAllowPartialLoads(false)
.unloadAllFromSource();
// If the source HU was destroyed, then "remove" it from picking slots
final ImmutableSet<HuId> destroyedHUIds = fromHUs.stream()
.filter(handlingUnitsBL::isDestroyedRefreshFirst)
.map(I_M_HU::getM_HU_ID)
.map(HuId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
if (!destroyedHUIds.isEmpty())
{
pickingCandidateService.inactivateForHUIds(destroyedHUIds);
}
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
// Invalidate views
getPickingSlotsClearingView().invalidateAll();
getPackingHUsView().invalidateAll();
}
private IHUProducerAllocationDestination createHUProducer()
{
final PickingSlotRow pickingRow = getRootRowForSelectedPickingSlotRows();
return createNewHUProducer(pickingRow, targetHUPI);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutMultiHUsAndAddToNewHU.java | 2 |
请完成以下Java代码 | public class StringMaxLengthMain {
public static void main(String[] args) {
displayRuntimeMaxStringLength();
displayMaxStringLength();
simulateStringOverflow();
}
public static void simulateStringOverflow() {
try {
int maxLength = Integer.MAX_VALUE;
char[] charArray = new char[maxLength];
for (int i = 0; i < maxLength; i++) {
charArray[i] = 'a';
}
String longString = new String(charArray);
System.out.println("Successfully created a string of length: " + longString.length()); | } catch (OutOfMemoryError e) {
System.err.println("Overflow error: Attempting to create a string longer than Integer.MAX_VALUE");
e.printStackTrace();
}
}
public static void displayRuntimeMaxStringLength() {
long maxMemory = Runtime.getRuntime().maxMemory();
System.out.println("Maximum String length based on available memory: " + (maxMemory));
}
public static void displayMaxStringLength() {
int maxStringLength = Integer.MAX_VALUE;
System.out.println("Maximum String length based on Integer.MAX_VALUE: " + maxStringLength);
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations-7\src\main\java\com\baeldung\stringmaxlength\StringMaxLengthMain.java | 1 |
请完成以下Java代码 | public int getC_InvoiceLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_InvoiceLine_ID);
}
@Override
public void setC_InvoiceLine_Tax_ID (final int C_InvoiceLine_Tax_ID)
{
if (C_InvoiceLine_Tax_ID < 1)
set_Value (COLUMNNAME_C_InvoiceLine_Tax_ID, null);
else
set_Value (COLUMNNAME_C_InvoiceLine_Tax_ID, C_InvoiceLine_Tax_ID);
}
@Override
public int getC_InvoiceLine_Tax_ID()
{
return get_ValueAsInt(COLUMNNAME_C_InvoiceLine_Tax_ID);
}
@Override
public org.compiere.model.I_C_Invoice_Verification_Set getC_Invoice_Verification_Set()
{
return get_ValueAsPO(COLUMNNAME_C_Invoice_Verification_Set_ID, org.compiere.model.I_C_Invoice_Verification_Set.class);
}
@Override
public void setC_Invoice_Verification_Set(final org.compiere.model.I_C_Invoice_Verification_Set C_Invoice_Verification_Set)
{
set_ValueFromPO(COLUMNNAME_C_Invoice_Verification_Set_ID, org.compiere.model.I_C_Invoice_Verification_Set.class, C_Invoice_Verification_Set);
}
@Override
public void setC_Invoice_Verification_Set_ID (final int C_Invoice_Verification_Set_ID)
{
if (C_Invoice_Verification_Set_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Invoice_Verification_Set_ID, null);
else | set_ValueNoCheck (COLUMNNAME_C_Invoice_Verification_Set_ID, C_Invoice_Verification_Set_ID);
}
@Override
public int getC_Invoice_Verification_Set_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Invoice_Verification_Set_ID);
}
@Override
public void setC_Invoice_Verification_SetLine_ID (final int C_Invoice_Verification_SetLine_ID)
{
if (C_Invoice_Verification_SetLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Invoice_Verification_SetLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Invoice_Verification_SetLine_ID, C_Invoice_Verification_SetLine_ID);
}
@Override
public int getC_Invoice_Verification_SetLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Invoice_Verification_SetLine_ID);
}
@Override
public void setRelevantDate (final @Nullable java.sql.Timestamp RelevantDate)
{
set_ValueNoCheck (COLUMNNAME_RelevantDate, RelevantDate);
}
@Override
public java.sql.Timestamp getRelevantDate()
{
return get_ValueAsTimestamp(COLUMNNAME_RelevantDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Verification_SetLine.java | 1 |
请完成以下Java代码 | public boolean releaseHU(final I_M_HU hu)
{
Check.assume(allowRequestReleaseIncludedHU, "Requesting/Releasing new HU shall be allowed for {}", this);
final int count = getHUCount();
if (count <= 0)
{
return false;
}
decrementHUCount();
return true;
}
private void incrementHUCount()
{
final BigDecimal count = item.getQty();
final BigDecimal countNew = count.add(BigDecimal.ONE);
item.setQty(countNew);
dao.save(item);
}
private void decrementHUCount()
{
final BigDecimal count = item.getQty();
final BigDecimal countNew = count.subtract(BigDecimal.ONE);
item.setQty(countNew);
dao.save(item);
}
@Override
public int getHUCount()
{
final int count = item.getQty().intValueExact();
return count;
}
@Override
public int getHUCapacity()
{
if (X_M_HU_Item.ITEMTYPE_HUAggregate.equals(item.getItemType()))
{
return Quantity.QTY_INFINITE.intValue();
}
return Services.get(IHandlingUnitsBL.class).getPIItem(item).getQty().intValueExact();
}
@Override
public IProductStorage getProductStorage(final ProductId productId, final I_C_UOM uom, final ZonedDateTime date)
{
return new HUItemProductStorage(this, productId, uom, date);
}
@Override
public List<IProductStorage> getProductStorages(final ZonedDateTime date)
{
final List<I_M_HU_Item_Storage> storages = dao.retrieveItemStorages(item);
final List<IProductStorage> result = new ArrayList<>(storages.size());
for (final I_M_HU_Item_Storage storage : storages)
{
final ProductId productId = ProductId.ofRepoId(storage.getM_Product_ID());
final I_C_UOM uom = extractUOM(storage);
final HUItemProductStorage productStorage = new HUItemProductStorage(this, productId, uom, date);
result.add(productStorage);
}
return result; | }
private I_C_UOM extractUOM(final I_M_HU_Item_Storage storage)
{
return Services.get(IUOMDAO.class).getById(storage.getC_UOM_ID());
}
@Override
public boolean isEmpty()
{
final List<I_M_HU_Item_Storage> storages = dao.retrieveItemStorages(item);
for (final I_M_HU_Item_Storage storage : storages)
{
if (!isEmpty(storage))
{
return false;
}
}
return true;
}
private boolean isEmpty(final I_M_HU_Item_Storage storage)
{
final BigDecimal qty = storage.getQty();
if (qty.signum() != 0)
{
return false;
}
return true;
}
@Override
public boolean isEmpty(final ProductId productId)
{
final I_M_HU_Item_Storage storage = dao.retrieveItemStorage(item, productId);
if (storage == null)
{
return true;
}
return isEmpty(storage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUItemStorage.java | 1 |
请完成以下Java代码 | public Date getStartedAfter() {
return startedAfter;
}
public void setStartedAfter(Date startedAfter) {
this.startedAfter = startedAfter;
}
public String getStartedBy() {
return startedBy;
}
public void setStartedBy(String startedBy) {
this.startedBy = startedBy;
}
public boolean isWithJobException() {
return withJobException;
}
public String getLocale() {
return locale;
}
public boolean isNeedsProcessDefinitionOuterJoin() {
if (isNeedsPaging()) {
if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType)
|| AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType)
|| AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) {
// When using oracle, db2 or mssql we don't need outer join for the process definition join.
// It is not needed because the outer join order by is done by the row number instead | return false;
}
}
return hasOrderByForColumn(ProcessInstanceQueryProperty.PROCESS_DEFINITION_KEY.getName());
}
public List<List<String>> getSafeProcessInstanceIds() {
return safeProcessInstanceIds;
}
public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) {
this.safeProcessInstanceIds = safeProcessInstanceIds;
}
public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public boolean setDefaultTenantProfile(TenantId tenantId, TenantProfileId tenantProfileId) {
log.trace("Executing setDefaultTenantProfile [{}]", tenantProfileId);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
validateId(tenantProfileId, id -> INCORRECT_TENANT_PROFILE_ID + id);
TenantProfile tenantProfile = tenantProfileDao.findById(tenantId, tenantProfileId.getId());
if (!tenantProfile.isDefault()) {
tenantProfile.setDefault(true);
TenantProfile previousDefaultTenantProfile = findDefaultTenantProfile(tenantId);
boolean changed = false;
if (previousDefaultTenantProfile == null) {
tenantProfileDao.save(tenantId, tenantProfile);
publishEvictEvent(new TenantProfileEvictEvent(tenantProfileId, true));
changed = true;
} else if (!previousDefaultTenantProfile.getId().equals(tenantProfile.getId())) {
previousDefaultTenantProfile.setDefault(false);
tenantProfileDao.save(tenantId, previousDefaultTenantProfile);
tenantProfileDao.save(tenantId, tenantProfile);
publishEvictEvent(new TenantProfileEvictEvent(previousDefaultTenantProfile.getId(), false));
publishEvictEvent(new TenantProfileEvictEvent(tenantProfileId, true));
changed = true;
}
return changed;
}
return false;
}
@Override
public List<TenantProfile> findTenantProfilesByIds(TenantId tenantId, UUID[] ids) {
return tenantProfileDao.findTenantProfilesByIds(tenantId, ids);
}
@Override
public void deleteTenantProfiles(TenantId tenantId) {
log.trace("Executing deleteTenantProfiles");
tenantProfilesRemover.removeEntities(tenantId, null);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findTenantProfileById(tenantId, new TenantProfileId(entityId.getId())));
}
@Override | public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(tenantProfileDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.TENANT_PROFILE;
}
private final PaginatedRemover<String, TenantProfile> tenantProfilesRemover = new PaginatedRemover<>() {
@Override
protected PageData<TenantProfile> findEntities(TenantId tenantId, String id, PageLink pageLink) {
return tenantProfileDao.findTenantProfiles(tenantId, pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, TenantProfile entity) {
removeTenantProfile(tenantId, entity, entity.isDefault());
}
};
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\tenant\TenantProfileServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Address {
@Id
private int id;
private String street;
private String city;
private int zipode;
@OneToOne
@JoinColumn(name = "id")
@MapsId
private Person person;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getZipode() {
return zipode;
}
public void setZipode(int zipode) {
this.zipode = zipode;
}
public String getStreet() {
return street;
} | public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\mapsid\Address.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.