instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public TypeSpec getComparatorAnonymousClass() {
return TypeSpec
.anonymousClassBuilder("")
.addSuperinterface(ParameterizedTypeName.get(Comparator.class, String.class))
.addMethod(MethodSpec
.methodBuilder("compare")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.addParameter(String.class, "a")
.addParameter(String.class, "b")
.returns(int.class)
.addStatement("return a.length() - b.length()")
.build())
.build();
}
public void generateGenderEnum() throws IOException {
writeToOutputFile(getPersonPackageName(), getGenderEnum());
}
public void generatePersonInterface() throws IOException {
writeToOutputFile(getPersonPackageName(), getPersonInterface()); | }
public void generateStudentClass() throws IOException {
writeToOutputFile(getPersonPackageName(), getStudentClass());
}
private void writeToOutputFile(String packageName, TypeSpec typeSpec) throws IOException {
JavaFile javaFile = JavaFile
.builder(packageName, typeSpec)
.skipJavaLangImports(true)
.indent(FOUR_WHITESPACES)
.build();
javaFile.writeTo(outputFile);
}
} | repos\tutorials-master\libraries-2\src\main\java\com\baeldung\javapoet\PersonGenerator.java | 1 |
请完成以下Java代码 | public RequiredRule getRequiredRule() {
return requiredRule;
}
public void setRequiredRule(RequiredRule requiredRule) {
this.requiredRule = requiredRule;
}
public RepetitionRule getRepetitionRule() {
return repetitionRule;
}
public void setRepetitionRule(RepetitionRule repetitionRule) {
this.repetitionRule = repetitionRule;
}
public ManualActivationRule getManualActivationRule() {
return manualActivationRule;
}
public void setManualActivationRule(ManualActivationRule manualActivationRule) {
this.manualActivationRule = manualActivationRule;
}
public CompletionNeutralRule getCompletionNeutralRule() {
return completionNeutralRule;
}
public void setCompletionNeutralRule(CompletionNeutralRule completionNeutralRule) {
this.completionNeutralRule = completionNeutralRule;
} | public ParentCompletionRule getParentCompletionRule() {
return parentCompletionRule;
}
public void setParentCompletionRule(ParentCompletionRule parentCompletionRule) {
this.parentCompletionRule = parentCompletionRule;
}
public ReactivationRule getReactivationRule() {
return reactivationRule;
}
public void setReactivationRule(ReactivationRule reactivationRule) {
this.reactivationRule = reactivationRule;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\PlanItemControl.java | 1 |
请完成以下Java代码 | public Visit loadPetWithVisit(@PathVariable("ownerId") int ownerId, @PathVariable("petId") int petId,
Map<String, Object> model) {
Optional<Owner> optionalOwner = owners.findById(ownerId);
Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException(
"Owner not found with id: " + ownerId + ". Please ensure the ID is correct "));
Pet pet = owner.getPet(petId);
if (pet == null) {
throw new IllegalArgumentException(
"Pet with id " + petId + " not found for owner with id " + ownerId + ".");
}
model.put("pet", pet);
model.put("owner", owner);
Visit visit = new Visit();
pet.addVisit(visit);
return visit;
}
// Spring MVC calls method loadPetWithVisit(...) before initNewVisitForm is
// called
@GetMapping("/owners/{ownerId}/pets/{petId}/visits/new")
public String initNewVisitForm() { | return "pets/createOrUpdateVisitForm";
}
// Spring MVC calls method loadPetWithVisit(...) before processNewVisitForm is
// called
@PostMapping("/owners/{ownerId}/pets/{petId}/visits/new")
public String processNewVisitForm(@ModelAttribute Owner owner, @PathVariable int petId, @Valid Visit visit,
BindingResult result, RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
return "pets/createOrUpdateVisitForm";
}
owner.addVisit(petId, visit);
this.owners.save(owner);
redirectAttributes.addFlashAttribute("message", "Your visit has been booked");
return "redirect:/owners/{ownerId}";
}
} | repos\spring-petclinic-main\src\main\java\org\springframework\samples\petclinic\owner\VisitController.java | 1 |
请完成以下Java代码 | private void jbInit() throws Exception
{
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
bShowAll.setText(Msg.getMsg(Env.getCtx(), "All"));
bShowAll.addActionListener(this);
bShowAll.setMargin(s_margin);
bShowYear.setText(Msg.getMsg(Env.getCtx(), "Year"));
bShowYear.addActionListener(this);
bShowYear.setMargin(s_margin);
bShowMonth.setText(Msg.getMsg(Env.getCtx(), "Month"));
bShowMonth.addActionListener(this);
bShowMonth.setMargin(s_margin);
bShowWeek.setText(Msg.getMsg(Env.getCtx(), "Week"));
bShowWeek.addActionListener(this);
bShowWeek.setMargin(s_margin);
bShowDay.setText(Msg.getMsg(Env.getCtx(), "Day"));
bShowDay.addActionListener(this);
bShowDay.setMargin(s_margin);
bShowDay.setDefaultCapable(true);
//
mainPanel.add(bShowDay, null);
mainPanel.add(bShowWeek, null);
mainPanel.add(bShowMonth, null);
mainPanel.add(bShowYear, null);
mainPanel.add(bShowAll, null);
//
mainPanel.setToolTipText(Msg.getMsg(Env.getCtx(), "VOnlyCurrentDays", false));
this.getContentPane().add(mainPanel, BorderLayout.CENTER);
this.getRootPane().setDefaultButton(bShowDay);
//
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
m_isCancel = true;
}
});
} // jbInit
/**
* Action Listener
* @param e evant
*/
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == bShowDay)
m_days = 1; | else if (e.getSource() == bShowWeek)
m_days = 7;
else if (e.getSource() == bShowMonth)
m_days = 31;
else if (e.getSource() == bShowYear)
m_days = 365;
else
m_days = 0; // all
dispose();
} // actionPerformed
/**
* Get selected number of days
* @return days or -1 for all
*/
public int getCurrentDays()
{
return m_days;
} // getCurrentDays
/**
* @return true if user has canceled this form
*/
public boolean isCancel() {
return m_isCancel;
}
} // VOnlyCurrentDays | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\VOnlyCurrentDays.java | 1 |
请完成以下Java代码 | public class C_Invoice_Candidate_RevokeApprovalForInvoicing extends C_Invoice_Candidate_ProcessHelper
{
@Override
protected boolean isApproveForInvoicing()
{
return false;
}
/**
* Implementation detail: during `checkPreconditionsApplicable` `getProcessInfo` throws exception because it is not configured for the Process, so we ignore it.
*/
@Override
protected IQuery<I_C_Invoice_Candidate> retrieveQuery(final boolean includeProcessInfoFilters)
{
final IQueryBuilder<I_C_Invoice_Candidate> queryBuilder = Services.get(IQueryBL.class).createQueryBuilder(I_C_Invoice_Candidate.class);
if (includeProcessInfoFilters)
{
queryBuilder.filter(getProcessInfo().getQueryFilterOrElseFalse());
}
queryBuilder.addOnlyActiveRecordsFilter() // not processed
.addNotNull(I_C_Invoice_Candidate.COLUMNNAME_C_Currency_ID)
.addNotEqualsFilter(I_C_Invoice_Candidate.COLUMN_ApprovalForInvoicing, false) // not already rejected
.addFilter(getSelectionFilter())
; | // Only selected rows
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (!selectedRowIds.isAll())
{
final Set<Integer> invoiceCandidateIds = selectedRowIds.toIntSet();
if (invoiceCandidateIds.isEmpty())
{
// shall not happen
throw new AdempiereException("@NoSelection@");
}
queryBuilder.addInArrayFilter(I_C_Invoice_Candidate.COLUMN_C_Invoice_Candidate_ID, invoiceCandidateIds);
}
return queryBuilder.create();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoicecandidate\process\C_Invoice_Candidate_RevokeApprovalForInvoicing.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void regionGetEntryPointcut() { }
@Pointcut("execution(* org.apache.geode.cache.Region.selectValue(..))")
private void regionSelectValuePointcut() {
}
@Pointcut("execution(* org.apache.geode.cache.Region.values())")
private void regionValuesPointcut() { }
@Around("regionPointcut() && regionGetPointcut()")
public Object regionGetAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
return PdxInstanceWrapper.from(joinPoint.proceed());
}
@Around("regionPointcut() && regionGetAllPointcut()")
public Object regionGetAllAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
return asMap(joinPoint.proceed()).entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, mapEntry -> PdxInstanceWrapper.from(mapEntry.getValue())));
}
@Around("regionPointcut() && regionGetEntryPointcut()")
public Object regionGetEntryAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
return RegionEntryWrapper.from(joinPoint.proceed());
}
@Around("regionPointcut() && regionSelectValuePointcut()")
public Object regionSelectValueAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
return PdxInstanceWrapper.from(joinPoint.proceed());
}
@Around("regionPointcut() && regionValuesPointcut()")
public Object regionValuesAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
return asCollection(joinPoint.proceed()).stream()
.map(PdxInstanceWrapper::from)
.collect(Collectors.toList());
}
public static class RegionEntryWrapper<K, V> implements Region.Entry<K, V> {
@SuppressWarnings("unchecked")
public static <T, K, V> T from(T value) {
return value instanceof Region.Entry
? (T) new RegionEntryWrapper<>((Region.Entry<K, V>) value)
: value;
}
private final Region.Entry<K, V> delegate;
protected RegionEntryWrapper(@NonNull Region.Entry<K, V> regionEntry) {
Assert.notNull(regionEntry, "Region.Entry must not be null");
this.delegate = regionEntry;
}
protected @NonNull Region.Entry<K, V> getDelegate() {
return this.delegate;
}
@Override
public boolean isDestroyed() {
return getDelegate().isDestroyed();
}
@Override
public boolean isLocal() { | return getDelegate().isLocal();
}
@Override
public K getKey() {
return getDelegate().getKey();
}
@Override
public Region<K, V> getRegion() {
return getDelegate().getRegion();
}
@Override
public CacheStatistics getStatistics() {
return getDelegate().getStatistics();
}
@Override
public Object setUserAttribute(Object userAttribute) {
return getDelegate().setUserAttribute(userAttribute);
}
@Override
public Object getUserAttribute() {
return getDelegate().getUserAttribute();
}
@Override
public V setValue(V value) {
return getDelegate().setValue(value);
}
@Override
@SuppressWarnings("unchecked")
public V getValue() {
return (V) PdxInstanceWrapper.from(getDelegate().getValue());
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\support\PdxInstanceWrapperRegionAspect.java | 2 |
请完成以下Java代码 | public String getTransformation() {
return transformation;
}
public void setTransformation(String transformation) {
this.transformation = transformation;
}
public List<Assignment> getAssignments() {
return assignments;
}
public void setAssignments(List<Assignment> assignments) {
this.assignments = assignments;
}
public DataAssociation clone() {
DataAssociation clone = new DataAssociation();
clone.setValues(this);
return clone; | }
public void setValues(DataAssociation otherAssociation) {
setSourceRef(otherAssociation.getSourceRef());
setTargetRef(otherAssociation.getTargetRef());
setTransformation(otherAssociation.getTransformation());
assignments = new ArrayList<Assignment>();
if (otherAssociation.getAssignments() != null && !otherAssociation.getAssignments().isEmpty()) {
for (Assignment assignment : otherAssociation.getAssignments()) {
assignments.add(assignment.clone());
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\DataAssociation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JsonNode esSearch(JSONObject search, String endpoint, RestClient restClient) {
JsonNode responseNode = null;
try {
logger.info("查询es语句为 {}, endpoint 为:{}", search, endpoint.toString());
Request request = new Request(HttpGet.METHOD_NAME, endpoint);
if (search != null) {
String data = search.toString();
request.setJsonEntity(data);
}
try {
restClient.performRequest(request);
} catch (IOException e) {
logger.error("查询es语句报错为 {}", e.getMessage());
}
Response response = restClient.performRequest(request);
String responseStr = EntityUtils.toString(response.getEntity());
logger.info("查询结果为", responseStr);
responseNode = mapper.readTree(responseStr);
} catch (IOException e) {
logger.error("查询失败", e);
}
return responseNode;
}
/**
* 设置页面
*
* @param pageIndex
* @param pageSize
* @param search
* @return
*/
public static JSONObject setPage(Integer pageIndex, Integer pageSize, JSONObject search) {
search.put("from", (pageIndex - 1) * pageSize);
search.put("size", pageSize); | return search;
}
/**
* 获取json 对象
*
* @param key
* @param value
* @return
*/
public static JSONObject getJSONObject(String key, Object value) {
JSONObject term = new JSONObject();
term.put(key, value);
return term;
}
} | repos\springBoot-master\springboot-elasticsearch\src\main\java\cn\abel\service\UserService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Result<String> delete(HttpServletRequest request,@RequestParam(name = "id", required = true) String id) {
//update-begin---author:chenrui ---date:20250606 for:[issues/8337]关于ai工作列表的数据权限问题 #8337------------
//如果是saas隔离的情况下,判断当前租户id是否是当前租户下的
if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
AiragApp app = airagAppService.getById(id);
//获取当前租户
String currentTenantId = TokenUtils.getTenantIdByRequest(request);
if (null == app || !app.getTenantId().equals(currentTenantId)) {
return Result.error("删除AI应用失败,不能删除其他租户的AI应用!");
}
}
//update-end---author:chenrui ---date:20250606 for:[issues/8337]关于ai工作列表的数据权限问题 #8337------------
airagAppService.removeById(id);
return Result.OK("删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@IgnoreAuth
@GetMapping(value = "/queryById")
public Result<AiragApp> queryById(@RequestParam(name = "id", required = true) String id) {
AiragApp airagApp = airagAppService.getById(id);
if (airagApp == null) {
return Result.error("未找到对应数据");
}
return Result.OK(airagApp);
}
/**
* 调试应用
*
* @param appDebugParams | * @return
* @author chenrui
* @date 2025/2/28 10:49
*/
@PostMapping(value = "/debug")
public SseEmitter debugApp(@RequestBody AppDebugParams appDebugParams) {
return airagChatService.debugApp(appDebugParams);
}
/**
* 根据需求生成提示词
*
* @param prompt
* @return
* @author chenrui
* @date 2025/3/12 15:30
*/
@GetMapping(value = "/prompt/generate")
public Result<?> generatePrompt(@RequestParam(name = "prompt", required = true) String prompt) {
return (Result<?>) airagAppService.generatePrompt(prompt,true);
}
/**
* 根据需求生成提示词
*
* @param prompt
* @return
* @author chenrui
* @date 2025/3/12 15:30
*/
@PostMapping(value = "/prompt/generate")
public SseEmitter generatePromptSse(@RequestParam(name = "prompt", required = true) String prompt) {
return (SseEmitter) airagAppService.generatePrompt(prompt,false);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\app\controller\AiragAppController.java | 2 |
请完成以下Java代码 | public String getDepreciationType ()
{
return (String)get_Value(COLUMNNAME_DepreciationType);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
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 Text.
@param Text Text */
public void setText (String Text)
{
set_Value (COLUMNNAME_Text, Text);
}
/** Get Text.
@return Text */
public String getText ()
{
return (String)get_Value(COLUMNNAME_Text);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation.java | 1 |
请完成以下Java代码 | public boolean isPersistent() {
return this.persistent;
}
public void setPersistent(boolean persistent) {
this.persistent = persistent;
}
/**
* Return the directory used to store session data.
* @return the session data store directory
*/
public @Nullable File getStoreDir() {
return this.storeDir;
}
public void setStoreDir(@Nullable File storeDir) {
this.sessionStoreDirectory.setDirectory(storeDir);
this.storeDir = storeDir;
}
public Cookie getCookie() {
return this.cookie;
}
public SessionStoreDirectory getSessionStoreDirectory() {
return this.sessionStoreDirectory;
}
/**
* Available session tracking modes (mirrors
* {@link jakarta.servlet.SessionTrackingMode}). | */
public enum SessionTrackingMode {
/**
* Send a cookie in response to the client's first request.
*/
COOKIE,
/**
* Rewrite the URL to append a session ID.
*/
URL,
/**
* Use SSL build-in mechanism to track the session.
*/
SSL
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\Session.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getM_DemandDetail_ID()));
}
public I_M_DemandLine getM_DemandLine() throws RuntimeException
{
return (I_M_DemandLine)MTable.get(getCtx(), I_M_DemandLine.Table_Name)
.getPO(getM_DemandLine_ID(), get_TrxName()); }
/** Set Demand Line.
@param M_DemandLine_ID
Material Demand Line
*/
public void setM_DemandLine_ID (int M_DemandLine_ID)
{
if (M_DemandLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DemandLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DemandLine_ID, Integer.valueOf(M_DemandLine_ID));
}
/** Get Demand Line.
@return Material Demand Line
*/
public int getM_DemandLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DemandLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_ForecastLine getM_ForecastLine() throws RuntimeException
{
return (I_M_ForecastLine)MTable.get(getCtx(), I_M_ForecastLine.Table_Name)
.getPO(getM_ForecastLine_ID(), get_TrxName()); }
/** Set Forecast Line.
@param M_ForecastLine_ID
Forecast Line
*/
public void setM_ForecastLine_ID (int M_ForecastLine_ID)
{
if (M_ForecastLine_ID < 1)
set_Value (COLUMNNAME_M_ForecastLine_ID, null); | else
set_Value (COLUMNNAME_M_ForecastLine_ID, Integer.valueOf(M_ForecastLine_ID));
}
/** Get Forecast Line.
@return Forecast Line
*/
public int getM_ForecastLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ForecastLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_RequisitionLine getM_RequisitionLine() throws RuntimeException
{
return (I_M_RequisitionLine)MTable.get(getCtx(), I_M_RequisitionLine.Table_Name)
.getPO(getM_RequisitionLine_ID(), get_TrxName()); }
/** Set Requisition Line.
@param M_RequisitionLine_ID
Material Requisition Line
*/
public void setM_RequisitionLine_ID (int M_RequisitionLine_ID)
{
if (M_RequisitionLine_ID < 1)
set_Value (COLUMNNAME_M_RequisitionLine_ID, null);
else
set_Value (COLUMNNAME_M_RequisitionLine_ID, Integer.valueOf(M_RequisitionLine_ID));
}
/** Get Requisition Line.
@return Material Requisition Line
*/
public int getM_RequisitionLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_RequisitionLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DemandDetail.java | 1 |
请完成以下Java代码 | public PaymentTerm getById(@NonNull final PaymentTermId paymentTermId)
{
return paymentTermRepository.getById(paymentTermId);
}
@Nullable
public PaymentTermId getOrCreateDerivedPaymentTerm(@Nullable final PaymentTermId basePaymentTermId, @Nullable final Percent discount)
{
return paymentTermRepository.getOrCreateDerivedPaymentTerm(basePaymentTermId, discount);
}
@NonNull
public Percent getPaymentTermDiscount(PaymentTermId paymentTermId)
{
return paymentTermRepository.getById(paymentTermId).getDiscount();
}
public void validateNow(@NonNull final PaymentTermId paymentTermId)
{
validateNow(ImmutableSet.of(paymentTermId));
} | public void validateBeforeCommit(final PaymentTermId paymentTermId)
{
trxManager.accumulateAndProcessBeforeCommit(
"PaymentTermService.validateBeforeCommit",
Collections.singleton(paymentTermId),
this::validateNow
);
}
private void validateNow(@NonNull final Collection<PaymentTermId> paymentTermIds)
{
paymentTermRepository.newLoaderAndSaver()
.syncStateToDatabase(ImmutableSet.copyOf(paymentTermIds));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\paymentterm\PaymentTermService.java | 1 |
请完成以下Java代码 | public void setName(String name) {
this.name = name;
}
public Double getRating() {
return rating;
}
public void setRating(Double rating) {
this.rating = rating;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getLatitude() {
return lattitude;
}
public void setLatitude(double latitude) {
this.lattitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude; | }
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Hotel hotel = (Hotel) o;
if (Double.compare(hotel.lattitude, lattitude) != 0) return false;
if (Double.compare(hotel.longitude, longitude) != 0) return false;
if (deleted != hotel.deleted) return false;
if (!Objects.equals(id, hotel.id)) return false;
if (!Objects.equals(name, hotel.name)) return false;
if (!Objects.equals(rating, hotel.rating)) return false;
if (!Objects.equals(city, hotel.city)) return false;
return Objects.equals(address, hotel.address);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-caching\src\main\java\com\baeldung\caching\ttl\model\Hotel.java | 1 |
请完成以下Java代码 | private void put(OtaPackageType type, LwM2MClientOtaInfo<?, ?, ?> info) {
try (var connection = connectionFactory.getConnection()) {
connection.set((OTA_EP + type + info.getEndpoint()).getBytes(), JacksonUtil.toString(info).getBytes());
}
}
@Override
public LwM2MClientFwOtaInfo getFw(String endpoint) {
return getLwM2MClientOtaInfo(OtaPackageType.FIRMWARE, endpoint, LwM2MClientFwOtaInfo.class);
}
@Override
public void putFw(LwM2MClientFwOtaInfo info) {
put(OtaPackageType.FIRMWARE, info);
}
@Override
public LwM2MClientSwOtaInfo getSw(String endpoint) { | return getLwM2MClientOtaInfo(OtaPackageType.SOFTWARE, endpoint, LwM2MClientSwOtaInfo.class);
}
@Override
public void putSw(LwM2MClientSwOtaInfo info) {
put(OtaPackageType.SOFTWARE, info);
}
private <T extends LwM2MClientOtaInfo<?, ?, ?>> T getLwM2MClientOtaInfo(OtaPackageType type, String endpoint, Class<T> clazz) {
try (var connection = connectionFactory.getConnection()) {
byte[] data = connection.get((OTA_EP + type + endpoint).getBytes());
return JacksonUtil.fromBytes(data, clazz);
}
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbLwM2mRedisClientOtaInfoStore.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class UpdateShipmentScheduleRequest
{
@NonNull
ShipmentScheduleId shipmentScheduleId;
@Nullable
ZonedDateTime deliveryDate;
@Nullable
BigDecimal qtyToDeliverInStockingUOM;
@Nullable
LocationBasicInfo bPartnerLocation;
@Nullable
String bPartnerCode;
@Nullable
List<CreateAttributeInstanceReq> attributes;
@Nullable
DeliveryRule deliveryRule;
@Nullable
ShipperId shipperId;
@Builder
public UpdateShipmentScheduleRequest(
@NonNull final ShipmentScheduleId shipmentScheduleId,
@Nullable final ZonedDateTime deliveryDate,
@Nullable final BigDecimal qtyToDeliverInStockingUOM,
@Nullable final LocationBasicInfo bPartnerLocation,
@Nullable final String bPartnerCode,
@Nullable final DeliveryRule deliveryRule,
@Nullable final List<CreateAttributeInstanceReq> attributes,
@Nullable final ShipperId shipperId)
{
if (Check.isNotBlank(bPartnerCode) && bPartnerLocation == null) | {
throw new AdempiereException("Invalid request! The bPartenr cannot be changed without changing the location!");
}
if (deliveryDate == null
&& qtyToDeliverInStockingUOM == null
&& bPartnerLocation == null
&& Check.isBlank(bPartnerCode)
&& Check.isEmpty(attributes)
&& deliveryRule == null
&& shipperId == null)
{
throw new AdempiereException("Empty request");
}
this.shipmentScheduleId = shipmentScheduleId;
this.deliveryDate = deliveryDate;
this.qtyToDeliverInStockingUOM = qtyToDeliverInStockingUOM;
this.bPartnerLocation = bPartnerLocation;
this.bPartnerCode = bPartnerCode;
this.attributes = attributes;
this.deliveryRule = deliveryRule;
this.shipperId = shipperId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\shipping\UpdateShipmentScheduleRequest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class PrepareApiClientsProcessor implements Processor
{
@Override
public void process(@NonNull final Exchange exchange) throws Exception
{
final var request = exchange.getIn().getBody(JsonExternalSystemRequest.class);
final var basePath = request.getParameters().get(ExternalSystemConstants.PARAM_BASE_PATH);
final var apiKey = request.getParameters().get(ExternalSystemConstants.PARAM_API_KEY);
final var tenant = request.getParameters().get(ExternalSystemConstants.PARAM_TENANT);
final String rootBPartnerId = request.getParameters().get(ExternalSystemConstants.PARAM_ROOT_BPARTNER_ID_FOR_USERS);
final JsonMetasfreshId rootBPartnerMFId = Check.isNotBlank(rootBPartnerId) ? JsonMetasfreshId.of(Integer.parseInt(rootBPartnerId)) : null;
final var apiClient = new ApiClient().setBasePath(basePath);
final AlbertaConnectionDetails albertaConnectionDetails = AlbertaConnectionDetails.builder()
.apiKey(apiKey)
.basePath(basePath)
.tenant(tenant)
.build();
final String updatedAfter = CoalesceUtil.coalesce(
request.getParameters().get(ExternalSystemConstants.PARAM_UPDATED_AFTER_OVERRIDE),
request.getParameters().get(ExternalSystemConstants.PARAM_UPDATED_AFTER),
Instant.ofEpochMilli(0).toString()); | final GetPatientsRouteContext context = GetPatientsRouteContext.builder()
.doctorApi(new DoctorApi(apiClient))
.hospitalApi(new HospitalApi(apiClient))
.nursingHomeApi(new NursingHomeApi(apiClient))
.nursingServiceApi(new NursingServiceApi(apiClient))
.patientApi(new PatientApi(apiClient))
.payerApi(new PayerApi(apiClient))
.pharmacyApi(new PharmacyApi(apiClient))
.userApi(new UserApi(apiClient))
.albertaConnectionDetails(albertaConnectionDetails)
.rootBPartnerIdForUsers(rootBPartnerMFId)
.request(request)
.updatedAfterValue(Instant.parse(updatedAfter))
.build();
exchange.setProperty(GetPatientsRouteConstants.ROUTE_PROPERTY_GET_PATIENTS_CONTEXT, context);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\patient\processor\PrepareApiClientsProcessor.java | 2 |
请完成以下Java代码 | private <T extends I_M_ShipmentSchedule_QtyPicked> ImmutableListMultimap<ShipmentScheduleId, T> retrieveRecordsByScheduleIds(
@NonNull final ShipmentScheduleAndJobScheduleIdSet scheduleIds,
final boolean onShipmentLine,
@NonNull final Class<T> type)
{
if (scheduleIds.isEmpty())
{
return ImmutableListMultimap.of();
}
return stream(
type,
ShipmentScheduleAllocQuery.builder()
.scheduleIds(scheduleIds)
.alreadyShipped(onShipmentLine)
.build()
)
.collect(ImmutableListMultimap.toImmutableListMultimap(
record -> ShipmentScheduleId.ofRepoId(record.getM_ShipmentSchedule_ID()),
record -> record
));
}
@NonNull
public <T extends I_M_ShipmentSchedule_QtyPicked> List<T> retrievePickedOnTheFlyAndNotDelivered(
@NonNull final ShipmentScheduleId shipmentScheduleId,
@NonNull final Class<T> modelClass)
{
return queryBL
.createQueryBuilder(I_M_ShipmentSchedule_QtyPicked.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_ShipmentSchedule_QtyPicked.COLUMN_M_ShipmentSchedule_ID, shipmentScheduleId)
.addEqualsFilter(I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_Processed, false) | .addEqualsFilter(I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_IsAnonymousHuPickedOnTheFly, true)
.create()
.list(modelClass);
}
@Override
@NonNull
public Set<OrderId> retrieveOrderIds(@NonNull final org.compiere.model.I_M_InOut inOut)
{
return queryBL.createQueryBuilder(I_M_InOutLine.class, inOut)
.addEqualsFilter(I_M_InOutLine.COLUMN_M_InOut_ID, inOut.getM_InOut_ID())
.andCollectChildren(I_M_ShipmentSchedule_QtyPicked.COLUMN_M_InOutLine_ID, I_M_ShipmentSchedule_QtyPicked.class)
.andCollect(I_M_ShipmentSchedule_QtyPicked.COLUMN_M_ShipmentSchedule_ID)
.andCollect(I_M_ShipmentSchedule.COLUMN_C_Order_ID)
.create()
.listIds()
.stream()
.map(OrderId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ShipmentScheduleAllocDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
} | public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return "PermissionEntity{" +
"id='" + id + '\'' +
", permission='" + permission + '\'' +
", desc='" + desc + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\PermissionEntity.java | 2 |
请完成以下Java代码 | public class HUScannedAttributeHandler implements IAttributeValueCallout, IAttributeValueHandler, IAttributeValueGeneratorAdapter
{
@Override
public void onValueChanged(final IAttributeValueContext attributeValueContext, final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueOld, final Object valueNew)
{
// nothing
}
@Override
public Object generateSeedValue(final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueInitialDefault)
{
return SecurPharmAttributesStatus.UNKNOW.getCode();
}
@Override
public boolean isReadonlyUI(final IAttributeValueContext ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
return true;
}
@Override
public boolean isAlwaysEditableUI(final IAttributeValueContext ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{ | return false;
}
@Override
public boolean isDisplayedUI(final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
return Adempiere.getBean(SecurPharmService.class).hasConfig();
}
@Override
public String getAttributeValueType()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_List;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\attribute\HUScannedAttributeHandler.java | 1 |
请完成以下Java代码 | public PickingJobStep reduceWithUnpickEvent(
@NonNull PickingJobStepPickFromKey key,
@NonNull PickingJobStepUnpickInfo unpicked)
{
return withChangedPickFroms(pickFroms -> pickFroms.reduceWithUnpickEvent(key, unpicked));
}
private PickingJobStep withChangedPickFroms(@NonNull final UnaryOperator<PickingJobStepPickFromMap> mapper)
{
final PickingJobStepPickFromMap newPickFroms = mapper.apply(this.pickFroms);
return !Objects.equals(this.pickFroms, newPickFroms)
? toBuilder().pickFroms(newPickFroms).build()
: this;
}
public ImmutableSet<PickingJobStepPickFromKey> getPickFromKeys()
{
return pickFroms.getKeys();
}
public PickingJobStepPickFrom getPickFrom(@NonNull final PickingJobStepPickFromKey key)
{
return pickFroms.getPickFrom(key);
}
public PickingJobStepPickFrom getPickFromByHUQRCode(@NonNull final HUQRCode qrCode) | {
return pickFroms.getPickFromByHUQRCode(qrCode);
}
@NonNull
public List<HuId> getPickedHUIds()
{
return pickFroms.getPickedHUIds();
}
@NonNull
public Optional<PickingJobStepPickedToHU> getLastPickedHU()
{
return pickFroms.getLastPickedHU();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStep.java | 1 |
请完成以下Java代码 | private void setFlatrateConditionsIdToCompensationGroup(final int flatrateConditionsId,
final GroupId groupId,
final GroupTemplateId groupTemplateId,
final int excludeOrderLineId)
{
groupChangesHandler.retrieveGroupOrderLinesQuery(groupId)
.addNotEqualsFilter(I_C_OrderLine.COLUMN_C_OrderLine_ID, excludeOrderLineId)
.addNotEqualsFilter(I_C_OrderLine.COLUMNNAME_C_Flatrate_Conditions_ID, flatrateConditionsId > 0 ? flatrateConditionsId : null)
.create()
.list(I_C_OrderLine.class)
.stream()
.filter(ol -> !groupChangesHandler.isProductExcludedFromFlatrateConditions(groupTemplateId, ProductId.ofRepoId(ol.getM_Product_ID())))
.forEach(otherOrderLine -> {
otherOrderLine.setC_Flatrate_Conditions_ID(flatrateConditionsId);
DYNATTR_SkipUpdatingGroupFlatrateConditions.setValue(otherOrderLine, Boolean.TRUE);
save(otherOrderLine);
});
}
/**
* Set QtyOrderedInPriceUOM, just to make sure is up2date.
*/
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW,
ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = { de.metas.interfaces.I_C_OrderLine.COLUMNNAME_QtyEntered,
de.metas.interfaces.I_C_OrderLine.COLUMNNAME_Price_UOM_ID, | de.metas.interfaces.I_C_OrderLine.COLUMNNAME_C_UOM_ID,
de.metas.interfaces.I_C_OrderLine.COLUMNNAME_M_Product_ID
})
public void setQtyEnteredInPriceUOM(final I_C_OrderLine orderLine)
{
if (subscriptionBL.isSubscription(orderLine))
{
final org.compiere.model.I_C_Order order = orderLine.getC_Order();
final SOTrx soTrx = SOTrx.ofBoolean(order.isSOTrx());
if (soTrx.isPurchase())
{
return; // leave this job to the adempiere standard callouts
}
subscriptionBL.updateQtysAndPrices(orderLine, soTrx, true);
}
else
{
if(!orderLine.isManualQtyInPriceUOM())
{
final BigDecimal qtyEnteredInPriceUOM = orderLineBL.convertQtyEnteredToPriceUOM(orderLine).toBigDecimal();
orderLine.setQtyEnteredInPriceUOM(qtyEnteredInPriceUOM);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_OrderLine.java | 1 |
请完成以下Java代码 | public LookupValue createAttachment(@NonNull final String emailId, @NonNull final MultipartFile file)
{
//
// Extract the original filename
String originalFilename = file.getOriginalFilename();
if (Check.isEmpty(originalFilename, true))
{
originalFilename = file.getName();
}
if (Check.isEmpty(originalFilename, true))
{
throw new AdempiereException("Filename not provided");
}
byte[] fileContent;
try
{
fileContent = file.getBytes();
}
catch (IOException e)
{
throw new AdempiereException("Failed fetching attachment content")
.setParameter("filename", originalFilename);
}
return createAttachment(emailId, originalFilename, new ByteArrayResource(fileContent));
}
public LookupValue createAttachment(
@NonNull final String emailId,
@NonNull final String filename,
@NonNull Resource fileContent)
{
final String attachmentId = UUID.randomUUID().toString();
//
// Store it to internal attachments storage
final File attachmentFile = getAttachmentFile(emailId, attachmentId);
try(final FileOutputStream fileOutputStream = new FileOutputStream(attachmentFile))
{
FileCopyUtils.copy(fileContent.getInputStream(), fileOutputStream);
}
catch (final IOException e) | {
throw new AdempiereException("Failed storing " + filename)
.setParameter("filename", fileContent)
.setParameter("attachmentFile", attachmentFile);
}
//
return StringLookupValue.of(attachmentId, filename);
}
public byte[] getAttachmentAsByteArray(@NonNull final String emailId, @NonNull final LookupValue attachment)
{
final File attachmentFile = getAttachmentFile(emailId, attachment.getIdAsString());
return Util.readBytes(attachmentFile);
}
public void deleteAttachments(@NonNull final String emailId, @NonNull final LookupValuesList attachmentsList)
{
attachmentsList.stream().forEach(attachment -> deleteAttachment(emailId, attachment));
}
public void deleteAttachment(@NonNull final String emailId, @NonNull final LookupValue attachment)
{
final String attachmentId = attachment.getIdAsString();
final File attachmentFile = getAttachmentFile(emailId, attachmentId);
if (!attachmentFile.exists())
{
logger.debug("Attachment file {} is missing. Nothing to delete", attachmentFile);
return;
}
if (!attachmentFile.delete())
{
attachmentFile.deleteOnExit();
logger.warn("Cannot delete attachment file {}. Scheduled to be deleted on exit", attachmentFile);
}
else
{
logger.debug("Deleted attachment file {}", attachmentFile);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\mail\WebuiMailAttachmentsRepository.java | 1 |
请完成以下Java代码 | private HUListAllocationSourceDestination createSourceOrDestForVHU(final I_M_HU vhu)
{
final HUListAllocationSourceDestination huListAllocationSourceDestination = HUListAllocationSourceDestination.of(vhu);
// gh #943: in case of aggregate HUs we *only* want to change the storage. we don't want AggregateHUTrxListener do change the TU-per-CU quantity or do other stuff.
huListAllocationSourceDestination.setStoreCUQtyBeforeProcessing(false);
return huListAllocationSourceDestination;
}
private AbstractAllocationSourceDestination createSourceOrDestForReceiptSchedule(final I_M_ReceiptSchedule receiptSchedule)
{
final IProductStorage storage = huReceiptScheduleBL.createProductStorage(receiptSchedule);
final Object trxReferencedModel = receiptSchedule;
return new GenericAllocationSourceDestination(storage, trxReferencedModel);
}
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 void setTaxIndicator (final @Nullable java.lang.String TaxIndicator)
{
set_Value (COLUMNNAME_TaxIndicator, TaxIndicator);
}
@Override
public java.lang.String getTaxIndicator()
{
return get_ValueAsString(COLUMNNAME_TaxIndicator);
}
@Override
public org.compiere.model.I_C_Country getTo_Country()
{
return get_ValueAsPO(COLUMNNAME_To_Country_ID, org.compiere.model.I_C_Country.class);
}
@Override
public void setTo_Country(final org.compiere.model.I_C_Country To_Country)
{
set_ValueFromPO(COLUMNNAME_To_Country_ID, org.compiere.model.I_C_Country.class, To_Country);
}
@Override
public void setTo_Country_ID (final int To_Country_ID)
{
if (To_Country_ID < 1)
set_Value (COLUMNNAME_To_Country_ID, null);
else
set_Value (COLUMNNAME_To_Country_ID, To_Country_ID);
}
@Override
public int getTo_Country_ID()
{
return get_ValueAsInt(COLUMNNAME_To_Country_ID);
}
@Override
public org.compiere.model.I_C_Region getTo_Region()
{
return get_ValueAsPO(COLUMNNAME_To_Region_ID, org.compiere.model.I_C_Region.class);
}
@Override
public void setTo_Region(final org.compiere.model.I_C_Region To_Region)
{
set_ValueFromPO(COLUMNNAME_To_Region_ID, org.compiere.model.I_C_Region.class, To_Region);
}
@Override
public void setTo_Region_ID (final int To_Region_ID)
{
if (To_Region_ID < 1)
set_Value (COLUMNNAME_To_Region_ID, null);
else
set_Value (COLUMNNAME_To_Region_ID, To_Region_ID);
}
@Override
public int getTo_Region_ID()
{
return get_ValueAsInt(COLUMNNAME_To_Region_ID);
}
/**
* TypeOfDestCountry AD_Reference_ID=541323
* Reference name: TypeDestCountry
*/
public static final int TYPEOFDESTCOUNTRY_AD_Reference_ID=541323;
/** Domestic = DOMESTIC */
public static final String TYPEOFDESTCOUNTRY_Domestic = "DOMESTIC";
/** EU-foreign = WITHIN_COUNTRY_AREA */
public static final String TYPEOFDESTCOUNTRY_EU_Foreign = "WITHIN_COUNTRY_AREA";
/** Non-EU country = OUTSIDE_COUNTRY_AREA */
public static final String TYPEOFDESTCOUNTRY_Non_EUCountry = "OUTSIDE_COUNTRY_AREA";
@Override | public void setTypeOfDestCountry (final @Nullable java.lang.String TypeOfDestCountry)
{
set_Value (COLUMNNAME_TypeOfDestCountry, TypeOfDestCountry);
}
@Override
public java.lang.String getTypeOfDestCountry()
{
return get_ValueAsString(COLUMNNAME_TypeOfDestCountry);
}
@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);
}
@Override
public void setValidTo (final java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Tax.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setNoteText(String noteText) {
this.noteText = noteText;
}
public PatientNote patientId(String patientId) {
this.patientId = patientId;
return this;
}
/**
* Id des Patienten in Alberta
* @return patientId
**/
@Schema(example = "a4adecb6-126a-4fa6-8fac-e80165ac4264", description = "Id des Patienten in Alberta")
public String getPatientId() {
return patientId;
}
public void setPatientId(String patientId) {
this.patientId = patientId;
}
public PatientNote archived(Boolean archived) {
this.archived = archived;
return this;
}
/**
* Kennzeichen, ob die Notiz vom Benutzer archiviert wurde
* @return archived
**/
@Schema(example = "false", description = "Kennzeichen, ob die Notiz vom Benutzer archiviert wurde")
public Boolean isArchived() {
return archived;
}
public void setArchived(Boolean archived) {
this.archived = archived;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PatientNote patientNote = (PatientNote) o;
return Objects.equals(this.status, patientNote.status) &&
Objects.equals(this.noteText, patientNote.noteText) &&
Objects.equals(this.patientId, patientNote.patientId) &&
Objects.equals(this.archived, patientNote.archived);
}
@Override
public int hashCode() {
return Objects.hash(status, noteText, patientId, archived);
} | @Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PatientNote {\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" noteText: ").append(toIndentedString(noteText)).append("\n");
sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\PatientNote.java | 2 |
请完成以下Java代码 | public Object getPrincipal() {
return this.clientRegistration.getClientId();
}
@Override
public Object getCredentials() {
return (this.accessToken != null) ? this.accessToken.getTokenValue()
: this.authorizationExchange.getAuthorizationResponse().getCode();
}
/**
* Returns the {@link ClientRegistration client registration}.
* @return the {@link ClientRegistration}
*/
public ClientRegistration getClientRegistration() {
return this.clientRegistration;
}
/**
* Returns the {@link OAuth2AuthorizationExchange authorization exchange}.
* @return the {@link OAuth2AuthorizationExchange}
*/
public OAuth2AuthorizationExchange getAuthorizationExchange() {
return this.authorizationExchange;
}
/** | * Returns the {@link OAuth2AccessToken access token}.
* @return the {@link OAuth2AccessToken}
*/
public OAuth2AccessToken getAccessToken() {
return this.accessToken;
}
/**
* Returns the {@link OAuth2RefreshToken refresh token}.
* @return the {@link OAuth2RefreshToken}
*/
public @Nullable OAuth2RefreshToken getRefreshToken() {
return this.refreshToken;
}
/**
* Returns the additional parameters
* @return the additional parameters
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\authentication\OAuth2AuthorizationCodeAuthenticationToken.java | 1 |
请完成以下Java代码 | public void setAD_Tab_Callout_ID (int AD_Tab_Callout_ID)
{
if (AD_Tab_Callout_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Tab_Callout_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Tab_Callout_ID, Integer.valueOf(AD_Tab_Callout_ID));
}
/** Get AD_Tab_Callout.
@return AD_Tab_Callout */
public int getAD_Tab_Callout_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tab_Callout_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Tab getAD_Tab() throws RuntimeException
{
return (org.compiere.model.I_AD_Tab)MTable.get(getCtx(), org.compiere.model.I_AD_Tab.Table_Name)
.getPO(getAD_Tab_ID(), get_TrxName()); }
/** Set Register.
@param AD_Tab_ID
Register auf einem Fenster
*/
public void setAD_Tab_ID (int AD_Tab_ID)
{
if (AD_Tab_ID < 1)
set_Value (COLUMNNAME_AD_Tab_ID, null);
else
set_Value (COLUMNNAME_AD_Tab_ID, Integer.valueOf(AD_Tab_ID));
}
/** Get Register.
@return Register auf einem Fenster
*/
public int getAD_Tab_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tab_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Classname.
@param Classname
Java Classname
*/
public void setClassname (String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Classname.
@return Java Classname
*/
public String getClassname ()
{
return (String)get_Value(COLUMNNAME_Classname);
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art. | @param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
public void setSeqNo (String SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
public String getSeqNo ()
{
return (String)get_Value(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_AD_Tab_Callout.java | 1 |
请完成以下Java代码 | private void createAndSubmitWorkpackagesByAsyncBatch(@NonNull final IWorkPackageQueue workPackageQueue)
{
for (final Map.Entry<AsyncBatchId, List<Object>> entry : batchId2Models.entrySet())
{
final AsyncBatchId key = entry.getKey();
final List<Object> value = entry.getValue();
createAndSubmitWorkpackage(workPackageQueue, value, AsyncBatchId.toAsyncBatchIdOrNull(key));
}
}
private boolean hasNoModels()
{
return isCreateOneWorkpackagePerAsyncBatch() ? batchId2Models.isEmpty() : models.isEmpty();
}
}
private static final class ModelsScheduler<ModelType> extends WorkpackagesOnCommitSchedulerTemplate<ModelType>
{
private final Class<ModelType> modelType;
private final boolean collectModels;
public ModelsScheduler(final Class<? extends IWorkpackageProcessor> workpackageProcessorClass, final Class<ModelType> modelType, final boolean collectModels)
{
super(workpackageProcessorClass);
this.modelType = modelType;
this.collectModels = collectModels;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("collectModels", collectModels)
.add("workpackageProcessorClass", getWorkpackageProcessorClass())
.add("modelType", modelType)
.toString();
}
@Override
protected Properties extractCtxFromItem(final ModelType item) | {
return InterfaceWrapperHelper.getCtx(item);
}
@Override
protected String extractTrxNameFromItem(final ModelType item)
{
return InterfaceWrapperHelper.getTrxName(item);
}
@Nullable
@Override
protected Object extractModelToEnqueueFromItem(final Collector collector, final ModelType item)
{
return collectModels ? item : null;
}
@Override
protected boolean isEnqueueWorkpackageWhenNoModelsEnqueued()
{
return !collectModels;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\WorkpackagesOnCommitSchedulerTemplate.java | 1 |
请完成以下Java代码 | public int getHR_ListType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value | Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPayMessage() {
return payMessage;
}
public void setPayMessage(String payMessage) {
this.payMessage = payMessage;
} | public String getBankReturnMsg() {
return bankReturnMsg;
}
public void setBankReturnMsg(String bankReturnMsg) {
this.bankReturnMsg = bankReturnMsg;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\ProgramPayResultVo.java | 2 |
请完成以下Java代码 | public List<PurchaseCandidateReminder> toList()
{
return ImmutableList.copyOf(reminders);
}
public boolean add(@NonNull final PurchaseCandidateReminder reminder)
{
return reminders.add(reminder);
}
public void setReminders(final Collection<PurchaseCandidateReminder> reminders)
{
this.reminders.clear();
this.reminders.addAll(reminders);
}
public List<PurchaseCandidateReminder> removeAllUntil(final ZonedDateTime maxNotificationTime)
{
final List<PurchaseCandidateReminder> result = new ArrayList<>();
for (final Iterator<PurchaseCandidateReminder> it = reminders.iterator(); it.hasNext();)
{
final PurchaseCandidateReminder reminder = it.next();
final ZonedDateTime notificationTime = reminder.getNotificationTime();
if (notificationTime.compareTo(maxNotificationTime) <= 0)
{
it.remove();
result.add(reminder);
}
}
return result;
}
public ZonedDateTime getMinNotificationTime()
{
if (reminders.isEmpty())
{
return null;
}
return reminders.first().getNotificationTime();
}
}
@lombok.Value
@lombok.Builder
private static class NextDispatch
{
public static NextDispatch schedule(final Runnable task, final ZonedDateTime date, final TaskScheduler taskScheduler)
{
final ScheduledFuture<?> scheduledFuture = taskScheduler.schedule(task, TimeUtil.asDate(date));
return builder()
.task(task)
.scheduledFuture(scheduledFuture)
.notificationTime(date)
.build();
} | Runnable task;
ScheduledFuture<?> scheduledFuture;
ZonedDateTime notificationTime;
public void cancel()
{
final boolean canceled = scheduledFuture.cancel(false);
logger.trace("Cancel requested for {} (result was: {})", this, canceled);
}
public NextDispatch rescheduleIfAfter(final ZonedDateTime date, final TaskScheduler taskScheduler)
{
if (!notificationTime.isAfter(date) && !scheduledFuture.isDone())
{
logger.trace("Skip rescheduling {} because it's not after {}", date);
return this;
}
cancel();
final ScheduledFuture<?> nextScheduledFuture = taskScheduler.schedule(task, TimeUtil.asTimestamp(date));
NextDispatch nextDispatch = NextDispatch.builder()
.task(task)
.scheduledFuture(nextScheduledFuture)
.notificationTime(date)
.build();
logger.trace("Rescheduled {} to {}", this, nextDispatch);
return nextDispatch;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\purchasecandidate\reminder\PurchaseCandidateReminderScheduler.java | 1 |
请完成以下Java代码 | public void removeAttribute(String namespaceUri, String localName) {
synchronized(document) {
XmlQName xmlQName = new XmlQName(this, namespaceUri, localName);
if (xmlQName.hasLocalNamespace()) {
element.removeAttributeNS(null, xmlQName.getLocalName());
}
else {
element.removeAttributeNS(xmlQName.getNamespaceUri(), xmlQName.getLocalName());
}
}
}
public String getTextContent() {
synchronized(document) {
return element.getTextContent();
}
}
public void setTextContent(String textContent) {
synchronized(document) {
element.setTextContent(textContent);
}
}
public void addCDataSection(String data) {
synchronized (document) {
CDATASection cdataSection = document.createCDATASection(data);
element.appendChild(cdataSection);
}
}
public ModelElementInstance getModelElementInstance() {
synchronized(document) {
return (ModelElementInstance) element.getUserData(MODEL_ELEMENT_KEY);
}
}
public void setModelElementInstance(ModelElementInstance modelElementInstance) {
synchronized(document) {
element.setUserData(MODEL_ELEMENT_KEY, modelElementInstance, null);
}
}
public String registerNamespace(String namespaceUri) {
synchronized(document) {
String lookupPrefix = lookupPrefix(namespaceUri);
if (lookupPrefix == null) {
// check if a prefix is known
String prefix = XmlQName.KNOWN_PREFIXES.get(namespaceUri);
// check if prefix is not already used
if (prefix != null && getRootElement() != null &&
getRootElement().hasAttribute(XMLNS_ATTRIBUTE_NS_URI, prefix)) {
prefix = null;
}
if (prefix == null) {
// generate prefix
prefix = ((DomDocumentImpl) getDocument()).getUnusedGenericNsPrefix();
}
registerNamespace(prefix, namespaceUri);
return prefix;
} | else {
return lookupPrefix;
}
}
}
public void registerNamespace(String prefix, String namespaceUri) {
synchronized(document) {
element.setAttributeNS(XMLNS_ATTRIBUTE_NS_URI, XMLNS_ATTRIBUTE + ":" + prefix, namespaceUri);
}
}
public String lookupPrefix(String namespaceUri) {
synchronized(document) {
return element.lookupPrefix(namespaceUri);
}
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DomElementImpl that = (DomElementImpl) o;
return element.equals(that.element);
}
public int hashCode() {
return element.hashCode();
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\instance\DomElementImpl.java | 1 |
请完成以下Java代码 | public void setIsPartitionComplete(final boolean IsPartitionComplete)
{
set_Value(COLUMNNAME_IsPartitionComplete, Boolean.valueOf(IsPartitionComplete));
}
/**
* Get Partition is vollständig.
*
* @return Sagt aus, ob das System dieser Partition noch weitere Datensätze hinzufügen muss bevor sie als Ganzes verschoben werden kann.
*/
@Override
public boolean isPartitionComplete()
{
final Object oo = get_Value(COLUMNNAME_IsPartitionComplete);
if (oo != null)
{
if (oo instanceof Boolean)
{
return ((Boolean)oo).booleanValue();
}
return "Y".equals(oo);
}
return false;
}
/**
* Set Anz. zugeordneter Datensätze.
*
* @param PartitionSize Anz. zugeordneter Datensätze
*/
@Override
public void setPartitionSize(final int PartitionSize)
{
set_Value(COLUMNNAME_PartitionSize, Integer.valueOf(PartitionSize));
}
/**
* Get Anz. zugeordneter Datensätze.
*
* @return Anz. zugeordneter Datensätze | */
@Override
public int getPartitionSize()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_PartitionSize);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set Ziel-DLM-Level.
*
* @param Target_DLM_Level Ziel-DLM-Level
*/
@Override
public void setTarget_DLM_Level(final int Target_DLM_Level)
{
set_Value(COLUMNNAME_Target_DLM_Level, Integer.valueOf(Target_DLM_Level));
}
/**
* Get Ziel-DLM-Level.
*
* @return Ziel-DLM-Level
*/
@Override
public int getTarget_DLM_Level()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_Target_DLM_Level);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition.java | 1 |
请完成以下Java代码 | public String getDescription()
{
return description;
}
@Override
public void setDescription(@Nullable final String description)
{
this.description = description;
}
@Override
public Collection<Integer> getC_InvoiceCandidate_InOutLine_IDs()
{
return iciolIds;
}
@Override
public void negateAmounts()
{
setQtysToInvoice(getQtysToInvoice().negate());
setNetLineAmt(getNetLineAmt().negate());
}
@Override
public int getC_Activity_ID()
{
return activityID;
}
@Override
public void setC_Activity_ID(final int activityID)
{
this.activityID = activityID;
}
@Override
public Tax getC_Tax()
{
return tax;
}
@Override
public void setC_Tax(final Tax tax)
{
this.tax = tax;
}
@Override
public boolean isPrinted()
{
return printed;
}
@Override
public void setPrinted(final boolean printed)
{
this.printed = printed;
}
@Override
public int getLineNo()
{
return lineNo;
}
@Override
public void setLineNo(final int lineNo)
{
this.lineNo = lineNo;
} | @Override
public void setInvoiceLineAttributes(@NonNull final List<IInvoiceLineAttribute> invoiceLineAttributes)
{
this.invoiceLineAttributes = ImmutableList.copyOf(invoiceLineAttributes);
}
@Override
public List<IInvoiceLineAttribute> getInvoiceLineAttributes()
{
return invoiceLineAttributes;
}
@Override
public List<InvoiceCandidateInOutLineToUpdate> getInvoiceCandidateInOutLinesToUpdate()
{
return iciolsToUpdate;
}
@Override
public int getC_PaymentTerm_ID()
{
return C_PaymentTerm_ID;
}
@Override
public void setC_PaymentTerm_ID(final int paymentTermId)
{
C_PaymentTerm_ID = paymentTermId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineImpl.java | 1 |
请完成以下Java代码 | private Class<?> resolveIfNecessary(Class<?> resultClass, boolean resolve) {
if (resolve) {
resolveClass(resultClass);
}
return (resultClass);
}
@Override
protected void addURL(URL url) {
// Ignore URLs added by the Tomcat 8 implementation (see gh-919)
if (logger.isTraceEnabled()) {
logger.trace("Ignoring request to add " + url + " to the tomcat classloader");
}
}
private @Nullable Class<?> loadFromParent(String name) {
if (this.parent == null) {
return null;
} | try {
return Class.forName(name, false, this.parent);
}
catch (ClassNotFoundException ex) {
return null;
}
}
private @Nullable Class<?> findClassIgnoringNotFound(String name) {
try {
return findClass(name);
}
catch (ClassNotFoundException ex) {
return null;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\TomcatEmbeddedWebappClassLoader.java | 1 |
请完成以下Java代码 | public JsonObject writeConfiguration(SetRemovalTimeBatchConfiguration configuration) {
JsonObject json = JsonUtil.createObject();
JsonUtil.addListField(json, IDS, configuration.getIds());
JsonUtil.addListField(json, ID_MAPPINGS, DeploymentMappingJsonConverter.INSTANCE, configuration.getIdMappings());
JsonUtil.addDateField(json, REMOVAL_TIME, configuration.getRemovalTime());
JsonUtil.addField(json, HAS_REMOVAL_TIME, configuration.hasRemovalTime());
JsonUtil.addField(json, IS_HIERARCHICAL, configuration.isHierarchical());
JsonUtil.addField(json, UPDATE_IN_CHUNKS, configuration.isUpdateInChunks());
JsonUtil.addField(json, CHUNK_SIZE, configuration.getChunkSize());
if (configuration.getEntities() != null) {
JsonUtil.addListField(json, ENTITIES, new ArrayList<>(configuration.getEntities()));
}
return json;
}
@Override
public SetRemovalTimeBatchConfiguration readConfiguration(JsonObject jsonObject) {
long removalTimeMills = JsonUtil.getLong(jsonObject, REMOVAL_TIME);
Date removalTime = removalTimeMills > 0 ? new Date(removalTimeMills) : null;
List<String> instanceIds = JsonUtil.asStringList(JsonUtil.getArray(jsonObject, IDS));
DeploymentMappings mappings = JsonUtil.asList(JsonUtil.getArray(jsonObject, ID_MAPPINGS),
DeploymentMappingJsonConverter.INSTANCE, DeploymentMappings::new);
boolean hasRemovalTime = JsonUtil.getBoolean(jsonObject, HAS_REMOVAL_TIME);
boolean isHierarchical = JsonUtil.getBoolean(jsonObject, IS_HIERARCHICAL);
boolean updateInChunks = JsonUtil.getBoolean(jsonObject, UPDATE_IN_CHUNKS); | Integer chunkSize = jsonObject.has(CHUNK_SIZE)? JsonUtil.getInt(jsonObject, CHUNK_SIZE) : null;
Set<String> entities = null;
if (jsonObject.has(ENTITIES)) {
entities = new HashSet<>(JsonUtil.asStringList(JsonUtil.getArray(jsonObject, ENTITIES)));
}
return new SetRemovalTimeBatchConfiguration(instanceIds, mappings)
.setRemovalTime(removalTime)
.setHasRemovalTime(hasRemovalTime)
.setHierarchical(isHierarchical)
.setUpdateInChunks(updateInChunks)
.setChunkSize(chunkSize)
.setEntities(entities);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\removaltime\SetRemovalTimeJsonConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OptimisticLockingStudent {
@Id
private Long id;
private String name;
private String lastName;
@Version
private Integer version;
@OneToMany(mappedBy = "student")
private List<OptimisticLockingCourse> courses;
public OptimisticLockingStudent(Long id, String name, String lastName, List<OptimisticLockingCourse> courses) {
this.id = id;
this.name = name;
this.lastName = lastName;
this.courses = courses;
}
public OptimisticLockingStudent() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) { | this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<OptimisticLockingCourse> getCourses() {
return courses;
}
public void setCourses(List<OptimisticLockingCourse> courses) {
this.courses = courses;
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\hibernate\optimisticlocking\OptimisticLockingStudent.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ISyncAfterCommitCollector add(@NonNull final ProductSupply productSupply)
{
createAndStoreSyncConfirmRecord(productSupply);
productSupplies.add(productSupply);
logger.debug("Enqueued {}", productSupply);
return this;
}
@Override
public ISyncAfterCommitCollector add(@NonNull final WeekSupply weeklySupply)
{
createAndStoreSyncConfirmRecord(weeklySupply);
weeklySupplies.add(weeklySupply);
return this;
}
@Override
public ISyncAfterCommitCollector add(@NonNull final Rfq rfq)
{
createAndStoreSyncConfirmRecord(rfq);
rfqs.add(rfq);
return this;
}
@Override
public ISyncAfterCommitCollector add(@NonNull final User user)
{
users.add(user);
return this;
}
/**
* Creates a new local DB record for the given <code>abstractEntity</code>.
*/
private void createAndStoreSyncConfirmRecord(final AbstractSyncConfirmAwareEntity abstractEntity)
{
final SyncConfirm syncConfirmRecord = new SyncConfirm();
syncConfirmRecord.setEntryType(abstractEntity.getClass().getSimpleName());
syncConfirmRecord.setEntryUuid(abstractEntity.getUuid());
syncConfirmRecord.setEntryId(abstractEntity.getId());
syncConfirmRepo.save(syncConfirmRecord);
abstractEntity.setSyncConfirmId(syncConfirmRecord.getId());
}
@Override
public void afterCommit()
{
publishToMetasfreshAsync();
}
public void publishToMetasfreshAsync()
{
logger.debug("Synchronizing: {}", this);
//
// Sync daily product supplies
{
final List<ProductSupply> productSupplies = ImmutableList.copyOf(this.productSupplies);
this.productSupplies.clear(); | pushDailyReportsAsync(productSupplies);
}
//
// Sync weekly product supplies
{
final List<WeekSupply> weeklySupplies = ImmutableList.copyOf(this.weeklySupplies);
this.weeklySupplies.clear();
pushWeeklyReportsAsync(weeklySupplies);
}
//
// Sync RfQ changes
{
final List<Rfq> rfqs = ImmutableList.copyOf(this.rfqs);
this.rfqs.clear();
pushRfqsAsync(rfqs);
}
//
// Sync User changes
{
final List<User> users = ImmutableList.copyOf(this.users);
this.users.clear();
pushUsersAsync(users);
}
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\SenderToMetasfreshService.java | 2 |
请完成以下Java代码 | public long getPriority() {
return priority;
}
public void setPriority(long priority) {
this.priority = priority;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
@Override
public boolean isCreationLog() {
return state == ExternalTaskState.CREATED.getStateCode();
}
@Override
public boolean isFailureLog() {
return state == ExternalTaskState.FAILED.getStateCode();
}
@Override
public boolean isSuccessLog() {
return state == ExternalTaskState.SUCCESSFUL.getStateCode(); | }
@Override
public boolean isDeletionLog() {
return state == ExternalTaskState.DELETED.getStateCode();
}
@Override
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricExternalTaskLogEntity.java | 1 |
请完成以下Java代码 | public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID);
}
@Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public void setEventData (final @Nullable java.lang.String EventData)
{
set_ValueNoCheck (COLUMNNAME_EventData, EventData);
}
@Override
public java.lang.String getEventData()
{
return get_ValueAsString(COLUMNNAME_EventData);
}
@Override
public void setEventName (final @Nullable java.lang.String EventName)
{
set_Value (COLUMNNAME_EventName, EventName);
}
@Override
public java.lang.String getEventName()
{
return get_ValueAsString(COLUMNNAME_EventName);
}
@Override
public void setEventTime (final @Nullable java.sql.Timestamp EventTime)
{
set_ValueNoCheck (COLUMNNAME_EventTime, EventTime);
}
@Override
public java.sql.Timestamp getEventTime()
{
return get_ValueAsTimestamp(COLUMNNAME_EventTime);
}
@Override
public void setEventTopicName (final @Nullable java.lang.String EventTopicName)
{
set_Value (COLUMNNAME_EventTopicName, EventTopicName);
}
@Override
public java.lang.String getEventTopicName()
{
return get_ValueAsString(COLUMNNAME_EventTopicName);
}
/**
* EventTypeName AD_Reference_ID=540802
* Reference name: EventTypeName
*/
public static final int EVENTTYPENAME_AD_Reference_ID=540802;
/** LOCAL = LOCAL */
public static final String EVENTTYPENAME_LOCAL = "LOCAL";
/** DISTRIBUTED = DISTRIBUTED */
public static final String EVENTTYPENAME_DISTRIBUTED = "DISTRIBUTED";
@Override
public void setEventTypeName (final @Nullable java.lang.String EventTypeName)
{
set_Value (COLUMNNAME_EventTypeName, EventTypeName);
} | @Override
public java.lang.String getEventTypeName()
{
return get_ValueAsString(COLUMNNAME_EventTypeName);
}
@Override
public void setEvent_UUID (final java.lang.String Event_UUID)
{
set_ValueNoCheck (COLUMNNAME_Event_UUID, Event_UUID);
}
@Override
public java.lang.String getEvent_UUID()
{
return get_ValueAsString(COLUMNNAME_Event_UUID);
}
@Override
public void setIsError (final boolean IsError)
{
set_Value (COLUMNNAME_IsError, IsError);
}
@Override
public boolean isError()
{
return get_ValueAsBoolean(COLUMNNAME_IsError);
}
@Override
public void setIsErrorAcknowledged (final boolean IsErrorAcknowledged)
{
set_Value (COLUMNNAME_IsErrorAcknowledged, IsErrorAcknowledged);
}
@Override
public boolean isErrorAcknowledged()
{
return get_ValueAsBoolean(COLUMNNAME_IsErrorAcknowledged);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\event\model\X_AD_EventLog.java | 1 |
请完成以下Java代码 | public class MessageEventDefinitionParseHandler extends AbstractBpmnParseHandler<MessageEventDefinition> {
public Class<? extends BaseElement> getHandledType() {
return MessageEventDefinition.class;
}
protected void executeParse(BpmnParse bpmnParse, MessageEventDefinition messageDefinition) {
BpmnModel bpmnModel = bpmnParse.getBpmnModel();
String messageRef = messageDefinition.getMessageRef();
if (bpmnModel.containsMessageId(messageRef)) {
Message message = bpmnModel.getMessage(messageRef);
messageDefinition.setMessageRef(message.getName());
messageDefinition.setExtensionElements(message.getExtensionElements());
}
if (bpmnParse.getCurrentFlowElement() instanceof IntermediateCatchEvent) {
IntermediateCatchEvent intermediateCatchEvent = (IntermediateCatchEvent) bpmnParse.getCurrentFlowElement();
intermediateCatchEvent.setBehavior(
bpmnParse
.getActivityBehaviorFactory() | .createIntermediateCatchMessageEventActivityBehavior(intermediateCatchEvent, messageDefinition)
);
} else if (bpmnParse.getCurrentFlowElement() instanceof BoundaryEvent) {
BoundaryEvent boundaryEvent = (BoundaryEvent) bpmnParse.getCurrentFlowElement();
boundaryEvent.setBehavior(
bpmnParse
.getActivityBehaviorFactory()
.createBoundaryMessageEventActivityBehavior(
boundaryEvent,
messageDefinition,
boundaryEvent.isCancelActivity()
)
);
} else {
// What to do here?
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\MessageEventDefinitionParseHandler.java | 1 |
请完成以下Java代码 | public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setExternalId (final @Nullable java.lang.String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setIsBillTo (final boolean IsBillTo)
{
set_Value (COLUMNNAME_IsBillTo, IsBillTo);
}
@Override
public boolean isBillTo()
{
return get_ValueAsBoolean(COLUMNNAME_IsBillTo);
}
@Override
public void setIsFetchedFrom (final boolean IsFetchedFrom)
{
set_Value (COLUMNNAME_IsFetchedFrom, IsFetchedFrom);
}
@Override
public boolean isFetchedFrom()
{
return get_ValueAsBoolean(COLUMNNAME_IsFetchedFrom);
}
@Override
public void setIsPayFrom (final boolean IsPayFrom)
{
set_Value (COLUMNNAME_IsPayFrom, IsPayFrom);
}
@Override
public boolean isPayFrom()
{
return get_ValueAsBoolean(COLUMNNAME_IsPayFrom);
}
@Override
public void setIsRemitTo (final boolean IsRemitTo)
{
set_Value (COLUMNNAME_IsRemitTo, IsRemitTo);
}
@Override
public boolean isRemitTo()
{
return get_ValueAsBoolean(COLUMNNAME_IsRemitTo);
}
@Override
public void setIsShipTo (final boolean IsShipTo)
{
set_Value (COLUMNNAME_IsShipTo, IsShipTo);
}
@Override
public boolean isShipTo()
{
return get_ValueAsBoolean(COLUMNNAME_IsShipTo);
}
@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);
}
/**
* Role AD_Reference_ID=541254
* Reference name: Role
*/
public static final int ROLE_AD_Reference_ID=541254;
/** Main Producer = MP */
public static final String ROLE_MainProducer = "MP";
/** Hostpital = HO */
public static final String ROLE_Hostpital = "HO";
/** Physician Doctor = PD */
public static final String ROLE_PhysicianDoctor = "PD";
/** General Practitioner = GP */
public static final String ROLE_GeneralPractitioner = "GP";
/** Health Insurance = HI */
public static final String ROLE_HealthInsurance = "HI";
/** Nursing Home = NH */
public static final String ROLE_NursingHome = "NH";
/** Caregiver = CG */
public static final String ROLE_Caregiver = "CG";
/** Preferred Pharmacy = PP */
public static final String ROLE_PreferredPharmacy = "PP";
/** Nursing Service = NS */
public static final String ROLE_NursingService = "NS";
/** Payer = PA */
public static final String ROLE_Payer = "PA";
/** Payer = PA */
public static final String ROLE_Pharmacy = "PH";
@Override
public void setRole (final @Nullable java.lang.String Role)
{
set_Value (COLUMNNAME_Role, Role);
}
@Override
public java.lang.String getRole()
{
return get_ValueAsString(COLUMNNAME_Role);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Relation.java | 1 |
请完成以下Java代码 | static @Nullable ReactiveWebServerApplicationContext getWebServerApplicationContextIfPossible(
ApplicationContext context) {
try {
return (ReactiveWebServerApplicationContext) context;
}
catch (NoClassDefFoundError | ClassCastException ex) {
return null;
}
}
@Override
public @Nullable LocalTestWebServer getLocalTestWebServer() {
if (this.context == null) {
return null;
}
return LocalTestWebServer.of((isSslEnabled(this.context)) ? Scheme.HTTPS : Scheme.HTTP, () -> {
int port = this.context.getEnvironment().getProperty("local.server.port", Integer.class, 8080);
String path = this.context.getEnvironment().getProperty("spring.webflux.base-path", ""); | return new BaseUriDetails(port, path);
});
}
private boolean isSslEnabled(ReactiveWebServerApplicationContext context) {
try {
AbstractConfigurableWebServerFactory webServerFactory = context
.getBean(AbstractConfigurableWebServerFactory.class);
return webServerFactory.getSsl() != null && webServerFactory.getSsl().isEnabled();
}
catch (NoSuchBeanDefinitionException ex) {
return false;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\reactive\context\ReactiveWebServerApplicationContextLocalTestWebServerProvider.java | 1 |
请完成以下Java代码 | public Builder setMinPrecision(@NonNull final OptionalInt minPrecision)
{
this.minPrecision = minPrecision;
return this;
}
private OptionalInt getMinPrecision()
{
return minPrecision;
}
public Builder setSqlValueClass(final Class<?> sqlValueClass)
{
this._sqlValueClass = sqlValueClass;
return this;
}
private Class<?> getSqlValueClass()
{
if (_sqlValueClass != null)
{
return _sqlValueClass;
}
return getValueClass();
}
public Builder setLookupDescriptor(@Nullable final LookupDescriptor lookupDescriptor)
{
this._lookupDescriptor = lookupDescriptor;
return this;
}
public OptionalBoolean getNumericKey()
{
return _numericKey;
}
public Builder setKeyColumn(final boolean keyColumn)
{
this.keyColumn = keyColumn;
return this;
}
public Builder setEncrypted(final boolean encrypted)
{
this.encrypted = encrypted;
return this;
} | /**
* Sets ORDER BY priority and direction (ascending/descending)
*
* @param priority priority; if positive then direction will be ascending; if negative then direction will be descending
*/
public Builder setDefaultOrderBy(final int priority)
{
if (priority >= 0)
{
orderByPriority = priority;
orderByAscending = true;
}
else
{
orderByPriority = -priority;
orderByAscending = false;
}
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlDocumentFieldDataBindingDescriptor.java | 1 |
请完成以下Java代码 | public String getName() {
return "date";
}
@Override
public Object getInformation(String key) {
if ("datePattern".equals(key)) {
return datePattern;
}
return null;
}
@Override
public Object convertFormValueToModelValue(String propertyValue) {
if (StringUtils.isEmpty(propertyValue)) {
return null; | }
try {
return dateFormat.parseObject(propertyValue);
} catch (ParseException e) {
throw new FlowableIllegalArgumentException("invalid date value " + propertyValue, e);
}
}
@Override
public String convertModelValueToFormValue(Object modelValue) {
if (modelValue == null) {
return null;
}
return dateFormat.format(modelValue);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\DateFormType.java | 1 |
请完成以下Java代码 | public I_AD_Issue prepareNewIssueRecord(@NonNull final Properties ctx, @NonNull final I_AD_Issue issue)
{
final ISystemBL systemBL = Services.get(ISystemBL.class);
final ADSystemInfo system = systemBL.get();
issue.setName("-");
issue.setUserName("?");
issue.setDBAddress("-");
issue.setSystemStatus(system.getSystemStatus());
issue.setReleaseNo("-");
issue.setVersion(system.getDbVersion());
issue.setDatabaseInfo(DB.getDatabaseInfo());
issue.setOperatingSystemInfo(Adempiere.getOSInfo());
issue.setJavaInfo(Adempiere.getJavaInfo());
issue.setReleaseTag(Adempiere.getImplementationVersion());
issue.setLocal_Host(NetUtils.getLocalHost().toString());
final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); | if (requestAttributes instanceof ServletRequestAttributes)
{
final ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes;
final HttpServletRequest httpServletRequest = servletRequestAttributes.getRequest();
issue.setRemote_Addr(httpServletRequest.getRemoteAddr());
issue.setRemote_Host(httpServletRequest.getRemoteHost());
final String userAgent = httpServletRequest.getHeader("User-Agent");
issue.setUserAgent(userAgent);
}
return issue;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\error\AdIssueFactory.java | 1 |
请完成以下Java代码 | public SubProcess clone() {
SubProcess clone = new SubProcess();
clone.setValues(this);
return clone;
}
public void setValues(SubProcess otherElement) {
super.setValues(otherElement);
/*
* This is required because data objects in Designer have no DI info and are added as properties, not flow elements
*
* Determine the differences between the 2 elements' data object
*/
for (ValuedDataObject thisObject : getDataObjects()) {
boolean exists = false;
for (ValuedDataObject otherObject : otherElement.getDataObjects()) {
if (thisObject.getId().equals(otherObject.getId())) {
exists = true;
}
}
if (!exists) {
// missing object
removeFlowElement(thisObject.getId());
}
}
dataObjects = new ArrayList<ValuedDataObject>();
if (otherElement.getDataObjects() != null && !otherElement.getDataObjects().isEmpty()) {
for (ValuedDataObject dataObject : otherElement.getDataObjects()) {
ValuedDataObject clone = dataObject.clone();
dataObjects.add(clone);
// add it to the list of FlowElements
// if it is already there, remove it first so order is same as
// data object list
removeFlowElement(clone.getId());
addFlowElement(clone);
} | }
flowElementList.clear();
for (FlowElement flowElement : otherElement.getFlowElements()) {
addFlowElement(flowElement);
}
artifactList.clear();
for (Artifact artifact : otherElement.getArtifacts()) {
addArtifact(artifact);
}
}
public List<ValuedDataObject> getDataObjects() {
return dataObjects;
}
public void setDataObjects(List<ValuedDataObject> dataObjects) {
this.dataObjects = dataObjects;
}
@Override
public void accept(ReferenceOverrider referenceOverrider) {
getFlowElements().forEach(flowElement -> flowElement.accept(referenceOverrider));
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\SubProcess.java | 1 |
请完成以下Java代码 | public boolean isSOTrx ()
{
Object oo = get_Value(COLUMNNAME_IsSOTrx);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Exclude Lot.
@param M_LotCtlExclude_ID
Exclude the ability to create Lots in Attribute Sets
*/
public void setM_LotCtlExclude_ID (int M_LotCtlExclude_ID)
{
if (M_LotCtlExclude_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_LotCtlExclude_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_LotCtlExclude_ID, Integer.valueOf(M_LotCtlExclude_ID));
}
/** Get Exclude Lot.
@return Exclude the ability to create Lots in Attribute Sets
*/
public int getM_LotCtlExclude_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_LotCtlExclude_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_LotCtl getM_LotCtl() throws RuntimeException
{ | return (I_M_LotCtl)MTable.get(getCtx(), I_M_LotCtl.Table_Name)
.getPO(getM_LotCtl_ID(), get_TrxName()); }
/** Set Lot Control.
@param M_LotCtl_ID
Product Lot Control
*/
public void setM_LotCtl_ID (int M_LotCtl_ID)
{
if (M_LotCtl_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, Integer.valueOf(M_LotCtl_ID));
}
/** Get Lot Control.
@return Product Lot Control
*/
public int getM_LotCtl_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_LotCtl_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_LotCtlExclude.java | 1 |
请完成以下Java代码 | public class User {
private String username;
private String password;
private String email;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
} | public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
} | repos\tutorials-master\libraries-data-3\src\main\java\com\baeldung\storm\model\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean anyMatch(@NonNull final PickingJobScheduleQuery query)
{
return toSqlQuery(query).anyMatch();
}
private IQuery<I_M_Picking_Job_Schedule> toSqlQuery(@NonNull final PickingJobScheduleQuery query)
{
if (query.isAny())
{
throw new AdempiereException("Any query is not allowed");
}
final IQueryBuilder<I_M_Picking_Job_Schedule> queryBuilder = queryBL.createQueryBuilder(I_M_Picking_Job_Schedule.class)
.orderBy(I_M_Picking_Job_Schedule.COLUMNNAME_M_ShipmentSchedule_ID)
.orderBy(I_M_Picking_Job_Schedule.COLUMNNAME_M_Picking_Job_Schedule_ID)
.addOnlyActiveRecordsFilter();
if (!query.getWorkplaceIds().isEmpty())
{
queryBuilder.addInArrayFilter(I_M_Picking_Job_Schedule.COLUMNNAME_C_Workplace_ID, query.getWorkplaceIds());
} | if (!query.getExcludeJobScheduleIds().isEmpty())
{
queryBuilder.addNotInArrayFilter(I_M_Picking_Job_Schedule.COLUMNNAME_M_Picking_Job_Schedule_ID, query.getExcludeJobScheduleIds());
}
if (!query.getOnlyShipmentScheduleIds().isEmpty())
{
queryBuilder.addInArrayFilter(I_M_Picking_Job_Schedule.COLUMNNAME_M_ShipmentSchedule_ID, query.getOnlyShipmentScheduleIds());
}
if (query.getIsProcessed() != null)
{
queryBuilder.addEqualsFilter(I_M_Picking_Job_Schedule.COLUMNNAME_Processed, query.getIsProcessed());
}
return queryBuilder.create();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\job_schedule\repository\PickingJobScheduleRepository.java | 2 |
请完成以下Java代码 | public List<ActivityMigrationMapping> getActivityMigrationMappings() {
return activityMigrationMappings;
}
@Override
public List<EnableActivityMapping> getEnableActivityMappings() {
return enableActivityMappings;
}
@Override
public Map<String, Map<String, Object>> getActivitiesLocalVariables() {
return activitiesLocalVariables;
}
public void setProcessInstanceVariables(Map<String, Object> processInstanceVariables) {
this.processInstanceVariables = processInstanceVariables;
} | @Override
public Map<String, Object> getProcessInstanceVariables() {
return processInstanceVariables;
}
@Override
public String asJsonString() {
JsonNode jsonNode = ProcessInstanceMigrationDocumentConverter.convertToJson(this);
return jsonNode.toString();
}
@Override
public String toString() {
return ProcessInstanceMigrationDocumentConverter.convertToJsonString(this);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\migration\ProcessInstanceMigrationDocumentImpl.java | 1 |
请完成以下Java代码 | public String docValidate(PO po, int timing)
{
return null;
}
private void configDatabase()
{
//
// Get configuration from SysConfigs
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
final Duration unreturnedConnectionTimeout = Duration.ofSeconds(sysConfigBL.getIntValue(SYSCONFIG_C3P0_UnreturnedConnectionTimeoutInSeconds, 0));
final boolean debugUnreturnedConnectionStackTraces = sysConfigBL.getBooleanValue(SYSCONFIG_C3P0_DebugUnreturnedConnectionStackTraces, false);
final String maxStatementsSysConfig;
if (Ini.isSwingClient())
{
maxStatementsSysConfig = SYSCONFIG_C3P0_Client_MaxStatements;
}
else
{
maxStatementsSysConfig = SYSCONFIG_C3P0_Server_MaxStatements;
}
final int maxStatementsValue = sysConfigBL.getIntValue(maxStatementsSysConfig, 0);
final CConnection cc = CConnection.get();
DataSource ds = cc.getDataSource();
//
// On server side, the cc.getDataSource() always return null,
// so we need to take the DataSource from it's original place
if (ds == null)
{
ds = cc.getDatabase().getDataSource(cc);
}
if (ds instanceof ComboPooledDataSource)
{
ComboPooledDataSource cpds = (ComboPooledDataSource)ds; | if (unreturnedConnectionTimeout.getSeconds() > 0)
{
final int old = cpds.getUnreturnedConnectionTimeout();
// IMPORTANT: unreturnedConnectionTimeout is in seconds, see https://www.mchange.com/projects/c3p0/#unreturnedConnectionTimeout
cpds.setUnreturnedConnectionTimeout((int)unreturnedConnectionTimeout.getSeconds());
log.info("Config " + SYSCONFIG_C3P0_UnreturnedConnectionTimeoutInSeconds + "=" + unreturnedConnectionTimeout + " (Old: " + old + " seconds)");
}
{
final boolean old = cpds.isDebugUnreturnedConnectionStackTraces();
cpds.setDebugUnreturnedConnectionStackTraces(debugUnreturnedConnectionStackTraces);
log.info("Config " + SYSCONFIG_C3P0_DebugUnreturnedConnectionStackTraces + "=" + debugUnreturnedConnectionStackTraces + " (Old: " + old + ")");
}
{
final int old = cpds.getMaxStatements();
cpds.setMaxStatements(maxStatementsValue);
log.info("Config " + maxStatementsSysConfig + "=" + maxStatementsValue + " (Old: " + old + ")");
}
}
else
{
log.warn("Can not configure datasource because is not an instance of ComboPooledDataSource: " + ds);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\modelvalidator\SwatValidator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setGeneralShipmentData(GeneralShipmentData value) {
this.generalShipmentData = value;
}
/**
* Gets the value of the parcels property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the parcels property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getParcels().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Parcel }
*
*
*/
public List<Parcel> getParcels() {
if (parcels == null) {
parcels = new ArrayList<Parcel>();
} | return this.parcels;
}
/**
* Gets the value of the productAndServiceData property.
*
* @return
* possible object is
* {@link ProductAndServiceData }
*
*/
public ProductAndServiceData getProductAndServiceData() {
return productAndServiceData;
}
/**
* Sets the value of the productAndServiceData property.
*
* @param value
* allowed object is
* {@link ProductAndServiceData }
*
*/
public void setProductAndServiceData(ProductAndServiceData value) {
this.productAndServiceData = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ShipmentServiceData.java | 2 |
请完成以下Java代码 | public class RedisObjectSerializer implements RedisSerializer<Object> {
private Converter<Object, byte[]> serializer = new SerializingConverter();
private Converter<byte[], Object> deserializer = new DeserializingConverter();
static final byte[] EMPTY_ARRAY = new byte[0];
public Object deserialize(byte[] bytes) {
if (isEmpty(bytes)) {
return null;
}
try {
return deserializer.convert(bytes);
} catch (Exception ex) {
throw new SerializationException("Cannot deserialize", ex);
} | }
public byte[] serialize(Object object) {
if (object == null) {
return EMPTY_ARRAY;
}
try {
return serializer.convert(object);
} catch (Exception ex) {
return EMPTY_ARRAY;
}
}
private boolean isEmpty(byte[] data) {
return (data == null || data.length == 0);
}
} | repos\SpringBoot-Learning-master\1.x\Chapter3-2-5\src\main\java\com\didispace\RedisObjectSerializer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ConcurrentKafkaListenerContainerFactory<K, V>
extends AbstractKafkaListenerContainerFactory<ConcurrentMessageListenerContainer<K, V>, K, V> {
private @Nullable Integer concurrency;
/**
* Specify the container concurrency.
* @param concurrency the number of consumers to create.
* @see ConcurrentMessageListenerContainer#setConcurrency(int)
*/
public void setConcurrency(Integer concurrency) {
this.concurrency = concurrency;
}
@Override
protected ConcurrentMessageListenerContainer<K, V> createContainerInstance(KafkaListenerEndpoint endpoint) {
TopicPartitionOffset[] topicPartitions = endpoint.getTopicPartitionsToAssign();
if (topicPartitions != null && topicPartitions.length > 0) {
ContainerProperties properties = new ContainerProperties(topicPartitions);
return new ConcurrentMessageListenerContainer<>(getConsumerFactory(), properties);
}
else {
Collection<String> topics = endpoint.getTopics();
Assert.state(topics != null, "'topics' must not be null");
if (!topics.isEmpty()) { // NOSONAR
ContainerProperties properties = new ContainerProperties(topics.toArray(new String[0]));
return new ConcurrentMessageListenerContainer<>(getConsumerFactory(), properties);
}
else {
ContainerProperties properties = new ContainerProperties(endpoint.getTopicPattern()); // NOSONAR
return new ConcurrentMessageListenerContainer<>(getConsumerFactory(), properties);
} | }
}
@Override
protected void initializeContainer(ConcurrentMessageListenerContainer<K, V> instance,
KafkaListenerEndpoint endpoint) {
super.initializeContainer(instance, endpoint);
Integer conc = endpoint.getConcurrency();
if (conc != null) {
instance.setConcurrency(conc);
}
else if (this.concurrency != null) {
instance.setConcurrency(this.concurrency);
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\config\ConcurrentKafkaListenerContainerFactory.java | 2 |
请完成以下Java代码 | public XMLGregorianCalendar getCaseDate() {
return caseDate;
}
/**
* Sets the value of the caseDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setCaseDate(XMLGregorianCalendar value) {
this.caseDate = value;
}
/**
* Gets the value of the ssn property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSsn() {
return ssn;
}
/**
* Sets the value of the ssn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSsn(String value) {
this.ssn = value;
}
/**
* Gets the value of the nif property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getNif() {
return nif;
}
/**
* Sets the value of the nif property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNif(String value) {
this.nif = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\IvgLawType.java | 1 |
请完成以下Java代码 | public ResponseEntity<PageResult<ServerDeployDto>> queryServerDeploy(ServerDeployQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(serverDeployService.queryAll(criteria,pageable),HttpStatus.OK);
}
@Log("新增服务器")
@ApiOperation(value = "新增服务器")
@PostMapping
@PreAuthorize("@el.check('serverDeploy:add')")
public ResponseEntity<Object> createServerDeploy(@Validated @RequestBody ServerDeploy resources){
serverDeployService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改服务器")
@ApiOperation(value = "修改服务器")
@PutMapping
@PreAuthorize("@el.check('serverDeploy:edit')")
public ResponseEntity<Object> updateServerDeploy(@Validated @RequestBody ServerDeploy resources){
serverDeployService.update(resources); | return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除服务器")
@ApiOperation(value = "删除Server")
@DeleteMapping
@PreAuthorize("@el.check('serverDeploy:del')")
public ResponseEntity<Object> deleteServerDeploy(@RequestBody Set<Long> ids){
serverDeployService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("测试连接服务器")
@ApiOperation(value = "测试连接服务器")
@PostMapping("/testConnect")
@PreAuthorize("@el.check('serverDeploy:add')")
public ResponseEntity<Object> testConnectServerDeploy(@Validated @RequestBody ServerDeploy resources){
return new ResponseEntity<>(serverDeployService.testConnect(resources),HttpStatus.CREATED);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\rest\ServerDeployController.java | 1 |
请完成以下Java代码 | public ZonedDateTime getParameterAsZonedDateTime(final String parameterName)
{
return null;
}
@Nullable
@Override
public Instant getParameterAsInstant(final String parameterName)
{
return null;
}
@Override
public BigDecimal getParameterAsBigDecimal(final String paraCheckNetamttoinvoice)
{
return null; | }
/**
* Returns an empty list.
*/
@Override
public Collection<String> getParameterNames()
{
return ImmutableList.of();
}
@Override
public <T extends Enum<T>> Optional<T> getParameterAsEnum(final String parameterName, final Class<T> enumType)
{
return Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\api\NullParams.java | 1 |
请完成以下Java代码 | public DDOrderLineId getDDOrderLineId() {return id.toDDOrderLineId();}
public ProductId getProductId() {return product.getProductId();}
public LocatorId getPickFromLocatorId() {return pickFromLocator.getLocatorId();}
public LocatorId getDropToLocatorId() {return dropToLocator.getLocatorId();}
public I_C_UOM getUOM() {return qtyToMove.getUOM();}
public boolean isInTransit()
{
return !steps.isEmpty() && steps.stream().anyMatch(DistributionJobStep::isInTransit);
}
public boolean isEligibleForPicking() {return getQtyInTransit().isLessThan(qtyToMove);}
private Quantity getQtyInTransit()
{
return steps.stream()
.map(DistributionJobStep::getQtyInTransit)
.reduce(Quantity::add)
.orElseGet(qtyToMove::toZero);
}
public boolean isFullyMoved()
{
return !steps.isEmpty() && steps.stream().allMatch(DistributionJobStep::isDroppedToLocator);
}
private static WFActivityStatus computeStatusFromSteps(final @NonNull List<DistributionJobStep> steps)
{
return steps.isEmpty()
? WFActivityStatus.NOT_STARTED
: WFActivityStatus.computeStatusFromLines(steps, DistributionJobStep::getStatus);
}
public DDOrderLineId getDdOrderLineId() {return id.toDDOrderLineId();}
public DistributionJobLine withNewStep(final DistributionJobStep stepToAdd)
{
final ArrayList<DistributionJobStep> changedSteps = new ArrayList<>(this.steps);
boolean added = false;
boolean changed = false;
for (final DistributionJobStep step : steps)
{
if (DistributionJobStepId.equals(step.getId(), stepToAdd.getId()))
{
changedSteps.add(stepToAdd);
added = true;
if (!Objects.equals(step, stepToAdd))
{
changed = true;
}
}
else
{
changedSteps.add(step);
}
}
if (!added)
{ | changedSteps.add(stepToAdd);
changed = true;
}
return changed
? toBuilder().steps(ImmutableList.copyOf(changedSteps)).build()
: this;
}
public DistributionJobLine withChangedSteps(@NonNull final UnaryOperator<DistributionJobStep> stepMapper)
{
final ImmutableList<DistributionJobStep> changedSteps = CollectionUtils.map(steps, stepMapper);
return changedSteps.equals(steps)
? this
: toBuilder().steps(changedSteps).build();
}
public DistributionJobLine removeStep(@NonNull final DistributionJobStepId stepId)
{
final ImmutableList<DistributionJobStep> updatedStepCollection = steps.stream()
.filter(step -> !step.getId().equals(stepId))
.collect(ImmutableList.toImmutableList());
return updatedStepCollection.equals(steps)
? this
: toBuilder().steps(updatedStepCollection).build();
}
@NonNull
public Optional<DistributionJobStep> getStepById(@NonNull final DistributionJobStepId stepId)
{
return getSteps().stream().filter(step -> step.getId().equals(stepId)).findFirst();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\model\DistributionJobLine.java | 1 |
请完成以下Java代码 | public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Override
public String getDescription() {
return (String) getProperty("documentation");
}
/**
* @return all lane-sets defined on this process-instance. Returns an empty list if none are defined. | */
public List<LaneSet> getLaneSets() {
if (laneSets == null) {
laneSets = new ArrayList<>();
}
return laneSets;
}
public void setParticipantProcess(ParticipantProcess participantProcess) {
this.participantProcess = participantProcess;
}
public ParticipantProcess getParticipantProcess() {
return participantProcess;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ProcessDefinitionImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Date getFrom() {
return from;
}
public void setFrom(Date from) {
this.from = from;
}
public Date getTo() {
return to;
}
public void setTo(Date to) {
this.to = to;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
} | public Long getFromLogNumber() {
return fromLogNumber;
}
public void setFromLogNumber(Long fromLogNumber) {
this.fromLogNumber = fromLogNumber;
}
public Long getToLogNumber() {
return toLogNumber;
}
public void setToLogNumber(Long toLogNumber) {
this.toLogNumber = toLogNumber;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskLogEntryQueryRequest.java | 2 |
请完成以下Java代码 | public QueryBuildContext<T> deriveForSubFilter(final IQueryFilter<T> subFilter)
{
final QueryBuildContext<T> subQueryCtx = new QueryBuildContext<>(this);
subQueryCtx.mainFilter = subFilter;
subQueryCtx.queryOrderBy = null;
subQueryCtx.queryLimit = QueryLimit.NO_LIMIT;
return subQueryCtx;
}
public Properties getCtx()
{
return ctx;
}
public String getTrxName()
{
return trxName;
}
public Class<T> getModelClass()
{
return modelClass;
}
public String getModelTableName()
{
return modelTableName;
}
public ImmutableMap<String, Object> getQueryOptions()
{
return queryOptions;
}
public PInstanceId getQueryOnlySelectionId()
{
return queryOnlySelectionId;
}
public IQueryFilter<T> getMainFilter()
{
return mainFilter; | }
public ICompositeQueryFilter<T> getMainFilterAsComposite()
{
return (ICompositeQueryFilter<T>)mainFilter;
}
public ICompositeQueryFilter<T> getMainFilterAsCompositeOrNull()
{
return mainFilter instanceof ICompositeQueryFilter ? (ICompositeQueryFilter<T>)mainFilter : null;
}
public IQueryOrderBy getQueryOrderBy()
{
return queryOrderBy;
}
public QueryLimit getQueryLimit()
{
return queryLimit;
}
public void setQueryLimit(@NonNull final QueryLimit queryLimit)
{
this.queryLimit = queryLimit;
}
public boolean isExplodeORJoinsToUnions()
{
return explodeORJoinsToUnions;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\AbstractQueryBuilderDAO.java | 1 |
请完成以下Java代码 | public abstract class GolfCourseBuilder {
/**
* Builds the {@literal Augusta National} {@link GolfCourse}, home of the {@literal Masters} major golf tournament.
*
* @return a new instance of {@link GolfCourse} modeling {@literal Augusta National} in Augusta, GA; USA.
* @see example.app.caching.inline.async.client.model.GolfCourse
*/
public static GolfCourse buildAugustaNational() {
return GolfCourse.newGolfCourse("Augusta National")
.withHole(1, 4)
.withHole(2, 5)
.withHole(3, 4)
.withHole(4, 3)
.withHole(5, 4) | .withHole(6, 3)
.withHole(7, 4)
.withHole(8, 5)
.withHole(9, 4)
.withHole(10, 4)
.withHole(11, 4)
.withHole(12, 3)
.withHole(13, 5)
.withHole(14, 4)
.withHole(15, 5)
.withHole(16, 3)
.withHole(17, 4)
.withHole(18, 4);
}
} | repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\model\support\GolfCourseBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OrderQueryService {
private final QueryGateway queryGateway;
public OrderQueryService(QueryGateway queryGateway) {
this.queryGateway = queryGateway;
}
public CompletableFuture<List<OrderResponse>> findAllOrders() {
return queryGateway.query(new FindAllOrderedProductsQuery(), ResponseTypes.multipleInstancesOf(Order.class))
.thenApply(r -> r.stream()
.map(OrderResponse::new)
.collect(Collectors.toList()));
}
public Flux<OrderResponse> allOrdersStreaming() {
Publisher<Order> publisher = queryGateway.streamingQuery(new FindAllOrderedProductsQuery(), Order.class);
return Flux.from(publisher)
.map(OrderResponse::new); | }
public Integer totalShipped(String productId) {
return queryGateway.scatterGather(new TotalProductsShippedQuery(productId), ResponseTypes.instanceOf(Integer.class), 10L, TimeUnit.SECONDS)
.reduce(0, Integer::sum);
}
public Flux<OrderResponse> orderUpdates(String orderId) {
return subscriptionQuery(new OrderUpdatesQuery(orderId), ResponseTypes.instanceOf(Order.class)).map(OrderResponse::new);
}
private <Q, R> Flux<R> subscriptionQuery(Q query, ResponseType<R> resultType) {
SubscriptionQueryResult<R, R> result = queryGateway.subscriptionQuery(query, resultType, resultType);
return result.initialResult()
.concatWith(result.updates())
.doFinally(signal -> result.close());
}
} | repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\querymodel\OrderQueryService.java | 2 |
请完成以下Java代码 | public static void changeDLMLevel(final Connection c, final int dlmLevel) throws SQLException
{
changeSetting(c, SETTING_DLM_LEVEL, dlmLevel);
}
public static int retrieveCurrentDLMLevel(final Connection c) throws SQLException
{
return restrieveSetting(c, FUNCTION_DLM_LEVEL);
}
public static int retrieveCurrentDLMCoalesceLevel(final Connection c) throws SQLException
{
return restrieveSetting(c, FUNCTION_DLM_COALESCE_LEVEL);
}
private static int restrieveSetting(final Connection c, final String functionName) throws SQLException
{
final ResultSet rs = c.prepareStatement("SELECT " + functionName).executeQuery();
final Integer dlmLevel = rs.next() ? rs.getInt(1) : null;
Check.errorIf(dlmLevel == null, "Unable to retrieve the current setting for {} from the DB", SETTING_DLM_COALESCE_LEVEL);
return dlmLevel; | }
private static void changeSetting(final Connection c, final String setting, final int value) throws SQLException
{
final String valueStr = Integer.toString(value);
changeSetting(c, setting, valueStr);
}
private static void changeSetting(final Connection c, final String setting, final String valueStr) throws SQLException
{
final PreparedStatement ps = c.prepareStatement("select set_config('" + setting + "'::text, ?::text, ?::boolean)");
ps.setString(1, valueStr);
ps.setBoolean(2, false);
ps.execute();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\connection\DLMConnectionUtils.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8888
eureka:
instance:
hostname: registry
prefer-ip-address: true
metadata-map:
user.name: ${security.user.name}
user.password: ${security.user.password}
client:
service-url:
defaultZone: http://user:${REGISTRY_SERVER_PASSWORD:password}@registry:8761/eureka/
spring:
cloud:
config:
server:
git:
uri: https://github.com/zha | ngxd1989/spring-boot-cloud
search-paths: config-repo
rabbitmq:
host: rabbitmq
security:
user:
name: user
password: ${CONFIG_SERVER_PASSWORD:password} | repos\spring-boot-cloud-master\config\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public class WEBUI_PP_Order_ChangeExportStatus extends JavaProcess implements IProcessPrecondition
{
private static final String PARAM_ExportStatus = "ExportStatus";
@Param(parameterName = PARAM_ExportStatus, mandatory = true)
private String exportStatus;
private final IPPOrderBL ppOrderBL = Services.get(IPPOrderBL.class);
private final IPPOrderDAO ppOrderDAO = Services.get(IPPOrderDAO.class);
private static final AdMessageKey MSG_ONLY_CLOSED_LINES = AdMessageKey.of("PP_Order_No_Closed_Lines");
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected void prepare()
{
final IQueryFilter<I_PP_Order> userSelectionFilter = getProcessInfo().getQueryFilterOrElseFalse();
final IQueryBuilder<I_PP_Order> queryBuilderForShipmentSchedulesSelection = ppOrderDAO.createQueryForPPOrderSelection(userSelectionFilter);
// Create selection and return how many items were added
final int selectionCount = queryBuilderForShipmentSchedulesSelection
.create()
.createSelection(getPinstanceId());
if (selectionCount <= 0) | {
throw new AdempiereException(MSG_ONLY_CLOSED_LINES)
.markAsUserValidationError();
}
}
@Override
protected String doIt() throws Exception
{
final PInstanceId pinstanceId = getPinstanceId();
ppOrderBL.updateExportStatus(APIExportStatus.ofCode(exportStatus), pinstanceId);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_ChangeExportStatus.java | 1 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseTask.class, CMMN_ELEMENT_CASE_TASK)
.extendsType(Task.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<CaseTask>() {
public CaseTask newInstance(ModelTypeInstanceContext instanceContext) {
return new CaseTaskImpl(instanceContext);
}
});
caseRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CASE_REF)
.build();
/** camunda extensions */
camundaCaseBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_BINDING)
.namespace(CAMUNDA_NS)
.build(); | camundaCaseVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_VERSION)
.namespace(CAMUNDA_NS)
.build();
camundaCaseTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_TENANT_ID)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class)
.build();
caseRefExpressionChild = sequenceBuilder.element(CaseRefExpression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseTaskImpl.java | 1 |
请完成以下Java代码 | public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() { | return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
} | repos\tutorials-master\spring-reactive-modules\spring-webflux\src\main\java\com\baeldung\spring\convertmonoobject\User.java | 1 |
请完成以下Java代码 | public boolean checkIfFree(@NonNull final FreightCostContext context)
{
if (!context.getDeliveryViaRule().isShipper())
{
logger.debug("No freight cost because DeliveryViaRule is not shipper: ", context);
return true;
}
if (context.getShipToBPartnerId() == null)
{
logger.debug("No freight cost because ShipToBPartner is not set: {}", context);
return true;
}
if (context.getFreightCostRule() == FreightCostRule.FreightIncluded)
{
logger.debug("No freight cost because the freight is included: {}", context);
return true;
}
if (context.getShipperId() == null)
{
logger.debug("No freightcost because no shipper is set: {}", context);
return true;
}
return false;
}
/**
* Attempts to load the freight costs for a given business partner and location (actually the location's country).
* Looks at different freight cost records in this context:
* <ul>
* <li>Freight cost attached to the bParter</li>
* <li>Freight cost attached to the bParter's bPartnerGroup</li>
* <li>Default freight cost</li>
* </ul>
*
* @throws AdempiereException if there is no freight cost record for the given inOut
*/
public FreightCost findBestMatchingFreightCost(final FreightCostContext context)
{
final BPartnerId shipToBPartnerId = context.getShipToBPartnerId();
if (shipToBPartnerId == null)
{
throw new AdempiereException("ShipToBPartner not set");
}
final CountryId shipToCountryId = context.getShipToCountryId(); | if (shipToCountryId == null)
{
throw new AdempiereException("ShipToCountryId not set");
}
final ShipperId shipperId = context.getShipperId();
if (shipperId == null)
{
throw new AdempiereException(MSG_Order_No_Shipper);
}
//
//
final FreightCost freightCost = getFreightCostByBPartnerId(shipToBPartnerId);
final FreightCostShipper shipper = freightCost.getShipper(shipperId, context.getDate());
if (!shipper.isShipToCountry(shipToCountryId))
{
throw new AdempiereException("@NotFound@ @M_FreightCost_ID@ (@M_Shipper_ID@:" + shipperId + ", @C_Country_ID@:" + shipToCountryId + ")");
}
return freightCost;
}
public FreightCost getFreightCostByBPartnerId(final BPartnerId bpartnerId)
{
final IBPartnerBL bpartnerBL = Services.get(IBPartnerBL.class);
final FreightCostId bpFreightCostId = FreightCostId.ofRepoIdOrNull(bpartnerBL.getFreightCostIdByBPartnerId(bpartnerId));
if (bpFreightCostId != null)
{
return freightCostRepo.getById(bpFreightCostId);
}
final FreightCost defaultFreightCost = freightCostRepo.getDefaultFreightCost().orElse(null);
if (defaultFreightCost != null)
{
return defaultFreightCost;
}
throw new AdempiereException("@NotFound@ @M_FreightCost_ID@: " + bpartnerId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\freighcost\FreightCostService.java | 1 |
请完成以下Java代码 | public static LocalToRemoteSyncResult inserted(@NonNull final DataRecord datarecord)
{
return LocalToRemoteSyncResult.builder()
.synchedDataRecord(datarecord)
.localToRemoteStatus(LocalToRemoteStatus.INSERTED_ON_REMOTE)
.build();
}
public static LocalToRemoteSyncResult updated(@NonNull final DataRecord datarecord)
{
return LocalToRemoteSyncResult.builder()
.synchedDataRecord(datarecord)
.localToRemoteStatus(LocalToRemoteStatus.UPDATED_ON_REMOTE)
.build();
}
public static LocalToRemoteSyncResult deleted(@NonNull final DataRecord datarecord)
{
return LocalToRemoteSyncResult.builder()
.synchedDataRecord(datarecord)
.localToRemoteStatus(LocalToRemoteStatus.DELETED_ON_REMOTE)
.build();
}
public static LocalToRemoteSyncResult error(
@NonNull final DataRecord datarecord,
@NonNull final String errorMessage)
{
return LocalToRemoteSyncResult.builder()
.synchedDataRecord(datarecord)
.localToRemoteStatus(LocalToRemoteStatus.ERROR)
.errorMessage(errorMessage)
.build();
}
public enum LocalToRemoteStatus
{
INSERTED_ON_REMOTE,
UPDATED_ON_REMOTE,
UPSERTED_ON_REMOTE,
DELETED_ON_REMOTE, UNCHANGED, ERROR; | }
LocalToRemoteStatus localToRemoteStatus;
String errorMessage;
DataRecord synchedDataRecord;
@Builder
private LocalToRemoteSyncResult(
@NonNull final DataRecord synchedDataRecord,
@Nullable final LocalToRemoteStatus localToRemoteStatus,
@Nullable final String errorMessage)
{
this.synchedDataRecord = synchedDataRecord;
this.localToRemoteStatus = localToRemoteStatus;
this.errorMessage = errorMessage;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\LocalToRemoteSyncResult.java | 1 |
请完成以下Java代码 | public abstract class AbstractEdgeEntity<T extends Edge> extends BaseVersionedEntity<T> {
@Column(name = EDGE_TENANT_ID_PROPERTY, columnDefinition = "uuid")
private UUID tenantId;
@Column(name = EDGE_CUSTOMER_ID_PROPERTY, columnDefinition = "uuid")
private UUID customerId;
@Column(name = EDGE_ROOT_RULE_CHAIN_ID_PROPERTY, columnDefinition = "uuid")
private UUID rootRuleChainId;
@Column(name = EDGE_TYPE_PROPERTY)
private String type;
@Column(name = EDGE_NAME_PROPERTY)
private String name;
@Column(name = EDGE_LABEL_PROPERTY)
private String label;
@Column(name = EDGE_ROUTING_KEY_PROPERTY)
private String routingKey;
@Column(name = EDGE_SECRET_PROPERTY)
private String secret;
@Convert(converter = JsonConverter.class)
@Column(name = ModelConstants.EDGE_ADDITIONAL_INFO_PROPERTY)
private JsonNode additionalInfo;
public AbstractEdgeEntity() {
super();
}
public AbstractEdgeEntity(T edge) {
super(edge);
if (edge.getTenantId() != null) {
this.tenantId = edge.getTenantId().getId();
}
if (edge.getCustomerId() != null) {
this.customerId = edge.getCustomerId().getId();
}
if (edge.getRootRuleChainId() != null) {
this.rootRuleChainId = edge.getRootRuleChainId().getId();
}
this.type = edge.getType();
this.name = edge.getName();
this.label = edge.getLabel();
this.routingKey = edge.getRoutingKey();
this.secret = edge.getSecret();
this.additionalInfo = edge.getAdditionalInfo();
}
public AbstractEdgeEntity(EdgeEntity edgeEntity) {
super(edgeEntity);
this.tenantId = edgeEntity.getTenantId();
this.customerId = edgeEntity.getCustomerId();
this.rootRuleChainId = edgeEntity.getRootRuleChainId();
this.type = edgeEntity.getType();
this.name = edgeEntity.getName();
this.label = edgeEntity.getLabel(); | this.routingKey = edgeEntity.getRoutingKey();
this.secret = edgeEntity.getSecret();
this.additionalInfo = edgeEntity.getAdditionalInfo();
}
protected Edge toEdge() {
Edge edge = new Edge(new EdgeId(getUuid()));
edge.setCreatedTime(createdTime);
edge.setVersion(version);
if (tenantId != null) {
edge.setTenantId(TenantId.fromUUID(tenantId));
}
if (customerId != null) {
edge.setCustomerId(new CustomerId(customerId));
}
if (rootRuleChainId != null) {
edge.setRootRuleChainId(new RuleChainId(rootRuleChainId));
}
edge.setType(type);
edge.setName(name);
edge.setLabel(label);
edge.setRoutingKey(routingKey);
edge.setSecret(secret);
edge.setAdditionalInfo(additionalInfo);
return edge;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\AbstractEdgeEntity.java | 1 |
请完成以下Java代码 | public boolean convert(String textmodel, String binarymodel)
{
try
{
InputStreamReader isr = new InputStreamReader(IOUtil.newInputStream(textmodel), "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
int version = Integer.valueOf(br.readLine().substring("version: ".length()));
costFactor_ = Double.valueOf(br.readLine().substring("cost-factor: ".length()));
maxid_ = Integer.valueOf(br.readLine().substring("maxid: ".length()));
xsize_ = Integer.valueOf(br.readLine().substring("xsize: ".length()));
System.out.println("Done reading meta-info");
br.readLine();
while ((line = br.readLine()) != null && line.length() > 0)
{
y_.add(line);
}
System.out.println("Done reading labels");
while ((line = br.readLine()) != null && line.length() > 0)
{
if (line.startsWith("U"))
{
unigramTempls_.add(line);
}
else if (line.startsWith("B"))
{
bigramTempls_.add(line);
}
}
System.out.println("Done reading templates");
dic_ = new MutableDoubleArrayTrieInteger();
while ((line = br.readLine()) != null && line.length() > 0)
{
String[] content = line.trim().split(" ");
if (content.length != 2)
{
System.err.println("feature indices format error");
return false;
}
dic_.put(content[1], Integer.valueOf(content[0]));
}
System.out.println("Done reading feature indices");
List<Double> alpha = new ArrayList<Double>();
while ((line = br.readLine()) != null && line.length() > 0)
{
alpha.add(Double.valueOf(line));
}
System.out.println("Done reading weights");
alpha_ = new double[alpha.size()];
for (int i = 0; i < alpha.size(); i++)
{
alpha_[i] = alpha.get(i);
} | br.close();
System.out.println("Writing binary model to " + binarymodel);
return save(binarymodel, false);
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
public static void main(String[] args)
{
if (args.length < 2)
{
return;
}
else
{
EncoderFeatureIndex featureIndex = new EncoderFeatureIndex(1);
if (!featureIndex.convert(args[0], args[1]))
{
System.err.println("Fail to convert text model");
}
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\EncoderFeatureIndex.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected DeploymentQuery createNewQuery(ProcessEngine engine) {
return engine.getRepositoryService().createDeploymentQuery();
}
@Override
protected void applyFilters(DeploymentQuery query) {
if (withoutSource != null && withoutSource && source != null) {
throw new InvalidRequestException(Status.BAD_REQUEST, "The query parameters \"withoutSource\" and \"source\" cannot be used in combination.");
}
if (id != null) {
query.deploymentId(id);
}
if (name != null) {
query.deploymentName(name);
}
if (nameLike != null) {
query.deploymentNameLike(nameLike);
}
if (TRUE.equals(withoutSource)) {
query.deploymentSource(null);
}
if (source != null) {
query.deploymentSource(source);
}
if (before != null) {
query.deploymentBefore(before);
}
if (after != null) {
query.deploymentAfter(after);
}
if (tenantIds != null && !tenantIds.isEmpty()) {
query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()]));
}
if (TRUE.equals(withoutTenantId)) {
query.withoutTenantId(); | }
if (TRUE.equals(includeDeploymentsWithoutTenantId)) {
query.includeDeploymentsWithoutTenantId();
}
}
@Override
protected void applySortBy(DeploymentQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_ID_VALUE)) {
query.orderByDeploymentId();
} else if (sortBy.equals(SORT_BY_NAME_VALUE)) {
query.orderByDeploymentName();
} else if (sortBy.equals(SORT_BY_DEPLOYMENT_TIME_VALUE)) {
query.orderByDeploymentTime();
} else if (sortBy.equals(SORT_BY_TENANT_ID)) {
query.orderByTenantId();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\DeploymentQueryDto.java | 2 |
请完成以下Java代码 | private static final class UserCodeStringKeyGenerator implements StringKeyGenerator {
// @formatter:off
private static final char[] VALID_CHARS = {
'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Z'
};
// @formatter:on
private final BytesKeyGenerator keyGenerator = KeyGenerators.secureRandom(8);
@Override
public String generateKey() {
byte[] bytes = this.keyGenerator.generateKey();
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
int offset = Math.abs(b % 20);
sb.append(VALID_CHARS[offset]);
}
sb.insert(4, '-');
return sb.toString();
}
}
private static final class OAuth2UserCodeGenerator implements OAuth2TokenGenerator<OAuth2UserCode> {
private final StringKeyGenerator userCodeGenerator = new UserCodeStringKeyGenerator();
@Nullable | @Override
public OAuth2UserCode generate(OAuth2TokenContext context) {
if (context.getTokenType() == null
|| !OAuth2ParameterNames.USER_CODE.equals(context.getTokenType().getValue())) {
return null;
}
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt
.plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive());
return new OAuth2UserCode(this.userCodeGenerator.generateKey(), issuedAt, expiresAt);
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2DeviceAuthorizationRequestAuthenticationProvider.java | 1 |
请完成以下Java代码 | public class EntityManagerSessionFactory implements SessionFactory {
protected EntityManagerFactory entityManagerFactory;
protected boolean handleTransactions;
protected boolean closeEntityManager;
public EntityManagerSessionFactory(
Object entityManagerFactory,
boolean handleTransactions,
boolean closeEntityManager
) {
if (entityManagerFactory == null) {
throw new ActivitiIllegalArgumentException("entityManagerFactory is null");
}
if (!(entityManagerFactory instanceof EntityManagerFactory)) {
throw new ActivitiIllegalArgumentException(
"EntityManagerFactory must implement 'jakarta.persistence.EntityManagerFactory'"
);
}
this.entityManagerFactory = (EntityManagerFactory) entityManagerFactory; | this.handleTransactions = handleTransactions;
this.closeEntityManager = closeEntityManager;
}
public Class<?> getSessionType() {
return EntityManagerSession.class;
}
public Session openSession(CommandContext commandContext) {
return new EntityManagerSessionImpl(entityManagerFactory, handleTransactions, closeEntityManager);
}
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\variable\EntityManagerSessionFactory.java | 1 |
请完成以下Java代码 | class StudentComplex {
private String firstName;
private String lastName;
private Course[] courses;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() { | return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Course[] getCourses() {
return courses;
}
public void setCourses(Course[] courses) {
this.courses = courses;
}
} | repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\xwwwformurlencoded\StudentComplex.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class TicketBookingEventHandler {
private final MovieRepository screenRooms;
TicketBookingEventHandler(MovieRepository screenRooms) {
this.screenRooms = screenRooms;
}
@DomainEventHandler
@ApplicationModuleListener
void handleTicketBooked(BookingCreated booking) {
Movie room = screenRooms.findById(booking.movieId())
.orElseThrow();
room.occupySeat(booking.seatNumber());
screenRooms.save(room);
}
@DomainEventHandler
@ApplicationModuleListener
void handleTicketCancelled(BookingCancelled cancellation) { | Movie room = screenRooms.findById(cancellation.movieId())
.orElseThrow();
room.freeSeat(cancellation.seatNumber());
screenRooms.save(room);
}
@EventListener(ApplicationReadyEvent.class)
void insertDummyMovies() {
List<Movie> dummyMovies = LongStream.range(1, 30)
.mapToObj(nr -> new Movie("Dummy movie #" + nr, "Screen #" + nr % 5, Instant.now()
.plus(nr, HOURS)))
.toList();
screenRooms.saveAll(dummyMovies);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-libraries-3\src\main\java\com\baeldung\spring\modulith\cqrs\movie\TicketBookingEventHandler.java | 2 |
请完成以下Java代码 | public VariableMap getVariablesTyped(boolean deserializeValues) {
return getVariablesLocalTyped(deserializeValues);
}
public Map<String, Object> getVariablesLocal() {
return wrappedScope.getVariablesLocal();
}
public VariableMap getVariablesLocalTyped() {
return wrappedScope.getVariablesLocalTyped();
}
public VariableMap getVariablesLocalTyped(boolean deserializeValues) {
return wrappedScope.getVariablesLocalTyped(deserializeValues);
}
public Object getVariable(String variableName) {
return getVariableLocal(variableName);
}
public Object getVariableLocal(String variableName) {
return wrappedScope.getVariableLocal(variableName);
}
public <T extends TypedValue> T getVariableTyped(String variableName) {
return getVariableLocalTyped(variableName);
}
public <T extends TypedValue> T getVariableTyped(String variableName, boolean deserializeValue) {
return getVariableLocalTyped(variableName, deserializeValue);
}
public <T extends TypedValue> T getVariableLocalTyped(String variableName) {
return wrappedScope.getVariableLocalTyped(variableName);
}
public <T extends TypedValue> T getVariableLocalTyped(String variableName, boolean deserializeValue) {
return wrappedScope.getVariableLocalTyped(variableName, deserializeValue);
}
public Set<String> getVariableNames() {
return getVariableNamesLocal();
}
public Set<String> getVariableNamesLocal() {
return wrappedScope.getVariableNamesLocal();
}
public void setVariable(String variableName, Object value) {
setVariableLocal(variableName, value);
}
public void setVariableLocal(String variableName, Object value) {
wrappedScope.setVariableLocal(variableName, value);
} | public void setVariables(Map<String, ? extends Object> variables) {
setVariablesLocal(variables);
}
public void setVariablesLocal(Map<String, ? extends Object> variables) {
wrappedScope.setVariablesLocal(variables);
}
public boolean hasVariables() {
return hasVariablesLocal();
}
public boolean hasVariablesLocal() {
return wrappedScope.hasVariablesLocal();
}
public boolean hasVariable(String variableName) {
return hasVariableLocal(variableName);
}
public boolean hasVariableLocal(String variableName) {
return wrappedScope.hasVariableLocal(variableName);
}
public void removeVariable(String variableName) {
removeVariableLocal(variableName);
}
public void removeVariableLocal(String variableName) {
wrappedScope.removeVariableLocal(variableName);
}
public void removeVariables(Collection<String> variableNames) {
removeVariablesLocal(variableNames);
}
public void removeVariablesLocal(Collection<String> variableNames) {
wrappedScope.removeVariablesLocal(variableNames);
}
public void removeVariables() {
removeVariablesLocal();
}
public void removeVariablesLocal() {
wrappedScope.removeVariablesLocal();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\VariableScopeLocalAdapter.java | 1 |
请完成以下Java代码 | public boolean removeHUIds(final Collection<HuId> huIdsToRemove)
{
return rowsBuffer.removeHUIds(huIdsToRemove);
}
private static Set<HuId> extractHUIds(final Collection<I_M_HU> hus)
{
if (hus == null || hus.isEmpty())
{
return ImmutableSet.of();
}
return hus.stream()
.filter(Objects::nonNull)
.map(I_M_HU::getM_HU_ID)
.map(HuId::ofRepoId)
.collect(Collectors.toSet());
}
@Override
public void notifyRecordsChanged(
@NonNull final TableRecordReferenceSet recordRefs,
final boolean watchedByFrontend)
{
// TODO: notifyRecordsChanged:
// get M_HU_IDs from recordRefs,
// find the top level records from this view which contain our HUs
// invalidate those top levels only
final Set<HuId> huIdsToCheck = recordRefs
.streamIds(I_M_HU.Table_Name, HuId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
if (huIdsToCheck.isEmpty())
{
return;
}
final boolean containsSomeRecords = rowsBuffer.containsAnyOfHUIds(huIdsToCheck);
if (!containsSomeRecords)
{
return;
}
invalidateAll();
}
@Override
public Stream<HUEditorRow> streamByIds(final DocumentIdsSelection rowIds)
{
if (rowIds.isEmpty())
{
return Stream.empty();
}
return streamByIds(HUEditorRowFilter.onlyRowIds(rowIds)); | }
public Stream<HUEditorRow> streamByIds(final HUEditorRowFilter filter)
{
return rowsBuffer.streamByIdsExcludingIncludedRows(filter);
}
/**
* @return top level rows and included rows recursive stream which are matching the given filter
*/
public Stream<HUEditorRow> streamAllRecursive(final HUEditorRowFilter filter)
{
return rowsBuffer.streamAllRecursive(filter);
}
/**
* @return true if there is any top level or included row which is matching given filter
*/
public boolean matchesAnyRowRecursive(final HUEditorRowFilter filter)
{
return rowsBuffer.matchesAnyRowRecursive(filter);
}
@Override
public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass)
{
final Set<HuId> huIds = streamByIds(rowIds)
.filter(HUEditorRow::isPureHU)
.map(HUEditorRow::getHuId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
if (huIds.isEmpty())
{
return ImmutableList.of();
}
final List<I_M_HU> hus = Services.get(IQueryBL.class)
.createQueryBuilder(I_M_HU.class)
.addInArrayFilter(I_M_HU.COLUMN_M_HU_ID, huIds)
.create()
.list(I_M_HU.class);
return InterfaceWrapperHelper.createList(hus, modelClass);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorView.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public GetArticleResult findBySlug(String slug) {
return bus.executeQuery(new GetArticle(slug));
}
@Override
public UpdateArticleResult updateBySlug(String slug, @Valid UpdateArticle command) {
return bus.executeCommand(command.withSlug(slug));
}
@Override
public void deleteBySlug(String slug) {
bus.executeCommand(new DeleteArticle(slug));
}
@Override
public FavoriteArticleResult favorite(String slug) {
return bus.executeCommand(new FavoriteArticle(slug));
}
@Override
public UnfavoriteArticleResult unfavorite(String slug) {
return bus.executeCommand(new UnfavoriteArticle(slug));
}
@Override | public GetCommentsResult findAllComments(String slug) {
return bus.executeQuery(new GetComments(slug));
}
@Override
public AddCommentResult addComment(String slug, @Valid AddComment command) {
return bus.executeCommand(command.withSlug(slug));
}
@Override
public void deleteComment(String slug, Long id) {
bus.executeCommand(new DeleteComment(slug, id));
}
} | repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\infrastructure\web\ArticleController.java | 2 |
请完成以下Java代码 | protected ScopeImpl getScope(PvmExecutionImpl execution) {
ActivityImpl activity = execution.getActivity();
if (activity!=null) {
return activity;
} else {
PvmExecutionImpl parent = execution.getParent();
if (parent != null) {
return getScope(execution.getParent());
}
return execution.getProcessDefinition();
}
}
protected String getEventName() {
return ExecutionListener.EVENTNAME_START;
}
protected void eventNotificationsCompleted(PvmExecutionImpl execution) {
super.eventNotificationsCompleted(execution);
execution.activityInstanceStarted();
ScopeInstantiationContext startContext = execution.getScopeInstantiationContext();
InstantiationStack instantiationStack = startContext.getInstantiationStack();
PvmExecutionImpl propagatingExecution = execution;
ActivityImpl activity = execution.getActivity();
if (activity.getActivityBehavior() instanceof ModificationObserverBehavior) {
ModificationObserverBehavior behavior = (ModificationObserverBehavior) activity.getActivityBehavior();
List<ActivityExecution> concurrentExecutions = behavior.initializeScope(propagatingExecution, 1);
propagatingExecution = (PvmExecutionImpl) concurrentExecutions.get(0);
}
// if the stack has been instantiated
if (instantiationStack.getActivities().isEmpty() && instantiationStack.getTargetActivity() != null) {
// as if we are entering the target activity instance id via a transition
propagatingExecution.setActivityInstanceId(null);
// execute the target activity with this execution
startContext.applyVariables(propagatingExecution);
propagatingExecution.setActivity(instantiationStack.getTargetActivity()); | propagatingExecution.disposeScopeInstantiationContext();
propagatingExecution.performOperation(ACTIVITY_START_CREATE_SCOPE);
}
else if (instantiationStack.getActivities().isEmpty() && instantiationStack.getTargetTransition() != null) {
// as if we are entering the target activity instance id via a transition
propagatingExecution.setActivityInstanceId(null);
// execute the target transition with this execution
PvmTransition transition = instantiationStack.getTargetTransition();
startContext.applyVariables(propagatingExecution);
propagatingExecution.setActivity(transition.getSource());
propagatingExecution.setTransition((TransitionImpl) transition);
propagatingExecution.disposeScopeInstantiationContext();
propagatingExecution.performOperation(TRANSITION_START_NOTIFY_LISTENER_TAKE);
}
else {
// else instantiate the activity stack further
propagatingExecution.setActivity(null);
propagatingExecution.performOperation(ACTIVITY_INIT_STACK);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationActivityInitStackNotifyListenerStart.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void addAllocatedAmt(@NonNull final Money allocatedAmtToAdd)
{
allocatedAmt = allocatedAmt.add(allocatedAmtToAdd);
amountToAllocate = amountToAllocate.subtract(allocatedAmtToAdd);
}
@Override
public LocalDate getDate()
{
return dateTrx;
}
@Override
public boolean isFullyAllocated()
{
return getAmountToAllocate().signum() == 0;
}
private Money getOpenAmtRemaining()
{
final Money totalAllocated = allocatedAmt;
return openAmtInitial.subtract(totalAllocated);
} | @Override
public Money calculateProjectedOverUnderAmt(@NonNull final Money amountToAllocate)
{
return getOpenAmtRemaining().subtract(amountToAllocate);
}
@Override
public boolean canPay(@NonNull final PayableDocument payable)
{
return true;
}
@Override
public Money getPaymentDiscountAmt()
{
return amountToAllocate.toZero();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\PaymentDocument.java | 2 |
请完成以下Java代码 | public IHUAttributeTransferRequestBuilder setQuantity(final Quantity quantity)
{
qty = quantity.toBigDecimal();
uom = quantity.getUOM();
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setAttributeStorageFrom(final IAttributeSet attributeStorageFrom)
{
this.attributeStorageFrom = attributeStorageFrom;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setAttributeStorageTo(final IAttributeStorage attributeStorageTo)
{
this.attributeStorageTo = attributeStorageTo;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setHUStorageFrom(final IHUStorage huStorageFrom)
{
this.huStorageFrom = huStorageFrom;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setHUStorageTo(final IHUStorage huStorageTo)
{
this.huStorageTo = huStorageTo;
return this;
} | @Override
public IHUAttributeTransferRequestBuilder setQtyUnloaded(final BigDecimal qtyUnloaded)
{
this.qtyUnloaded = qtyUnloaded;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setVHUTransfer(final boolean vhuTransfer)
{
this.vhuTransfer = vhuTransfer;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\strategy\impl\HUAttributeTransferRequestBuilder.java | 1 |
请完成以下Java代码 | public List<HuId> getClosedLUs(
@NonNull final WFProcessId wfProcessId,
@Nullable final PickingJobLineId lineId,
@NonNull final UserId callerId)
{
final WFProcess wfProcess = getWFProcessById(wfProcessId);
wfProcess.assertHasAccess(callerId);
final PickingJob pickingJob = getPickingJob(wfProcess);
return pickingJobRestService.getClosedLUs(pickingJob, lineId);
}
public WFProcess pickAll(@NonNull final WFProcessId wfProcessId, @NonNull final UserId callerId)
{
final PickingJobId pickingJobId = toPickingJobId(wfProcessId);
final PickingJob pickingJob = pickingJobRestService.pickAll(pickingJobId, callerId);
return toWFProcess(pickingJob);
}
public PickingJobQtyAvailable getQtyAvailable(final WFProcessId wfProcessId, final @NotNull UserId callerId)
{
final PickingJobId pickingJobId = toPickingJobId(wfProcessId);
return pickingJobRestService.getQtyAvailable(pickingJobId, callerId);
} | public JsonGetNextEligibleLineResponse getNextEligibleLineToPack(final @NonNull JsonGetNextEligibleLineRequest request, final @NotNull UserId callerId)
{
final GetNextEligibleLineToPackResponse response = pickingJobRestService.getNextEligibleLineToPack(
GetNextEligibleLineToPackRequest.builder()
.callerId(callerId)
.pickingJobId(toPickingJobId(request.getWfProcessId()))
.excludeLineId(request.getExcludeLineId())
.huScannedCode(request.getHuScannedCode())
.build()
);
return JsonGetNextEligibleLineResponse.builder()
.lineId(response.getLineId())
.logs(response.getLogs())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\PickingMobileApplication.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private AssertionConsumerService buildAssertionConsumerService(RelyingPartyRegistration registration) {
AssertionConsumerService assertionConsumerService = this.saml
.build(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
assertionConsumerService.setLocation(registration.getAssertionConsumerServiceLocation());
assertionConsumerService.setBinding(registration.getAssertionConsumerServiceBinding().getUrn());
assertionConsumerService.setIndex(1);
return assertionConsumerService;
}
private SingleLogoutService buildSingleLogoutService(RelyingPartyRegistration registration,
Saml2MessageBinding binding) {
SingleLogoutService singleLogoutService = this.saml.build(SingleLogoutService.DEFAULT_ELEMENT_NAME);
singleLogoutService.setLocation(registration.getSingleLogoutServiceLocation());
singleLogoutService.setResponseLocation(registration.getSingleLogoutServiceResponseLocation());
singleLogoutService.setBinding(binding.getUrn());
return singleLogoutService;
}
private NameIDFormat buildNameIDFormat(RelyingPartyRegistration registration) {
NameIDFormat nameIdFormat = this.saml.build(NameIDFormat.DEFAULT_ELEMENT_NAME);
nameIdFormat.setURI(registration.getNameIdFormat());
return nameIdFormat;
}
private String serialize(EntityDescriptor entityDescriptor) {
return this.saml.serialize(entityDescriptor).prettyPrint(this.usePrettyPrint).serialize();
}
private String serialize(EntitiesDescriptor entities) {
return this.saml.serialize(entities).prettyPrint(this.usePrettyPrint).serialize();
}
/**
* Configure whether to sign the metadata, defaults to {@code false}.
*
* @since 6.4
*/
void setSignMetadata(boolean signMetadata) {
this.signMetadata = signMetadata;
} | /**
* A tuple containing an OpenSAML {@link EntityDescriptor} and its associated
* {@link RelyingPartyRegistration}
*
* @since 5.7
*/
static final class EntityDescriptorParameters {
private final EntityDescriptor entityDescriptor;
private final RelyingPartyRegistration registration;
EntityDescriptorParameters(EntityDescriptor entityDescriptor, RelyingPartyRegistration registration) {
this.entityDescriptor = entityDescriptor;
this.registration = registration;
}
EntityDescriptor getEntityDescriptor() {
return this.entityDescriptor;
}
RelyingPartyRegistration getRelyingPartyRegistration() {
return this.registration;
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\metadata\BaseOpenSamlMetadataResolver.java | 2 |
请完成以下Java代码 | public class ProcessArchiveXmlImpl implements ProcessArchiveXml {
private String name;
private String tenantId;
private String processEngineName;
private List<String> processResourceNames;
private Map<String, String> properties;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getProcessEngineName() {
return processEngineName; | }
public void setProcessEngineName(String processEngineName) {
this.processEngineName = processEngineName;
}
public List<String> getProcessResourceNames() {
return processResourceNames;
}
public void setProcessResourceNames(List<String> processResourceNames) {
this.processResourceNames = processResourceNames;
}
public Map<String, String> getProperties() {
return properties;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\metadata\ProcessArchiveXmlImpl.java | 1 |
请完成以下Java代码 | public PageData<EntityView> findEntityViewsByTenantIdAndEdgeId(TenantId tenantId, EdgeId edgeId, PageLink pageLink) {
log.trace("Executing findEntityViewsByTenantIdAndEdgeId, tenantId [{}], edgeId [{}], pageLink [{}]", tenantId, edgeId, pageLink);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
validateId(edgeId, id -> INCORRECT_EDGE_ID + id);
validatePageLink(pageLink);
return entityViewDao.findEntityViewsByTenantIdAndEdgeId(tenantId.getId(), edgeId.getId(), pageLink);
}
@Override
public PageData<EntityView> findEntityViewsByTenantIdAndEdgeIdAndType(TenantId tenantId, EdgeId edgeId, String type, PageLink pageLink) {
log.trace("Executing findEntityViewsByTenantIdAndEdgeIdAndType, tenantId [{}], edgeId [{}], type [{}], pageLink [{}]", tenantId, edgeId, type, pageLink);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
validateId(edgeId, id -> INCORRECT_EDGE_ID + id);
validateString(type, t -> "Incorrect type " + t);
validatePageLink(pageLink);
return entityViewDao.findEntityViewsByTenantIdAndEdgeIdAndType(tenantId.getId(), edgeId.getId(), type, pageLink);
}
private final PaginatedRemover<TenantId, EntityView> tenantEntityViewRemover = new PaginatedRemover<>() {
@Override
protected PageData<EntityView> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return entityViewDao.findEntityViewsByTenantId(id.getId(), pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, EntityView entity) {
deleteEntityView(tenantId, new EntityViewId(entity.getUuidId()));
}
};
private final PaginatedRemover<CustomerId, EntityView> customerEntityViewsRemover = new PaginatedRemover<>() {
@Override
protected PageData<EntityView> findEntities(TenantId tenantId, CustomerId id, PageLink pageLink) {
return entityViewDao.findEntityViewsByTenantIdAndCustomerId(tenantId.getId(), id.getId(), pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, EntityView entity) {
unassignEntityViewFromCustomer(tenantId, new EntityViewId(entity.getUuidId()));
}
}; | @Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findEntityViewById(tenantId, new EntityViewId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(findEntityViewByIdAsync(tenantId, new EntityViewId(entityId.getId())))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.ENTITY_VIEW;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\entityview\EntityViewServiceImpl.java | 1 |
请完成以下Java代码 | protected Class<? extends ProcessApplicationInterface> getBusinessInterface() {
return ProcessApplicationInterface.class;
}
@Override
public <T> T execute(Callable<T> callable) throws ProcessApplicationExecutionException {
ClassLoader originalClassloader = ClassLoaderUtil.getContextClassloader();
ClassLoader processApplicationClassloader = getProcessApplicationClassloader();
try {
if (originalClassloader != processApplicationClassloader) {
ClassLoaderUtil.setContextClassloader(processApplicationClassloader);
}
return callable.call();
}
catch(Exception e) {
throw LOG.processApplicationExecutionException(e);
}
finally {
ClassLoaderUtil.setContextClassloader(originalClassloader);
}
}
protected void ensureInitialized() {
if(selfReference == null) {
selfReference = lookupSelfReference();
}
ensureEjbProcessApplicationReferenceInitialized();
}
protected abstract void ensureEjbProcessApplicationReferenceInitialized();
protected abstract ProcessApplicationReference getEjbProcessApplicationReference();
/**
* lookup a proxy object representing the invoked business view of this component.
*/
protected abstract ProcessApplicationInterface lookupSelfReference();
/**
* determine the ee application name based on information obtained from JNDI.
*/
protected String lookupEeApplicationName() { | try {
InitialContext initialContext = new InitialContext();
String appName = (String) initialContext.lookup(JAVA_APP_APP_NAME_PATH);
String moduleName = (String) initialContext.lookup(MODULE_NAME_PATH);
// make sure that if an EAR carries multiple PAs, they are correctly
// identified by appName + moduleName
if (moduleName != null && !moduleName.equals(appName)) {
return appName + "/" + moduleName;
} else {
return appName;
}
}
catch (NamingException e) {
throw LOG.ejbPaCannotAutodetectName(e);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\AbstractEjbProcessApplication.java | 1 |
请完成以下Java代码 | private void addKeyValue_Attribute(List<Object> values, ModelType model, AggregationItem aggregationItem)
{
final AggregationAttribute attribute = aggregationItem.getAttribute();
final Evaluatee ctx = InterfaceWrapperHelper.getEvaluatee(model);
Object value = attribute.evaluate(ctx);
values.add(value);
}
private Object normalizeValue(final Object value, final ModelType model, final AggregationItem aggregationItem)
{
final int displayType = aggregationItem.getDisplayType();
if (DisplayType.isID(displayType))
{
final Integer valueInt = (Integer)value;
if (valueInt == null)
{
return 0;
}
else if (valueInt <= 0)
{
return 0;
}
else
{
return valueInt;
}
}
else if (displayType == DisplayType.Date)
{
return value == null ? null : dateFormat.format(value);
}
else if (displayType == DisplayType.Time)
{
return value == null ? null : timeFormat.format(value);
}
else if (displayType == DisplayType.DateTime) | {
return value == null ? null : dateTimeFormat.format(value);
}
else if (DisplayType.isText(displayType))
{
return value == null ? 0 : toHashcode(value.toString());
}
else if (displayType == DisplayType.YesNo)
{
return DisplayType.toBooleanNonNull(value, false);
}
else
{
return value;
}
}
private static int toHashcode(final String s)
{
if (Check.isEmpty(s, true))
{
return 0;
}
return s.hashCode();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\api\impl\GenericAggregationKeyBuilder.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getGrowth() {
return growth;
}
public void setGrowth(Integer growth) {
this.growth = growth;
}
public Integer getIntergration() {
return intergration;
} | public void setIntergration(Integer intergration) {
this.intergration = intergration;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", growth=").append(growth);
sb.append(", intergration=").append(intergration);
sb.append(", type=").append(type);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberTask.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void logSendToMetasfresh(final String queueName, final RequestToMetasfresh message)
{
log(queueName,
"OUT",
message,
message.getEventId(),
null);
}
public void logReceivedFromMetasfresh(final String queueName, final RequestToProcurementWeb message)
{
log(queueName,
"IN",
message,
message.getEventId(),
message.getRelatedEventId());
}
private void log(
final String queueName,
final String direction,
final Object message,
final String eventId,
final String relatedEventId)
{
try
{
final RabbitMQAuditEntry entry = new RabbitMQAuditEntry();
entry.setQueue(queueName);
entry.setDirection(direction);
entry.setContent(Ascii.truncate(convertToString(message), RabbitMQAuditEntry.CONTENT_LENGTH, "...")); | entry.setEventId(eventId);
entry.setRelatedEventId(relatedEventId);
repository.save(entry);
}
catch (Exception ex)
{
logger.warn("Failed saving audit entry for queueName={}, direction={}, message=`{}`.", queueName, direction, message, ex);
}
}
private String convertToString(@NonNull final Object message)
{
try
{
return Constants.PROCUREMENT_WEBUI_OBJECT_MAPPER.writeValueAsString(message);
}
catch (final Exception ex)
{
logger.warn("Failed converting message to JSON: {}. Returning toString().", message, ex);
return message.toString();
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\RabbitMQAuditService.java | 2 |
请完成以下Java代码 | private Integer dayOfWeek(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_WEEK);
}
@Override
public BatchWindow getCurrentOrNextBatchWindow(Date date, ProcessEngineConfigurationImpl configuration) {
final BatchWindow previousDayBatchWindow = getPreviousDayBatchWindow(date, configuration);
if (previousDayBatchWindow != null && previousDayBatchWindow.isWithin(date)) {
return previousDayBatchWindow;
}
final BatchWindow currentDayBatchWindow = getBatchWindowForDate(date, configuration);
if (currentDayBatchWindow!= null && (currentDayBatchWindow.isWithin(date) || date.before(currentDayBatchWindow.getStart()))) {
return currentDayBatchWindow;
}
//check next week
for (int i=1; i<=7; i++ ) {
Date dateToCheck = addDays(date, i);
final BatchWindow batchWindowForDate = getBatchWindowForDate(dateToCheck, configuration);
if (batchWindowForDate != null) {
return batchWindowForDate;
}
}
return null;
}
@Override
public BatchWindow getNextBatchWindow(Date date, ProcessEngineConfigurationImpl configuration) {
final BatchWindow currentDayBatchWindow = getBatchWindowForDate(date, configuration);
if (currentDayBatchWindow != null && date.before(currentDayBatchWindow.getStart())) {
return currentDayBatchWindow;
} else {
//check next week
for (int i=1; i<=7; i++ ) {
Date dateToCheck = addDays(date, i);
final BatchWindow batchWindowForDate = getBatchWindowForDate(dateToCheck, configuration);
if (batchWindowForDate != null) { | return batchWindowForDate;
}
}
}
return null;
}
@Override
public boolean isBatchWindowConfigured(ProcessEngineConfigurationImpl configuration) {
return configuration.getHistoryCleanupBatchWindowStartTimeAsDate() != null ||
!configuration.getHistoryCleanupBatchWindows().isEmpty();
}
private static Date updateTime(Date now, Date newTime) {
Calendar c = Calendar.getInstance();
c.setTime(now);
Calendar newTimeCalendar = Calendar.getInstance();
newTimeCalendar.setTime(newTime);
c.set(Calendar.ZONE_OFFSET, newTimeCalendar.get(Calendar.ZONE_OFFSET));
c.set(Calendar.DST_OFFSET, newTimeCalendar.get(Calendar.DST_OFFSET));
c.set(Calendar.HOUR_OF_DAY, newTimeCalendar.get(Calendar.HOUR_OF_DAY));
c.set(Calendar.MINUTE, newTimeCalendar.get(Calendar.MINUTE));
c.set(Calendar.SECOND, newTimeCalendar.get(Calendar.SECOND));
c.set(Calendar.MILLISECOND, newTimeCalendar.get(Calendar.MILLISECOND));
return c.getTime();
}
private static Date addDays(Date date, int amount) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, amount);
return c.getTime();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\DefaultBatchWindowManager.java | 1 |
请完成以下Java代码 | protected void writeInternal(OAuth2AccessTokenResponse tokenResponse, HttpOutputMessage outputMessage)
throws HttpMessageNotWritableException {
try {
Map<String, Object> tokenResponseParameters = this.accessTokenResponseParametersConverter
.convert(tokenResponse);
this.jsonMessageConverter.write(tokenResponseParameters, STRING_OBJECT_MAP.getType(),
MediaType.APPLICATION_JSON, outputMessage);
}
catch (Exception ex) {
throw new HttpMessageNotWritableException(
"An error occurred writing the OAuth 2.0 Access Token Response: " + ex.getMessage(), ex);
}
}
/**
* Sets the {@link Converter} used for converting the OAuth 2.0 Access Token Response
* parameters to an {@link OAuth2AccessTokenResponse}.
* @param accessTokenResponseConverter the {@link Converter} used for converting to an
* {@link OAuth2AccessTokenResponse}
* @since 5.6
*/
public final void setAccessTokenResponseConverter(
Converter<Map<String, Object>, OAuth2AccessTokenResponse> accessTokenResponseConverter) { | Assert.notNull(accessTokenResponseConverter, "accessTokenResponseConverter cannot be null");
this.accessTokenResponseConverter = accessTokenResponseConverter;
}
/**
* Sets the {@link Converter} used for converting the
* {@link OAuth2AccessTokenResponse} to a {@code Map} representation of the OAuth 2.0
* Access Token Response parameters.
* @param accessTokenResponseParametersConverter the {@link Converter} used for
* converting to a {@code Map} representation of the Access Token Response parameters
* @since 5.6
*/
public final void setAccessTokenResponseParametersConverter(
Converter<OAuth2AccessTokenResponse, Map<String, Object>> accessTokenResponseParametersConverter) {
Assert.notNull(accessTokenResponseParametersConverter, "accessTokenResponseParametersConverter cannot be null");
this.accessTokenResponseParametersConverter = accessTokenResponseParametersConverter;
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\http\converter\OAuth2AccessTokenResponseHttpMessageConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UpdateSalesOrderFromPurchaseOrderProjectListener implements PurchaseOrderProjectListener
{
@NonNull private final PurchaseCandidateRepository purchaseCandidateRepo;
private final IOrderDAO orderDAO = Services.get(IOrderDAO.class);
@Override
public void onCreated(@NonNull final ProjectCreatedEvent event)
{
@NonNull final ProjectId projectId = event.getProjectId();
@NonNull final Collection<OrderAndLineId> purchaseOrderLineIds = event.getPurchaseOrderLineIds();
final Set<OrderAndLineId> salesOrderAndLineIds = purchaseCandidateRepo.getAllByPurchaseOrderLineIds(purchaseOrderLineIds)
.stream()
.map(PurchaseCandidate::getSalesOrderAndLineIdOrNull)
.filter(Objects::nonNull)
.collect(Collectors.toSet()); | final Set<OrderId> salesOrderIds = OrderAndLineId.getOrderIds(salesOrderAndLineIds);
final Set<OrderLineId> salesOrderLineIds = OrderAndLineId.getOrderLineIds(salesOrderAndLineIds);
final List<I_C_OrderLine> orderLines = orderDAO.retrieveOrderLinesByOrderIds(salesOrderIds);
//persist the ProjectId on all related order lines
final Set<I_C_OrderLine> updatedOrderLines = orderLines.stream()
.filter(orderLine -> salesOrderLineIds.contains(OrderLineId.ofRepoId(orderLine.getC_OrderLine_ID())))
.filter(orderLine -> ProjectId.ofRepoIdOrNull(orderLine.getC_Project_ID()) == null)
.peek(orderLine -> orderLine.setC_Project_ID(projectId.getRepoId()))
.collect(Collectors.toSet());
InterfaceWrapperHelper.saveAll(updatedOrderLines);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\UpdateSalesOrderFromPurchaseOrderProjectListener.java | 2 |
请完成以下Java代码 | private static POSTerminalPaymentProcessorConfig extractPaymentProcessorConfig(final I_C_POS record)
{
final POSPaymentProcessorType type = POSPaymentProcessorType.ofNullableCode(record.getPOSPaymentProcessor());
if (type == null)
{
return null;
}
return POSTerminalPaymentProcessorConfig.builder()
.type(type)
.sumUpConfigId(SumUpConfigId.ofRepoIdOrNull(record.getSUMUP_Config_ID()))
.build();
}
private POSShipFrom extractShipFrom(final I_C_POS record)
{
final WarehouseId shipFromWarehouseId = WarehouseId.ofRepoId(record.getM_Warehouse_ID());
return POSShipFrom.builder()
.warehouseId(shipFromWarehouseId)
.clientAndOrgId(warehouseBL.getWarehouseClientAndOrgId(shipFromWarehouseId))
.countryId(warehouseBL.getCountryId(shipFromWarehouseId))
.build();
}
private @NonNull BPartnerLocationAndCaptureId extractWalkInCustomerShipTo(final I_C_POS record)
{
final BPartnerId walkInCustomerId = BPartnerId.ofRepoId(record.getC_BPartnerCashTrx_ID());
return BPartnerLocationAndCaptureId.ofRecord( | bpartnerDAO.retrieveBPartnerLocation(BPartnerLocationQuery.builder()
.type(BPartnerLocationQuery.Type.SHIP_TO)
.bpartnerId(walkInCustomerId)
.build())
);
}
public POSTerminal updateById(@NonNull final POSTerminalId posTerminalId, @NonNull final UnaryOperator<POSTerminal> updater)
{
return trxManager.callInThreadInheritedTrx(() -> {
final I_C_POS record = retrieveRecordById(posTerminalId);
final POSTerminal posTerminalBeforeChange = fromRecord(record);
final POSTerminal posTerminal = updater.apply(posTerminalBeforeChange);
if (Objects.equals(posTerminal, posTerminalBeforeChange))
{
return posTerminalBeforeChange;
}
updateRecord(record, posTerminal);
InterfaceWrapperHelper.save(record);
return posTerminal;
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSTerminalService.java | 1 |
请完成以下Java代码 | public int getP_Revenue_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_P_Revenue_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Recognized Amount.
@param RecognizedAmt Recognized Amount */
public void setRecognizedAmt (BigDecimal RecognizedAmt)
{
set_ValueNoCheck (COLUMNNAME_RecognizedAmt, RecognizedAmt);
}
/** Get Recognized Amount.
@return Recognized Amount */
public BigDecimal getRecognizedAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RecognizedAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Total Amount.
@param TotalAmt
Total Amount
*/
public void setTotalAmt (BigDecimal TotalAmt)
{
set_ValueNoCheck (COLUMNNAME_TotalAmt, TotalAmt);
}
/** Get Total Amount.
@return Total Amount
*/
public BigDecimal getTotalAmt () | {
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_C_ValidCombination getUnEarnedRevenue_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getUnEarnedRevenue_Acct(), get_TrxName()); }
/** Set Unearned Revenue.
@param UnEarnedRevenue_Acct
Account for unearned revenue
*/
public void setUnEarnedRevenue_Acct (int UnEarnedRevenue_Acct)
{
set_ValueNoCheck (COLUMNNAME_UnEarnedRevenue_Acct, Integer.valueOf(UnEarnedRevenue_Acct));
}
/** Get Unearned Revenue.
@return Account for unearned revenue
*/
public int getUnEarnedRevenue_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UnEarnedRevenue_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RevenueRecognition_Plan.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CustomRouteController customRouteController()
{
return new CustomRouteController(this.camelContext);
}
@Bean
CamelContextConfiguration contextConfiguration(
@NonNull final MetasfreshAuthProvider metasfreshAuthProvider,
@NonNull final CustomRouteController customRouteController,
@NonNull final ProducerTemplate producerTemplate
)
{
return new CamelContextConfiguration()
{
@Override
public void beforeApplicationStart(final CamelContext camelContext)
{
camelContext.setAutoStartup(false);
final Environment env = context.getEnvironment();
logger.log(Level.INFO, "Configured RabbitMQ hostname:port is {}:{}", env.getProperty("camel.component.rabbitmq.hostname"), env.getProperty("camel.component.rabbitmq.port-number"));
final String metasfreshAPIBaseURL = context.getEnvironment().getProperty(ExternalSystemCamelConstants.MF_API_BASE_URL_PROPERTY);
if (Check.isBlank(metasfreshAPIBaseURL))
{ | throw new RuntimeException("Missing mandatory property! property = " + ExternalSystemCamelConstants.MF_API_BASE_URL_PROPERTY);
}
camelContext.getManagementStrategy()
.addEventNotifier(new MetasfreshAuthorizationTokenNotifier(metasfreshAuthProvider, metasfreshAPIBaseURL, customRouteController, producerTemplate));
camelContext.getManagementStrategy()
.addEventNotifier(new AuditEventNotifier(producerTemplate));
}
@Override
public void afterApplicationStart(final CamelContext camelContext)
{
customRouteController().startAlwaysRunningRoutes();
producerTemplate
.sendBody("direct:" + CUSTOM_TO_MF_ROUTE_ID, "Trigger external system authentication!");
}
};
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\AppConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ChartOfAccountsRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final CCache<Integer, ChartOfAccountsMap> cache = CCache.<Integer, ChartOfAccountsMap>builder()
.tableName(I_C_Element.Table_Name)
.build();
private ChartOfAccountsMap getMap()
{
return cache.getOrLoad(0, this::retrieveMap);
}
private ChartOfAccountsMap retrieveMap()
{
return new ChartOfAccountsMap(
queryBL.createQueryBuilder(I_C_Element.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(ChartOfAccountsRepository::fromRecord)
.collect(ImmutableList.toImmutableList()));
}
private static ChartOfAccounts fromRecord(@NonNull final I_C_Element record)
{
return ChartOfAccounts.builder()
.id(ChartOfAccountsId.ofRepoId(record.getC_Element_ID()))
.name(record.getName())
.clientId(ClientId.ofRepoId(record.getAD_Client_ID()))
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.treeId(AdTreeId.ofRepoId(record.getAD_Tree_ID()))
.build();
}
public ChartOfAccounts getById(final ChartOfAccountsId chartOfAccountsId)
{
return getMap().getById(chartOfAccountsId);
}
public List<ChartOfAccounts> getByIds(final Set<ChartOfAccountsId> chartOfAccountsIds)
{
return getMap().getByIds(chartOfAccountsIds);
} | public Optional<ChartOfAccounts> getByName(@NonNull final String chartOfAccountsName, @NonNull final ClientId clientId, @NonNull final OrgId orgId)
{
return getMap().getByName(chartOfAccountsName, clientId, orgId);
}
public Optional<ChartOfAccounts> getByTreeId(@NonNull final AdTreeId treeId)
{
return getMap().getByTreeId(treeId);
}
ChartOfAccounts createChartOfAccounts(
@NonNull final String name,
@NonNull final ClientId clientId,
@NonNull final OrgId orgId,
@NonNull final AdTreeId chartOfAccountsTreeId)
{
final I_C_Element record = InterfaceWrapperHelper.newInstance(I_C_Element.class);
InterfaceWrapperHelper.setValue(record, I_C_Element.COLUMNNAME_AD_Client_ID, clientId.getRepoId());
record.setAD_Org_ID(orgId.getRepoId());
record.setName(name);
record.setAD_Tree_ID(chartOfAccountsTreeId.getRepoId());
record.setElementType(X_C_Element.ELEMENTTYPE_Account);
record.setIsNaturalAccount(true);
InterfaceWrapperHelper.save(record);
return fromRecord(record);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\elementvalue\ChartOfAccountsRepository.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.