instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescritpion() {
return descritpion;
}
public void setDescritpion(String descritpion) {
this.descritpion = descritpion;
}
public String getUrl() {
return url;
|
}
public void setUrl(String url) {
this.url = url;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
}
|
repos\springBoot-master\springboot-SpringSecurity1\src\main\java\com\us\example\domain\Permission.java
| 1
|
请完成以下Java代码
|
public class ComponentLifecycleMsg implements TenantAwareMsg, ToAllNodesMsg {
@Serial
private static final long serialVersionUID = -5303421482781273062L;
private final TenantId tenantId;
private final EntityId entityId;
private final ComponentLifecycleEvent event;
private final String oldName;
private final String name;
private final EntityId oldProfileId;
private final EntityId profileId;
private final boolean ownerChanged;
private final JsonNode info;
public ComponentLifecycleMsg(TenantId tenantId, EntityId entityId, ComponentLifecycleEvent event) {
this(tenantId, entityId, event, null, null, null, null, false, null);
}
@Builder
private ComponentLifecycleMsg(TenantId tenantId, EntityId entityId, ComponentLifecycleEvent event, String oldName, String name, EntityId oldProfileId, EntityId profileId, boolean ownerChanged, JsonNode info) {
this.tenantId = tenantId;
this.entityId = entityId;
|
this.event = event;
this.oldName = oldName;
this.name = name;
this.oldProfileId = oldProfileId;
this.profileId = profileId;
this.ownerChanged = ownerChanged;
this.info = info;
}
public Optional<RuleChainId> getRuleChainId() {
return entityId.getEntityType() == EntityType.RULE_CHAIN ? Optional.of((RuleChainId) entityId) : Optional.empty();
}
@Override
public MsgType getMsgType() {
return MsgType.COMPONENT_LIFE_CYCLE_MSG;
}
}
|
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\plugin\ComponentLifecycleMsg.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
// Skip if processed before, prevent duplicated execution in Hierarchical ApplicationContext
if (processed.get()) {
return;
}
/**
* Gets Logger After LoggingSystem configuration ready
* @see LoggingApplicationListener
*/
final Logger logger = LoggerFactory.getLogger(getClass());
String bannerText = buildBannerText();
if (logger.isInfoEnabled()) {
logger.info(bannerText);
} else {
System.out.print(bannerText);
}
// mark processed to be true
processed.compareAndSet(false, true);
}
String buildBannerText() {
StringBuilder bannerTextBuilder = new StringBuilder();
bannerTextBuilder
.append(LINE_SEPARATOR)
.append(LINE_SEPARATOR)
.append(" :: Dubbo Spring Boot (v").append(Version.getVersion(getClass(), Version.getVersion())).append(") : ")
|
.append(DUBBO_SPRING_BOOT_GITHUB_URL)
.append(LINE_SEPARATOR)
.append(" :: Dubbo (v").append(Version.getVersion()).append(") : ")
.append(DUBBO_GITHUB_URL)
.append(LINE_SEPARATOR)
.append(" :: Discuss group : ")
.append(DUBBO_MAILING_LIST)
.append(LINE_SEPARATOR)
;
return bannerTextBuilder.toString();
}
}
|
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\context\event\WelcomeLogoApplicationListener.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private Optional<I_MobileUI_UserProfile_MFG> retrieveUserConfigRecord(final @NonNull UserId userId)
{
return queryBL.createQueryBuilder(I_MobileUI_UserProfile_MFG.class)
//.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_MobileUI_UserProfile_MFG.COLUMNNAME_AD_User_ID, userId)
.create()
.firstOnlyOptional(I_MobileUI_UserProfile_MFG.class);
}
private static MobileUIManufacturingConfig fromRecord(@NonNull final I_MobileUI_UserProfile_MFG record)
{
return MobileUIManufacturingConfig.builder()
.isScanResourceRequired(OptionalBoolean.ofNullableString(record.getIsScanResourceRequired()))
.isAllowIssuingAnyHU(OptionalBoolean.ofNullableString(record.getIsAllowIssuingAnyHU()))
.build();
}
private static void updateRecord(@NonNull final I_MobileUI_UserProfile_MFG record, @NonNull final MobileUIManufacturingConfig from)
{
record.setIsScanResourceRequired(from.getIsScanResourceRequired().toBooleanString());
record.setIsAllowIssuingAnyHU(from.getIsAllowIssuingAnyHU().toBooleanString());
}
private Optional<MobileUIManufacturingConfig> retrieveGlobalConfig(@NonNull final ClientId clientId)
{
return queryBL.createQueryBuilder(I_MobileUI_MFG_Config.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_MobileUI_MFG_Config.COLUMNNAME_AD_Client_ID, clientId)
|
.create()
.firstOnlyOptional(I_MobileUI_MFG_Config.class)
.map(MobileUIManufacturingConfigRepository::fromRecord);
}
private static MobileUIManufacturingConfig fromRecord(@NonNull final I_MobileUI_MFG_Config record)
{
return MobileUIManufacturingConfig.builder()
.isScanResourceRequired(OptionalBoolean.ofBoolean(record.isScanResourceRequired()))
.isAllowIssuingAnyHU(OptionalBoolean.ofBoolean(record.isAllowIssuingAnyHU()))
.build();
}
public void saveUserConfig(@NonNull final MobileUIManufacturingConfig newConfig, @NonNull final UserId userId)
{
final I_MobileUI_UserProfile_MFG record = retrieveUserConfigRecord(userId).orElseGet(() -> InterfaceWrapperHelper.newInstance(I_MobileUI_UserProfile_MFG.class));
record.setIsActive(true);
record.setAD_User_ID(userId.getRepoId());
updateRecord(record, newConfig);
InterfaceWrapperHelper.save(record);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\config\MobileUIManufacturingConfigRepository.java
| 2
|
请完成以下Java代码
|
private IDunningCandidateProducer createProducer(final Class<? extends IDunningCandidateProducer> clazz)
{
try
{
final IDunningCandidateProducer producer = clazz.newInstance();
return producer;
}
catch (Exception e)
{
throw new DunningException("Cannot create producer for " + clazz, e);
}
}
@Override
public IDunningCandidateProducer getDunningCandidateProducer(final IDunnableDoc sourceDoc)
{
Check.assume(sourceDoc != null, "sourceDoc is not null");
IDunningCandidateProducer selectedProducer = null;
for (final IDunningCandidateProducer producer : producers)
{
if (!producer.isHandled(sourceDoc))
{
continue;
}
if (selectedProducer != null)
{
throw new DunningException("Multiple producers found for " + sourceDoc + ": " + selectedProducer + ", " + producer);
}
|
selectedProducer = producer;
}
if (selectedProducer == null)
{
throw new DunningException("No " + IDunningCandidateProducer.class + " found for " + sourceDoc);
}
return selectedProducer;
}
@Override
public String toString()
{
return "DefaultDunningCandidateProducerFactory [producerClasses=" + producerClasses + ", producers=" + producers + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DefaultDunningCandidateProducerFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<Country> getAll(Country country) {
if (country.getPage() != null && country.getRows() != null) {
PageHelper.startPage(country.getPage(), country.getRows());
}
Example example = new Example(Country.class);
Example.Criteria criteria = example.createCriteria();
if (country.getCountryname() != null && country.getCountryname().length() > 0) {
criteria.andLike("countryname", "%" + country.getCountryname() + "%");
}
if (country.getCountrycode() != null && country.getCountrycode().length() > 0) {
criteria.andLike("countrycode", "%" + country.getCountrycode() + "%");
}
return countryMapper.selectByExample(example);
}
public List<Country> getAllByWeekend(Country country) {
if (country.getPage() != null && country.getRows() != null) {
PageHelper.startPage(country.getPage(), country.getRows());
}
Weekend<Country> weekend = Weekend.of(Country.class);
WeekendCriteria<Country, Object> criteria = weekend.weekendCriteria();
if (country.getCountryname() != null && country.getCountryname().length() > 0) {
criteria.andLike(Country::getCountryname, "%" + country.getCountryname() + "%");
}
if (country.getCountrycode() != null && country.getCountrycode().length() > 0) {
|
criteria.andLike(Country::getCountrycode, "%" + country.getCountrycode() + "%");
}
return countryMapper.selectByExample(weekend);
}
public Country getById(Integer id) {
return countryMapper.selectByPrimaryKey(id);
}
public void deleteById(Integer id) {
countryMapper.deleteByPrimaryKey(id);
}
public void save(Country country) {
if (country.getId() != null) {
countryMapper.updateByPrimaryKey(country);
} else {
countryMapper.insert(country);
}
}
}
|
repos\MyBatis-Spring-Boot-master\src\main\java\tk\mybatis\springboot\service\CountryService.java
| 2
|
请完成以下Java代码
|
public class BalancedBracketsUsingDeque {
public boolean isBalanced(String str) {
if (null == str || ((str.length() % 2) != 0)) {
return false;
} else {
char[] ch = str.toCharArray();
for (char c : ch) {
if (!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) {
return false;
}
}
}
Deque<Character> deque = new LinkedList<>();
|
for (char ch : str.toCharArray()) {
if (ch == '{' || ch == '[' || ch == '(') {
deque.addFirst(ch);
} else {
if (!deque.isEmpty() && ((deque.peekFirst() == '{' && ch == '}') || (deque.peekFirst() == '[' && ch == ']') || (deque.peekFirst() == '(' && ch == ')'))) {
deque.removeFirst();
} else {
return false;
}
}
}
return deque.isEmpty();
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\balancedbrackets\BalancedBracketsUsingDeque.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @ResponseBody List<User> getUserList() {
List<User> list = new ArrayList<>();
User user1 = new User();
user1.setId(1l);
user1.setName("mrbird");
user1.setAge(25);
list.add(user1);
User user2 = new User();
user2.setId(2l);
user2.setName("scott");
user2.setAge(29);
list.add(user2);
return list;
}
@ApiOperation(value = "新增用户", notes = "根据用户实体创建用户")
@ApiImplicitParam(name = "user", value = "用户实体", required = true, dataType = "User")
@PostMapping("/add")
public @ResponseBody Map<String, Object> addUser(@RequestBody User user) {
Map<String, Object> map = new HashMap<>();
map.put("result", "success");
return map;
}
@ApiOperation(value = "删除用户", notes = "根据用户id删除用户")
@ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long", paramType = "path")
@DeleteMapping("/{id}")
public @ResponseBody Map<String, Object> deleteUser(@PathVariable(value = "id") Long id) {
Map<String, Object> map = new HashMap<>();
|
map.put("result", "success");
return map;
}
@ApiOperation(value = "更新用户", notes = "根据用户id更新用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long", paramType = "path"),
@ApiImplicitParam(name = "user", value = "用户实体", required = true, dataType = "User") })
@PutMapping("/{id}")
public @ResponseBody Map<String, Object> updateUser(@PathVariable(value = "id") Long id, @RequestBody User user) {
Map<String, Object> map = new HashMap<>();
map.put("result", "success");
return map;
}
}
|
repos\SpringAll-master\20.Spring-Boot-Swagger2\src\main\java\com\example\demo\controller\UserController.java
| 2
|
请完成以下Java代码
|
public <ReqT, RespT> Listener<ReqT> interceptCall(
final ServerCall<ReqT, RespT> call,
final Metadata headers,
final ServerCallHandler<ReqT, RespT> next) {
final InterceptorStatusToken token;
try {
token = beforeInvocation(call);
} catch (final AuthenticationException | AccessDeniedException e) {
log.debug("Access denied");
throw e;
}
log.debug("Access granted");
final Listener<ReqT> result;
try {
result = next.startCall(call, headers);
|
} finally {
finallyInvocation(token);
}
return (Listener<ReqT>) afterInvocation(token, result);
}
@Override
public Class<?> getSecureObjectClass() {
return ServerCall.class;
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\security\interceptors\AuthorizationCheckingServerInterceptor.java
| 1
|
请完成以下Java代码
|
protected Capacity retrieveTotalCapacity()
{
final ProductId productId = ProductId.ofRepoId(ppOrder.getM_Product_ID());
// we allow negative qty because we want to allow receiving more then expected
final PPOrderQuantities ppOrderQtys = getPPOrderQuantities();
final Quantity qtyCapacity = ppOrderQtys.getQtyRequiredToProduce(); // i.e. target Qty To Receive
final boolean allowNegativeCapacity = true;
return Capacity.createCapacity(
qtyCapacity.toBigDecimal(), // qty
productId, // product
qtyCapacity.getUOM(), // uom
allowNegativeCapacity // allowNegativeCapacity
);
}
private PPOrderQuantities getPPOrderQuantities()
{
return orderBOMBL.getQuantities(ppOrder);
}
@Override
protected BigDecimal retrieveQtyInitial()
{
checkStaled();
|
final PPOrderQuantities ppOrderQtys = getPPOrderQuantities();
final Quantity qtyToReceive = ppOrderQtys.getQtyRemainingToProduce();
return qtyToReceive.toBigDecimal();
}
@Override
protected void beforeMarkingStalled()
{
staled = true;
}
private void checkStaled()
{
if (!staled)
{
return;
}
InterfaceWrapperHelper.refresh(ppOrder);
staled = false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\PPOrderProductStorage.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
public String getDecisionInstanceId() {
return decisionInstanceId;
}
public String getClauseId() {
return clauseId;
}
public String getClauseName() {
return clauseName;
}
public String getErrorMessage() {
return errorMessage;
}
public Date getCreateTime() {
return createTime;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public static HistoricDecisionInputInstanceDto fromHistoricDecisionInputInstance(HistoricDecisionInputInstance historicDecisionInputInstance) {
HistoricDecisionInputInstanceDto dto = new HistoricDecisionInputInstanceDto();
dto.id = historicDecisionInputInstance.getId();
|
dto.decisionInstanceId = historicDecisionInputInstance.getDecisionInstanceId();
dto.clauseId = historicDecisionInputInstance.getClauseId();
dto.clauseName = historicDecisionInputInstance.getClauseName();
dto.createTime = historicDecisionInputInstance.getCreateTime();
dto.removalTime = historicDecisionInputInstance.getRemovalTime();
dto.rootProcessInstanceId = historicDecisionInputInstance.getRootProcessInstanceId();
if(historicDecisionInputInstance.getErrorMessage() == null) {
VariableValueDto.fromTypedValue(dto, historicDecisionInputInstance.getTypedValue());
}
else {
dto.errorMessage = historicDecisionInputInstance.getErrorMessage();
dto.type = VariableValueDto.toRestApiTypeName(historicDecisionInputInstance.getTypeName());
}
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricDecisionInputInstanceDto.java
| 1
|
请完成以下Java代码
|
public void setP_String_To (String P_String_To)
{
set_Value (COLUMNNAME_P_String_To, P_String_To);
}
/** Get Process String To.
@return Process Parameter
*/
public String getP_String_To ()
{
return (String)get_Value(COLUMNNAME_P_String_To);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
|
{
set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance_Para.java
| 1
|
请完成以下Java代码
|
public boolean isA_New_Used ()
{
Object oo = get_Value(COLUMNNAME_A_New_Used);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Account State.
@param A_State
State of the Credit Card or Account holder
*/
public void setA_State (String A_State)
{
set_Value (COLUMNNAME_A_State, A_State);
}
/** Get Account State.
@return State of the Credit Card or Account holder
*/
public String getA_State ()
{
return (String)get_Value(COLUMNNAME_A_State);
}
/** Set Tax Entity.
@param A_Tax_Entity Tax Entity */
public void setA_Tax_Entity (String A_Tax_Entity)
{
set_Value (COLUMNNAME_A_Tax_Entity, A_Tax_Entity);
}
/** Get Tax Entity.
@return Tax Entity */
public String getA_Tax_Entity ()
|
{
return (String)get_Value(COLUMNNAME_A_Tax_Entity);
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Tax.java
| 1
|
请完成以下Java代码
|
private BodyMod createBodyMod(
@NonNull final DunningToExport dunning)
{
return BodyMod
.builder()
.prologMod(createPrologMod(dunning.getMetasfreshVersion()))
.balanceMod(createBalanceMod(dunning))
.build();
}
private PrologMod createPrologMod(@NonNull final MetasfreshVersion metasfreshVersion)
{
final SoftwareMod softwareMod = createSoftwareMod(metasfreshVersion);
return PrologMod.builder()
.pkgMod(softwareMod)
.generatorMod(createSoftwareMod(metasfreshVersion))
.build();
}
private XMLGregorianCalendar asXmlCalendar(@NonNull final Calendar cal)
{
try
{
final GregorianCalendar gregorianCal = new GregorianCalendar(cal.getTimeZone());
gregorianCal.setTime(cal.getTime());
return DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCal);
}
catch (final DatatypeConfigurationException e)
{
throw new AdempiereException(e).appendParametersToMessage()
.setParameter("cal", cal);
}
}
private SoftwareMod createSoftwareMod(@NonNull final MetasfreshVersion metasfreshVersion)
{
final long versionNumber = metasfreshVersion.getMajor() * 100 + metasfreshVersion.getMinor(); // .. as advised in the documentation
return SoftwareMod
|
.builder()
.name("metasfresh")
.version(versionNumber)
.description(metasfreshVersion.getFullVersion())
.id(0L)
.copyright("Copyright (C) 2018 metas GmbH")
.build();
}
private BalanceMod createBalanceMod(@NonNull final DunningToExport dunning)
{
final Money amount = dunning.getAmount();
final Money alreadyPaidAmount = dunning.getAlreadyPaidAmount();
final BigDecimal amountDue = amount.getAmount().subtract(alreadyPaidAmount.getAmount());
return BalanceMod.builder()
.currency(amount.getCurrency())
.amount(amount.getAmount())
.amountDue(amountDue)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\export\dunning\DunningExportClientImpl.java
| 1
|
请完成以下Java代码
|
public void sendMessage(ReqT message) {
log.debug("Request message: {}", message);
super.sendMessage(message);
}
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
super.start(
new ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>(responseListener) {
@Override
public void onMessage(RespT message) {
log.debug("Response message: {}", message);
super.onMessage(message);
}
@Override
public void onHeaders(Metadata headers) {
log.debug("gRPC headers: {}", headers);
|
super.onHeaders(headers);
}
@Override
public void onClose(Status status, Metadata trailers) {
log.info("Interaction ends with status: {}", status);
log.info("Trailers: {}", trailers);
super.onClose(status, trailers);
}
}, headers);
}
};
}
}
|
repos\grpc-spring-master\examples\cloud-grpc-client\src\main\java\net\devh\boot\grpc\examples\cloud\client\LogGrpcInterceptor.java
| 1
|
请完成以下Java代码
|
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
@Override
public void setM_HU_PI_Attribute_ID (final int M_HU_PI_Attribute_ID)
{
if (M_HU_PI_Attribute_ID < 1)
set_Value (COLUMNNAME_M_HU_PI_Attribute_ID, null);
else
set_Value (COLUMNNAME_M_HU_PI_Attribute_ID, M_HU_PI_Attribute_ID);
}
@Override
public int getM_HU_PI_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Attribute_ID);
}
@Override
public void setSnapshot_UUID (final java.lang.String Snapshot_UUID)
{
set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID);
}
@Override
public java.lang.String getSnapshot_UUID()
{
return get_ValueAsString(COLUMNNAME_Snapshot_UUID);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setValueInitial (final @Nullable java.lang.String ValueInitial)
{
set_ValueNoCheck (COLUMNNAME_ValueInitial, ValueInitial);
}
@Override
|
public java.lang.String getValueInitial()
{
return get_ValueAsString(COLUMNNAME_ValueInitial);
}
@Override
public void setValueNumber (final @Nullable BigDecimal ValueNumber)
{
set_Value (COLUMNNAME_ValueNumber, ValueNumber);
}
@Override
public BigDecimal getValueNumber()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValueNumberInitial (final @Nullable BigDecimal ValueNumberInitial)
{
set_ValueNoCheck (COLUMNNAME_ValueNumberInitial, ValueNumberInitial);
}
@Override
public BigDecimal getValueNumberInitial()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumberInitial);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Attribute_Snapshot.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AccountServiceImpl implements AccountService {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private StatisticsServiceClient statisticsClient;
@Autowired
private AuthServiceClient authClient;
@Autowired
private AccountRepository repository;
/**
* {@inheritDoc}
*/
@Override
public Account findByName(String accountName) {
Assert.hasLength(accountName);
return repository.findByName(accountName);
}
/**
* {@inheritDoc}
*/
@Override
public Account create(User user) {
Account existing = repository.findByName(user.getUsername());
Assert.isNull(existing, "account already exists: " + user.getUsername());
authClient.createUser(user);
Saving saving = new Saving();
saving.setAmount(new BigDecimal(0));
saving.setCurrency(Currency.getDefault());
saving.setInterest(new BigDecimal(0));
saving.setDeposit(false);
saving.setCapitalization(false);
Account account = new Account();
account.setName(user.getUsername());
account.setLastSeen(new Date());
account.setSaving(saving);
|
repository.save(account);
log.info("new account has been created: " + account.getName());
return account;
}
/**
* {@inheritDoc}
*/
@Override
public void saveChanges(String name, Account update) {
Account account = repository.findByName(name);
Assert.notNull(account, "can't find account with name " + name);
account.setIncomes(update.getIncomes());
account.setExpenses(update.getExpenses());
account.setSaving(update.getSaving());
account.setNote(update.getNote());
account.setLastSeen(new Date());
repository.save(account);
log.debug("account {} changes has been saved", name);
statisticsClient.updateStatistics(name, account);
}
}
|
repos\piggymetrics-master\account-service\src\main\java\com\piggymetrics\account\service\AccountServiceImpl.java
| 2
|
请完成以下Java代码
|
protected boolean isHeldExclusively() {
return getState() <= 0;
}
public Condition newCondition() {
return new ConditionObject();
}
}
private Sync sync;
/**
* @param count 能同时获取到锁的线程数
*/
public SharedLock(int count) {
this.sync = new Sync(count);
}
@Override
public void lock() {
sync.acquireShared(1);
}
@Override
public void lockInterruptibly() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
@Override
public boolean tryLock() {
try {
return sync.tryAcquireSharedNanos(1, 100L);
} catch (InterruptedException e) {
return false;
}
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(time));
}
@Override
|
public void unlock() {
sync.releaseShared(1);
}
@Override
public Condition newCondition() {
return sync.newCondition();
}
public static void main(String[] args) {
final Lock lock = new SharedLock(5);
// 启动10个线程
for (int i = 0; i < 100; i++) {
new Thread(() -> {
lock.lock();
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
} catch (Exception e) {
} finally {
lock.unlock();
}
}).start();
}
// 每隔1秒换行
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println();
}
}
}
|
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\SharedLock.java
| 1
|
请完成以下Java代码
|
public class GrpcServerTerminatedEvent extends GrpcServerLifecycleEvent {
private static final long serialVersionUID = 1L;
/**
* Creates a new GrpcServerTerminatedEvent.
*
* @param lifecyle The lifecycle that caused this event.
* @param clock The clock used to determine the timestamp.
* @param server The server related to this event.
*/
public GrpcServerTerminatedEvent(
final GrpcServerLifecycle lifecyle,
final Clock clock,
final Server server) {
super(lifecyle, clock, server);
}
|
/**
* Creates a new GrpcServerTerminatedEvent.
*
* @param lifecyle The lifecycle that caused this event.
* @param server The server related to this event.
*/
public GrpcServerTerminatedEvent(
final GrpcServerLifecycle lifecyle,
final Server server) {
super(lifecyle, server);
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\event\GrpcServerTerminatedEvent.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class GoodConsumeService {
@Autowired
GoodsRepository goodsRepository;
@Autowired
RetailerRepository retailerRepository;
@Autowired
OrderDetailsRepository orderDetailsRepository;
@Autowired
OrderRepository orderRepository;
@Autowired
UserRepository userRepository;
public void goodProcess(GoodListResponse goodListResponse){
for(GoodResponse goodResponse: goodListResponse.getGoodList())
{
Retailer retailer = retailerRepository.findByInternalCode(goodResponse.getGoodId()).orElse(null);
if(retailer == null)
continue;
List<Good> existGoods = goodsRepository.findByInternalCodeAndRetailer(goodResponse.getInternalCode(), retailer);
if(!existGoods.isEmpty()) {
existGoods.forEach(
o -> {
o.setIsOutdated(true);
goodsRepository.save(o);
});
// removeOutdatedGoodsFromBuckets(existGoods);
}
if(goodResponse.getIsOutdated() !=null && !goodResponse.getIsOutdated())
{
Good good = new Good(
goodResponse.getName(),
goodResponse.getPrice(),
goodResponse.getImage(),
goodResponse.getIngredients(),
retailerRepository.findByInternalCode(goodResponse.getRetailer()).orElse(null),
goodResponse.getInternalCode());
|
goodsRepository.save(good);
}
}
}
private void removeOutdatedGoodsFromBuckets(List<Good> outdatedGoods){
for(Good good: outdatedGoods)
{
for(User user: userRepository.findAll())
{
orderRepository.findFirstByStatusAndUser(OrderStatus.NEW, user)
.flatMap(orders -> orderDetailsRepository.findByGoodAndOrder(good, orders))
.ifPresent(orderDetails -> orderDetailsRepository.delete(orderDetails));
}
}
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\service\GoodConsumeService.java
| 2
|
请完成以下Java代码
|
public Object getValue()
{
return String.valueOf(getPassword());
} // getValue
/**
* Return Display Value
* @return value
*/
public String getDisplay()
{
return String.valueOf(getPassword());
} // getDisplay
/**************************************************************************
* Key Listener Interface
* @param e event
*/
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {}
/**
* Key Listener.
* @param e event
*/
public void keyReleased(KeyEvent e)
{
String newText = String.valueOf(getPassword());
m_setting = true;
try
{
fireVetoableChange(m_columnName, m_oldText, newText);
}
catch (PropertyVetoException pve) {}
m_setting = false;
} // keyReleased
/**
* Data Binding to MTable (via GridController) - Enter pressed
|
* @param e event
*/
public void actionPerformed(ActionEvent e)
{
String newText = String.valueOf(getPassword());
// Data Binding
try
{
fireVetoableChange(m_columnName, m_oldText, newText);
}
catch (PropertyVetoException pve) {}
} // actionPerformed
/**
* Set Field/WindowNo for ValuePreference
* @param mField field
*/
public void setField (GridField mField)
{
m_mField = mField;
} // setField
@Override
public GridField getField() {
return m_mField;
}
// metas: Ticket#2011062310000013
public boolean isAutoCommit()
{
return false;
}
} // VPassword
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VPassword.java
| 1
|
请完成以下Java代码
|
public int getData_Export_Audit_ID()
{
return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_ID);
}
@Override
public void setData_Export_Audit_Log_ID (final int Data_Export_Audit_Log_ID)
{
if (Data_Export_Audit_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_Log_ID, Data_Export_Audit_Log_ID);
}
@Override
public int getData_Export_Audit_Log_ID()
{
return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_Log_ID);
}
|
@Override
public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID)
{
if (ExternalSystem_Config_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_Config_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID);
}
@Override
public int getExternalSystem_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Data_Export_Audit_Log.java
| 1
|
请完成以下Java代码
|
public BigDecimal getFlatDiscount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_FlatDiscount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setIsBPartnerFlatDiscount (final boolean IsBPartnerFlatDiscount)
{
set_Value (COLUMNNAME_IsBPartnerFlatDiscount, IsBPartnerFlatDiscount);
}
@Override
public boolean isBPartnerFlatDiscount()
{
return get_ValueAsBoolean(COLUMNNAME_IsBPartnerFlatDiscount);
}
@Override
public org.compiere.model.I_M_DiscountSchema_Calculated_Surcharge getM_DiscountSchema_Calculated_Surcharge()
{
return get_ValueAsPO(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, org.compiere.model.I_M_DiscountSchema_Calculated_Surcharge.class);
}
@Override
public void setM_DiscountSchema_Calculated_Surcharge(final org.compiere.model.I_M_DiscountSchema_Calculated_Surcharge M_DiscountSchema_Calculated_Surcharge)
{
set_ValueFromPO(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, org.compiere.model.I_M_DiscountSchema_Calculated_Surcharge.class, M_DiscountSchema_Calculated_Surcharge);
}
@Override
public void setM_DiscountSchema_Calculated_Surcharge_ID (final int M_DiscountSchema_Calculated_Surcharge_ID)
{
if (M_DiscountSchema_Calculated_Surcharge_ID < 1)
set_Value (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, null);
else
set_Value (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, M_DiscountSchema_Calculated_Surcharge_ID);
}
@Override
public int getM_DiscountSchema_Calculated_Surcharge_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID);
}
@Override
public void setM_DiscountSchema_ID (final int M_DiscountSchema_ID)
{
if (M_DiscountSchema_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_ID, M_DiscountSchema_ID);
}
@Override
public int getM_DiscountSchema_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
|
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setScript (final @Nullable java.lang.String Script)
{
set_Value (COLUMNNAME_Script, Script);
}
@Override
public java.lang.String getScript()
{
return get_ValueAsString(COLUMNNAME_Script);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchema.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void rewriteDatePromised(@Nullable final XMLGregorianCalendar datePromised)
{
if (datePromised == null)
{
return;
}
if (datePromised.getHour() == 0 && datePromised.getMinute() == 0)
{
datePromised.setHour(23);
datePromised.setMinute(59);
datePromised.setSecond(0);
}
}
private void initRouteContext(final Exchange exchange)
{
final String clientValue = Util.resolveProperty(getContext(), AbstractEDIRoute.EDI_ORDER_ADClientValue);
final EcosioOrdersRouteContext context = EcosioOrdersRouteContext.builder()
.clientValue(clientValue)
.build();
exchange.setProperty(ROUTE_PROPERTY_ECOSIO_ORDER_ROUTE_CONTEXT, context);
}
private static void prepareNotifyReplicationTrxDone(@NonNull final Exchange exchange)
|
{
final EcosioOrdersRouteContext context = exchange.getProperty(ROUTE_PROPERTY_ECOSIO_ORDER_ROUTE_CONTEXT, EcosioOrdersRouteContext.class);
final List<NotifyReplicationTrxRequest> trxUpdateList = context.getImportedTrxName2TrxStatus()
.keySet()
.stream()
.map(context::getStatusRequestFor)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(ImmutableList.toImmutableList());
exchange.getIn().setBody(trxUpdateList);
}
private static void setImportStatusOk(@NonNull final Exchange exchange)
{
final EcosioOrdersRouteContext context = exchange.getProperty(ROUTE_PROPERTY_ECOSIO_ORDER_ROUTE_CONTEXT, EcosioOrdersRouteContext.class);
context.setCurrentReplicationTrxStatus(EcosioOrdersRouteContext.TrxImportStatus.ok());
}
private static void setImportStatusError(@NonNull final Exchange exchange)
{
final EcosioOrdersRouteContext context = exchange.getProperty(ROUTE_PROPERTY_ECOSIO_ORDER_ROUTE_CONTEXT, EcosioOrdersRouteContext.class);
final String errorMsg = ExceptionUtil.extractErrorMessage(exchange);
context.setCurrentReplicationTrxStatus(EcosioOrdersRouteContext.TrxImportStatus.error(errorMsg));
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\ecosio\EcosioOrdersRoute.java
| 2
|
请完成以下Java代码
|
public static GlobalQRCode toGlobalQRCode(final WorkplaceQRCode qrCode)
{
return JsonConverterV1.toGlobalQRCode(qrCode);
}
public static WorkplaceQRCode fromGlobalQRCodeJsonString(final String qrCodeString)
{
return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString));
}
public static WorkplaceQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode)
{
if (!isTypeMatching(globalQRCode))
{
throw new AdempiereException("Invalid QR Code")
.setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long
}
final GlobalQRCodeVersion version = globalQRCode.getVersion();
if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), JsonConverterV1.GLOBAL_QRCODE_VERSION))
|
{
return JsonConverterV1.fromGlobalQRCode(globalQRCode);
}
else
{
throw new AdempiereException("Invalid QR Code version: " + version);
}
}
public static boolean isTypeMatching(final @NonNull GlobalQRCode globalQRCode)
{
return GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workplace\qrcode\WorkplaceQRCodeJsonConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void fetchWithDuplicates() {
System.out.println("\nFetching authors with duplicates ...");
List<Author> authors = authorRepository.fetchWithDuplicates();
authors.forEach(a -> {
System.out.println("Id: " + a.getId() + ": Name: " + a.getName() + " Books: " + a.getBooks());
});
}
public void fetchWithoutHint() {
System.out.println("\nFetching authors without HINT_PASS_DISTINCT_THROUGH hint ...");
List<Author> authors = authorRepository.fetchWithoutHint();
|
authors.forEach(a -> {
System.out.println("Id: " + a.getId() + ": Name: " + a.getName() + " Books: " + a.getBooks());
});
}
public void fetchWithHint() {
System.out.println("\nFetching authors with HINT_PASS_DISTINCT_THROUGH hint ...");
List<Author> authors = authorRepository.fetchWithHint();
authors.forEach(a -> {
System.out.println("Id: " + a.getId() + ": Name: " + a.getName() + " Books: " + a.getBooks());
});
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootHintPassDistinctThrough\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请完成以下Java代码
|
public boolean triggeredByEvent() {
return triggeredByEventAttribute.getValue(this);
}
public void setTriggeredByEvent(boolean triggeredByEvent) {
triggeredByEventAttribute.setValue(this, triggeredByEvent);
}
public Collection<LaneSet> getLaneSets() {
return laneSetCollection.get(this);
}
public Collection<FlowElement> getFlowElements() {
return flowElementCollection.get(this);
}
public Collection<Artifact> getArtifacts() {
return artifactCollection.get(this);
}
/** camunda extensions */
|
/**
* @deprecated use isCamundaAsyncBefore() instead.
*/
@Deprecated
public boolean isCamundaAsync() {
return camundaAsyncAttribute.getValue(this);
}
/**
* @deprecated use setCamundaAsyncBefore(isCamundaAsyncBefore) instead.
*/
@Deprecated
public void setCamundaAsync(boolean isCamundaAsync) {
camundaAsyncAttribute.setValue(this, isCamundaAsync);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\SubProcessImpl.java
| 1
|
请完成以下Java代码
|
public CountResultDto getDecisionRequirementsDefinitionsCount(UriInfo uriInfo) {
DecisionRequirementsDefinitionQueryDto queryDto = new DecisionRequirementsDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
ProcessEngine engine = getProcessEngine();
DecisionRequirementsDefinitionQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
@Override
public DecisionRequirementsDefinitionResource getDecisionRequirementsDefinitionById(String decisionRequirementsDefinitionId) {
return new DecisionRequirementsDefinitionResourceImpl(getProcessEngine(), decisionRequirementsDefinitionId);
}
@Override
public DecisionRequirementsDefinitionResource getDecisionRequirementsDefinitionByKey(String decisionRequirementsDefinitionKey) {
DecisionRequirementsDefinition decisionRequirementsDefinition = getProcessEngine().getRepositoryService()
.createDecisionRequirementsDefinitionQuery()
.decisionRequirementsDefinitionKey(decisionRequirementsDefinitionKey)
.withoutTenantId().latestVersion().singleResult();
if (decisionRequirementsDefinition == null) {
|
String errorMessage = String.format("No matching decision requirements definition with key: %s and no tenant-id", decisionRequirementsDefinitionKey);
throw new RestException(Status.NOT_FOUND, errorMessage);
} else {
return getDecisionRequirementsDefinitionById(decisionRequirementsDefinition.getId());
}
}
@Override
public DecisionRequirementsDefinitionResource getDecisionRequirementsDefinitionByKeyAndTenantId(String decisionRequirementsDefinitionKey, String tenantId) {
DecisionRequirementsDefinition decisionRequirementsDefinition = getProcessEngine().getRepositoryService()
.createDecisionRequirementsDefinitionQuery()
.decisionRequirementsDefinitionKey(decisionRequirementsDefinitionKey)
.tenantIdIn(tenantId).latestVersion().singleResult();
if (decisionRequirementsDefinition == null) {
String errorMessage = String.format("No matching decision requirements definition with key: %s and tenant-id: %s", decisionRequirementsDefinitionKey, tenantId);
throw new RestException(Status.NOT_FOUND, errorMessage);
} else {
return getDecisionRequirementsDefinitionById(decisionRequirementsDefinition.getId());
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\DecisionRequirementsDefinitionRestServiceImpl.java
| 1
|
请完成以下Java代码
|
protected boolean shouldRegisterInstanceBasedOnMetadata(ServiceInstance instance) {
boolean shouldRegister = isInstanceAllowedBasedOnMetadata(instance)
&& !isInstanceIgnoredBasedOnMetadata(instance);
if (!shouldRegister) {
log.debug("Ignoring instance '{}' of '{}' service from discovery based on metadata.",
instance.getInstanceId(), instance.getServiceId());
}
return shouldRegister;
}
protected Mono<InstanceId> registerInstance(ServiceInstance instance) {
try {
Registration registration = converter.convert(instance).toBuilder().source(SOURCE).build();
log.debug("Registering discovered instance {}", registration);
return registry.register(registration);
}
catch (Exception ex) {
log.error("Couldn't register instance for discovered instance ({})", toString(instance), ex);
return Mono.empty();
}
}
protected String toString(ServiceInstance instance) {
String httpScheme = instance.isSecure() ? "https" : "http";
return String.format("serviceId=%s, instanceId=%s, url= %s://%s:%d", instance.getServiceId(),
instance.getInstanceId(), (instance.getScheme() != null) ? instance.getScheme() : httpScheme,
instance.getHost(), instance.getPort());
}
public void setConverter(ServiceInstanceConverter converter) {
this.converter = converter;
}
public void setIgnoredServices(Set<String> ignoredServices) {
this.ignoredServices = ignoredServices;
}
public Set<String> getIgnoredServices() {
return ignoredServices;
}
public Set<String> getServices() {
return services;
}
public void setServices(Set<String> services) {
this.services = services;
}
public Map<String, String> getInstancesMetadata() {
return instancesMetadata;
}
public void setInstancesMetadata(Map<String, String> instancesMetadata) {
this.instancesMetadata = instancesMetadata;
}
public Map<String, String> getIgnoredInstancesMetadata() {
return ignoredInstancesMetadata;
}
public void setIgnoredInstancesMetadata(Map<String, String> ignoredInstancesMetadata) {
|
this.ignoredInstancesMetadata = ignoredInstancesMetadata;
}
private boolean isInstanceAllowedBasedOnMetadata(ServiceInstance instance) {
if (instancesMetadata.isEmpty()) {
return true;
}
for (Map.Entry<String, String> metadata : instance.getMetadata().entrySet()) {
if (isMapContainsEntry(instancesMetadata, metadata)) {
return true;
}
}
return false;
}
private boolean isInstanceIgnoredBasedOnMetadata(ServiceInstance instance) {
if (ignoredInstancesMetadata.isEmpty()) {
return false;
}
for (Map.Entry<String, String> metadata : instance.getMetadata().entrySet()) {
if (isMapContainsEntry(ignoredInstancesMetadata, metadata)) {
return true;
}
}
return false;
}
private boolean isMapContainsEntry(Map<String, String> map, Map.Entry<String, String> entry) {
String value = map.get(entry.getKey());
return value != null && value.equals(entry.getValue());
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server-cloud\src\main\java\de\codecentric\boot\admin\server\cloud\discovery\InstanceDiscoveryListener.java
| 1
|
请完成以下Java代码
|
public Set<Object> keySet() {
throw new ActivitiException("unsupported operation on configuration beans");
// List<String> beanNames =
// asList(beanFactory.getBeanDefinitionNames());
// return new HashSet<Object>(beanNames);
}
public void clear() {
throw new ActivitiException("can't clear configuration beans");
}
public boolean containsValue(Object value) {
throw new ActivitiException("can't search values in configuration beans");
}
public Set<Map.Entry<Object, Object>> entrySet() {
throw new ActivitiException("unsupported operation on configuration beans");
}
public boolean isEmpty() {
throw new ActivitiException("unsupported operation on configuration beans");
|
}
public Object put(Object key, Object value) {
throw new ActivitiException("unsupported operation on configuration beans");
}
public void putAll(Map<? extends Object, ? extends Object> m) {
throw new ActivitiException("unsupported operation on configuration beans");
}
public Object remove(Object key) {
throw new ActivitiException("unsupported operation on configuration beans");
}
public int size() {
throw new ActivitiException("unsupported operation on configuration beans");
}
public Collection<Object> values() {
throw new ActivitiException("unsupported operation on configuration beans");
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\SpringBeanFactoryProxyMap.java
| 1
|
请完成以下Java代码
|
public void setDatePromised (java.sql.Timestamp DatePromised)
{
set_ValueNoCheck (COLUMNNAME_DatePromised, DatePromised);
}
/** Get Zugesagter Termin.
@return Zugesagter Termin für diesen Auftrag
*/
@Override
public java.sql.Timestamp getDatePromised ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DatePromised);
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Bestellte Menge.
@param QtyOrdered
Bestellte Menge
*/
@Override
|
public void setQtyOrdered (java.math.BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
/** Get Bestellte Menge.
@return Bestellte Menge
*/
@Override
public java.math.BigDecimal getQtyOrdered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Zusagbar.
@param QtyPromised Zusagbar */
@Override
public void setQtyPromised (java.math.BigDecimal QtyPromised)
{
set_Value (COLUMNNAME_QtyPromised, QtyPromised);
}
/** Get Zusagbar.
@return Zusagbar */
@Override
public java.math.BigDecimal getQtyPromised ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_PurchaseCandidate_Weekly.java
| 1
|
请完成以下Java代码
|
public class C_OLCandToOrderWorkpackageProcessor extends WorkpackageProcessorAdapter
{
public static final String PARAM_OLCandProcessor_ID = I_C_OLCandAggAndOrder.COLUMNNAME_C_OLCandProcessor_ID;
/**
* If we propagate the async-batch-Id to the order, it means that a bunch of future workpackages are going to inherit that ID and will therefore be part of the batch.
* This means that it will take much longer until the batch is done.
*/
public static final String PARAM_PROPAGATE_ASYNC_BATCH_ID_TO_ORDER_RECORD = "PROPAGATE_ASYNC_BATCH_ID_TO_ORDER_RECORD";
private final static Logger logger = LogManager.getLogger(C_OLCandToOrderWorkpackageProcessor.class);
private final IOLCandBL olCandBL = Services.get(IOLCandBL.class);
private final IQueueDAO queueDAO = Services.get(IQueueDAO.class);
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final OLCandProcessorRepository olCandProcessorRepo = SpringContextHolder.instance.getBean(OLCandProcessorRepository.class);
@Override
public Result processWorkPackage(@NonNull final I_C_Queue_WorkPackage workPackage, @NonNull final String localTrxName)
{
final List<OLCandId> candidateIds = queueDAO.retrieveItems(workPackage, I_C_OLCand.class, localTrxName)
.stream()
.map(I_C_OLCand::getC_OLCand_ID)
.map(OLCandId::ofRepoId)
.collect(ImmutableList.toImmutableList());
if (candidateIds.isEmpty())
{
Loggables.withLogger(logger, Level.DEBUG).addLog("No OLCands enqueued to be processed for C_Queue_WorkPackage_ID={}", workPackage.getC_Queue_WorkPackage_ID());
return Result.SUCCESS;
}
final PInstanceId enqueuedSelection = queryBL.createQueryBuilder(I_C_OLCand.class)
.addInArrayFilter(I_C_OLCand.COLUMNNAME_C_OLCand_ID, candidateIds)
.create()
.createSelection();
final int olCandProcessorId = getParameters().getParameterAsInt(PARAM_OLCandProcessor_ID, C_OlCandProcessor_ID_Default);
final boolean propagateAsyncBatchIdToOrderRecord = getParameters().getParameterAsBool(PARAM_PROPAGATE_ASYNC_BATCH_ID_TO_ORDER_RECORD);
final OLCandProcessorDescriptor olCandProcessorDescriptor = olCandProcessorRepo.getById(olCandProcessorId);
|
try
{
olCandBL.process(IOLCandBL.OLCandProcessRequest.builder()
.processor(olCandProcessorDescriptor)
.selectionId(enqueuedSelection)
.asyncBatchId(AsyncBatchId.ofRepoIdOrNull(workPackage.getC_Async_Batch_ID()))
.propagateAsyncBatchIdToOrderRecord(propagateAsyncBatchIdToOrderRecord)
.build());
}
catch (final Exception ex)
{
Loggables.withLogger(logger, Level.ERROR).addLog("@Error@: " + ex.getLocalizedMessage());
Loggables.withLogger(logger, Level.ERROR).addLog("@Rollback@");
throw AdempiereException.wrapIfNeeded(ex);
}
return Result.SUCCESS;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\async\C_OLCandToOrderWorkpackageProcessor.java
| 1
|
请完成以下Java代码
|
protected void prepare() {
ProcessInfoParameter[] parameter = getParametersAsArray();
for (int i = 0; i < parameter.length; i++)
{
String name = parameter[i].getParameterName();
if (parameter[i].getParameter() == null);
else if (name.equals("AD_HouseKeeping_ID"))
p_AD_HouseKeeping_ID = parameter[i].getParameterAsInt();
else
log.error("Unknown Parameter: " + name);
}
if (p_AD_HouseKeeping_ID == 0)
p_AD_HouseKeeping_ID = getRecord_ID();
} //prepare
protected String doIt() throws Exception {
X_AD_HouseKeeping houseKeeping = new X_AD_HouseKeeping(getCtx(), p_AD_HouseKeeping_ID,get_TrxName());
int tableID = houseKeeping.getAD_Table_ID();
MTable table = new MTable(getCtx(), tableID, get_TrxName());
String tableName = table.getTableName();
String whereClause = houseKeeping.getWhereClause();
int noins = 0;
int noexp = 0;
int nodel = 0;
if (houseKeeping.isSaveInHistoric()){
String sql = "INSERT INTO hst_"+tableName + " SELECT * FROM " + tableName;
if (whereClause != null && whereClause.length() > 0)
sql = sql + " WHERE " + whereClause;
noins = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName());
if (noins == -1)
throw new AdempiereSystemError("Cannot insert into hst_"+tableName);
addLog("@Inserted@ " + noins);
} //saveInHistoric
Date date = new Date();
if (houseKeeping.isExportXMLBackup()){
String pathFile = houseKeeping.getBackupFolder();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = dateFormat.format(date);
FileWriter file = new FileWriter(pathFile+File.separator+tableName+dateString+".xml");
String sql = "SELECT * FROM " + tableName;
if (whereClause != null && whereClause.length() > 0)
sql = sql + " WHERE " + whereClause;
PreparedStatement pstmt = null;
ResultSet rs = null;
StringBuilder linexml = null;
|
try
{
pstmt = DB.prepareStatement(sql, get_TrxName());
rs = pstmt.executeQuery();
while (rs.next()) {
GenericPO po = new GenericPO(tableName, getCtx(), rs, get_TrxName());
linexml = po.get_xmlString(linexml);
noexp++;
}
if(linexml != null)
file.write(linexml.toString());
file.close();
}
catch (Exception e)
{
throw e;
}
finally
{
DB.close(rs, pstmt);
pstmt = null;
rs=null;
}
addLog("@Exported@ " + noexp);
}//XmlExport
String sql = "DELETE FROM " + tableName;
if (whereClause != null && whereClause.length() > 0)
sql = sql + " WHERE " + whereClause;
nodel = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName());
if (nodel == -1)
throw new AdempiereSystemError("Cannot delete from " + tableName);
Timestamp time = new Timestamp(date.getTime());
houseKeeping.setLastRun(time);
houseKeeping.setLastDeleted(nodel);
houseKeeping.saveEx();
addLog("@Deleted@ " + nodel);
String msg = Msg.translate(getCtx(), tableName + "_ID") + " #" + nodel;
return msg;
}//doIt
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\process\HouseKeeping.java
| 1
|
请完成以下Java代码
|
public FinancialInstitutionIdentification7 getFinInstnId() {
return finInstnId;
}
/**
* Sets the value of the finInstnId property.
*
* @param value
* allowed object is
* {@link FinancialInstitutionIdentification7 }
*
*/
public void setFinInstnId(FinancialInstitutionIdentification7 value) {
this.finInstnId = value;
}
/**
* Gets the value of the brnchId property.
*
* @return
|
* possible object is
* {@link BranchData2 }
*
*/
public BranchData2 getBrnchId() {
return brnchId;
}
/**
* Sets the value of the brnchId property.
*
* @param value
* allowed object is
* {@link BranchData2 }
*
*/
public void setBrnchId(BranchData2 value) {
this.brnchId = 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\BranchAndFinancialInstitutionIdentification4.java
| 1
|
请完成以下Java代码
|
public void setIsAcknowledged (final boolean IsAcknowledged)
{
set_Value (COLUMNNAME_IsAcknowledged, IsAcknowledged);
}
@Override
public boolean isAcknowledged()
{
return get_ValueAsBoolean(COLUMNNAME_IsAcknowledged);
}
@Override
public void setMsgText (final java.lang.String MsgText)
{
set_Value (COLUMNNAME_MsgText, MsgText);
}
@Override
public java.lang.String getMsgText()
{
return get_ValueAsString(COLUMNNAME_MsgText);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setRoot_AD_Table_ID (final int Root_AD_Table_ID)
{
if (Root_AD_Table_ID < 1)
set_Value (COLUMNNAME_Root_AD_Table_ID, null);
else
set_Value (COLUMNNAME_Root_AD_Table_ID, Root_AD_Table_ID);
}
@Override
public int getRoot_AD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_Root_AD_Table_ID);
}
@Override
public void setRoot_Record_ID (final int Root_Record_ID)
{
if (Root_Record_ID < 1)
set_Value (COLUMNNAME_Root_Record_ID, null);
else
set_Value (COLUMNNAME_Root_Record_ID, Root_Record_ID);
}
|
@Override
public int getRoot_Record_ID()
{
return get_ValueAsInt(COLUMNNAME_Root_Record_ID);
}
/**
* Severity AD_Reference_ID=541949
* Reference name: Severity
*/
public static final int SEVERITY_AD_Reference_ID=541949;
/** Notice = N */
public static final String SEVERITY_Notice = "N";
/** Error = E */
public static final String SEVERITY_Error = "E";
@Override
public void setSeverity (final java.lang.String Severity)
{
set_Value (COLUMNNAME_Severity, Severity);
}
@Override
public java.lang.String getSeverity()
{
return get_ValueAsString(COLUMNNAME_Severity);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Record_Warning.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setUserDnPatterns(String... userDnPatterns) {
this.userDnPatterns = userDnPatterns;
}
/**
* The LDAP filter used to search for users (optional). For example "(uid={0})". The
* substituted parameter is the user's login name.
* @param userSearchFilter the LDAP filter used to search for users
*/
public void setUserSearchFilter(String userSearchFilter) {
this.userSearchFilter = userSearchFilter;
}
/**
* Search base for user searches. Defaults to "". Only used with
* {@link #setUserSearchFilter(String)}.
* @param userSearchBase search base for user searches
*/
public void setUserSearchBase(String userSearchBase) {
this.userSearchBase = userSearchBase;
}
/**
* Returns the configured {@link AuthenticationManager} that can be used to perform
* LDAP authentication.
* @return the configured {@link AuthenticationManager}
*/
public final AuthenticationManager createAuthenticationManager() {
LdapAuthenticationProvider ldapAuthenticationProvider = getProvider();
return new ProviderManager(ldapAuthenticationProvider);
}
private LdapAuthenticationProvider getProvider() {
AbstractLdapAuthenticator authenticator = getAuthenticator();
LdapAuthenticationProvider provider;
if (this.ldapAuthoritiesPopulator != null) {
provider = new LdapAuthenticationProvider(authenticator, this.ldapAuthoritiesPopulator);
}
else {
provider = new LdapAuthenticationProvider(authenticator);
}
if (this.authoritiesMapper != null) {
provider.setAuthoritiesMapper(this.authoritiesMapper);
|
}
if (this.userDetailsContextMapper != null) {
provider.setUserDetailsContextMapper(this.userDetailsContextMapper);
}
return provider;
}
private AbstractLdapAuthenticator getAuthenticator() {
AbstractLdapAuthenticator authenticator = createDefaultLdapAuthenticator();
if (this.userSearchFilter != null) {
authenticator.setUserSearch(
new FilterBasedLdapUserSearch(this.userSearchBase, this.userSearchFilter, this.contextSource));
}
if (this.userDnPatterns != null && this.userDnPatterns.length > 0) {
authenticator.setUserDnPatterns(this.userDnPatterns);
}
authenticator.afterPropertiesSet();
return authenticator;
}
/**
* Allows subclasses to supply the default {@link AbstractLdapAuthenticator}.
* @return the {@link AbstractLdapAuthenticator} that will be configured for LDAP
* authentication
*/
protected abstract T createDefaultLdapAuthenticator();
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\AbstractLdapAuthenticationManagerFactory.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private IQuery<I_M_ProductPrice> createProductPriceQueryForDiscontinuedProduct(
@NonNull final IQueryFilter<I_M_Product> productFilter,
@Nullable final LocalDate dateFrom)
{
final IQueryBuilder<I_M_ProductPrice> queryBuilder = queryBL.createQueryBuilder(I_M_Product.class)
.filter(productFilter)
.andCollectChildren(I_M_ProductPrice.COLUMNNAME_M_Product_ID, I_M_ProductPrice.class);
if (dateFrom == null)
{
return queryBuilder
.create();
}
final IQuery<I_M_PriceList_Version> currentPriceListVersionQuery = currentPriceListVersionQuery(dateFrom);
final IQueryFilter<I_M_PriceList_Version> futurePriceListVersionFilter = futurePriceListVersionFilter(dateFrom);
final IQuery<I_M_PriceList_Version> priceListVersionQuery = queryBL.createQueryBuilder(I_M_PriceList_Version.class)
.setJoinOr()
.addInSubQueryFilter(I_M_PriceList_Version.COLUMN_M_PriceList_Version_ID, I_M_PriceList_Version.COLUMN_M_PriceList_Version_ID, currentPriceListVersionQuery)
.filter(futurePriceListVersionFilter)
.create();
return queryBuilder
.addInSubQueryFilter(I_M_ProductPrice.COLUMNNAME_M_PriceList_Version_ID, I_M_PriceList_Version.COLUMNNAME_M_PriceList_Version_ID, priceListVersionQuery)
.create();
}
private void invalidateCacheForProductPrice(final int updatedRecords, final IQuery<I_M_ProductPrice> productPriceQuery)
{
final CacheInvalidateMultiRequest cacheInvalidateMultiRequest;
if (updatedRecords > 100)
{
cacheInvalidateMultiRequest = CacheInvalidateMultiRequest.allRecordsForTable(I_M_ProductPrice.Table_Name);
|
}
else
{
cacheInvalidateMultiRequest = CacheInvalidateMultiRequest.fromTableNameAndRecordIds(I_M_ProductPrice.Table_Name, productPriceQuery.listIds());
}
ModelCacheInvalidationService.get()
.invalidate(cacheInvalidateMultiRequest, ModelCacheInvalidationTiming.AFTER_CHANGE);
}
@Override
public CurrencyId getCurrencyId(@NonNull final PriceListId priceListId)
{
final I_M_PriceList priceList = getById(priceListId);
if (priceList == null)
{
throw new AdempiereException("@NotFound@ @M_PriceList_ID@: " + priceListId);
}
return CurrencyId.ofRepoId(priceList.getC_Currency_ID());
}
@Override
public I_M_ProductScalePrice retrieveScalePriceForExactBreak(@NonNull final ProductPriceId productPriceId, @NonNull final BigDecimal scalePriceBreak)
{
return queryBL.createQueryBuilder(I_M_ProductScalePrice.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_ProductScalePrice.COLUMNNAME_M_ProductPrice_ID, productPriceId)
.addEqualsFilter(I_M_ProductScalePrice.COLUMNNAME_Qty, scalePriceBreak)
.create()
.firstOnly(I_M_ProductScalePrice.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PriceListDAO.java
| 2
|
请完成以下Java代码
|
public boolean isRfQQty ()
{
Object oo = get_Value(COLUMNNAME_IsRfQQty);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Margin %.
@param Margin
Margin for a product as a percentage
*/
@Override
public void setMargin (java.math.BigDecimal Margin)
{
set_Value (COLUMNNAME_Margin, Margin);
}
/** Get Margin %.
@return Margin for a product as a percentage
*/
@Override
public java.math.BigDecimal getMargin ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Margin);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Offer Amount.
@param OfferAmt
Amount of the Offer
*/
@Override
public void setOfferAmt (java.math.BigDecimal OfferAmt)
{
set_Value (COLUMNNAME_OfferAmt, OfferAmt);
}
/** Get Offer Amount.
@return Amount of the Offer
*/
|
@Override
public java.math.BigDecimal getOfferAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OfferAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQLineQty.java
| 1
|
请完成以下Java代码
|
private static String buildMsgIllegalDate(final Timestamp date, final I_C_SubscriptionProgress sp1,
final I_C_SubscriptionProgress sp2)
{
return Msg.getMsg(Env.getCtx(), MSG_ILLEGAL_DATE, new Object[] { date });
}
private static String buildMsgNoChangeconditions(
final int oldSubscriptionId,
final int newSubscriptionId,
final Timestamp date)
{
final I_C_Flatrate_Conditions oldS = InterfaceWrapperHelper.create(Env.getCtx(), oldSubscriptionId, I_C_Flatrate_Conditions.class, null);
final I_C_Flatrate_Conditions newS = InterfaceWrapperHelper.create(Env.getCtx(), newSubscriptionId, I_C_Flatrate_Conditions.class, null);
|
return Msg.getMsg(Env.getCtx(), MSG_NO_CHANGE_ALLOWED,
new Object[] { oldS.getName(), newS.getName(), date });
}
private static String buildMsgNoChangeconditions(
final int oldSubscriptionId,
final String newStatus,
final Timestamp date)
{
final I_C_Flatrate_Conditions oldS = InterfaceWrapperHelper.create(Env.getCtx(), oldSubscriptionId, I_C_Flatrate_Conditions.class, null);
return Msg.getMsg(Env.getCtx(), MSG_NO_CHANGE_ALLOWED,
new Object[] { oldS.getName(), newStatus, date });
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\exceptions\SubscriptionChangeException.java
| 1
|
请完成以下Java代码
|
public int getPurchaser_User_ID()
{
return get_ValueAsInt(COLUMNNAME_Purchaser_User_ID);
}
/**
* SOCreditStatus AD_Reference_ID=289
* Reference name: C_BPartner SOCreditStatus
*/
public static final int SOCREDITSTATUS_AD_Reference_ID=289;
/** CreditStop = S */
public static final String SOCREDITSTATUS_CreditStop = "S";
/** CreditHold = H */
public static final String SOCREDITSTATUS_CreditHold = "H";
/** CreditWatch = W */
public static final String SOCREDITSTATUS_CreditWatch = "W";
/** NoCreditCheck = X */
public static final String SOCREDITSTATUS_NoCreditCheck = "X";
/** CreditOK = O */
public static final String SOCREDITSTATUS_CreditOK = "O";
/** NurEineRechnung = I */
public static final String SOCREDITSTATUS_NurEineRechnung = "I";
@Override
public void setSOCreditStatus (final java.lang.String SOCreditStatus)
{
set_Value (COLUMNNAME_SOCreditStatus, SOCreditStatus);
}
|
@Override
public java.lang.String getSOCreditStatus()
{
return get_ValueAsString(COLUMNNAME_SOCreditStatus);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Group.java
| 1
|
请完成以下Java代码
|
public String getDelivery() {
if (delivery == null) {
return "first";
} else {
return delivery;
}
}
/**
* Sets the value of the delivery property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDelivery(String value) {
this.delivery = value;
}
/**
* Gets the value of the regulationAttributes property.
*
* @return
* possible object is
* {@link Long }
*
*/
public long getRegulationAttributes() {
if (regulationAttributes == null) {
return 0L;
} else {
return regulationAttributes;
}
}
/**
* Sets the value of the regulationAttributes property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setRegulationAttributes(Long value) {
this.regulationAttributes = value;
}
/**
|
* Gets the value of the limitation property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isLimitation() {
return limitation;
}
/**
* Sets the value of the limitation property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setLimitation(Boolean value) {
this.limitation = value;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\RecordDrugType.java
| 1
|
请完成以下Java代码
|
public Comment addComment(User author, String body) {
final var commentToAdd = new Comment(this, author, body);
comments.add(commentToAdd);
return commentToAdd;
}
public void removeCommentByUser(User user, long commentId) {
final var commentsToDelete = comments.stream()
.filter(comment -> comment.getId().equals(commentId))
.findFirst()
.orElseThrow(NoSuchElementException::new);
if (!user.equals(author) || !user.equals(commentsToDelete.getAuthor())) {
throw new IllegalAccessError("Not authorized to delete comment");
}
comments.remove(commentsToDelete);
}
public void updateArticle(ArticleUpdateRequest updateRequest) {
contents.updateArticleContentsIfPresent(updateRequest);
}
public Article updateFavoriteByUser(User user) {
favorited = userFavorited.contains(user);
return this;
}
public User getAuthor() {
return author;
}
public ArticleContents getContents() {
return contents;
}
public Instant getCreatedAt() {
return createdAt;
}
|
public Instant getUpdatedAt() {
return updatedAt;
}
public int getFavoritedCount() {
return userFavorited.size();
}
public boolean isFavorited() {
return favorited;
}
public Set<Comment> getComments() {
return comments;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
var article = (Article) o;
return author.equals(article.author) && contents.getTitle().equals(article.contents.getTitle());
}
@Override
public int hashCode() {
return Objects.hash(author, contents.getTitle());
}
}
|
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\article\Article.java
| 1
|
请完成以下Java代码
|
public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
Object returnValue = result.getReturnValue();
Object body;
// 处理返回结果为 Mono 的情况
if (returnValue instanceof Mono) {
body = ((Mono<Object>) result.getReturnValue())
.map((Function<Object, Object>) GlobalResponseBodyHandler::wrapCommonResult)
.defaultIfEmpty(COMMON_RESULT_SUCCESS);
// 处理返回结果为 Flux 的情况
} else if (returnValue instanceof Flux) {
body = ((Flux<Object>) result.getReturnValue())
.collectList()
.map((Function<Object, Object>) GlobalResponseBodyHandler::wrapCommonResult)
.defaultIfEmpty(COMMON_RESULT_SUCCESS);
// 处理结果为其它类型
} else {
body = wrapCommonResult(returnValue);
}
|
return writeBody(body, METHOD_PARAMETER_MONO_COMMON_RESULT, exchange);
}
private static Mono<CommonResult> methodForParams() {
return null;
}
private static CommonResult<?> wrapCommonResult(Object body) {
// 如果已经是 CommonResult 类型,则直接返回
if (body instanceof CommonResult) {
return (CommonResult<?>) body;
}
// 如果不是,则包装成 CommonResult 类型
return CommonResult.success(body);
}
}
|
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-02\src\main\java\cn\iocoder\springboot\lab27\springwebflux\core\web\GlobalResponseBodyHandler.java
| 1
|
请完成以下Java代码
|
public CompiledScript compile(ScriptEngine scriptEngine, String language, String src) {
if(scriptEngine instanceof Compilable && !scriptEngine.getFactory().getLanguageName().equalsIgnoreCase("ecmascript")) {
Compilable compilingEngine = (Compilable) scriptEngine;
try {
CompiledScript compiledScript = compilingEngine.compile(src);
LOG.debugCompiledScriptUsing(language);
return compiledScript;
} catch (ScriptException e) {
throw new ScriptCompilationException("Unable to compile script: " + e.getMessage(), e);
}
} else {
// engine does not support compilation
return null;
}
}
protected Object evaluateScript(ScriptEngine engine, Bindings bindings) throws ScriptException {
LOG.debugEvaluatingNonCompiledScript(scriptSource);
return engine.eval(scriptSource, bindings);
}
public String getScriptSource() {
return scriptSource;
|
}
/**
* Sets the script source code. And invalidates any cached compilation result.
*
* @param scriptSource
* the new script source code
*/
public void setScriptSource(String scriptSource) {
this.compiledScript = null;
shouldBeCompiled = true;
this.scriptSource = scriptSource;
}
public boolean isShouldBeCompiled() {
return shouldBeCompiled;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\SourceExecutableScript.java
| 1
|
请完成以下Java代码
|
public GLDistributionBuilder setGLDistribution(final I_GL_Distribution distribution)
{
_glDistribution = distribution;
return this;
}
private I_GL_Distribution getGLDistribution()
{
Check.assumeNotNull(_glDistribution, "glDistribution not null");
return _glDistribution;
}
private List<I_GL_DistributionLine> getGLDistributionLines()
{
final I_GL_Distribution glDistribution = getGLDistribution();
return glDistributionDAO.retrieveLines(glDistribution);
}
public GLDistributionBuilder setCurrencyId(final CurrencyId currencyId)
{
_currencyId = currencyId;
_precision = null;
return this;
}
private CurrencyId getCurrencyId()
{
Check.assumeNotNull(_currencyId, "currencyId not null");
return _currencyId;
}
private CurrencyPrecision getPrecision()
{
if (_precision == null)
{
_precision = currencyDAO.getStdPrecision(getCurrencyId());
}
return _precision;
}
public GLDistributionBuilder setAmountToDistribute(final BigDecimal amountToDistribute)
{
_amountToDistribute = amountToDistribute;
return this;
}
private BigDecimal getAmountToDistribute()
|
{
Check.assumeNotNull(_amountToDistribute, "amountToDistribute not null");
return _amountToDistribute;
}
public GLDistributionBuilder setAmountSign(@NonNull final Sign amountSign)
{
_amountSign = amountSign;
return this;
}
private Sign getAmountSign()
{
Check.assumeNotNull(_amountSign, "amountSign not null");
return _amountSign;
}
public GLDistributionBuilder setQtyToDistribute(final BigDecimal qtyToDistribute)
{
_qtyToDistribute = qtyToDistribute;
return this;
}
private BigDecimal getQtyToDistribute()
{
Check.assumeNotNull(_qtyToDistribute, "qtyToDistribute not null");
return _qtyToDistribute;
}
public GLDistributionBuilder setAccountDimension(final AccountDimension accountDimension)
{
_accountDimension = accountDimension;
return this;
}
private AccountDimension getAccountDimension()
{
Check.assumeNotNull(_accountDimension, "_accountDimension not null");
return _accountDimension;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gldistribution\GLDistributionBuilder.java
| 1
|
请完成以下Java代码
|
public class CoapResourceObserver implements ResourceObserver {
@Override
public void changedName(String old) {
}
@Override
public void changedPath(String old) {
}
@Override
public void addedChild(Resource child) {
}
@Override
public void removedChild(Resource child) {
}
@Override
public void addedObserveRelation(ObserveRelation relation) {
Request request = relation.getExchange().getRequest();
String token = getTokenFromRequest(request);
clients.registerObserveRelation(token, relation);
log.trace("Added Observe relation for token: {}", token);
}
@Override
public void removedObserveRelation(ObserveRelation relation) {
Request request = relation.getExchange().getRequest();
String token = getTokenFromRequest(request);
clients.deregisterObserveRelation(token);
log.trace("Relation removed for token: {}", token);
}
}
private TbCoapDtlsSessionInfo getCoapDtlsSessionInfo(EndpointContext endpointContext) {
|
InetSocketAddress peerAddress = endpointContext.getPeerAddress();
String certPemStr = getCertPem(endpointContext);
TbCoapDtlsSessionKey tbCoapDtlsSessionKey = StringUtils.isNotBlank(certPemStr) ? new TbCoapDtlsSessionKey(peerAddress, certPemStr) : null;
TbCoapDtlsSessionInfo tbCoapDtlsSessionInfo;
if (tbCoapDtlsSessionKey != null) {
tbCoapDtlsSessionInfo = dtlsSessionsMap
.computeIfPresent(tbCoapDtlsSessionKey, (dtlsSessionIdStr, dtlsSessionInfo) -> {
dtlsSessionInfo.setLastActivityTime(System.currentTimeMillis());
return dtlsSessionInfo;
});
} else {
tbCoapDtlsSessionInfo = null;
}
return tbCoapDtlsSessionInfo;
}
private String getCertPem(EndpointContext endpointContext) {
try {
X509CertPath certPath = (X509CertPath) endpointContext.getPeerIdentity();
X509Certificate x509Certificate = (X509Certificate) certPath.getPath().getCertificates().get(0);
return Base64.getEncoder().encodeToString(x509Certificate.getEncoded());
} catch (Exception e) {
log.error("Failed to get cert PEM: [{}]", endpointContext.getPeerAddress(), e);
return null;
}
}
}
|
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\CoapTransportResource.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AtomikosJtaPlatform extends AbstractJtaPlatform {
@Override
@Bean(name = "atomikosTransactionManager")
protected TransactionManager locateTransactionManager() {
UserTransactionManager userTransactionManager = new UserTransactionManager();
userTransactionManager.setForceShutdown(true);
return userTransactionManager;
}
@Override
@Bean(name = "userTransaction")
protected UserTransaction locateUserTransaction() {
UserTransactionImp userTransactionImp = new UserTransactionImp();
try {
|
userTransactionImp.setTransactionTimeout(300);
} catch (SystemException e) {
e.printStackTrace();
}
return userTransactionImp;
}
@Bean(name = "transactionManager")
@DependsOn({ "userTransaction", "atomikosTransactionManager" })
public PlatformTransactionManager transactionManager() throws SystemException {
JtaTransactionManager jtaTransactionManager = new JtaTransactionManager();
jtaTransactionManager.setTransactionManager(locateTransactionManager());
jtaTransactionManager.setUserTransaction(locateUserTransaction());
return jtaTransactionManager;
}
}
|
repos\spring-boot-leaning-master\2.x_data\1-5 Spring Boot 下的(分布式)事务解决方案\spring-boot-atomikos\src\main\java\com\neo\config\AtomikosJtaPlatform.java
| 2
|
请完成以下Java代码
|
public void renameFolder(String bucketName, String sourceFolderKey, String destinationFolderKey) {
ListObjectsV2Request listRequest = ListObjectsV2Request.builder()
.bucket(bucketName)
.prefix(sourceFolderKey)
.build();
ListObjectsV2Response listResponse = s3Client.listObjectsV2(listRequest);
List<S3Object> objects = listResponse.contents();
for (S3Object s3Object : objects) {
String newKey = destinationFolderKey + s3Object.key()
.substring(sourceFolderKey.length());
// Copy object to destination folder
CopyObjectRequest copyRequest = CopyObjectRequest.builder()
.sourceBucket(bucketName)
.sourceKey(s3Object.key())
|
.destinationBucket(bucketName)
.destinationKey(newKey)
.build();
s3Client.copyObject(copyRequest);
// Delete object from source folder
DeleteObjectRequest deleteRequest = DeleteObjectRequest.builder()
.bucket(bucketName)
.key(s3Object.key())
.build();
s3Client.deleteObject(deleteRequest);
}
}
}
|
repos\tutorials-master\aws-modules\aws-s3\src\main\java\com\baeldung\s3\RenameObjectService.java
| 1
|
请完成以下Java代码
|
private JsonOLCand toJson(
@NonNull final OLCand olCand,
@NonNull final MasterdataProvider masterdataProvider)
{
final OrgId orgId = OrgId.ofRepoId(olCand.getAD_Org_ID());
final ZoneId orgTimeZone = masterdataProvider.getOrgTimeZone(orgId);
final String orgCode = orgDAO.retrieveOrgValue(orgId);
return JsonOLCand.builder()
.id(olCand.getId())
.poReference(olCand.getPOReference())
.externalLineId(olCand.getExternalLineId())
.externalHeaderId(olCand.getExternalHeaderId())
//
.org(masterdataProvider.getJsonOrganizationById(orgId))
//
.bpartner(toJson(orgCode, olCand.getBPartnerInfo(), masterdataProvider))
.billBPartner(toJson(orgCode, olCand.getBillBPartnerInfo(), masterdataProvider))
.dropShipBPartner(toJson(orgCode, olCand.getDropShipBPartnerInfo().orElse(null), masterdataProvider))
.handOverBPartner(toJson(orgCode, olCand.getHandOverBPartnerInfo().orElse(null), masterdataProvider))
//
.dateOrdered(olCand.getDateOrdered())
.datePromised(TimeUtil.asLocalDate(olCand.getDatePromised(), orgTimeZone))
.flatrateConditionsId(olCand.getFlatrateConditionsId())
//
|
.productId(olCand.getM_Product_ID())
.productDescription(olCand.getProductDescription())
.qty(olCand.getQty().toBigDecimal())
.uomId(olCand.getQty().getUomId().getRepoId())
.qtyItemCapacity(Quantitys.toBigDecimalOrNull(olCand.getQtyItemCapacityEff()))
.huPIItemProductId(olCand.getHUPIProductItemId())
//
.pricingSystemId(PricingSystemId.toRepoId(olCand.getPricingSystemId()))
.price(olCand.getPriceActual())
.discount(olCand.getDiscount())
//
.warehouseDestId(WarehouseId.toRepoId(olCand.getWarehouseDestId()))
//
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\ordercandidates\impl\JsonConverters.java
| 1
|
请完成以下Java代码
|
protected POInfo initPO(final Properties ctx)
{
final PropertiesWrapper wrapper = (PropertiesWrapper)ctx;
setCtx(wrapper.source);
tableName = wrapper.tableName;
final POInfo poInfo = POInfo.getPOInfo(tableName);
this.tableID = poInfo.getAD_Table_ID();
return poInfo;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("GenericPO[")
.append("TableName=").append(get_TableName())
.append(",ID=").append(get_ID())
.append("]");
return sb.toString();
}
public static final String COLUMNNAME_AD_OrgTrx_ID = "AD_OrgTrx_ID";
public static final int AD_ORGTRX_ID_AD_Reference_ID = 130;
/**
* Set Trx Organization. Performing or initiating organization
*/
public void setAD_OrgTrx_ID(int AD_OrgTrx_ID)
{
if (AD_OrgTrx_ID == 0)
set_Value(COLUMNNAME_AD_OrgTrx_ID, null);
else
set_Value(COLUMNNAME_AD_OrgTrx_ID, new Integer(AD_OrgTrx_ID));
}
/**
* Get Trx Organization. Performing or initiating organization
*/
public int getAD_OrgTrx_ID()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_OrgTrx_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
protected final GenericPO newInstance()
{
return new GenericPO(tableName, getCtx(), ID_NewInstanceNoInit);
}
@Override
public final PO copy()
|
{
final GenericPO po = (GenericPO)super.copy();
po.tableName = this.tableName;
po.tableID = this.tableID;
return po;
}
} // GenericPO
/**
* Wrapper class to workaround the limit of PO constructor that doesn't take a tableName or
* tableID parameter. Note that in the generated class scenario ( X_ ), tableName and tableId
* is generated as a static field.
*
* @author Low Heng Sin
*
*/
final class PropertiesWrapper extends Properties
{
/**
*
*/
private static final long serialVersionUID = 8887531951501323594L;
protected Properties source;
protected String tableName;
PropertiesWrapper(Properties source, String tableName)
{
this.source = source;
this.tableName = tableName;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\GenericPO.java
| 1
|
请完成以下Java代码
|
public class LoginUser {
/**
* 登录人id
*/
@SensitiveField
private String id;
/**
* 登录人账号
*/
@SensitiveField
private String username;
/**
* 登录人名字
*/
@SensitiveField
private String realname;
/**
* 登录人密码
*/
@SensitiveField
private String password;
/**
* 当前登录部门code
*/
@SensitiveField
private String orgCode;
/**
* 当前登录部门id
*/
@SensitiveField
private String orgId;
/**
* 当前登录角色code(多个逗号分割)
*/
@SensitiveField
private String roleCode;
/**
* 头像
*/
@SensitiveField
private String avatar;
/**
* 工号
*/
@SensitiveField
private String workNo;
/**
* 生日
*/
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthday;
/**
* 性别(1:男 2:女)
*/
private Integer sex;
/**
* 电子邮件
*/
@SensitiveField
private String email;
/**
* 电话
*/
@SensitiveField
private String phone;
/**
* 状态(1:正常 2:冻结 )
*/
private Integer status;
private Integer delFlag;
/**
* 同步工作流引擎1同步0不同步
*/
private Integer activitiSync;
|
/**
* 创建时间
*/
private Date createTime;
/**
* 身份(1 普通员工 2 上级)
*/
private Integer userIdentity;
/**
* 管理部门ids
*/
@SensitiveField
private String departIds;
/**
* 职务,关联职务表
*/
@SensitiveField
private String post;
/**
* 座机号
*/
@SensitiveField
private String telephone;
/** 多租户ids临时用,不持久化数据库(数据库字段不存在) */
@SensitiveField
private String relTenantIds;
/**设备id uniapp推送用*/
private String clientId;
/**
* 主岗位
*/
private String mainDepPostId;
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\LoginUser.java
| 1
|
请完成以下Java代码
|
public class RetrieveIdExample {
public static void main(String[] args) {
try ( MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017") ) {
MongoDatabase database = mongoClient.getDatabase("myMongoDb");
MongoCollection<Document> collection = database.getCollection("example");
// Create document with user-generated ID
ObjectId generatedId = new ObjectId();
System.out.println(generatedId.toString());
Document document = new Document();
document.put("_id", generatedId);
document.put("name", "Shubham");
document.put("company", "Baeldung");
collection.insertOne(document);
// Check that the ID of the document is still the one we set
System.out.println(document.getObjectId("_id").equals(generatedId));
// Create a second document by injecting the ID in the constructor
ObjectId generatedId2 = ObjectId.get();
|
Document document2 = new Document("_id", generatedId2);
document2.put("name", "Shubham");
document2.put("company", "Baeldung");
collection.insertOne(document2);
Date creationDate = generatedId.getDate();
System.out.println(creationDate);
int timestamp = generatedId.getTimestamp();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
|
repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\objectid\RetrieveIdExample.java
| 1
|
请完成以下Java代码
|
public final List<I_C_BP_BankAccount> fetchOrgEsrAccounts(@NonNull final I_AD_Org org)
{
final IBPartnerOrgBL bPartnerOrgBL = Services.get(IBPartnerOrgBL.class);
final IQueryBL queryBL = Services.get(IQueryBL.class);
// task 07647: we need to get the Org's BPArtner!
final I_C_BPartner linkedBPartner = bPartnerOrgBL.retrieveLinkedBPartner(org);
if (linkedBPartner == null)
{
throwMissingEsrAccount(org);
}
final IQueryBuilder<I_C_BP_BankAccount> queryBuilder = queryBL.createQueryBuilder(I_C_BP_BankAccount.class, org);
queryBuilder.addOnlyActiveRecordsFilter();
queryBuilder.addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_IsEsrAccount, true)
.addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_C_BPartner_ID, linkedBPartner.getC_BPartner_ID());
queryBuilder.orderBy()
.addColumn(I_C_BP_BankAccount.COLUMNNAME_IsDefaultESR, Direction.Descending, Nulls.Last)
.addColumn(I_C_BP_BankAccount.COLUMNNAME_C_BP_BankAccount_ID)
.endOrderBy();
final List<I_C_BP_BankAccount> esrAccounts = queryBuilder
.create()
.list();
if (esrAccounts.isEmpty())
{
throwMissingEsrAccount(org);
}
return esrAccounts;
}
private void throwMissingEsrAccount(final I_AD_Org org)
{
final IMsgBL msgBL = Services.get(IMsgBL.class);
final Properties ctx = InterfaceWrapperHelper.getCtx(org);
final String msg = msgBL.getMsg(ctx, MSG_NOT_ESR_ACCOUNT_FOR_ORG,
new Object[] { msgBL.translate(ctx, org.getValue())
|
});
throw new AdempiereException(msg);
}
@Override
public final List<I_C_BP_BankAccount> retrieveQRBPBankAccounts(@NonNull final String IBAN)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryFilter<I_C_BP_BankAccount> esrAccountmatichingIBANorQR_IBAN = queryBL.createCompositeQueryFilter(I_C_BP_BankAccount.class)
.setJoinOr()
.addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_IBAN, IBAN)
.addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_QR_IBAN, IBAN);
return queryBL.createQueryBuilder(I_C_BP_BankAccount.class)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_IsEsrAccount, true)
.filter(esrAccountmatichingIBANorQR_IBAN)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.create()
.list();
}
@Override
public boolean isESRBankAccount(final int bpBankAccountId)
{
if (bpBankAccountId <= 0)
{
return false;
}
final I_C_BP_BankAccount bpBankAccount = InterfaceWrapperHelper.load(bpBankAccountId, I_C_BP_BankAccount.class);
return bpBankAccount.isEsrAccount();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\api\impl\ESRBPBankAccountDAO.java
| 1
|
请完成以下Java代码
|
public ModelApiResponse message(String message) {
this.message = message;
return this;
}
/**
* Get message
* @return message
**/
@ApiModelProperty(value = "")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ModelApiResponse _apiResponse = (ModelApiResponse) o;
return Objects.equals(this.code, _apiResponse.code) &&
Objects.equals(this.type, _apiResponse.type) &&
Objects.equals(this.message, _apiResponse.message);
}
@Override
public int hashCode() {
return Objects.hash(code, type, message);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ModelApiResponse {\n");
|
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" message: ").append(toIndentedString(message)).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\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\ModelApiResponse.java
| 1
|
请完成以下Java代码
|
public void setMaxid_(int maxid_)
{
this.maxid_ = maxid_;
}
public double[] getAlpha_()
{
return alpha_;
}
public void setAlpha_(double[] alpha_)
{
this.alpha_ = alpha_;
}
public float[] getAlphaFloat_()
{
return alphaFloat_;
}
public void setAlphaFloat_(float[] alphaFloat_)
{
this.alphaFloat_ = alphaFloat_;
}
public double getCostFactor_()
{
return costFactor_;
}
public void setCostFactor_(double costFactor_)
{
this.costFactor_ = costFactor_;
}
public int getXsize_()
{
return xsize_;
}
public void setXsize_(int xsize_)
{
this.xsize_ = xsize_;
}
public int getMax_xsize_()
{
return max_xsize_;
}
public void setMax_xsize_(int max_xsize_)
{
this.max_xsize_ = max_xsize_;
}
public int getThreadNum_()
{
return threadNum_;
}
public void setThreadNum_(int threadNum_)
{
this.threadNum_ = threadNum_;
}
public List<String> getUnigramTempls_()
{
return unigramTempls_;
}
public void setUnigramTempls_(List<String> unigramTempls_)
{
|
this.unigramTempls_ = unigramTempls_;
}
public List<String> getBigramTempls_()
{
return bigramTempls_;
}
public void setBigramTempls_(List<String> bigramTempls_)
{
this.bigramTempls_ = bigramTempls_;
}
public List<String> getY_()
{
return y_;
}
public void setY_(List<String> y_)
{
this.y_ = y_;
}
public List<List<Path>> getPathList_()
{
return pathList_;
}
public void setPathList_(List<List<Path>> pathList_)
{
this.pathList_ = pathList_;
}
public List<List<Node>> getNodeList_()
{
return nodeList_;
}
public void setNodeList_(List<List<Node>> nodeList_)
{
this.nodeList_ = nodeList_;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\FeatureIndex.java
| 1
|
请完成以下Java代码
|
public void attachHeaders(HttpServletResponse response) {
if (authentication != null) {
// header != null checks required for websphere compatibility
if (authentication.getIdentityId() != null) {
response.addHeader("X-Authorized-User", authentication.getIdentityId());
}
if (authentication.getProcessEngineName() != null) {
response.addHeader("X-Authorized-Engine", authentication.getProcessEngineName());
}
if (authentication instanceof UserAuthentication) {
response.addHeader("X-Authorized-Apps", join(",", ((UserAuthentication) authentication).getAuthorizedApps()));
}
}
// response.addHeader("X-Authorized", Boolean.toString(granted));
}
public boolean isAuthenticated() {
return authentication != null && authentication != Authentication.ANONYMOUS;
}
public String getApplication() {
return application;
}
////// static helpers //////////////////////////////
public static Authorization granted(Authentication authentication) {
return new Authorization(authentication, true);
}
public static Authorization denied(Authentication authentication) {
|
return new Authorization(authentication, false);
}
public static Authorization grantedUnlessNull(Authentication authentication) {
return authentication != null ? granted(authentication) : denied(authentication);
}
private static String join(String delimiter, Collection<?> collection) {
StringBuilder builder = new StringBuilder();
for (Object o: collection) {
if (builder.length() > 0) {
builder.append(delimiter);
}
builder.append(o);
}
return builder.toString();
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\Authorization.java
| 1
|
请完成以下Java代码
|
private I_M_Warehouse toRecord(@NonNull final Warehouse warehouse)
{
final I_M_Warehouse record = Optional.ofNullable(getById(warehouse.getId()))
.orElseThrow(() -> new AdempiereException("No warehouse found for ID!")
.appendParametersToMessage()
.setParameter("WarehouseId", warehouse.getId()));
record.setAD_Org_ID(warehouse.getOrgId().getRepoId());
record.setValue(warehouse.getValue());
record.setName(warehouse.getName());
record.setC_BPartner_ID(warehouse.getPartnerLocationId().getBpartnerId().getRepoId());
record.setC_BPartner_Location_ID(warehouse.getPartnerLocationId().getRepoId());
record.setIsActive(warehouse.isActive());
return record;
}
@NonNull
private static Warehouse ofRecord(@NonNull final I_M_Warehouse warehouseRecord)
{
return Warehouse.builder()
.id(WarehouseId.ofRepoId(warehouseRecord.getM_Warehouse_ID()))
.orgId(OrgId.ofRepoId(warehouseRecord.getAD_Org_ID()))
.name(warehouseRecord.getName())
.value(warehouseRecord.getValue())
.partnerLocationId(BPartnerLocationId.ofRepoId(warehouseRecord.getC_BPartner_ID(), warehouseRecord.getC_BPartner_Location_ID()))
.active(warehouseRecord.isActive())
|
.build();
}
@Override
public ClientAndOrgId getClientAndOrgIdByLocatorId(@NonNull LocatorId locatorId)
{
return getClientAndOrgIdByLocatorId(locatorId.getWarehouseId());
}
public ClientAndOrgId getClientAndOrgIdByLocatorId(@NonNull WarehouseId warehouseId)
{
final I_M_Warehouse warehouse = getById(warehouseId);
return ClientAndOrgId.ofClientAndOrg(warehouse.getAD_Client_ID(), warehouse.getAD_Org_ID());
}
@Override
@NonNull
public ImmutableSet<LocatorId> getLocatorIdsByRepoId(@NonNull final Collection<Integer> locatorIds)
{
return getLocatorsByRepoIds(ImmutableSet.copyOf(locatorIds))
.stream()
.map(LocatorId::ofRecord)
.collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\api\impl\WarehouseDAO.java
| 1
|
请完成以下Java代码
|
public String toString() {
return "(" + source.getId() + ")--" + (id != null ? id + "-->(" : ">(") + destination.getId() + ")";
}
@SuppressWarnings("unchecked")
public List<ExecutionListener> getExecutionListeners() {
if (executionListeners == null) {
return Collections.EMPTY_LIST;
}
return executionListeners;
}
// getters and setters //////////////////////////////////////////////////////
protected void setSource(ActivityImpl source) {
this.source = source;
}
@Override
public ActivityImpl getDestination() {
return destination;
}
public void setExecutionListeners(List<ExecutionListener> executionListeners) {
this.executionListeners = executionListeners;
}
public List<Integer> getWaypoints() {
|
return waypoints;
}
public void setWaypoints(List<Integer> waypoints) {
this.waypoints = waypoints;
}
@Override
public Expression getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(Expression skipExpression) {
this.skipExpression = skipExpression;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\TransitionImpl.java
| 1
|
请完成以下Java代码
|
public void setM_TourVersionLine_ID (int M_TourVersionLine_ID)
{
if (M_TourVersionLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_TourVersionLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_TourVersionLine_ID, Integer.valueOf(M_TourVersionLine_ID));
}
/** Get Tour Version Line.
@return Tour Version Line */
@Override
public int getM_TourVersionLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_TourVersionLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
|
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_TourVersionLine.java
| 1
|
请完成以下Java代码
|
private boolean isEligible(final I_M_ReceiptSchedule_Alloc rsa)
{
if (!rsa.isActive())
{
logger.debug("Allocation not eligible because it's not active: {}", rsa);
return false;
}
// Consider only TU/VHU allocations
final int tuHU_ID = rsa.getM_TU_HU_ID();
if (tuHU_ID <= 0)
{
logger.debug("Allocation not eligible because there is no M_TU_HU_ID: {}", rsa);
return false;
}
// Make sure the RSA's LU or TU is in our scope (if any)
final int luTU_ID = rsa.getM_LU_HU_ID();
if (!isInScopeHU(tuHU_ID) && !isInScopeHU(luTU_ID))
{
logger.debug("Allocation not eligible because the LU is not in scope: {}", rsa);
logger.debug("In Scope HUs are: {}", inScopeHU_IDs);
return false;
}
return true;
}
|
private boolean isInScopeHU(final int huId)
{
if (huId <= 0)
{
return false;
}
if (inScopeHU_IDs == null)
{
return true;
}
if (inScopeHU_IDs.isEmpty())
{
return true;
}
return inScopeHU_IDs.contains(HuId.ofRepoId(huId));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\HUReceiptScheduleWeightNetAdjuster.java
| 1
|
请完成以下Java代码
|
public Object getValue() {
if(value != null) {
return value.getValue();
}
else {
return null;
}
}
public TypedValue getTypedValue() {
return value;
}
public ProcessEngineServices getProcessEngineServices() {
return Context.getProcessEngineConfiguration().getProcessEngine();
}
public ProcessEngine getProcessEngine() {
return Context.getProcessEngineConfiguration().getProcessEngine();
}
public static DelegateCaseVariableInstanceImpl fromVariableInstance(VariableInstance variableInstance) {
|
DelegateCaseVariableInstanceImpl delegateInstance = new DelegateCaseVariableInstanceImpl();
delegateInstance.variableId = variableInstance.getId();
delegateInstance.processDefinitionId = variableInstance.getProcessDefinitionId();
delegateInstance.processInstanceId = variableInstance.getProcessInstanceId();
delegateInstance.executionId = variableInstance.getExecutionId();
delegateInstance.caseExecutionId = variableInstance.getCaseExecutionId();
delegateInstance.caseInstanceId = variableInstance.getCaseInstanceId();
delegateInstance.taskId = variableInstance.getTaskId();
delegateInstance.activityInstanceId = variableInstance.getActivityInstanceId();
delegateInstance.tenantId = variableInstance.getTenantId();
delegateInstance.errorMessage = variableInstance.getErrorMessage();
delegateInstance.name = variableInstance.getName();
delegateInstance.value = variableInstance.getTypedValue();
return delegateInstance;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\listener\DelegateCaseVariableInstanceImpl.java
| 1
|
请完成以下Java代码
|
public class PurchaseOrderRow {
@DataField(pos = 1)
private String warehouseIdentifier;
@DataField(pos = 2)
private String externalHeaderId;
@DataField(pos = 3)
private String poReference;
@DataField(pos = 4)
private String dateOrdered;
@DataField(pos = 5)
private String datePromised;
@DataField(pos = 6)
private String bpartnerIdentifier;
@DataField(pos = 7)
private String externalLineId;
@DataField(pos = 8)
private String productIdentifier;
@DataField(pos = 9)
|
private String qty;
@DataField(pos = 10)
private String price;
public BigDecimal getQty()
{
return CamelProcessorUtil.parseGermanNumberString(qty);
}
public BigDecimal getPrice()
{
return CamelProcessorUtil.parseGermanNumberString(price);
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\purchaseorder\model\PurchaseOrderRow.java
| 1
|
请完成以下Java代码
|
public XML 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 XML addElement (String hashcode, String element)
{
addElementToRegistry (hashcode, element);
return (this);
}
/**
* Add an element to the valuie of <>VALUE</>
*
* @param element
* the value of <>VALUE</>
*/
public XML addElement (Element element)
{
addElementToRegistry (element);
return (this);
}
/**
* Removes an Element from the element.
*
* @param hashcode
* the name of the element to be removed.
*/
public XML removeElement (String hashcode)
{
removeElementFromRegistry (hashcode);
return (this);
}
public boolean getNeedLineBreak ()
{
boolean linebreak = true;
|
java.util.Enumeration en = elements ();
// if this tag has one child, and it's a String, then don't
// do any linebreaks to preserve whitespace
while (en.hasMoreElements ())
{
Object obj = en.nextElement ();
if (obj instanceof StringElement)
{
linebreak = false;
break;
}
}
return linebreak;
}
public boolean getBeginEndModifierDefined ()
{
boolean answer = false;
if (!this.getNeedClosingTag ())
answer = true;
return answer;
}
public char getBeginEndModifier ()
{
return '/';
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xml\XML.java
| 1
|
请完成以下Java代码
|
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
|
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CourseRating other = (CourseRating) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
|
repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\manytomany\model\CourseRating.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
SAPGLJournal create(
@NonNull final SAPGLJournalCreateRequest createRequest,
@NonNull final SAPGLJournalCurrencyConverter currencyConverter)
{
final I_SAP_GLJournal headerRecord = InterfaceWrapperHelper.newInstance(I_SAP_GLJournal.class);
headerRecord.setTotalDr(createRequest.getTotalAcctDR().toBigDecimal());
headerRecord.setTotalCr(createRequest.getTotalAcctCR().toBigDecimal());
headerRecord.setC_DocType_ID(createRequest.getDocTypeId().getRepoId());
headerRecord.setC_AcctSchema_ID(createRequest.getAcctSchemaId().getRepoId());
headerRecord.setPostingType(createRequest.getPostingType().getCode());
headerRecord.setAD_Org_ID(createRequest.getOrgId().getRepoId());
headerRecord.setDescription(createRequest.getDescription());
headerRecord.setDocStatus(DocStatus.Drafted.getCode());
final SAPGLJournalCurrencyConversionCtx conversionCtx = createRequest.getConversionCtx();
headerRecord.setAcct_Currency_ID(conversionCtx.getAcctCurrencyId().getRepoId());
headerRecord.setC_Currency_ID(conversionCtx.getCurrencyId().getRepoId());
headerRecord.setC_ConversionType_ID(CurrencyConversionTypeId.toRepoId(conversionCtx.getConversionTypeId()));
|
Optional.ofNullable(conversionCtx.getFixedConversionRate())
.ifPresent(fixedConversionRate -> headerRecord.setCurrencyRate(fixedConversionRate.getMultiplyRate()));
headerRecord.setDateAcct(TimeUtil.asTimestamp(createRequest.getDateDoc()));
headerRecord.setDateDoc(TimeUtil.asTimestamp(createRequest.getDateDoc()));
headerRecord.setGL_Category_ID(createRequest.getGlCategoryId().getRepoId());
headerRecord.setReversal_ID(SAPGLJournalId.toRepoId(createRequest.getReversalId()));
saveRecord(headerRecord);
final SAPGLJournal createdJournal = fromRecord(headerRecord, ImmutableList.of());
createRequest.getLines()
.forEach(createLineRequest -> createdJournal.addLine(createLineRequest, currencyConverter));
save(createdJournal);
return createdJournal;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalLoaderAndSaver.java
| 2
|
请完成以下Java代码
|
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
final Metadata headers,
final ServerCallHandler<ReqT, RespT> next) {
try {
// Streaming calls error out here
return new ExceptionTranslatorServerCallListener<>(next.startCall(call, headers), call);
} catch (final AuthenticationException aex) {
closeCallUnauthenticated(call, aex);
return noOpCallListener();
} catch (final AccessDeniedException aex) {
closeCallAccessDenied(call, aex);
return noOpCallListener();
}
}
/**
* Creates a new no-op call listener because you can neither return null nor throw an exception in
* {@link #interceptCall(ServerCall, Metadata, ServerCallHandler)}.
*
* @param <ReqT> The type of the request.
* @return The newly created dummy listener.
*/
protected <ReqT> Listener<ReqT> noOpCallListener() {
return new Listener<ReqT>() {};
}
/**
* Close the call with {@link Status#UNAUTHENTICATED}.
*
* @param call The call to close.
* @param aex The exception that was the cause.
*/
protected void closeCallUnauthenticated(final ServerCall<?, ?> call, final AuthenticationException aex) {
log.debug(UNAUTHENTICATED_DESCRIPTION, aex);
call.close(Status.UNAUTHENTICATED.withCause(aex).withDescription(UNAUTHENTICATED_DESCRIPTION), new Metadata());
}
/**
* Close the call with {@link Status#PERMISSION_DENIED}.
*
* @param call The call to close.
* @param aex The exception that was the cause.
*/
|
protected void closeCallAccessDenied(final ServerCall<?, ?> call, final AccessDeniedException aex) {
log.debug(ACCESS_DENIED_DESCRIPTION, aex);
call.close(Status.PERMISSION_DENIED.withCause(aex).withDescription(ACCESS_DENIED_DESCRIPTION), new Metadata());
}
/**
* Server call listener that catches and handles exceptions in {@link #onHalfClose()}.
*
* @param <ReqT> The type of the request.
* @param <RespT> The type of the response.
*/
private class ExceptionTranslatorServerCallListener<ReqT, RespT> extends SimpleForwardingServerCallListener<ReqT> {
private final ServerCall<ReqT, RespT> call;
protected ExceptionTranslatorServerCallListener(final Listener<ReqT> delegate,
final ServerCall<ReqT, RespT> call) {
super(delegate);
this.call = call;
}
@Override
// Unary calls error out here
public void onHalfClose() {
try {
super.onHalfClose();
} catch (final AuthenticationException aex) {
closeCallUnauthenticated(this.call, aex);
} catch (final AccessDeniedException aex) {
closeCallAccessDenied(this.call, aex);
}
}
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\security\interceptors\ExceptionTranslatingServerInterceptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class HUConsolidateWFActivityHandler implements WFActivityHandler
{
public static final WFActivityType HANDLED_ACTIVITY_TYPE = WFActivityType.ofString("huConsolidation.consolidate");
public static final UIComponentType COMPONENT_TYPE = UIComponentType.ofString("huConsolidation/consolidate");
@NonNull private final PickingSlotService pickingSlotService;
@NonNull private final IDocumentLocationBL documentLocationBL;
@Override
public WFActivityType getHandledActivityType() {return HANDLED_ACTIVITY_TYPE;}
@Override
public UIComponent getUIComponent(final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts)
{
final HUConsolidationJob job = getHUConsolidationJob(wfProcess);
return UIComponent.builderFrom(COMPONENT_TYPE, wfActivity)
.properties(Params.builder()
.valueObj("job", toJson(job))
// TODO
// .valueObj("lines", lines)
// .valueObj("qtyRejectedReasons", qtyRejectedReasons)
.build())
.build();
}
@Override
public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity completeDistributionWFActivity)
{
final HUConsolidationJob job = getHUConsolidationJob(wfProcess);
return computeActivityState(job);
}
public static WFActivityStatus computeActivityState(final HUConsolidationJob ignoredJob)
{
// TODO
return WFActivityStatus.NOT_STARTED;
}
private JsonHUConsolidationJob toJson(@NonNull final HUConsolidationJob job)
|
{
final RenderedAddressProvider renderedAddressProvider = documentLocationBL.newRenderedAddressProvider();
final String shipToAddress = renderedAddressProvider.getAddress(job.getShipToBPLocationId());
return JsonHUConsolidationJob.builder()
.id(job.getId())
.shipToAddress(shipToAddress)
.pickingSlots(toJsonHUConsolidationJobPickingSlots(job.getPickingSlotIds()))
.currentTarget(JsonHUConsolidationTarget.ofNullable(job.getCurrentTarget()))
.build();
}
private ImmutableList<JsonHUConsolidationJobPickingSlot> toJsonHUConsolidationJobPickingSlots(final Set<PickingSlotId> pickingSlotIds)
{
if (pickingSlotIds.isEmpty())
{
return ImmutableList.of();
}
final Set<PickingSlotIdAndCaption> pickingSlotIdAndCaptions = pickingSlotService.getPickingSlotIdAndCaptions(pickingSlotIds);
final PickingSlotQueuesSummary summary = pickingSlotService.getNotEmptyQueuesSummary(PickingSlotQueueQuery.onlyPickingSlotIds(pickingSlotIds));
return pickingSlotIdAndCaptions.stream()
.map(pickingSlotIdAndCaption -> JsonHUConsolidationJobPickingSlot.builder()
.pickingSlotId(pickingSlotIdAndCaption.getPickingSlotId())
.pickingSlotQRCode(PickingSlotQRCode.ofPickingSlotIdAndCaption(pickingSlotIdAndCaption).toPrintableQRCode().toJsonDisplayableQRCode())
.countHUs(summary.getCountHUs(pickingSlotIdAndCaption.getPickingSlotId()).orElse(0))
.build())
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\workflows_api\activity_handlers\HUConsolidateWFActivityHandler.java
| 2
|
请完成以下Java代码
|
public Map<String, Object> getProcessVariables() {
return activiti5ProcessInstance.getProcessVariables();
}
@Override
public String getTenantId() {
return activiti5ProcessInstance.getTenantId();
}
@Override
public String getName() {
return activiti5ProcessInstance.getName();
}
@Override
public String getDescription() {
return activiti5ProcessInstance.getDescription();
}
@Override
public String getLocalizedName() {
return activiti5ProcessInstance.getLocalizedName();
}
@Override
public String getLocalizedDescription() {
return activiti5ProcessInstance.getLocalizedDescription();
}
public org.activiti.engine.runtime.ProcessInstance getRawObject() {
return activiti5ProcessInstance;
}
@Override
public Date getStartTime() {
return null;
}
@Override
public String getStartUserId() {
|
return null;
}
@Override
public String getCallbackId() {
return null;
}
@Override
public String getCallbackType() {
return null;
}
@Override
public String getReferenceId() {
return null;
}
@Override
public String getReferenceType() {
return null;
}
@Override
public String getPropagatedStageInstanceId() {
return null;
}
}
|
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5ProcessInstanceWrapper.java
| 1
|
请完成以下Java代码
|
private String getOnlineLogContent(Object obj, String content){
if (Result.class.isInstance(obj)){
Result res = (Result)obj;
String msg = res.getMessage();
String tableName = res.getOnlTable();
if(oConvertUtils.isNotEmpty(tableName)){
content+=",表名:"+tableName;
}
if(res.isSuccess()){
content+= ","+(oConvertUtils.isEmpty(msg)?"操作成功":msg);
}else{
content+= ","+(oConvertUtils.isEmpty(msg)?"操作失败":msg);
}
}
return content;
}
/* private void saveSysLog(ProceedingJoinPoint joinPoint, long time, Object obj) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
SysLog sysLog = new SysLog();
AutoLog syslog = method.getAnnotation(AutoLog.class);
if(syslog != null){
//update-begin-author:taoyan date:
String content = syslog.value();
if(syslog.module()== ModuleType.ONLINE){
content = getOnlineLogContent(obj, content);
}
//注解上的描述,操作日志内容
sysLog.setLogContent(content);
sysLog.setLogType(syslog.logType());
}
//请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
sysLog.setMethod(className + "." + methodName + "()");
|
//设置操作类型
if (sysLog.getLogType() == CommonConstant.LOG_TYPE_2) {
sysLog.setOperateType(getOperateType(methodName, syslog.operateType()));
}
//获取request
HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
//请求的参数
sysLog.setRequestParam(getReqestParams(request,joinPoint));
//设置IP地址
sysLog.setIp(IPUtils.getIpAddr(request));
//获取登录用户信息
LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
if(sysUser!=null){
sysLog.setUserid(sysUser.getUsername());
sysLog.setUsername(sysUser.getRealname());
}
//耗时
sysLog.setCostTime(time);
sysLog.setCreateTime(new Date());
//保存系统日志
sysLogService.save(sysLog);
}*/
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\aspect\AutoLogAspect.java
| 1
|
请完成以下Java代码
|
private String buildSqlInArrayWhereClause(String columnName, List<?> values, Accessor accessor, List<Object> params)
{
if (values == null || values.isEmpty())
return "";
boolean hasNull = false;
StringBuffer whereClause = new StringBuffer();
StringBuffer whereClauseCurrent = new StringBuffer();
int count = 0;
for (Object v : values)
{
final Object value;
if (accessor != null)
value = accessor.getValue(v);
else
value = v;
if (value == null)
{
hasNull = true;
continue;
}
if (whereClauseCurrent.length() > 0)
whereClauseCurrent.append(",");
if (params == null)
{
whereClauseCurrent.append(value);
}
else
{
whereClauseCurrent.append("?");
params.add(value);
}
if (count >= 30)
{
if (whereClause.length() > 0)
whereClause.append(" OR ");
whereClause.append(columnName).append(" IN (").append(whereClauseCurrent).append(")");
whereClauseCurrent = new StringBuffer();
count = 0;
}
}
if (whereClauseCurrent.length() > 0)
{
if (whereClause.length() > 0)
whereClause.append(" OR ");
whereClause.append(columnName).append(" IN (").append(whereClauseCurrent).append(")");
whereClauseCurrent = null;
}
if (hasNull)
{
if (whereClause.length() > 0)
whereClause.append(" OR ");
whereClause.append(columnName).append(" IS NULL");
}
if (whereClause.length() > 0)
whereClause.insert(0, "(").append(")");
return whereClause.toString();
|
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("InvoiceGenerateResult [");
sb.append("invoiceCount=").append(getInvoiceCount());
if (storeInvoices)
{
sb.append(", invoices=").append(invoices);
}
if (notifications != null && !notifications.isEmpty())
{
sb.append(", notifications=").append(notifications);
}
sb.append("]");
return sb.toString();
}
@Override
public String getSummary(final Properties ctx)
{
return Services.get(IMsgBL.class).getMsg(ctx, MSG_Summary, new Object[] { getInvoiceCount(), getNotificationCount() });
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceGenerateResult.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WhatsAppService {
private static final Logger logger = LoggerFactory.getLogger(WhatsAppService.class);
@Value("${whatsapp.api_url}")
private String apiUrl;
@Value("${whatsapp.access_token}")
private String apiToken;
@Autowired
private CamelContext camelContext;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private ProducerTemplate producerTemplate;
@Autowired
private ChatbotService chatbotService;
@PostConstruct
public void init() throws Exception {
camelContext.addRoutes(new RouteBuilder() {
@Override
public void configure() {
JacksonDataFormat jacksonDataFormat = new JacksonDataFormat();
jacksonDataFormat.setPrettyPrint(true);
from("direct:sendWhatsAppMessage")
.setHeader("Authorization", constant("Bearer " + apiToken))
.setHeader("Content-Type", constant("application/json"))
.marshal(jacksonDataFormat)
.process(exchange -> {
logger.debug("Sending JSON: {}", exchange.getIn().getBody(String.class));
}).to(apiUrl).process(exchange -> {
logger.debug("Response: {}", exchange.getIn().getBody(String.class));
});
}
});
}
public void sendWhatsAppMessage(String toNumber, String message) {
Map<String, Object> body = new HashMap<>();
body.put("messaging_product", "whatsapp");
body.put("to", toNumber);
body.put("type", "text");
|
Map<String, String> text = new HashMap<>();
text.put("body", message);
body.put("text", text);
producerTemplate.sendBody("direct:sendWhatsAppMessage", body);
}
public void processIncomingMessage(String payload) {
try {
JsonNode jsonNode = objectMapper.readTree(payload);
JsonNode messages = jsonNode.at("/entry/0/changes/0/value/messages");
if (messages.isArray() && messages.size() > 0) {
String receivedText = messages.get(0).at("/text/body").asText();
String fromNumber = messages.get(0).at("/from").asText();
logger.debug(fromNumber + " sent the message: " + receivedText);
this.sendWhatsAppMessage(fromNumber, chatbotService.getResponse(receivedText));
}
} catch (Exception e) {
logger.error("Error processing incoming payload: {} ", payload, e);
}
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-3-3\src\main\java\com\baeldung\chatbot\service\WhatsAppService.java
| 2
|
请完成以下Java代码
|
public static User create(String name) {
return new User(name);
}
private final String name;
public User(String name) {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("Username is required");
}
this.name = name;
}
public String getName() {
return this.name;
}
@Override
public int compareTo(User user) {
return this.getName().compareTo(user.getName());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof User)) {
return false;
}
User that = (User) obj;
return this.getName().equals(that.getName());
}
|
@Override
public int hashCode() {
int hashValue = 17;
hashValue = 37 * hashValue + getName().hashCode();
return hashValue;
}
@Override
public String toString() {
return getName();
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\security\TestSecurityManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static ClientId ofRepoIdOrSystem(final int repoId)
{
final ClientId clientId = ofRepoIdOrNull(repoId);
return clientId != null ? clientId : SYSTEM;
}
public static Optional<ClientId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
@Nullable
public static ClientId ofRepoIdOrNull(final int repoId)
{
if (repoId == SYSTEM.repoId)
{
return SYSTEM;
}
else if (repoId == TRASH.repoId)
{
return TRASH;
}
else if (repoId == METASFRESH.repoId)
{
return METASFRESH;
}
else if (repoId <= 0)
{
return null;
}
else
{
return new ClientId(repoId);
}
}
public static final ClientId SYSTEM = new ClientId(0);
@VisibleForTesting
static final ClientId TRASH = new ClientId(99);
public static final ClientId METASFRESH = new ClientId(1000000);
int repoId;
|
private ClientId(final int repoId)
{
// NOTE: validation happens in ofRepoIdOrNull method
this.repoId = repoId;
}
public boolean isSystem()
{
return repoId == SYSTEM.repoId;
}
public boolean isTrash()
{
return repoId == TRASH.repoId;
}
public boolean isRegular()
{
return !isSystem() && !isTrash();
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static int toRepoId(@Nullable final ClientId clientId)
{
return clientId != null ? clientId.getRepoId() : -1;
}
public static boolean equals(@Nullable final ClientId id1, @Nullable final ClientId id2)
{
return Objects.equals(id1, id2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\ClientId.java
| 2
|
请完成以下Java代码
|
public class TrustAllCertsClient {
public static OkHttpClient getTrustAllCertsClient() throws NoSuchAlgorithmException, KeyManagementException {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
|
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
OkHttpClient.Builder newBuilder = new OkHttpClient.Builder();
newBuilder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0]);
newBuilder.hostnameVerifier((hostname, session) -> true);
return newBuilder.build();
}
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, IOException {
OkHttpClient newClient = getTrustAllCertsClient();
newClient.newCall(new Request.Builder().url("https://expired.badssl.com/").build()).execute();
}
}
|
repos\tutorials-master\libraries-http\src\main\java\com\baeldung\okhttp\ssl\TrustAllCertsClient.java
| 1
|
请完成以下Java代码
|
public void putAll(Map< ? extends String, ? extends Object> toMerge) {
for (java.util.Map.Entry<? extends String, ? extends Object> entry : toMerge.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
public Object remove(Object key) {
if (UNSTORED_KEYS.contains(key)) {
return null;
}
return wrappedBindings.remove(key);
}
public void clear() {
wrappedBindings.clear();
}
public boolean containsValue(Object value) {
return calculateBindingMap().containsValue(value);
}
public boolean isEmpty() {
|
return calculateBindingMap().isEmpty();
}
protected Map<String, Object> calculateBindingMap() {
Map<String, Object> bindingMap = new HashMap<String, Object>();
for (Resolver resolver : scriptResolvers) {
for (String key : resolver.keySet()) {
bindingMap.put(key, resolver.get(key));
}
}
Set<java.util.Map.Entry<String, Object>> wrappedBindingsEntries = wrappedBindings.entrySet();
for (Entry<String, Object> entry : wrappedBindingsEntries) {
bindingMap.put(entry.getKey(), entry.getValue());
}
return bindingMap;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\engine\ScriptBindings.java
| 1
|
请完成以下Java代码
|
public static HUQRCodeUniqueId random()
{
return ofUUID(UUID.randomUUID());
}
public static HUQRCodeUniqueId ofUUID(@NonNull final UUID uuid)
{
final String uuidStr = uuid.toString().replace("-", ""); // expect 32 chars
final StringBuilder uuidFirstPart = new StringBuilder(32);
final StringBuilder uuidLastPart = new StringBuilder();
// TO reduce the change of having duplicate displayable suffix,
// we cannot just take the last 4 chars but we will pick some of them from the middle
// See https://www.ietf.org/rfc/rfc4122.txt section 3, to understand the UUID v4 format.
for (int i = 0; i < uuidStr.length(); i++)
{
final char ch = uuidStr.charAt(i);
if (// from time_low (0-7):
i == 5
// from: time_mid (8-11):
|| i == 8
|| i == 11
// from: time_hi_and_version (12-15)
|| i == 13
// from: clock_seq_hi_and_reserved (16-17)
// from: clock_seq_low (18-19)
// from: node (20-31)
)
{
uuidLastPart.append(ch);
}
else
{
uuidFirstPart.append(ch);
}
}
final String uuidLastPartNorm = Strings.padStart(
|
String.valueOf(Integer.parseInt(uuidLastPart.toString(), 16)),
5, // because 4 hex digits can lead to 5 decimal digits (i.e. FFFF -> 65535)
'0');
return new HUQRCodeUniqueId(uuidFirstPart.toString(), uuidLastPartNorm);
}
@JsonCreator
public static HUQRCodeUniqueId ofJson(@NonNull final String json)
{
final int idx = json.indexOf('-');
if (idx <= 0)
{
throw new AdempiereException("Invalid ID: `" + json + "`");
}
final String idBase = json.substring(0, idx);
final String displayableSuffix = json.substring(idx + 1);
return new HUQRCodeUniqueId(idBase, displayableSuffix);
}
@Override
@Deprecated
public String toString()
{
return getAsString();
}
@JsonValue
public String getAsString()
{
return idBase + "-" + displayableSuffix;
}
public static boolean equals(@Nullable final HUQRCodeUniqueId id1, @Nullable final HUQRCodeUniqueId id2)
{
return Objects.equals(id1, id2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\HUQRCodeUniqueId.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public VersionLoadResult getVersionLoadRequestStatus(@Parameter(description = VC_REQUEST_ID_PARAM_DESCRIPTION, required = true)
@PathVariable UUID requestId) throws Exception {
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.WRITE);
return versionControlService.getVersionLoadStatus(getCurrentUser(), requestId);
}
@ApiOperation(value = "List branches (listBranches)", notes = "" +
"Lists branches available in the remote repository. \n\n" +
"Response example: \n" +
MARKDOWN_CODE_BLOCK_START +
"[\n" +
" {\n" +
" \"name\": \"master\",\n" +
" \"default\": true\n" +
" },\n" +
" {\n" +
" \"name\": \"dev\",\n" +
" \"default\": false\n" +
" },\n" +
" {\n" +
" \"name\": \"dev-2\",\n" +
" \"default\": false\n" +
" }\n" +
"]" +
MARKDOWN_CODE_BLOCK_END)
@GetMapping("/branches")
public DeferredResult<List<BranchInfo>> listBranches() throws Exception {
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ);
final TenantId tenantId = getTenantId();
ListenableFuture<List<BranchInfo>> branches = versionControlService.listBranches(tenantId);
return wrapFuture(Futures.transform(branches, remoteBranches -> {
List<BranchInfo> infos = new ArrayList<>();
BranchInfo defaultBranch;
String defaultBranchName = versionControlService.getVersionControlSettings(tenantId).getDefaultBranch();
|
if (StringUtils.isNotEmpty(defaultBranchName)) {
defaultBranch = new BranchInfo(defaultBranchName, true);
} else {
defaultBranch = remoteBranches.stream().filter(BranchInfo::isDefault).findFirst().orElse(null);
}
if (defaultBranch != null) {
infos.add(defaultBranch);
}
infos.addAll(remoteBranches.stream().filter(b -> !b.equals(defaultBranch))
.map(b -> new BranchInfo(b.getName(), false)).collect(Collectors.toList()));
return infos;
}, MoreExecutors.directExecutor()));
}
@Override
protected <T> DeferredResult<T> wrapFuture(ListenableFuture<T> future) {
return wrapFuture(future, vcRequestTimeout);
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\EntitiesVersionControlController.java
| 2
|
请完成以下Java代码
|
public int getM_TourVersion_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_TourVersion_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Reihenfolge.
@param SeqNo
|
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_DeliveryDay.java
| 1
|
请完成以下Java代码
|
private Collection<I_M_CostElement> getElements()
{
if (m_costElements != null)
{
return m_costElements;
}
final IQueryBuilder<I_M_CostElement> queryBuilder = Services.get(IQueryBL.class)
.createQueryBuilder(I_M_CostElement.class, this)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient();
if (p_M_CostElement_ID > 0)
{
queryBuilder.addEqualsFilter(I_M_CostElement.COLUMNNAME_M_CostElement_ID, p_M_CostElement_ID);
}
m_costElements = queryBuilder
.create()
.list();
return m_costElements;
}
private Collection<I_M_CostElement> m_costElements = null;
private List<I_M_Product> getProducts()
{
if (m_products != null)
{
return m_products;
}
final IQueryBuilder<I_M_Product> queryBuilder = Services.get(IQueryBL.class)
.createQueryBuilder(I_M_Product.class, this)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient();
if (p_M_Product_Category_ID > 0)
|
{
queryBuilder.addEqualsFilter(I_M_Product.COLUMNNAME_M_Product_Category_ID, p_M_Product_Category_ID);
p_M_Product_ID = 0;
}
if (p_M_Product_ID > 0)
{
queryBuilder.addEqualsFilter(I_M_Product.COLUMNNAME_M_Product_ID, p_M_Product_ID);
}
else
{
p_M_AttributeSetInstance_ID = 0;
}
m_products = queryBuilder
.create()
.list();
return m_products;
}
private List<I_M_Product> m_products = null;
} // Create Cost Element
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\CreateCostElement.java
| 1
|
请完成以下Java代码
|
public boolean isLoading()
{
return _loading;
}
private Map<String, Integer> columnName2modelIndex = new HashMap<String, Integer>();
/**
* Note: this method only works as expected if the given <code>columnName</code> was set with {@link ColumnInfo#setColumnName(String)}.
*
* @param columnName
* @return
*/
public int getColumnModelIndex(final String columnName)
{
final Integer indexModel = columnName2modelIndex.get(columnName);
if (indexModel == null)
{
return -1;
}
return indexModel;
}
/**
* Note: this method only works as expected if the given <code>columnName</code> was set with {@link ColumnInfo#setColumnName(String)}.
*
* @param rowIndexView
* @param columnName
* @return
*/
public Object getValueAt(final int rowIndexView, final String columnName)
{
final int colIndexModel = getColumnModelIndex(columnName);
if (colIndexModel < 0) // it starts with 0, not with 1, so it's <0, not <=0
{
throw new IllegalArgumentException("No column index found for " + columnName);
}
|
final int rowIndexModel = convertRowIndexToModel(rowIndexView);
return getModel().getValueAt(rowIndexModel, colIndexModel);
}
public void setValueAt(final Object value, final int rowIndexView, final String columnName)
{
final int colIndexModel = getColumnModelIndex(columnName);
if (colIndexModel <= 0)
{
throw new IllegalArgumentException("No column index found for " + columnName);
}
final int rowIndexModel = convertRowIndexToModel(rowIndexView);
getModel().setValueAt(value, rowIndexModel, colIndexModel);
}
@Override
public void clear()
{
final PO[] pos = new PO[] {};
loadTable(pos);
}
} // MiniTable
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\minigrid\MiniTable.java
| 1
|
请完成以下Java代码
|
private JWKSet retrieve(String jwkSetUrl) {
URI jwkSetUri = null;
try {
jwkSetUri = new URI(jwkSetUrl);
}
catch (URISyntaxException ex) {
throwInvalidClient("jwk_set_uri", ex);
}
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON, APPLICATION_JWK_SET_JSON));
RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.GET, jwkSetUri);
ResponseEntity<String> response = null;
try {
response = this.restOperations.exchange(request, String.class);
}
catch (Exception ex) {
throwInvalidClient("jwk_set_response_error", ex);
}
if (response.getStatusCode().value() != 200) {
throwInvalidClient("jwk_set_response_status");
}
JWKSet jwkSet = null;
try {
jwkSet = JWKSet.parse(response.getBody());
}
catch (ParseException ex) {
throwInvalidClient("jwk_set_response_body", ex);
}
return jwkSet;
}
private final class JwkSetHolder implements Supplier<JWKSet> {
private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Clock clock = Clock.systemUTC();
private final String jwkSetUrl;
private JWKSet jwkSet;
private Instant lastUpdatedAt;
private JwkSetHolder(String jwkSetUrl) {
this.jwkSetUrl = jwkSetUrl;
}
@Override
public JWKSet get() {
this.rwLock.readLock().lock();
if (shouldRefresh()) {
this.rwLock.readLock().unlock();
this.rwLock.writeLock().lock();
try {
if (shouldRefresh()) {
this.jwkSet = retrieve(this.jwkSetUrl);
|
this.lastUpdatedAt = Instant.now();
}
this.rwLock.readLock().lock();
}
finally {
this.rwLock.writeLock().unlock();
}
}
try {
return this.jwkSet;
}
finally {
this.rwLock.readLock().unlock();
}
}
private boolean shouldRefresh() {
// Refresh every 5 minutes
return (this.jwkSet == null
|| this.clock.instant().isAfter(this.lastUpdatedAt.plus(5, ChronoUnit.MINUTES)));
}
}
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\X509SelfSignedCertificateVerifier.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CustomerTradeMarginLineId implements RepoIdAware
{
int repoId;
@NonNull
CustomerTradeMarginId customerTradeMarginId;
@JsonCreator
public static CustomerTradeMarginLineId ofRepoId(@NonNull final CustomerTradeMarginId customerTradeMarginId, final int repoId)
{
return new CustomerTradeMarginLineId(customerTradeMarginId, repoId);
}
@Nullable
public static CustomerTradeMarginLineId ofRepoIdOrNull(@Nullable final CustomerTradeMarginId customerTradeMarginId, final int repoId)
{
return customerTradeMarginId != null && repoId > 0 ? new CustomerTradeMarginLineId(customerTradeMarginId, repoId) : null;
}
public static int toRepoId(@Nullable final CustomerTradeMarginLineId repoId)
|
{
return repoId != null ? repoId.getRepoId() : -1;
}
private CustomerTradeMarginLineId(@NonNull final CustomerTradeMarginId customerTradeMarginId, final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, I_C_Customer_Trade_Margin_Line.COLUMNNAME_C_Customer_Trade_Margin_Line_ID);
this.customerTradeMarginId = customerTradeMarginId;
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\pricing\trade_margin\CustomerTradeMarginLineId.java
| 2
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public Long getPermissionId() {
return permissionId;
}
public void setPermissionId(Long permissionId) {
|
this.permissionId = permissionId;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", roleId=").append(roleId);
sb.append(", permissionId=").append(permissionId);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsRolePermissionRelation.java
| 1
|
请完成以下Java代码
|
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public Integer getForwardCount() {
return forwardCount;
}
public void setForwardCount(Integer forwardCount) {
this.forwardCount = forwardCount;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getContent() {
return content;
}
public void setContent(String content) {
|
this.content = content;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", categoryId=").append(categoryId);
sb.append(", title=").append(title);
sb.append(", pic=").append(pic);
sb.append(", productCount=").append(productCount);
sb.append(", recommendStatus=").append(recommendStatus);
sb.append(", createTime=").append(createTime);
sb.append(", collectCount=").append(collectCount);
sb.append(", readCount=").append(readCount);
sb.append(", commentCount=").append(commentCount);
sb.append(", albumPics=").append(albumPics);
sb.append(", description=").append(description);
sb.append(", showStatus=").append(showStatus);
sb.append(", forwardCount=").append(forwardCount);
sb.append(", categoryName=").append(categoryName);
sb.append(", content=").append(content);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsSubject.java
| 1
|
请完成以下Java代码
|
public class Lane extends BaseElement {
protected String name;
protected Process parentProcess;
protected List<String> flowReferences = new ArrayList<String>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonBackReference
public Process getParentProcess() {
return parentProcess;
}
public void setParentProcess(Process parentProcess) {
this.parentProcess = parentProcess;
}
public List<String> getFlowReferences() {
return flowReferences;
}
public void setFlowReferences(List<String> flowReferences) {
this.flowReferences = flowReferences;
}
|
public Lane clone() {
Lane clone = new Lane();
clone.setValues(this);
return clone;
}
public void setValues(Lane otherElement) {
super.setValues(otherElement);
setName(otherElement.getName());
setParentProcess(otherElement.getParentProcess());
flowReferences = new ArrayList<String>();
if (otherElement.getFlowReferences() != null && !otherElement.getFlowReferences().isEmpty()) {
flowReferences.addAll(otherElement.getFlowReferences());
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Lane.java
| 1
|
请完成以下Java代码
|
public void handleEscalation(TaskEscalationDto dto) {
TaskService taskService = engine.getTaskService();
try {
taskService.handleEscalation(taskId, dto.getEscalationCode(), VariableValueDto.toMap(dto.getVariables(), engine, objectMapper));
} catch (NotFoundException e) {
throw new RestException(Status.NOT_FOUND, e, e.getMessage());
} catch (BadUserRequestException e) {
throw new RestException(Status.BAD_REQUEST, e, e.getMessage());
}
}
protected Task getTaskById(String id, boolean withCommentAttachmentInfo) {
if (withCommentAttachmentInfo) {
return engine.getTaskService().createTaskQuery().taskId(id).withCommentAttachmentInfo().initializeFormKeys().singleResult();
}
else{
return engine.getTaskService().createTaskQuery().taskId(id).initializeFormKeys().singleResult();
}
}
protected String getTaskFormMediaType(String taskId) {
Task task = engine.getTaskService().createTaskQuery().initializeFormKeys().taskId(taskId).singleResult();
ensureNotNull("No task found for taskId '" + taskId + "'", "task", task);
String formKey = task.getFormKey();
if(formKey != null) {
return ContentTypeUtil.getFormContentType(formKey);
} else if(task.getCamundaFormRef() != null) {
return ContentTypeUtil.getFormContentType(task.getCamundaFormRef());
}
return MediaType.APPLICATION_XHTML_XML;
}
protected <V extends Object> V runWithoutAuthorization(Supplier<V> action) {
IdentityService identityService = engine.getIdentityService();
Authentication currentAuthentication = identityService.getCurrentAuthentication();
try {
identityService.clearAuthentication();
|
return action.get();
} catch (Exception e) {
throw e;
} finally {
identityService.setAuthentication(currentAuthentication);
}
}
private Map<String, VariableValueDto> getTaskVariables(boolean withTaskVariablesInReturn) {
VariableResource variableResource;
if (withTaskVariablesInReturn) {
variableResource = this.getVariables();
} else {
variableResource = this.getLocalVariables();
}
return variableResource.getVariables(true);
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\task\impl\TaskResourceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public long findHistoricTaskInstanceCountByQueryCriteria(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) {
return dataManager.findHistoricTaskInstanceCountByQueryCriteria(historicTaskInstanceQuery);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricTaskInstance> findHistoricTaskInstancesByQueryCriteria(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) {
return dataManager.findHistoricTaskInstancesByQueryCriteria(historicTaskInstanceQuery);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricTaskInstance> findHistoricTaskInstancesAndRelatedEntitiesByQueryCriteria(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) {
return dataManager.findHistoricTaskInstancesAndRelatedEntitiesByQueryCriteria(historicTaskInstanceQuery);
}
@Override
public List<HistoricTaskInstance> findHistoricTaskInstancesByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricTaskInstancesByNativeQuery(parameterMap);
}
@Override
public long findHistoricTaskInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricTaskInstanceCountByNativeQuery(parameterMap);
}
@Override
public void deleteHistoricTaskInstances(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) {
dataManager.deleteHistoricTaskInstances(historicTaskInstanceQuery);
}
|
@Override
public void bulkDeleteHistoricTaskInstancesForIds(Collection<String> taskIds) {
dataManager.bulkDeleteHistoricTaskInstancesForIds(taskIds);
}
@Override
public void deleteHistoricTaskInstancesForNonExistingProcessInstances() {
dataManager.deleteHistoricTaskInstancesForNonExistingProcessInstances();
}
@Override
public void deleteHistoricTaskInstancesForNonExistingCaseInstances() {
dataManager.deleteHistoricTaskInstancesForNonExistingCaseInstances();
}
public HistoricTaskInstanceDataManager getHistoricTaskInstanceDataManager() {
return dataManager;
}
public void setHistoricTaskInstanceDataManager(HistoricTaskInstanceDataManager historicTaskInstanceDataManager) {
this.dataManager = historicTaskInstanceDataManager;
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskInstanceEntityManagerImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public int getAsyncExecutorResetExpiredJobsMaxTimeout() {
return asyncExecutorResetExpiredJobsMaxTimeout;
}
public JobServiceConfiguration setAsyncExecutorResetExpiredJobsMaxTimeout(int asyncExecutorResetExpiredJobsMaxTimeout) {
this.asyncExecutorResetExpiredJobsMaxTimeout = asyncExecutorResetExpiredJobsMaxTimeout;
return this;
}
@Override
public ObjectMapper getObjectMapper() {
return objectMapper;
}
@Override
public JobServiceConfiguration setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
return this;
}
public List<JobProcessor> getJobProcessors() {
return jobProcessors;
}
public JobServiceConfiguration setJobProcessors(List<JobProcessor> jobProcessors) {
this.jobProcessors = Collections.unmodifiableList(jobProcessors);
return this;
}
public List<HistoryJobProcessor> getHistoryJobProcessors() {
return historyJobProcessors;
}
|
public JobServiceConfiguration setHistoryJobProcessors(List<HistoryJobProcessor> historyJobProcessors) {
this.historyJobProcessors = Collections.unmodifiableList(historyJobProcessors);
return this;
}
public void setJobParentStateResolver(InternalJobParentStateResolver jobParentStateResolver) {
this.jobParentStateResolver = jobParentStateResolver;
}
public InternalJobParentStateResolver getJobParentStateResolver() {
return jobParentStateResolver;
}
public List<String> getEnabledJobCategories() {
return enabledJobCategories;
}
public void setEnabledJobCategories(List<String> enabledJobCategories) {
this.enabledJobCategories = enabledJobCategories;
}
public void addEnabledJobCategory(String jobCategory) {
if (enabledJobCategories == null) {
enabledJobCategories = new ArrayList<>();
}
enabledJobCategories.add(jobCategory);
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\JobServiceConfiguration.java
| 2
|
请完成以下Java代码
|
public int getAD_Client_ID()
{
return m_AD_Client_ID;
}
@Override
public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
return null; // nothing
}
@Nullable
@Override
public String modelChange(final PO po, final int type) throws Exception
{
return null; // nothing
}
@Nullable
@Override
public String docValidate(final PO po, final int timing) throws Exception
{
Check.assume(isDocument(), "PO '{}' is a document", po);
if (timing == ModelValidator.TIMING_AFTER_COMPLETE
&& !documentBL.isReversalDocument(po))
{
externalSystemScriptedExportConversionService
.retrieveBestMatchingConfig(AdTableAndClientId.of(AdTableId.ofRepoId(po.get_Table_ID()),
ClientId.ofRepoId(getAD_Client_ID())), po.get_ID())
.ifPresent(config -> executeInvokeScriptedExportConversionAction(config, po.get_ID()));
}
return null;
}
@NonNull
public AdTableId getTableId()
{
return adTableId;
}
private void executeInvokeScriptedExportConversionAction(
@NonNull final ExternalSystemScriptedExportConversionConfig config,
final int recordId)
{
final int configTableId = tableDAO.retrieveTableId(I_ExternalSystem_Config_ScriptedExportConversion.Table_Name);
|
try
{
trxManager.runAfterCommit(() -> {
ProcessInfo.builder()
.setCtx(getCtx())
.setRecord(configTableId, config.getId().getRepoId())
.setAD_ProcessByClassname(InvokeScriptedExportConversionAction.class.getName())
.addParameter(PARAM_EXTERNAL_REQUEST, COMMAND_CONVERT_MESSAGE_FROM_METASFRESH)
.addParameter(PARAM_CHILD_CONFIG_ID, config.getId().getRepoId())
.addParameter(PARAM_Record_ID, recordId)
.buildAndPrepareExecution()
.executeSync();
});
}
catch (final Exception e)
{
log.warn(InvokeScriptedExportConversionAction.class.getName() + " process failed for Config ID {}, Record ID: {}",
config.getId(), recordId, e);
}
}
private String getTableName()
{
return tableName;
}
private boolean isDocument()
{
return isDocument;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\scriptedexportconversion\interceptor\ExternalSystemScriptedExportConversionInterceptor.java
| 1
|
请完成以下Java代码
|
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
OAuth2UserAuthority that = (OAuth2UserAuthority) obj;
if (!this.getAuthority().equals(that.getAuthority())) {
return false;
}
Map<String, Object> thatAttributes = that.getAttributes();
if (getAttributes().size() != thatAttributes.size()) {
return false;
}
for (Map.Entry<String, Object> e : getAttributes().entrySet()) {
String key = e.getKey();
Object value = convertURLIfNecessary(e.getValue());
if (value == null) {
if (!(thatAttributes.get(key) == null && thatAttributes.containsKey(key))) {
return false;
}
}
else {
Object thatValue = convertURLIfNecessary(thatAttributes.get(key));
if (!value.equals(thatValue)) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
int result = this.getAuthority().hashCode();
|
result = 31 * result;
for (Map.Entry<String, Object> e : getAttributes().entrySet()) {
Object key = e.getKey();
Object value = convertURLIfNecessary(e.getValue());
result += Objects.hashCode(key) ^ Objects.hashCode(value);
}
return result;
}
@Override
public String toString() {
return this.getAuthority();
}
/**
* @return {@code URL} converted to a string since {@code URL} shouldn't be used for
* equality/hashCode. For other instances the value is returned as is.
*/
private static Object convertURLIfNecessary(Object value) {
return (value instanceof URL) ? ((URL) value).toExternalForm() : value;
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\user\OAuth2UserAuthority.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setTaxAddress(TaxAddress taxAddress)
{
this.taxAddress = taxAddress;
}
public Buyer taxIdentifier(TaxIdentifier taxIdentifier)
{
this.taxIdentifier = taxIdentifier;
return this;
}
/**
* Get taxIdentifier
*
* @return taxIdentifier
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public TaxIdentifier getTaxIdentifier()
{
return taxIdentifier;
}
public void setTaxIdentifier(TaxIdentifier taxIdentifier)
{
this.taxIdentifier = taxIdentifier;
}
public Buyer username(String username)
{
this.username = username;
return this;
}
/**
* The buyer's eBay user ID.
*
* @return username
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The buyer's eBay user ID.")
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
|
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
Buyer buyer = (Buyer)o;
return Objects.equals(this.taxAddress, buyer.taxAddress) &&
Objects.equals(this.taxIdentifier, buyer.taxIdentifier) &&
Objects.equals(this.username, buyer.username);
}
@Override
public int hashCode()
{
return Objects.hash(taxAddress, taxIdentifier, username);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class Buyer {\n");
sb.append(" taxAddress: ").append(toIndentedString(taxAddress)).append("\n");
sb.append(" taxIdentifier: ").append(toIndentedString(taxIdentifier)).append("\n");
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\Buyer.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public CookieRememberMeManager rememberMeManager() {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
cookieRememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag=="));
return cookieRememberMeManager;
}
@Bean
@DependsOn({"lifecycleBeanPostProcessor"})
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
|
return authorizationAttributeSourceAdvisor;
}
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
return redisManager;
}
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
return redisCacheManager;
}
}
|
repos\SpringAll-master\14.Spring-Boot-Shiro-Redis\src\main\java\com\springboot\config\ShiroConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public boolean enabled() {
return obtain(StatsdProperties::isEnabled, StatsdConfig.super::enabled);
}
@Override
public String host() {
return obtain(StatsdProperties::getHost, StatsdConfig.super::host);
}
@Override
public int port() {
return obtain(StatsdProperties::getPort, StatsdConfig.super::port);
}
@Override
public StatsdProtocol protocol() {
return obtain(StatsdProperties::getProtocol, StatsdConfig.super::protocol);
}
@Override
public int maxPacketLength() {
return obtain(StatsdProperties::getMaxPacketLength, StatsdConfig.super::maxPacketLength);
}
@Override
public Duration pollingFrequency() {
return obtain(StatsdProperties::getPollingFrequency, StatsdConfig.super::pollingFrequency);
}
@Override
|
public Duration step() {
return obtain(StatsdProperties::getStep, StatsdConfig.super::step);
}
@Override
public boolean publishUnchangedMeters() {
return obtain(StatsdProperties::isPublishUnchangedMeters, StatsdConfig.super::publishUnchangedMeters);
}
@Override
public boolean buffered() {
return obtain(StatsdProperties::isBuffered, StatsdConfig.super::buffered);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\statsd\StatsdPropertiesConfigAdapter.java
| 2
|
请完成以下Java代码
|
static CompositeStringExpression.Builder composer()
{
return CompositeStringExpression.builder();
}
/**
* Returns a {@code Collector} that concatenates the input string expressions, separated by the specified delimiter, in encounter order.
*/
static Collector<IStringExpression, ?, IStringExpression> collectJoining(final String delimiter)
{
final Supplier<List<IStringExpression>> supplier = ArrayList::new;
final BiConsumer<List<IStringExpression>, IStringExpression> accumulator = (list, item) -> list.add(item);
final BinaryOperator<List<IStringExpression>> combiner = (list1, list2) -> {
list1.addAll(list2);
return list1;
};
final Function<List<IStringExpression>, IStringExpression> finisher = (list) -> composer()
.appendAllJoining(delimiter, list)
.build();
return Collector.of(supplier, accumulator, combiner, finisher);
}
String EMPTY_RESULT = new String(""); // NOTE: we get a new string instance because we will compare with it by identity
/**
* Null String Expression Object
*/
IStringExpression NULL = NullStringExpression.instance;
@Override
default Class<String> getValueClass()
{
return String.class;
}
default boolean requiresParameter(final String parameterName)
{
return getParameterNames().contains(parameterName);
}
@Override
default boolean isNoResult(final Object result)
{
return result == null
|| Util.same(result, EMPTY_RESULT);
}
@Override
default boolean isNullExpression()
{
return false;
}
/**
* Resolves all variables which available and returns a new string expression.
*
* @param ctx
* @return string expression with all available variables resolved.
* @throws ExpressionEvaluationException
|
*/
default IStringExpression resolvePartial(final Evaluatee ctx) throws ExpressionEvaluationException
{
final String expressionStr = evaluate(ctx, OnVariableNotFound.Preserve);
return StringExpressionCompiler.instance.compile(expressionStr);
}
/**
* Turns this expression in an expression which caches it's evaluation results.
* If this expression implements {@link ICachedStringExpression} it will be returned directly without any wrapping.
*
* @return cached expression
*/
default ICachedStringExpression caching()
{
return CachedStringExpression.wrapIfPossible(this);
}
/**
* @return same as {@link #toString()} but the whole string representation will be on one line (new lines are stripped)
*/
default String toOneLineString()
{
return toString()
.replace("\r", "")
.replace("\n", "");
}
default CompositeStringExpression.Builder toComposer()
{
return composer().append(this);
}
@Override
String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\IStringExpression.java
| 1
|
请完成以下Java代码
|
public MAlert[] getAlerts (boolean reload)
{
MAlert[] alerts = s_cacheAlerts.get(get_ID());
if (alerts != null && !reload)
return alerts;
String sql = "SELECT * FROM AD_Alert "
+ "WHERE AD_AlertProcessor_ID=? AND IsActive='Y' ";
ArrayList<MAlert> list = new ArrayList<>();
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, getAD_AlertProcessor_ID());
rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MAlert (getCtx(), rs, null));
}
catch (Exception e)
{
log.error(sql, e);
|
}
finally
{
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
//
alerts = new MAlert[list.size ()];
list.toArray (alerts);
s_cacheAlerts.put(get_ID(), alerts);
return alerts;
} // getAlerts
@Override
public boolean saveOutOfTrx()
{
return save(ITrx.TRXNAME_None);
}
} // MAlertProcessor
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAlertProcessor.java
| 1
|
请完成以下Java代码
|
public abstract class SubscriptionExceptionResolverAdapter implements SubscriptionExceptionResolver {
protected final Log logger = LogFactory.getLog(getClass());
private boolean threadLocalContextAware;
/**
* Subclasses can set this to indicate that ThreadLocal context from the
* transport handler (e.g. HTTP handler) should be restored when resolving
* exceptions.
* <p><strong>Note:</strong> This property is applicable only if transports
* use ThreadLocal's' (e.g. Spring MVC) and if a {@link ThreadLocalAccessor}
* is registered to extract ThreadLocal values of interest. There is no
* impact from setting this property otherwise.
* <p>By default this is set to "false" in which case there is no attempt
* to propagate ThreadLocal context.
* @param threadLocalContextAware whether this resolver needs access to
* ThreadLocal context or not.
*/
public void setThreadLocalContextAware(boolean threadLocalContextAware) {
this.threadLocalContextAware = threadLocalContextAware;
}
/**
* Whether ThreadLocal context needs to be restored for this resolver.
*/
public boolean isThreadLocalContextAware() {
return this.threadLocalContextAware;
}
@SuppressWarnings({"unused", "try"})
@Override
public final Mono<List<GraphQLError>> resolveException(Throwable exception) {
if (this.threadLocalContextAware) {
return Mono.deferContextual((contextView) -> {
ContextSnapshot snapshot = ContextPropagationHelper.captureFrom(contextView);
try {
List<GraphQLError> errors = snapshot.wrap(() -> resolveToMultipleErrors(exception)).call();
return Mono.justOrEmpty(errors);
|
}
catch (Exception ex2) {
this.logger.warn("Failed to resolve " + exception, ex2);
return Mono.empty();
}
});
}
else {
return Mono.justOrEmpty(resolveToMultipleErrors(exception));
}
}
/**
* Override this method to resolve the Exception to multiple GraphQL errors.
* @param exception the exception to resolve
* @return the resolved errors or {@code null} if unresolved
*/
protected @Nullable List<GraphQLError> resolveToMultipleErrors(Throwable exception) {
GraphQLError error = resolveToSingleError(exception);
return (error != null) ? Collections.singletonList(error) : null;
}
/**
* Override this method to resolve the Exception to a single GraphQL error.
* @param exception the exception to resolve
* @return the resolved error or {@code null} if unresolved
*/
protected @Nullable GraphQLError resolveToSingleError(Throwable exception) {
return null;
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\SubscriptionExceptionResolverAdapter.java
| 1
|
请完成以下Java代码
|
private Set<HUToReturn> getHUsToReturn()
{
Check.assumeNotEmpty(_husToReturn, "husToReturn is not empty");
return _husToReturn;
}
public List<I_M_HU> getHUsReturned()
{
return _husToReturn.stream()
.map(HUToReturn::getHu)
.collect(Collectors.toList());
}
public void addHUToReturn(@NonNull final I_M_HU hu, @NonNull final InOutLineId originalShipmentLineId)
{
|
_husToReturn.add(new HUToReturn(hu, originalShipmentLineId));
}
@Value
private static class HUToReturn
{
@NonNull I_M_HU hu;
@NonNull InOutLineId originalShipmentLineId;
private int getM_HU_ID()
{
return hu.getM_HU_ID();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\customer\CustomerReturnsInOutProducer.java
| 1
|
请完成以下Java代码
|
public class LwM2mRPkCredentials {
private PublicKey serverPublicKey;
private PrivateKey serverPrivateKey;
private X509Certificate certificate;
private List<Certificate> trustStore;
/**
* create All key RPK credentials
* @param publX
* @param publY
* @param privS
*/
public LwM2mRPkCredentials(String publX, String publY, String privS) {
generatePublicKeyRPK(publX, publY, privS);
}
private void generatePublicKeyRPK(String publX, String publY, String privS) {
try {
/*Get Elliptic Curve Parameter spec for secp256r1 */
AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
algoParameters.init(new ECGenParameterSpec("secp256r1"));
ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);
if (publX != null && !publX.isEmpty() && publY != null && !publY.isEmpty()) {
// Get point values
byte[] publicX = Hex.decodeHex(publX.toCharArray());
byte[] publicY = Hex.decodeHex(publY.toCharArray());
/* Create key specs */
KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)),
parameterSpec);
|
/* Get keys */
this.serverPublicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec);
}
if (privS != null && !privS.isEmpty()) {
/* Get point values */
byte[] privateS = Hex.decodeHex(privS.toCharArray());
/* Create key specs */
KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec);
/* Get keys */
this.serverPrivateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec);
}
} catch (GeneralSecurityException | IllegalArgumentException e) {
log.error("[{}] Failed generate Server KeyRPK", e.getMessage());
throw new RuntimeException(e);
}
}
}
|
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\secure\LwM2mRPkCredentials.java
| 1
|
请完成以下Java代码
|
public static double withDecimalFormatPattern(double value, int places) {
DecimalFormat df2 = new DecimalFormat("#,###,###,##0.00");
DecimalFormat df3 = new DecimalFormat("#,###,###,##0.000");
if (places == 2)
return Double.valueOf(df2.format(value));
else if (places == 3)
return Double.valueOf(df3.format(value));
else
throw new IllegalArgumentException();
}
public static double withDecimalFormatLocal(double value) {
DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.getDefault());
return Double.valueOf(df.format(value));
}
public static String withStringFormat(double value, int places) {
return String.format("%." + places + "f", value);
}
public static String byPaddingZeros(int value, int paddingLength) {
return String.format("%0" + paddingLength + "d", value);
}
public static double withTwoDecimalPlaces(double value) {
DecimalFormat df = new DecimalFormat("#.00");
return Double.valueOf(df.format(value));
}
public static String withLargeIntegers(double value) {
DecimalFormat df = new DecimalFormat("###,###,###");
return df.format(value);
}
public static String forPercentages(double value, Locale localisation) {
NumberFormat nf = NumberFormat.getPercentInstance(localisation);
return nf.format(value);
}
public static String currencyWithChosenLocalisation(double value, Locale localisation) {
|
NumberFormat nf = NumberFormat.getCurrencyInstance(localisation);
return nf.format(value);
}
public static String currencyWithDefaultLocalisation(double value) {
NumberFormat nf = NumberFormat.getCurrencyInstance();
return nf.format(value);
}
public static String formatScientificNotation(double value, Locale localisation) {
return String.format(localisation, "%.3E", value);
}
public static String formatScientificNotationWithMinChars(double value, Locale localisation) {
return String.format(localisation, "%12.4E", value);
}
}
|
repos\tutorials-master\core-java-modules\core-java-numbers\src\main\java\com\baeldung\formatNumber\FormatNumber.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ValidateLocatorInfo getValidateSourceLocatorInfo(final @NonNull PPOrderId ppOrderId)
{
final ImmutableList<LocatorInfo> sourceLocatorList = getSourceLocatorIds(ppOrderId)
.stream()
.map(locatorId -> {
final String caption = getLocatorName(locatorId);
return LocatorInfo.builder()
.id(locatorId)
.caption(caption)
.qrCode(LocatorQRCode.builder()
.locatorId(locatorId)
.caption(caption)
.build())
.build();
})
.collect(ImmutableList.toImmutableList());
|
return ValidateLocatorInfo.ofSourceLocatorList(sourceLocatorList);
}
@NonNull
public Optional<UomId> getCatchWeightUOMId(@NonNull final ProductId productId)
{
return productBL.getCatchUOMId(productId);
}
@NonNull
private ImmutableSet<LocatorId> getSourceLocatorIds(@NonNull final PPOrderId ppOrderId)
{
final ImmutableSet<HuId> huIds = sourceHUService.getSourceHUIds(ppOrderId);
return handlingUnitsBL.getLocatorIds(huIds);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\ManufacturingJobLoaderAndSaverSupportingServices.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.