instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public Mono<Void> fireAndForget(Payload payload) {
try {
dataPublisher.publish(payload); // forward the payload
return Mono.empty();
} catch (Exception x) {
return Mono.error(x);
}
}
/**
* Handle Request/Stream messages. Each request returns a new stream.
*
* @param payload Payload that can be used to determine which stream to return
* @return Flux stream containing simulated measurement data
*/
@Override
public Flux<Payload> requestStream(Payload payload) {
String streamName = payload.getDataUtf8();
if (DATA_STREAM_NAME.equals(streamName)) {
return Flux.from(dataPublisher);
}
return Flux.error(new IllegalArgumentException(streamName));
}
/** | * Handle request for bidirectional channel
*
* @param payloads Stream of payloads delivered from the client
* @return
*/
@Override
public Flux<Payload> requestChannel(Publisher<Payload> payloads) {
Flux.from(payloads)
.subscribe(gameController::processPayload);
Flux<Payload> channel = Flux.from(gameController);
return channel;
}
}
} | repos\tutorials-master\spring-reactive-modules\rsocket\src\main\java\com\baeldung\rsocket\Server.java | 1 |
请完成以下Java代码 | public class ScriptTaskXMLConverter extends BaseBpmnXMLConverter {
protected Map<String, BaseChildElementParser> childParserMap = new HashMap<String, BaseChildElementParser>();
public ScriptTaskXMLConverter() {
ScriptTextParser scriptTextParser = new ScriptTextParser();
childParserMap.put(scriptTextParser.getElementName(), scriptTextParser);
}
public Class<? extends BaseElement> getBpmnElementType() {
return ScriptTask.class;
}
@Override
protected String getXMLElementName() {
return ELEMENT_TASK_SCRIPT;
}
@Override
protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception {
ScriptTask scriptTask = new ScriptTask();
BpmnXMLUtil.addXMLLocation(scriptTask, xtr);
scriptTask.setScriptFormat(xtr.getAttributeValue(null, ATTRIBUTE_TASK_SCRIPT_FORMAT));
scriptTask.setResultVariable(
xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_TASK_SCRIPT_RESULTVARIABLE)
);
if (StringUtils.isEmpty(scriptTask.getResultVariable())) {
scriptTask.setResultVariable(
xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_TASK_SERVICE_RESULTVARIABLE)
);
}
String autoStoreVariables = xtr.getAttributeValue(
ACTIVITI_EXTENSIONS_NAMESPACE,
ATTRIBUTE_TASK_SCRIPT_AUTO_STORE_VARIABLE
);
if (StringUtils.isNotEmpty(autoStoreVariables)) {
scriptTask.setAutoStoreVariables(Boolean.valueOf(autoStoreVariables));
}
parseChildElements(getXMLElementName(), scriptTask, childParserMap, model, xtr);
return scriptTask;
}
@Override
protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw) | throws Exception {
ScriptTask scriptTask = (ScriptTask) element;
writeDefaultAttribute(ATTRIBUTE_TASK_SCRIPT_FORMAT, scriptTask.getScriptFormat(), xtw);
writeQualifiedAttribute(ATTRIBUTE_TASK_SCRIPT_RESULTVARIABLE, scriptTask.getResultVariable(), xtw);
writeQualifiedAttribute(
ATTRIBUTE_TASK_SCRIPT_AUTO_STORE_VARIABLE,
String.valueOf(scriptTask.isAutoStoreVariables()),
xtw
);
}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
ScriptTask scriptTask = (ScriptTask) element;
if (StringUtils.isNotEmpty(scriptTask.getScript())) {
xtw.writeStartElement(ATTRIBUTE_TASK_SCRIPT_TEXT);
xtw.writeCData(scriptTask.getScript());
xtw.writeEndElement();
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\ScriptTaskXMLConverter.java | 1 |
请完成以下Java代码 | public class ExecuteDecisionCmd extends AbstractExecuteDecisionCmd implements Command<Void> {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory.getLogger(ExecuteDecisionCmd.class);
public ExecuteDecisionCmd(ExecuteDecisionBuilderImpl decisionBuilder) {
super(decisionBuilder);
}
public ExecuteDecisionCmd(String decisionKey, Map<String, Object> variables) {
super(decisionKey, variables);
}
public ExecuteDecisionCmd(String decisionKey, String parentDeploymentId, Map<String, Object> variables) {
this(decisionKey, variables);
executeDecisionContext.setParentDeploymentId(parentDeploymentId);
}
public ExecuteDecisionCmd(String decisionKey, String parentDeploymentId, Map<String, Object> variables, String tenantId) {
this(decisionKey, parentDeploymentId, variables);
executeDecisionContext.setTenantId(tenantId);
} | public ExecuteDecisionCmd(ExecuteDecisionContext executeDecisionContext) {
super(executeDecisionContext);
}
@Override
public Void execute(CommandContext commandContext) {
if (executeDecisionContext.getDecisionKey() == null) {
throw new FlowableIllegalArgumentException("decisionKey is null");
}
DmnDefinition definition = resolveDefinition();
execute(commandContext, definition);
return null;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\cmd\ExecuteDecisionCmd.java | 1 |
请完成以下Java代码 | public void setMaxLoadWeight (final @Nullable BigDecimal MaxLoadWeight)
{
set_Value (COLUMNNAME_MaxLoadWeight, MaxLoadWeight);
}
@Override
public BigDecimal getMaxLoadWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxLoadWeight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_HU_PackingMaterial_ID (final int M_HU_PackingMaterial_ID)
{
if (M_HU_PackingMaterial_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PackingMaterial_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PackingMaterial_ID, M_HU_PackingMaterial_ID);
}
@Override
public int getM_HU_PackingMaterial_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PackingMaterial_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override | public void setStackabilityFactor (final int StackabilityFactor)
{
set_Value (COLUMNNAME_StackabilityFactor, StackabilityFactor);
}
@Override
public int getStackabilityFactor()
{
return get_ValueAsInt(COLUMNNAME_StackabilityFactor);
}
@Override
public void setWidth (final @Nullable BigDecimal Width)
{
set_Value (COLUMNNAME_Width, Width);
}
@Override
public BigDecimal getWidth()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PackingMaterial.java | 1 |
请完成以下Java代码 | public DeadLetterJobEntity findJobById(String jobId) {
return (DeadLetterJobEntity) getDbSqlSession().selectOne("selectDeadLetterJob", jobId);
}
@SuppressWarnings("unchecked")
public List<DeadLetterJobEntity> findDeadLetterJobsByDuedate(Date duedate, Page page) {
final String query = "selectDeadLetterJobsByDuedate";
return getDbSqlSession().selectList(query, duedate, page);
}
@SuppressWarnings("unchecked")
public List<DeadLetterJobEntity> findDeadLetterJobsByExecutionId(String executionId) {
return getDbSqlSession().selectList("selectDeadLetterJobsByExecutionId", executionId);
}
@SuppressWarnings("unchecked")
public List<Job> findJobsByQueryCriteria(JobQueryImpl jobQuery, Page page) {
final String query = "selectDeadLetterJobByQueryCriteria";
return getDbSqlSession().selectList(query, jobQuery, page);
}
@SuppressWarnings("unchecked")
public List<Job> findDeadLetterJobsByTypeAndProcessDefinitionKeyNoTenantId(String jobHandlerType, String processDefinitionKey) {
Map<String, String> params = new HashMap<>(2);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionKey", processDefinitionKey);
return getDbSqlSession().selectList("selectDeadLetterJobByTypeAndProcessDefinitionKeyNoTenantId", params);
}
@SuppressWarnings("unchecked")
public List<Job> findDeadLetterJobsByTypeAndProcessDefinitionKeyAndTenantId(String jobHandlerType, String processDefinitionKey, String tenantId) { | Map<String, String> params = new HashMap<>(3);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionKey", processDefinitionKey);
params.put("tenantId", tenantId);
return getDbSqlSession().selectList("selectDeadLetterJobByTypeAndProcessDefinitionKeyAndTenantId", params);
}
@SuppressWarnings("unchecked")
public List<Job> findDeadLetterJobsByTypeAndProcessDefinitionId(String jobHandlerType, String processDefinitionId) {
Map<String, String> params = new HashMap<>(2);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionId", processDefinitionId);
return getDbSqlSession().selectList("selectDeadLetterJobByTypeAndProcessDefinitionId", params);
}
public long findDeadLetterJobCountByQueryCriteria(JobQueryImpl jobQuery) {
return (Long) getDbSqlSession().selectOne("selectDeadLetterJobCountByQueryCriteria", jobQuery);
}
public void updateDeadLetterJobTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateDeadLetterJobTenantIdForDeployment", params);
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\DeadLetterJobEntityManager.java | 1 |
请完成以下Java代码 | public void rejectIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void voidIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void closeIt(final DocumentTableFields docFields)
{
final I_C_RfQ rfq = extractRfQ(docFields);
//
rfqEventDispacher.fireBeforeClose(rfq);
//
// Mark as closed
rfq.setDocStatus(X_C_RfQ.DOCSTATUS_Closed);
rfq.setDocAction(X_C_RfQ.DOCACTION_None);
rfq.setProcessed(true);
rfq.setIsRfQResponseAccepted(false);
InterfaceWrapperHelper.save(rfq);
//
// Close RfQ Responses
for (final I_C_RfQResponse rfqResponse : rfqDAO.retrieveAllResponses(rfq))
{
if (!rfqBL.isDraft(rfqResponse))
{
continue;
}
rfqBL.complete(rfqResponse);
}
//
rfqEventDispacher.fireAfterClose(rfq);
// Make sure it's saved
InterfaceWrapperHelper.save(rfq);
}
@Override
public void unCloseIt(final DocumentTableFields docFields)
{
final I_C_RfQ rfq = extractRfQ(docFields);
//
rfqEventDispacher.fireBeforeUnClose(rfq);
//
// Mark as completed
rfq.setDocStatus(X_C_RfQ.DOCSTATUS_Completed);
rfq.setDocAction(X_C_RfQ.DOCACTION_Close);
InterfaceWrapperHelper.save(rfq);
//
// UnClose RfQ Responses
for (final I_C_RfQResponse rfqResponse : rfqDAO.retrieveAllResponses(rfq))
{
if (!rfqBL.isClosed(rfqResponse))
{ | continue;
}
rfqBL.unclose(rfqResponse);
}
//
rfqEventDispacher.fireAfterUnClose(rfq);
// Make sure it's saved
InterfaceWrapperHelper.save(rfq);
}
@Override
public void reverseCorrectIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void reverseAccrualIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void reactivateIt(final DocumentTableFields docFields)
{
final I_C_RfQ rfq = extractRfQ(docFields);
//
// Void and delete all responses
for (final I_C_RfQResponse rfqResponse : rfqDAO.retrieveAllResponses(rfq))
{
voidAndDelete(rfqResponse);
}
rfq.setIsRfQResponseAccepted(false);
rfq.setDocAction(IDocument.ACTION_Complete);
rfq.setProcessed(false);
}
private void voidAndDelete(final I_C_RfQResponse rfqResponse)
{
// Prevent deleting/voiding an already closed RfQ response
if (rfqBL.isClosed(rfqResponse))
{
throw new RfQDocumentClosedException(rfqBL.getSummary(rfqResponse));
}
// TODO: FRESH-402 shall we throw exception if the rfqResponse was published?
rfqResponse.setProcessed(false);
InterfaceWrapperHelper.delete(rfqResponse);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\RfQDocumentHandler.java | 1 |
请完成以下Java代码 | public String initCreationForm(Owner owner, ModelMap model) {
Pet pet = new Pet();
owner.addPet(pet);
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
}
@PostMapping("/pets/new")
public String processCreationForm(Owner owner, @Valid Pet pet, BindingResult result,
RedirectAttributes redirectAttributes) {
if (StringUtils.hasText(pet.getName()) && pet.isNew() && owner.getPet(pet.getName(), true) != null)
result.rejectValue("name", "duplicate", "already exists");
LocalDate currentDate = LocalDate.now();
if (pet.getBirthDate() != null && pet.getBirthDate().isAfter(currentDate)) {
result.rejectValue("birthDate", "typeMismatch.birthDate");
}
if (result.hasErrors()) {
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
}
owner.addPet(pet);
this.owners.save(owner);
redirectAttributes.addFlashAttribute("message", "New Pet has been Added");
return "redirect:/owners/{ownerId}";
}
@GetMapping("/pets/{petId}/edit")
public String initUpdateForm() {
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
}
@PostMapping("/pets/{petId}/edit")
public String processUpdateForm(Owner owner, @Valid Pet pet, BindingResult result,
RedirectAttributes redirectAttributes) {
String petName = pet.getName();
// checking if the pet name already exists for the owner
if (StringUtils.hasText(petName)) {
Pet existingPet = owner.getPet(petName, false);
if (existingPet != null && !Objects.equals(existingPet.getId(), pet.getId())) {
result.rejectValue("name", "duplicate", "already exists");
}
}
LocalDate currentDate = LocalDate.now();
if (pet.getBirthDate() != null && pet.getBirthDate().isAfter(currentDate)) {
result.rejectValue("birthDate", "typeMismatch.birthDate");
}
if (result.hasErrors()) {
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
}
updatePetDetails(owner, pet); | redirectAttributes.addFlashAttribute("message", "Pet details has been edited");
return "redirect:/owners/{ownerId}";
}
/**
* Updates the pet details if it exists or adds a new pet to the owner.
* @param owner The owner of the pet
* @param pet The pet with updated details
*/
private void updatePetDetails(Owner owner, Pet pet) {
Integer id = pet.getId();
Assert.state(id != null, "'pet.getId()' must not be null");
Pet existingPet = owner.getPet(id);
if (existingPet != null) {
// Update existing pet's properties
existingPet.setName(pet.getName());
existingPet.setBirthDate(pet.getBirthDate());
existingPet.setType(pet.getType());
}
else {
owner.addPet(pet);
}
this.owners.save(owner);
}
} | repos\spring-petclinic-main\src\main\java\org\springframework\samples\petclinic\owner\PetController.java | 1 |
请完成以下Java代码 | private void init() {
this.requestHttpHeadersFilters = this.requestHttpHeadersFiltersProvider.orderedStream().toList();
this.responseHttpHeadersFilters = this.responseHttpHeadersFiltersProvider.orderedStream().toList();
}
@Override
public ServerResponse handle(ServerRequest serverRequest) {
URI uri = uriResolver.apply(serverRequest);
MultiValueMap<String, String> params = MvcUtils.encodeQueryParams(serverRequest.params());
// @formatter:off
URI url = UriComponentsBuilder.fromUri(serverRequest.uri())
.scheme(uri.getScheme())
.host(uri.getHost())
.port(uri.getPort())
.replaceQueryParams(params)
.build(true)
.toUri();
// @formatter:on
HttpHeaders filteredRequestHeaders = filterHeaders(this.requestHttpHeadersFilters,
serverRequest.headers().asHttpHeaders(), serverRequest);
boolean preserveHost = (boolean) serverRequest.attributes()
.getOrDefault(MvcUtils.PRESERVE_HOST_HEADER_ATTRIBUTE, false);
if (preserveHost) {
filteredRequestHeaders.set(HttpHeaders.HOST, serverRequest.headers().firstHeader(HttpHeaders.HOST));
}
else {
filteredRequestHeaders.remove(HttpHeaders.HOST);
}
// @formatter:off | ProxyExchange.Request proxyRequest = proxyExchange.request(serverRequest).uri(url)
.headers(filteredRequestHeaders)
// TODO: allow injection of ResponseConsumer
.responseConsumer((response, serverResponse) -> {
HttpHeaders httpHeaders = filterHeaders(this.responseHttpHeadersFilters, response.getHeaders(), serverResponse);
serverResponse.headers().putAll(httpHeaders);
})
.build();
// @formatter:on
return proxyExchange.exchange(proxyRequest);
}
private <REQUEST_OR_RESPONSE> HttpHeaders filterHeaders(@Nullable List<?> filters, HttpHeaders original,
REQUEST_OR_RESPONSE requestOrResponse) {
HttpHeaders filtered = original;
if (CollectionUtils.isEmpty(filters)) {
return filtered;
}
for (Object filter : filters) {
@SuppressWarnings("unchecked")
HttpHeadersFilter<REQUEST_OR_RESPONSE> typed = ((HttpHeadersFilter<REQUEST_OR_RESPONSE>) filter);
filtered = typed.apply(filtered, requestOrResponse);
}
return filtered;
}
public interface URIResolver extends Function<ServerRequest, URI> {
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\ProxyExchangeHandlerFunction.java | 1 |
请完成以下Java代码 | public void setContinent(String continent) {
this.continent = continent == null ? null : continent.trim();
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region == null ? null : region.trim();
}
public Float getSurfacearea() {
return surfacearea;
}
public void setSurfacearea(Float surfacearea) {
this.surfacearea = surfacearea;
}
public Short getIndepyear() {
return indepyear;
}
public void setIndepyear(Short indepyear) {
this.indepyear = indepyear;
}
public Integer getPopulation() {
return population;
}
public void setPopulation(Integer population) {
this.population = population;
}
public Float getLifeexpectancy() {
return lifeexpectancy;
}
public void setLifeexpectancy(Float lifeexpectancy) {
this.lifeexpectancy = lifeexpectancy;
}
public Float getGnp() {
return gnp;
}
public void setGnp(Float gnp) {
this.gnp = gnp;
}
public Float getGnpold() {
return gnpold;
}
public void setGnpold(Float gnpold) {
this.gnpold = gnpold;
}
public String getLocalname() {
return localname; | }
public void setLocalname(String localname) {
this.localname = localname == null ? null : localname.trim();
}
public String getGovernmentform() {
return governmentform;
}
public void setGovernmentform(String governmentform) {
this.governmentform = governmentform == null ? null : governmentform.trim();
}
public String getHeadofstate() {
return headofstate;
}
public void setHeadofstate(String headofstate) {
this.headofstate = headofstate == null ? null : headofstate.trim();
}
public Integer getCapital() {
return capital;
}
public void setCapital(Integer capital) {
this.capital = capital;
}
public String getCode2() {
return code2;
}
public void setCode2(String code2) {
this.code2 = code2 == null ? null : code2.trim();
}
} | repos\spring-boot-quick-master\quick-modules\dao\src\main\java\com\modules\entity\Country.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getMinimumPayment() {
return minimumPayment;
}
/**
* Sets the value of the minimumPayment property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setMinimumPayment(BigDecimal value) {
this.minimumPayment = value;
}
/**
* A free-text comment for the payment conditions.
*
* @return
* possible object is
* {@link String }
*
*/
public String getComment() {
return comment;
}
/**
* Sets the value of the comment property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setComment(String value) {
this.comment = value;
} | /**
* Gets the value of the paymentConditionsExtension property.
*
* @return
* possible object is
* {@link PaymentConditionsExtensionType }
*
*/
public PaymentConditionsExtensionType getPaymentConditionsExtension() {
return paymentConditionsExtension;
}
/**
* Sets the value of the paymentConditionsExtension property.
*
* @param value
* allowed object is
* {@link PaymentConditionsExtensionType }
*
*/
public void setPaymentConditionsExtension(PaymentConditionsExtensionType value) {
this.paymentConditionsExtension = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PaymentConditionsType.java | 2 |
请完成以下Java代码 | public static BufferedImage generateCaptchaPic(final String captchaCode) {
Assert.notNull(captchaCode, "captchaCode must not be null");
// 定义图像buffer
BufferedImage buffImg = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics gd = buffImg.getGraphics();
Random random = new Random();
// 将图像填充为白色
gd.setColor(Color.WHITE);
gd.fillRect(0, 0, WIDTH, HEIGHT);
Font font = new Font("Times New Roman", Font.BOLD, FONT_HEIGHT);
gd.setFont(font);
// 画边框。
gd.setColor(Color.BLACK);
gd.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);
// 随机产生40条干扰线,使图象中的认证码不易被其它程序探测到。
gd.setColor(Color.BLACK);
for (int i = 0; i < 30; i++) {
int x = random.nextInt(WIDTH);
int y = random.nextInt(HEIGHT);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
gd.drawLine(x, y, x + xl, y + yl);
}
// randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
int red, green, blue;
// 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
red = random.nextInt(255); | green = random.nextInt(255);
blue = random.nextInt(255);
// 用随机产生的颜色将验证码绘制到图像中。
gd.setColor(new Color(red, green, blue));
gd.drawString(captchaCode, 18, 27);
return buffImg;
}
/**
* 生成随机字符串。
* @return 字符串
*/
public static String generateCaptchaCode() {
Random random = new Random();
StringBuilder randomCode = new StringBuilder();
for (int i = 0; i < CODE_LENGTH; i++) {
randomCode.append(CODE_SEQUENCE[random.nextInt(52)]);
}
return randomCode.toString();
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\utils\CaptchaUtil.java | 1 |
请完成以下Java代码 | public int getMinCount()
{
return minCount;
}
public Config setNegative(int negative)
{
this.negative = negative;
return this;
}
public int getNegative()
{
return negative;
}
public Config setLayer1Size(int layer1Size)
{
this.layer1Size = layer1Size;
return this;
}
public int getLayer1Size()
{
return layer1Size;
}
public Config setNumThreads(int numThreads)
{
this.numThreads = numThreads;
return this;
}
public int getNumThreads()
{
return numThreads;
}
public Config setUseHierarchicalSoftmax(boolean hs)
{
this.hs = hs;
return this;
}
public boolean useHierarchicalSoftmax()
{
return hs;
}
public Config setUseContinuousBagOfWords(boolean cbow)
{
this.cbow = cbow;
return this; | }
public boolean useContinuousBagOfWords()
{
return cbow;
}
public Config setSample(float sample)
{
this.sample = sample;
return this;
}
public float getSample()
{
return sample;
}
public Config setAlpha(float alpha)
{
this.alpha = alpha;
return this;
}
public float getAlpha()
{
return alpha;
}
public Config setInputFile(String inputFile)
{
this.inputFile = inputFile;
return this;
}
public String getInputFile()
{
return inputFile;
}
public TrainingCallback getCallback()
{
return callback;
}
public void setCallback(TrainingCallback callback)
{
this.callback = callback;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Config.java | 1 |
请完成以下Java代码 | public class AdhocSubProcessActivityBehavior extends AbstractBpmnActivityBehavior {
private static final long serialVersionUID = 1L;
public void execute(DelegateExecution execution) {
SubProcess subProcess = getSubProcessFromExecution(execution);
execution.setScope(true);
// initialize the template-defined data objects as variables
Map<String, Object> dataObjectVars = processDataObjects(subProcess.getDataObjects());
if (dataObjectVars != null) {
execution.setVariablesLocal(dataObjectVars);
}
}
protected SubProcess getSubProcessFromExecution(DelegateExecution execution) {
FlowElement flowElement = execution.getCurrentFlowElement();
SubProcess subProcess = null;
if (flowElement instanceof SubProcess) {
subProcess = (SubProcess) flowElement;
} else {
throw new ActivitiException(
"Programmatic error: sub process behaviour can only be applied" + | " to a SubProcess instance, but got an instance of " +
flowElement
);
}
return subProcess;
}
protected Map<String, Object> processDataObjects(Collection<ValuedDataObject> dataObjects) {
Map<String, Object> variablesMap = new HashMap<String, Object>();
// convert data objects to process variables
if (dataObjects != null) {
for (ValuedDataObject dataObject : dataObjects) {
variablesMap.put(dataObject.getName(), dataObject.getValue());
}
}
return variablesMap;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\AdhocSubProcessActivityBehavior.java | 1 |
请完成以下Java代码 | public void setEnforceClientSecurity (boolean EnforceClientSecurity)
{
set_Value (COLUMNNAME_EnforceClientSecurity, Boolean.valueOf(EnforceClientSecurity));
}
/** Get Enforce Client Security.
@return Send alerts to recipient only if the client security rules of the role allows
*/
public boolean isEnforceClientSecurity ()
{
Object oo = get_Value(COLUMNNAME_EnforceClientSecurity);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Enforce Role Security.
@param EnforceRoleSecurity
Send alerts to recipient only if the data security rules of the role allows
*/
public void setEnforceRoleSecurity (boolean EnforceRoleSecurity)
{
set_Value (COLUMNNAME_EnforceRoleSecurity, Boolean.valueOf(EnforceRoleSecurity));
}
/** Get Enforce Role Security.
@return Send alerts to recipient only if the data security rules of the role allows
*/
public boolean isEnforceRoleSecurity ()
{
Object oo = get_Value(COLUMNNAME_EnforceRoleSecurity);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp () | {
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Valid.
@param IsValid
Element is valid
*/
public void setIsValid (boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid));
}
/** Get Valid.
@return Element is valid
*/
public boolean isValid ()
{
Object oo = get_Value(COLUMNNAME_IsValid);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Alert.java | 1 |
请完成以下Java代码 | private void initEndTimeAsDate() {
try {
endTimeAsDate = HistoryCleanupHelper.parseTimeConfiguration(endTime);
} catch (ParseException e) {
throw LOG.invalidPropertyValue("endTime", endTime);
}
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
initStartTimeAsDate();
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
initEndTimeAsDate();
}
public Date getStartTimeAsDate() {
return startTimeAsDate;
}
public Date getEndTimeAsDate() {
return endTimeAsDate;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true; | if (o == null || getClass() != o.getClass())
return false;
BatchWindowConfiguration that = (BatchWindowConfiguration) o;
if (startTime != null ? !startTime.equals(that.startTime) : that.startTime != null)
return false;
return endTime != null ? endTime.equals(that.endTime) : that.endTime == null;
}
@Override
public int hashCode() {
int result = startTime != null ? startTime.hashCode() : 0;
result = 31 * result + (endTime != null ? endTime.hashCode() : 0);
return result;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\BatchWindowConfiguration.java | 1 |
请完成以下Java代码 | public HistoricExternalTaskLogQuery createHistoricExternalTaskLogQuery() {
return new HistoricExternalTaskLogQueryImpl(commandExecutor);
}
@Override
public String getHistoricExternalTaskLogErrorDetails(String historicExternalTaskLogId) {
return commandExecutor.execute(new GetHistoricExternalTaskLogErrorDetailsCmd(historicExternalTaskLogId));
}
public SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder setRemovalTimeToHistoricProcessInstances() {
return new SetRemovalTimeToHistoricProcessInstancesBuilderImpl(commandExecutor);
}
public SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder setRemovalTimeToHistoricDecisionInstances() {
return new SetRemovalTimeToHistoricDecisionInstancesBuilderImpl(commandExecutor); | }
public SetRemovalTimeSelectModeForHistoricBatchesBuilder setRemovalTimeToHistoricBatches() {
return new SetRemovalTimeToHistoricBatchesBuilderImpl(commandExecutor);
}
public void setAnnotationForOperationLogById(String operationId, String annotation) {
commandExecutor.execute(new SetAnnotationForOperationLog(operationId, annotation));
}
public void clearAnnotationForOperationLogById(String operationId) {
commandExecutor.execute(new SetAnnotationForOperationLog(operationId, null));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoryServiceImpl.java | 1 |
请完成以下Java代码 | private static InvoiceRow mergeFromOldRow(
@NonNull final InvoiceRow newRow,
@NonNull final ImmutableMap<DocumentId, InvoiceRow> oldRowsById)
{
final InvoiceRow oldRow = oldRowsById.get(newRow.getId());
if (oldRow == null)
{
return newRow;
}
return newRow.withPreparedForAllocation(oldRow.isPreparedForAllocation());
}
public void addInvoice(@NonNull final InvoiceId invoiceId)
{
final InvoiceRow row = repository.getInvoiceRowByInvoiceId(invoiceId, evaluationDate).orElse(null);
if (row == null)
{
throw new AdempiereException("@InvoiceNotOpen@");
}
rowsHolder.compute(rows -> rows.addingRow(row));
}
@Override
public void patchRow(final RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
final DocumentId rowIdToChange = ctx.getRowId();
rowsHolder.compute(rows -> rows.changingRow(rowIdToChange, row -> InvoiceRowReducers.reduce(row, fieldChangeRequests)));
} | public ImmutableList<InvoiceRow> getRowsWithPreparedForAllocationFlagSet()
{
return getAllRows()
.stream()
.filter(InvoiceRow::isPreparedForAllocation)
.collect(ImmutableList.toImmutableList());
}
public void markPreparedForAllocation(@NonNull final DocumentIdsSelection rowIds)
{
rowsHolder.compute(rows -> rows.changingRows(rowIds, InvoiceRow::withPreparedForAllocationSet));
}
public void unmarkPreparedForAllocation(@NonNull final DocumentIdsSelection rowIds)
{
rowsHolder.compute(rows -> rows.changingRows(rowIds, InvoiceRow::withPreparedForAllocationUnset));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoiceRows.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setType(ChangeType type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Date getNoticeTime() {
return noticeTime;
} | public void setNoticeTime(Date noticeTime) {
this.noticeTime = noticeTime;
}
@Override
public String toString() {
return "ConfigChangeNotice{" +
"noticeTime=" + noticeTime +
", appid='" + appid + '\'' +
", type=" + type +
", value='" + value + '\'' +
'}';
}
} | repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\config\ConfigChangeNotice.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private LocalDate getDateCandidate(@NonNull final Order orderLine)
{
if (orderLine.getLastModifiedDate() != null)
{
return EbayUtils.toLocalDate(orderLine.getLastModifiedDate());
}
else if (orderLine.getCreationDate() != null)
{
return EbayUtils.toLocalDate(orderLine.getCreationDate());
}
return null;
}
@NonNull
private JsonMetasfreshId getMetasfreshIdForExternalIdentifier(
@NonNull final List<JsonResponseUpsertItem> bPartnerResponseUpsertItems,
@NonNull final String externalIdentifier)
{
return bPartnerResponseUpsertItems
.stream() | .filter(responseItem -> responseItem.getIdentifier().equals(externalIdentifier) && responseItem.getMetasfreshId() != null)
.findFirst()
.map(JsonResponseUpsertItem::getMetasfreshId)
.orElseThrow(() -> new RuntimeException("Something went wrong! No JsonResponseUpsertItem was found for the externalIdentifier:" + externalIdentifier));
}
@Nullable
private String getCurrencyCode(@NonNull final Order order)
{
return order.getPaymentSummary().getTotalDueSeller().getCurrency();
}
@Nullable
private LocalDate getDateOrdered(@NonNull final Order order)
{
return order.getCreationDate() != null
? EbayUtils.toLocalDate(order.getCreationDate())
: null;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\de-metas-camel-ebay-camelroutes\src\main\java\de\metas\camel\externalsystems\ebay\processor\order\CreateOrderLineCandidateUpsertReqForEbayOrderProcessor.java | 2 |
请完成以下Java代码 | public class Book {
private String bookId;
private String title;
private double price;
private boolean available;
public Book(String bookId, String title) {
this.bookId = bookId;
this.title = title;
}
public Book(String bookId, String title, int price, boolean available) {
this.bookId = bookId;
this.title = title;
this.price = price;
this.available = available;
}
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.bookId = bookId; | }
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
} | repos\tutorials-master\spring-reactive-modules\spring-webflux\src\main\java\com\baeldung\spring\convertmonoobject\Book.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TravelDeal {
@Id
private BigInteger id;
private String destination;
private String description;
@Field("deal_price")
private double dealPrice;
@Field("old_price")
private double oldPrice;
@Field("departure_date")
private Date departureDate;
@Field("arrival_date")
private Date arrivalDate;
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
} | public double getDealPrice() {
return dealPrice;
}
public void setDealPrice(double dealPrice) {
this.dealPrice = dealPrice;
}
public double getOldPrice() {
return oldPrice;
}
public void setOldPrice(double oldPrice) {
this.oldPrice = oldPrice;
}
public Date getDepartureDate() {
return departureDate;
}
public void setDepartureDate(Date departureDate) {
this.departureDate = departureDate;
}
public Date getArrivalDate() {
return arrivalDate;
}
public void setArrivalDate(Date arrivalDate) {
this.arrivalDate = arrivalDate;
}
@Override
public String toString() {
return "TravelDeal{" + "id=" + id + ", destination='" + destination + '\'' + ", description='" + description + '\'' + ", dealPrice=" + dealPrice + ", oldPrice=" + oldPrice + ", departureDate=" + departureDate + ", arrivalDate=" + arrivalDate + '}';
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-kubernetes\kubernetes-guide\travel-agency-service\src\main\java\com\baeldung\spring\cloud\kubernetes\travelagency\model\TravelDeal.java | 2 |
请完成以下Java代码 | public void onSuccess(ValidateDeviceCredentialsResponse msg) {
if (!StringUtils.isEmpty(msg.getCredentials())) {
credentialsBodyHolder[0] = msg.getCredentials();
}
latch.countDown();
}
@Override
public void onError(Throwable e) {
log.trace("Failed to process certificate chain: {}", certificateChain, e);
latch.countDown();
}
});
latch.await(10, TimeUnit.SECONDS);
if (!clientDeviceCertValue.equals(credentialsBodyHolder[0])) {
log.debug("Failed to find credentials for device certificate chain: {}", chain);
if (chain.length == 1) {
throw new CertificateException("Invalid Device Certificate");
} else {
throw new CertificateException("Invalid Chain of X509 Certificates");
}
} | } catch (Exception e) {
log.error(e.getMessage(), e);
}
}
private boolean validateCertificateChain(X509Certificate[] chain) {
try {
if (chain.length > 1) {
X509Certificate leafCert = chain[0];
for (int i = 1; i < chain.length; i++) {
X509Certificate intermediateCert = chain[i];
leafCert.verify(intermediateCert.getPublicKey());
leafCert = intermediateCert;
}
}
return true;
} catch (Exception e) {
return false;
}
}
}
} | repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\MqttSslHandlerProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**/*")
.addResourceLocations("/", "/resources/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
/**
* View resolver for JSP
*/
@Bean
public UrlBasedViewResolver viewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
} | /**
* Configuration for async thread bean
*
* More: https://docs.spring.io/autorepo/docs/spring-framework/5.0.3.RELEASE/javadoc-api/org/springframework/scheduling/SchedulingTaskExecutor.html
*/
@Bean
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("CsvThread");
executor.initialize();
return executor;
}
} | repos\tutorials-master\ethereum\src\main\java\com\baeldung\web3j\config\AppConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setWatermarkFontsize(String watermarkFontsize) {
setWatermarkFontsizeValue(watermarkFontsize);
}
public static String getWatermarkColor() {
return WATERMARK_COLOR;
}
public static void setWatermarkColorValue(String watermarkColor) {
WATERMARK_COLOR = watermarkColor;
}
@Value("${watermark.color:black}")
public void setWatermarkColor(String watermarkColor) {
setWatermarkColorValue(watermarkColor);
}
public static String getWatermarkAlpha() {
return WATERMARK_ALPHA;
}
public static void setWatermarkAlphaValue(String watermarkAlpha) {
WATERMARK_ALPHA = watermarkAlpha;
}
@Value("${watermark.alpha:0.2}")
public void setWatermarkAlpha(String watermarkAlpha) {
setWatermarkAlphaValue(watermarkAlpha);
}
public static String getWatermarkWidth() {
return WATERMARK_WIDTH;
}
public static void setWatermarkWidthValue(String watermarkWidth) {
WATERMARK_WIDTH = watermarkWidth;
}
@Value("${watermark.width:240}")
public void setWatermarkWidth(String watermarkWidth) {
WATERMARK_WIDTH = watermarkWidth;
} | public static String getWatermarkHeight() {
return WATERMARK_HEIGHT;
}
public static void setWatermarkHeightValue(String watermarkHeight) {
WATERMARK_HEIGHT = watermarkHeight;
}
@Value("${watermark.height:80}")
public void setWatermarkHeight(String watermarkHeight) {
WATERMARK_HEIGHT = watermarkHeight;
}
public static String getWatermarkAngle() {
return WATERMARK_ANGLE;
}
public static void setWatermarkAngleValue(String watermarkAngle) {
WATERMARK_ANGLE = watermarkAngle;
}
@Value("${watermark.angle:10}")
public void setWatermarkAngle(String watermarkAngle) {
WATERMARK_ANGLE = watermarkAngle;
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\config\WatermarkConfigConstants.java | 2 |
请完成以下Java代码 | public static int mod(int x) {
if (x >= 0) {
return (x % MOD);
} else {
return mod(MOD + x);
}
}
public static int mod(long x) {
if (x >= 0) {
return (int) (x % (long) MOD);
} else {
return mod(MOD + x);
}
}
public static int modSum(int a, int b) {
return mod(minSymmetricMod(a) + minSymmetricMod(b));
}
public static int modSubtract(int a, int b) {
return mod(minSymmetricMod(a) - minSymmetricMod(b));
}
public static int modMultiply(int a, int b) {
int result = minSymmetricMod((long) minSymmetricMod(a) * (long) minSymmetricMod(b));
return mod(result);
}
public static int modPower(int base, int exp) {
int result = 1; | int b = base;
while (exp > 0) {
if ((exp & 1) == 1) {
result = minSymmetricMod((long) minSymmetricMod(result) * (long) minSymmetricMod(b));
}
b = minSymmetricMod((long) minSymmetricMod(b) * (long) minSymmetricMod(b));
exp >>= 1;
}
return mod(result);
}
private static int[] extendedGcd(int a, int b) {
if (b == 0) {
return new int[] { a, 1, 0 };
}
int[] result = extendedGcd(b, a % b);
int gcd = result[0];
int x = result[2];
int y = result[1] - (a / b) * result[2];
return new int[] { gcd, x, y };
}
public static int modInverse(int a) {
int[] result = extendedGcd(a, MOD);
int x = result[1];
return mod(x);
}
public static int modDivide(int a, int b) {
return modMultiply(minSymmetricMod(a), minSymmetricMod(modInverse(b)));
}
} | repos\tutorials-master\core-java-modules\core-java-lang-math-4\src\main\java\com\baeldung\math\moduloarithmetic\ModularArithmetic.java | 1 |
请完成以下Java代码 | public void updateAllPayments(@NonNull final UnaryOperator<POSPayment> updater)
{
for (final ListIterator<POSPayment> it = payments.listIterator(); it.hasNext(); )
{
final POSPayment payment = it.next();
final POSPayment paymentChanged = updater.apply(payment);
if (paymentChanged == null)
{
payment.assertAllowDeleteFromDB();
it.remove();
}
else
{
it.set(paymentChanged);
}
}
updateTotals();
}
public void createOrUpdatePayment(@NonNull final POSPaymentExternalId externalId, @NonNull final UnaryOperator<POSPayment> updater)
{
final int paymentIdx = getPaymentIndexByExternalId(externalId).orElse(-1);
updatePaymentByIndex(paymentIdx, updater);
}
public void updatePaymentByExternalId(@NonNull final POSPaymentExternalId externalId, @NonNull final UnaryOperator<POSPayment> updater)
{
final int paymentIdx = getPaymentIndexByExternalId(externalId)
.orElseThrow(() -> new AdempiereException("No payment found for " + externalId + " in " + payments));
updatePaymentByIndex(paymentIdx, updater);
}
public void updatePaymentById(@NonNull POSPaymentId posPaymentId, @NonNull final UnaryOperator<POSPayment> updater)
{
final int paymentIdx = getPaymentIndexById(posPaymentId);
updatePaymentByIndex(paymentIdx, updater);
}
private void updatePaymentByIndex(final int paymentIndex, @NonNull final UnaryOperator<POSPayment> updater)
{
final POSPayment payment = paymentIndex >= 0 ? payments.get(paymentIndex) : null;
final POSPayment paymentChanged = updater.apply(payment);
if (paymentIndex >= 0)
{
payments.set(paymentIndex, paymentChanged);
}
else
{
payments.add(paymentChanged);
}
updateTotals();
}
private int getPaymentIndexById(final @NonNull POSPaymentId posPaymentId)
{ | for (int i = 0; i < payments.size(); i++)
{
if (POSPaymentId.equals(payments.get(i).getLocalId(), posPaymentId))
{
return i;
}
}
throw new AdempiereException("No payment found for " + posPaymentId + " in " + payments);
}
private OptionalInt getPaymentIndexByExternalId(final @NonNull POSPaymentExternalId externalId)
{
for (int i = 0; i < payments.size(); i++)
{
if (POSPaymentExternalId.equals(payments.get(i).getExternalId(), externalId))
{
return OptionalInt.of(i);
}
}
return OptionalInt.empty();
}
public void removePaymentsIf(@NonNull final Predicate<POSPayment> predicate)
{
updateAllPayments(payment -> {
// skip payments marked as DELETED
if (payment.isDeleted())
{
return payment;
}
if (!predicate.test(payment))
{
return payment;
}
if (payment.isAllowDeleteFromDB())
{
payment.assertAllowDelete();
return null;
}
else
{
return payment.changingStatusToDeleted();
}
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrder.java | 1 |
请完成以下Java代码 | public SqlAndParams buildJoinCondition(
@NonNull final String targetTableNameOrAlias,
@NonNull final String selectionTableAlias)
{
return SqlAndParams.builder()
.append(selectionTableAlias).append(".").append(I_T_ES_FTS_Search_Result.COLUMNNAME_Search_UUID).append("=?", searchId)
.append(" AND ").append(joinColumns.buildJoinCondition(targetTableNameOrAlias, selectionTableAlias))
.build();
}
public SqlAndParams buildExistsWhereClause(@NonNull final String targetTableNameOrAlias)
{
return SqlAndParams.builder()
.append("EXISTS (SELECT 1 FROM ").append(I_T_ES_FTS_Search_Result.Table_Name).append(" fts")
.append(" WHERE ").append(buildJoinCondition(targetTableNameOrAlias, "fts"))
.append(")")
.build();
}
public SqlAndParams buildOrderBy(@NonNull final String selectionTableAlias)
{
return SqlAndParams.of(selectionTableAlias + "." + I_T_ES_FTS_Search_Result.COLUMNNAME_Line);
}
}
//
//
// ------------------------------
//
//
@EqualsAndHashCode
@ToString
@NonFinal // because we want to mock it while testing
public static class RecordsToAlwaysIncludeSql
{
@NonNull private final SqlAndParams sqlAndParams;
private RecordsToAlwaysIncludeSql(@NonNull final SqlAndParams sqlAndParams)
{
if (sqlAndParams.isEmpty())
{
throw new AdempiereException("empty sqlAndParams is not allowed");
}
this.sqlAndParams = sqlAndParams;
}
public static RecordsToAlwaysIncludeSql ofColumnNameAndRecordIds(@NonNull final String columnName, @NonNull final Collection<?> recordIds)
{
final InArrayQueryFilter<?> builder = new InArrayQueryFilter<>(columnName, recordIds)
.setEmbedSqlParams(false);
final SqlAndParams sqlAndParams = SqlAndParams.of(builder.getSql(), builder.getSqlParams(Env.getCtx()));
return new RecordsToAlwaysIncludeSql(sqlAndParams);
}
public static RecordsToAlwaysIncludeSql ofColumnNameAndRecordIds(@NonNull final String columnName, @NonNull final Object... recordIds) | {
return ofColumnNameAndRecordIds(columnName, Arrays.asList(recordIds));
}
@Nullable
public static RecordsToAlwaysIncludeSql mergeOrNull(@Nullable final Collection<RecordsToAlwaysIncludeSql> collection)
{
if (collection == null || collection.isEmpty())
{
return null;
}
else if (collection.size() == 1)
{
return collection.iterator().next();
}
else
{
return SqlAndParams.orNullables(
collection.stream()
.filter(Objects::nonNull)
.map(RecordsToAlwaysIncludeSql::toSqlAndParams)
.collect(ImmutableSet.toImmutableSet()))
.map(RecordsToAlwaysIncludeSql::new)
.orElse(null);
}
}
public SqlAndParams toSqlAndParams()
{
return sqlAndParams;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\FilterSql.java | 1 |
请完成以下Java代码 | public static boolean isDeployable(String filename, String[] additionalResourceSuffixes) {
return isDeployable(filename) || hasSuffix(filename, additionalResourceSuffixes);
}
public static boolean hasSuffix(String filename, String[] suffixes) {
if (suffixes == null || suffixes.length == 0) {
return false;
} else {
for (String suffix : suffixes) {
if (filename.endsWith(suffix)) {
return true;
}
}
return false;
}
}
public static boolean isDiagram(String fileName, String modelFileName) {
// process resources
boolean isBpmnDiagram = checkDiagram(fileName, modelFileName, BpmnDeployer.DIAGRAM_SUFFIXES, BpmnDeployer.BPMN_RESOURCE_SUFFIXES);
// case resources
boolean isCmmnDiagram = checkDiagram(fileName, modelFileName, CmmnDeployer.DIAGRAM_SUFFIXES, CmmnDeployer.CMMN_RESOURCE_SUFFIXES);
// decision resources
boolean isDmnDiagram = checkDiagram(fileName, modelFileName, DecisionDefinitionDeployer.DIAGRAM_SUFFIXES, DecisionDefinitionDeployer.DMN_RESOURCE_SUFFIXES);
return isBpmnDiagram || isCmmnDiagram || isDmnDiagram;
}
/**
* Checks, whether a filename is a diagram for the given modelFileName.
*
* @param fileName filename to check.
* @param modelFileName model file name. | * @param diagramSuffixes suffixes of the diagram files.
* @param modelSuffixes suffixes of model files.
* @return true, if a file is a diagram for the model.
*/
protected static boolean checkDiagram(String fileName, String modelFileName, String[] diagramSuffixes, String[] modelSuffixes) {
for (String modelSuffix : modelSuffixes) {
if (modelFileName.endsWith(modelSuffix)) {
String caseFilePrefix = modelFileName.substring(0, modelFileName.length() - modelSuffix.length());
if (fileName.startsWith(caseFilePrefix)) {
for (String diagramResourceSuffix : diagramSuffixes) {
if (fileName.endsWith(diagramResourceSuffix)) {
return true;
}
}
}
}
}
return false;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\scanning\ProcessApplicationScanningUtil.java | 1 |
请完成以下Java代码 | public Stream<CityRecord> getCitiesStreamUsingSpliterator(Connection connection)
throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(QUERY);
connection.setAutoCommit(false);
preparedStatement.setFetchSize(5000);
ResultSet resultSet = preparedStatement.executeQuery();
return StreamSupport.stream(new Spliterators.AbstractSpliterator<CityRecord>(
Long.MAX_VALUE, Spliterator.ORDERED) {
@Override
public boolean tryAdvance(Consumer<? super CityRecord> action) {
try {
if(!resultSet.next()) return false;
action.accept(createCityRecord(resultSet));
return true;
} catch(SQLException ex) {
throw new RuntimeException(ex);
}
}
}, false)
.onClose(() -> closeResources(connection, resultSet, preparedStatement));
}
private void closeResources(Connection connection, ResultSet resultSet, PreparedStatement preparedStatement) {
try {
resultSet.close();
preparedStatement.close();
connection.close();
logger.info("Resources closed");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Stream<CityRecord> getCitiesStreamUsingJOOQ(Connection connection)
throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(QUERY); | connection.setAutoCommit(false);
preparedStatement.setFetchSize(5000);
ResultSet resultSet = preparedStatement.executeQuery();
return DSL.using(connection)
.fetchStream(resultSet)
.map(r -> new CityRecord(r.get("NAME", String.class),
r.get("COUNTRY", String.class)))
.onClose(() -> closeResources(connection, resultSet, preparedStatement));
}
public Stream<CityRecord> getCitiesStreamUsingJdbcStream(Connection connection)
throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(QUERY);
connection.setAutoCommit(false);
preparedStatement.setFetchSize(5000);
ResultSet resultSet = preparedStatement.executeQuery();
return JdbcStream.stream(resultSet)
.map(r -> {
try {
return createCityRecord(resultSet);
} catch (SQLException e) {
throw new RuntimeException(e);
}
})
.onClose(() -> closeResources(connection, resultSet, preparedStatement));
}
private CityRecord createCityRecord(ResultSet resultSet) throws SQLException {
return new CityRecord(resultSet.getString(1), resultSet.getString(2));
}
} | repos\tutorials-master\persistence-modules\core-java-persistence-3\src\main\java\com\baeldung\resultset\streams\JDBCStreamAPIRepository.java | 1 |
请完成以下Java代码 | public <V, ET extends IExpression<V>, CT extends IExpressionCompiler<V, ET>> CT getCompiler(final Class<ET> expressionType)
{
// Look for the particular compiler
final Object compilerObj = compilers.get(expressionType);
// No compiler found => fail
if (compilerObj == null)
{
throw new ExpressionCompileException("No compiler found for expressionType=" + expressionType
+ "\n Available compilers are: " + compilers.keySet());
}
// Assume this is always correct because we enforce the type when we add to map
@SuppressWarnings("unchecked")
final CT compiler = (CT)compilerObj;
return compiler;
}
@Override
public <V, ET extends IExpression<V>> ET compile(final String expressionStr, final Class<ET> expressionType)
{
final IExpressionCompiler<V, ET> compiler = getCompiler(expressionType);
return compiler.compile(ExpressionContext.EMPTY, expressionStr);
}
@Override
public <V, ET extends IExpression<V>> ET compileOrDefault(final String expressionStr, final ET defaultExpr, final Class<ET> expressionType)
{
if (Check.isEmpty(expressionStr, true))
{
return defaultExpr;
}
try
{ | return compile(expressionStr, expressionType);
}
catch (final Exception e)
{
logger.warn(e.getLocalizedMessage(), e);
return defaultExpr;
}
}
@Override
public <V, ET extends IExpression<V>> ET compile(final String expressionStr, final Class<ET> expressionType, final ExpressionContext context)
{
final IExpressionCompiler<V, ET> compiler = getCompiler(expressionType);
return compiler.compile(context, expressionStr);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\ExpressionFactory.java | 1 |
请完成以下Java代码 | public ImmutableSet<String> getParameters(@Nullable final String contextTableName)
{
return predicates.stream()
.flatMap(predicate -> predicate.getParameters(contextTableName).stream())
.collect(ImmutableSet.toImmutableSet());
}
@Override
public boolean accept(final IValidationContext evalCtx, final NamePair item)
{
for (final INamePairPredicate predicate : predicates)
{
if (predicate.accept(evalCtx, item))
{
return true;
}
}
return false;
}
}
public static class Composer
{
private Set<INamePairPredicate> collectedPredicates = null;
private Composer()
{
super();
}
public INamePairPredicate build()
{
if (collectedPredicates == null || collectedPredicates.isEmpty())
{
return ACCEPT_ALL;
} | else if (collectedPredicates.size() == 1)
{
return collectedPredicates.iterator().next();
}
else
{
return new ComposedNamePairPredicate(collectedPredicates);
}
}
public Composer add(@Nullable final INamePairPredicate predicate)
{
if (predicate == null || predicate == ACCEPT_ALL)
{
return this;
}
if (collectedPredicates == null)
{
collectedPredicates = new LinkedHashSet<>();
}
if (collectedPredicates.contains(predicate))
{
return this;
}
collectedPredicates.add(predicate);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\NamePairPredicates.java | 1 |
请完成以下Java代码 | public static MRequestCategory get (Properties ctx, int R_Category_ID)
{
Integer key = new Integer (R_Category_ID);
MRequestCategory retValue = (MRequestCategory) s_cache.get (key);
if (retValue != null)
return retValue;
retValue = new MRequestCategory (ctx, R_Category_ID, null);
if (retValue.get_ID () != 0)
s_cache.put (key, retValue);
return retValue;
} // get
/** Cache */
private static CCache<Integer,MRequestCategory> s_cache
= new CCache<Integer,MRequestCategory>("R_Category", 20);
/**************************************************************************
* Standard Constructor
* @param ctx context | * @param R_Category_ID id
* @param trxName trx
*/
public MRequestCategory (Properties ctx, int R_Category_ID, String trxName)
{
super (ctx, R_Category_ID, trxName);
} // MCategory
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
public MRequestCategory (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MCategory
} // MCategory | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MRequestCategory.java | 1 |
请完成以下Java代码 | public String toString() {
return filterToStringCreator(RewriteResponseHeaderGatewayFilterFactory.this)
.append("name", config.getName())
.append("regexp", config.getRegexp())
.append("replacement", config.getReplacement())
.toString();
}
};
}
protected void rewriteHeaders(ServerWebExchange exchange, Config config) {
final String name = Objects.requireNonNull(config.getName(), "name must not be null");
final HttpHeaders responseHeaders = exchange.getResponse().getHeaders();
if (responseHeaders.get(name) != null) {
List<String> oldValue = Objects.requireNonNull(responseHeaders.get(name), "oldValue must not be null");
List<String> newValue = rewriteHeaders(config, oldValue);
if (newValue != null) {
responseHeaders.put(name, newValue);
}
else {
responseHeaders.remove(name);
}
}
}
protected List<String> rewriteHeaders(Config config, List<String> headers) {
String regexp = Objects.requireNonNull(config.getRegexp(), "regexp must not be null");
String replacement = Objects.requireNonNull(config.getReplacement(), "replacement must not be null");
ArrayList<String> rewrittenHeaders = new ArrayList<>();
for (int i = 0; i < headers.size(); i++) {
String rewriten = rewrite(headers.get(i), regexp, replacement);
rewrittenHeaders.add(rewriten);
}
return rewrittenHeaders;
}
String rewrite(String value, String regexp, String replacement) {
return value.replaceAll(regexp, replacement.replace("$\\", "$"));
}
public static class Config extends AbstractGatewayFilterFactory.NameConfig {
private @Nullable String regexp;
private @Nullable String replacement; | public @Nullable String getRegexp() {
return regexp;
}
public Config setRegexp(String regexp) {
this.regexp = regexp;
return this;
}
public @Nullable String getReplacement() {
return replacement;
}
public Config setReplacement(String replacement) {
this.replacement = replacement;
return this;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RewriteResponseHeaderGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext() == this.applicationContext) {
this.contextRefreshed = true;
}
}
public RabbitOperations getRabbitOperations() {
return rabbitOperations;
}
public void setRabbitOperations(RabbitOperations rabbitOperations) {
this.rabbitOperations = rabbitOperations;
}
public RabbitListenerEndpointRegistry getEndpointRegistry() {
return endpointRegistry;
}
public void setEndpointRegistry(RabbitListenerEndpointRegistry endpointRegistry) {
this.endpointRegistry = endpointRegistry;
}
public String getContainerFactoryBeanName() { | return containerFactoryBeanName;
}
public void setContainerFactoryBeanName(String containerFactoryBeanName) {
this.containerFactoryBeanName = containerFactoryBeanName;
}
public RabbitListenerContainerFactory<?> getContainerFactory() {
return containerFactory;
}
public void setContainerFactory(RabbitListenerContainerFactory<?> containerFactory) {
this.containerFactory = containerFactory;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\rabbit\RabbitChannelDefinitionProcessor.java | 1 |
请完成以下Java代码 | public String getDisplay() {
if (m_value instanceof String)
return super.isSelected() ? "Y" : "N";
return Boolean.toString(super.isSelected());
} // getDisplay
/**
* Set Text
*
* @param mnemonicLabel
* text
*/
@Override
public void setText(String mnemonicLabel) {
super.setText(createMnemonic(mnemonicLabel));
} // setText
/**
* Create Mnemonics of text containing "&". Based on MS notation of &Help =>
* H is Mnemonics Creates ALT_
*
* @param text
* test with Mnemonics
* @return text w/o &
*/
private String createMnemonic(String text) {
if (text == null)
return text;
int pos = text.indexOf('&');
if (pos != -1) // We have a nemonic
{
char ch = text.charAt(pos + 1);
if (ch != ' ') // &_ - is the & character
{
setMnemonic(ch);
return text.substring(0, pos) + text.substring(pos + 1);
}
}
return text;
} // createMnemonic | /**
* Overrides the JCheckBox.setMnemonic() method, setting modifier keys to
* CTRL+SHIFT.
*
* @param mnemonic
* The mnemonic character code.
*/
@Override
public void setMnemonic(int mnemonic) {
super.setMnemonic(mnemonic);
InputMap map = SwingUtilities.getUIInputMap(this,
JComponent.WHEN_IN_FOCUSED_WINDOW);
if (map == null) {
map = new ComponentInputMapUIResource(this);
SwingUtilities.replaceUIInputMap(this,
JComponent.WHEN_IN_FOCUSED_WINDOW, map);
}
map.clear();
String className = this.getClass().getName();
int mask = InputEvent.ALT_MASK; // Default Buttons
if (this instanceof JCheckBox // In Tab
|| className.indexOf("VButton") != -1)
mask = InputEvent.SHIFT_MASK + InputEvent.CTRL_MASK;
map.put(KeyStroke.getKeyStroke(mnemonic, mask, false), "pressed");
map.put(KeyStroke.getKeyStroke(mnemonic, mask, true), "released");
map.put(KeyStroke.getKeyStroke(mnemonic, 0, true), "released");
setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, map);
} // setMnemonic
} // CCheckBox | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CCheckBox.java | 1 |
请完成以下Java代码 | public class DefaultCounter {
private final AtomicInteger aiCounter;
private final Counter micrometerCounter;
public DefaultCounter(AtomicInteger aiCounter, Counter micrometerCounter) {
this.aiCounter = aiCounter;
this.micrometerCounter = micrometerCounter;
}
public void increment() {
aiCounter.incrementAndGet();
micrometerCounter.increment();
}
public void clear() { | aiCounter.set(0);
}
public int get() {
return aiCounter.get();
}
public int getAndClear() {
return aiCounter.getAndSet(0);
}
public void add(int delta){
aiCounter.addAndGet(delta);
micrometerCounter.increment(delta);
}
} | repos\thingsboard-master\common\stats\src\main\java\org\thingsboard\server\common\stats\DefaultCounter.java | 1 |
请完成以下Java代码 | public class SpringAsyncTaskExecutor implements AsyncTaskExecutor {
protected final org.springframework.core.task.AsyncTaskExecutor asyncTaskExecutor;
protected final boolean isAsyncTaskExecutorAopProxied;
public SpringAsyncTaskExecutor(org.springframework.core.task.AsyncTaskExecutor asyncTaskExecutor) {
this.asyncTaskExecutor = asyncTaskExecutor;
this.isAsyncTaskExecutorAopProxied = AopUtils.isAopProxy(asyncTaskExecutor); // no need to repeat this every time, done once in constructor
}
@Override
public void execute(Runnable task) {
asyncTaskExecutor.execute(task);
}
@Override
public CompletableFuture<?> submit(Runnable task) {
return asyncTaskExecutor.submitCompletable(task);
}
@Override
public <T> CompletableFuture<T> submit(Callable<T> task) {
return asyncTaskExecutor.submitCompletable(task);
} | @Override
public void shutdown() {
// This uses spring resources passed in the constructor, therefore there is nothing to shutdown here
}
public org.springframework.core.task.AsyncTaskExecutor getAsyncTaskExecutor() {
return asyncTaskExecutor;
}
@Override
public int getRemainingCapacity() {
Object executor = asyncTaskExecutor;
if (isAsyncTaskExecutorAopProxied) {
executor = AopProxyUtils.getSingletonTarget(asyncTaskExecutor);
}
if (executor instanceof ThreadPoolTaskExecutor) {
return ((ThreadPoolTaskExecutor) executor).getThreadPoolExecutor().getQueue().remainingCapacity();
} else {
return Integer.MAX_VALUE;
}
}
} | repos\flowable-engine-main\modules\flowable-spring-common\src\main\java\org\flowable\common\spring\async\SpringAsyncTaskExecutor.java | 1 |
请完成以下Java代码 | protected void startInstance(ActivityExecution execution, VariableMap variables, String businessKey) {
ExecutionEntity executionEntity = (ExecutionEntity) execution;
ProcessDefinitionImpl definition = getProcessDefinitionToCall(
executionEntity,
executionEntity.getProcessDefinitionTenantId(),
getCallableElement());
PvmProcessInstance processInstance = execution.createSubProcessInstance(definition, businessKey);
processInstance.start(variables);
}
@Override
public void migrateScope(ActivityExecution scopeExecution) {
}
@Override | public void onParseMigratingInstance(MigratingInstanceParseContext parseContext, MigratingActivityInstance migratingInstance) {
ActivityImpl callActivity = (ActivityImpl) migratingInstance.getSourceScope();
// A call activity is typically scope and since we guarantee stability of scope executions during migration,
// the superExecution link does not have to be maintained during migration.
// There are some exceptions, though: A multi-instance call activity is not scope and therefore
// does not have a dedicated scope execution. In this case, the link to the super execution
// must be maintained throughout migration
if (!callActivity.isScope()) {
ExecutionEntity callActivityExecution = migratingInstance.resolveRepresentativeExecution();
ExecutionEntity calledProcessInstance = callActivityExecution.getSubProcessInstance();
migratingInstance.addMigratingDependentInstance(new MigratingCalledProcessInstance(calledProcessInstance));
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\CallActivityBehavior.java | 1 |
请完成以下Java代码 | public int getC_BP_PrintFormat_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BP_PrintFormat_ID);
}
@Override
public void setC_DocType_ID (final int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_Value (COLUMNNAME_C_DocType_ID, null);
else
set_Value (COLUMNNAME_C_DocType_ID, C_DocType_ID);
}
@Override
public int getC_DocType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DocType_ID);
}
@Override
public void setDocumentCopies_Override (final int DocumentCopies_Override)
{ | set_Value (COLUMNNAME_DocumentCopies_Override, DocumentCopies_Override);
}
@Override
public int getDocumentCopies_Override()
{
return get_ValueAsInt(COLUMNNAME_DocumentCopies_Override);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_PrintFormat.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@ApiParam("Only return jobs with the given scopeDefinitionId")
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
@ApiParam("Only return jobs with the given scope type")
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getElementId() {
return elementId;
}
@ApiParam("Only return jobs with the given elementId")
public void setElementId(String elementId) {
this.elementId = elementId;
}
public String getElementName() {
return elementName;
}
@ApiParam("Only return jobs with the given elementName")
public void setElementName(String elementName) {
this.elementName = elementName;
}
public boolean isWithException() {
return withException;
}
@ApiParam("Only return jobs with an exception")
public void setWithException(boolean withException) {
this.withException = withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
@ApiParam("Only return jobs with the given exception message")
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
public String getTenantId() {
return tenantId;
}
@ApiParam("Only return jobs with the given tenant id")
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
@ApiParam("Only return jobs with a tenantId like the given value")
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId; | }
@ApiParam("Only return jobs without a tenantId")
public void setWithoutTenantId(boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public boolean isLocked() {
return locked;
}
@ApiParam("Only return jobs that are locked")
public void setLocked(boolean locked) {
this.locked = locked;
}
public boolean isUnlocked() {
return unlocked;
}
@ApiParam("Only return jobs that are unlocked")
public void setUnlocked(boolean unlocked) {
this.unlocked = unlocked;
}
public boolean isWithoutScopeType() {
return withoutScopeType;
}
@ApiParam("Only return jobs without a scope type")
public void setWithoutScopeType(boolean withoutScopeType) {
this.withoutScopeType = withoutScopeType;
}
} | repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\query\ExternalWorkerJobQueryRequest.java | 2 |
请完成以下Java代码 | public class Reviewable {
protected String id;
protected String reviewedBy;
protected String title;
public Reviewable(String reviewedBy) {
this.reviewedBy = reviewedBy;
}
public Reviewable() {
}
public String getReviewedBy() {
return reviewedBy;
}
public void setReviewedBy(String reviewedBy) {
this.reviewedBy = reviewedBy;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id; | }
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
Reviewable that = (Reviewable) o;
return Objects.equals(reviewedBy, that.reviewedBy);
}
@Override
public int hashCode() {
return Objects.hashCode(reviewedBy);
}
} | repos\tutorials-master\mapstruct-3\src\main\java\com\baeldung\setnullproperty\entity\Reviewable.java | 1 |
请完成以下Java代码 | public static DocStatus ofNullableCode(@Nullable final String code)
{
return index.ofNullableCode(code);
}
@NonNull
public static DocStatus ofNullableCodeOrUnknown(@Nullable final String code)
{
final DocStatus docStatus = ofNullableCode(code);
return docStatus != null ? docStatus : Unknown;
}
public static DocStatus ofCode(@NonNull final String code) {return index.ofCode(code);}
public static String toCodeOrNull(@Nullable final DocStatus docStatus)
{
return docStatus != null ? docStatus.getCode() : null;
}
@Override
@JsonValue
public String getCode() {return code;}
public boolean isDrafted()
{
return this == Drafted;
}
public boolean isDraftedOrInProgress()
{
return this == Drafted
|| this == InProgress;
}
public boolean isReversed()
{
return this == Reversed;
}
public boolean isReversedOrVoided()
{
return this == Reversed
|| this == Voided;
}
public boolean isClosedReversedOrVoided()
{
return this == Closed
|| this == Reversed
|| this == Voided;
}
public boolean isCompleted()
{
return this == Completed;
}
public boolean isClosed()
{
return this == Closed;
}
public boolean isCompletedOrClosed()
{
return COMPLETED_OR_CLOSED_STATUSES.contains(this);
}
public static Set<DocStatus> completedOrClosedStatuses()
{
return COMPLETED_OR_CLOSED_STATUSES;
}
public boolean isCompletedOrClosedOrReversed()
{
return this == Completed
|| this == Closed
|| this == Reversed;
}
public boolean isCompletedOrClosedReversedOrVoided()
{
return this == Completed | || this == Closed
|| this == Reversed
|| this == Voided;
}
public boolean isWaitingForPayment()
{
return this == WaitingPayment;
}
public boolean isInProgress()
{
return this == InProgress;
}
public boolean isInProgressCompletedOrClosed()
{
return this == InProgress
|| this == Completed
|| this == Closed;
}
public boolean isDraftedInProgressOrInvalid()
{
return this == Drafted
|| this == InProgress
|| this == Invalid;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isDraftedInProgressOrCompleted()
{
return this == Drafted
|| this == InProgress
|| this == Completed;
}
public boolean isNotProcessed()
{
return isDraftedInProgressOrInvalid()
|| this == Approved
|| this == NotApproved;
}
public boolean isVoided() {return this == Voided;}
public boolean isAccountable()
{
return this == Completed
|| this == Reversed
|| this == Voided;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocStatus.java | 1 |
请完成以下Java代码 | public java.lang.String getInvoiceRecipient ()
{
return (java.lang.String)get_Value(COLUMNNAME_InvoiceRecipient);
}
/** Set Erledigt.
@param IsDone Erledigt */
@Override
public void setIsDone (boolean IsDone)
{
set_Value (COLUMNNAME_IsDone, Boolean.valueOf(IsDone));
}
/** Get Erledigt.
@return Erledigt */
@Override
public boolean isDone ()
{
Object oo = get_Value(COLUMNNAME_IsDone);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Telefon.
@param Phone
Beschreibt eine Telefon Nummer
*/
@Override
public void setPhone (java.lang.String Phone)
{
set_Value (COLUMNNAME_Phone, Phone);
}
/** Get Telefon.
@return Beschreibt eine Telefon Nummer
*/
@Override
public java.lang.String getPhone ()
{
return (java.lang.String)get_Value(COLUMNNAME_Phone);
}
/** Set Grund.
@param Reason Grund */
@Override
public void setReason (java.lang.String Reason)
{
set_Value (COLUMNNAME_Reason, Reason);
}
/** Get Grund.
@return Grund */
@Override
public java.lang.String getReason ()
{
return (java.lang.String)get_Value(COLUMNNAME_Reason);
} | /** Set Sachbearbeiter.
@param ResponsiblePerson Sachbearbeiter */
@Override
public void setResponsiblePerson (java.lang.String ResponsiblePerson)
{
set_Value (COLUMNNAME_ResponsiblePerson, ResponsiblePerson);
}
/** Get Sachbearbeiter.
@return Sachbearbeiter */
@Override
public java.lang.String getResponsiblePerson ()
{
return (java.lang.String)get_Value(COLUMNNAME_ResponsiblePerson);
}
/** Set Status.
@param Status Status */
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status */
@Override
public java.lang.String getStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Rejection_Detail.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
@ApiModelProperty(example = "123")
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
public void setPropagatedStageInstanceId(String propagatedStageInstanceId) {
this.propagatedStageInstanceId = propagatedStageInstanceId;
}
@ApiModelProperty(example = "123")
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@ApiModelProperty(example = "123")
public String getProcessInstanceId() {
return processInstanceId; | }
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@ApiModelProperty(example = "123")
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskResponse.java | 2 |
请完成以下Java代码 | private DocumentLayoutSingleRow.Builder getSingleRowLayout()
{
return singleRowLayout;
}
private ViewLayout.Builder getGridView()
{
return _gridView;
}
public Builder addDetail(@Nullable final DocumentLayoutDetailDescriptor detail)
{
if (detail == null)
{
return this;
}
if (detail.isEmpty())
{
logger.trace("Skip adding detail to layout because it is empty; detail={}", detail);
return this;
}
details.add(detail);
return this;
}
public Builder setSideListView(final ViewLayout sideListViewLayout)
{
this._sideListView = sideListViewLayout;
return this;
} | private ViewLayout getSideList()
{
Preconditions.checkNotNull(_sideListView, "sideList");
return _sideListView;
}
public Builder putDebugProperty(final String name, final String value)
{
debugProperties.put(name, value);
return this;
}
public Builder setStopwatch(final Stopwatch stopwatch)
{
this.stopwatch = stopwatch;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutDescriptor.java | 1 |
请完成以下Java代码 | public boolean evaluate(String sequenceFlowId, DelegateExecution execution) {
String conditionExpression = null;
if (Context.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) {
ObjectNode elementProperties = Context.getBpmnOverrideElementProperties(sequenceFlowId, execution.getProcessDefinitionId());
conditionExpression = getActiveValue(expression, DynamicBpmnConstants.SEQUENCE_FLOW_CONDITION, elementProperties);
} else {
conditionExpression = expression;
}
ScriptingEngines scriptingEngines = Context
.getProcessEngineConfiguration()
.getScriptingEngines();
Object result = scriptingEngines.evaluate(conditionExpression, language, execution);
if (result == null) {
throw new ActivitiException("condition script returns null: " + expression);
}
if (!(result instanceof Boolean)) {
throw new ActivitiException("condition script returns non-Boolean: " + result + " (" + result.getClass().getName() + ")");
}
return (Boolean) result;
} | protected String getActiveValue(String originalValue, String propertyName, ObjectNode elementProperties) {
String activeValue = originalValue;
if (elementProperties != null) {
JsonNode overrideValueNode = elementProperties.get(propertyName);
if (overrideValueNode != null) {
if (overrideValueNode.isNull()) {
activeValue = null;
} else {
activeValue = overrideValueNode.asString();
}
}
}
return activeValue;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\scripting\ScriptCondition.java | 1 |
请完成以下Java代码 | public Campaign syncCampaignLocalToRemote(@NonNull final Campaign campaign)
{
final PlatformClient platformClient = platformClientService.createPlatformClient(campaign.getPlatformId());
final List<LocalToRemoteSyncResult> syncResults = platformClient.syncCampaignsLocalToRemote(ImmutableList.of(campaign));
final LocalToRemoteSyncResult syncResult = CollectionUtils.singleElement(syncResults);
return campaignService.saveSyncResult(syncResult);
}
private Campaign syncCampaignLocalToRemoteIfRemoteIdMissing(@NonNull final Campaign campaign)
{
return campaign.getRemoteId() == null ? syncCampaignLocalToRemote(campaign) : campaign;
}
public void syncCampaigns(
@NonNull final PlatformId platformId,
@NonNull final SyncDirection syncDirection)
{
final PlatformClient platformClient = platformClientService.createPlatformClient(platformId);
final List<Campaign> locallyExistingCampaigns = campaignService.getByPlatformId(platformId);
final List<? extends SyncResult> syncResults;
if (SyncDirection.LOCAL_TO_REMOTE.equals(syncDirection))
{
syncResults = platformClient.syncCampaignsLocalToRemote(locallyExistingCampaigns);
}
else if (SyncDirection.REMOTE_TO_LOCAL.equals(syncDirection))
{
syncResults = platformClient.syncCampaignsRemoteToLocal(locallyExistingCampaigns);
}
else
{
throw new AdempiereException("Invalid sync direction: " + syncDirection);
}
campaignService.saveSyncResults(syncResults);
}
public void syncContacts(
@NonNull final CampaignId campaignId,
@NonNull final SyncDirection syncDirection) | {
final List<ContactPerson> contactsToSync = contactPersonService.getByCampaignId(campaignId);
syncContacts(campaignId, contactsToSync, syncDirection);
}
public void syncContacts(
@NonNull final CampaignId campaignId,
@NonNull final List<ContactPerson> contactsToSync,
@NonNull SyncDirection syncDirection)
{
final Campaign campaign = syncCampaignLocalToRemoteIfRemoteIdMissing(campaignService.getById(campaignId));
final PlatformClient platformClient = platformClientService.createPlatformClient(campaign.getPlatformId());
final List<? extends SyncResult> syncResults = syncDirection.map(new SyncDirection.CaseMapper<List<? extends SyncResult>>()
{
@Override
public List<? extends SyncResult> localToRemote() {return platformClient.syncContactPersonsLocalToRemote(campaign, contactsToSync);}
@Override
public List<? extends SyncResult> remoteToLocal() {return platformClient.syncContactPersonsRemoteToLocal(campaign, contactsToSync);}
});
final List<ContactPerson> savedContacts = contactPersonService.saveSyncResults(syncResults);
campaignService.addContactPersonsToCampaign(savedContacts, campaignId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\CampaignSyncService.java | 1 |
请完成以下Java代码 | public String toString() {
return "LoggerConfiguration [name=" + this.name + ", levelConfiguration=" + this.levelConfiguration
+ ", inheritedLevelConfiguration=" + this.inheritedLevelConfiguration + "]";
}
/**
* Supported logger configuration scopes.
*
* @since 2.7.13
*/
public enum ConfigurationScope {
/**
* Only return configuration that has been applied directly. Often referred to as
* 'configured' or 'assigned' configuration.
*/
DIRECT,
/**
* May return configuration that has been applied to a parent logger. Often
* referred to as 'effective' configuration.
*/
INHERITED
}
/**
* Logger level configuration.
*
* @since 2.7.13
*/
public static final class LevelConfiguration {
private final String name;
private final @Nullable LogLevel logLevel;
private LevelConfiguration(String name, @Nullable LogLevel logLevel) {
this.name = name;
this.logLevel = logLevel;
}
/**
* Return the name of the level.
* @return the level name
*/
public String getName() {
return this.name;
}
/**
* Return the actual level value if possible.
* @return the level value
* @throws IllegalStateException if this is a {@link #isCustom() custom} level
*/
public LogLevel getLevel() {
Assert.state(this.logLevel != null, () -> "Unable to provide LogLevel for '" + this.name + "'");
return this.logLevel;
}
/**
* Return if this is a custom level and cannot be represented by {@link LogLevel}.
* @return if this is a custom level
*/
public boolean isCustom() {
return this.logLevel == null;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
LevelConfiguration other = (LevelConfiguration) obj;
return this.logLevel == other.logLevel && ObjectUtils.nullSafeEquals(this.name, other.name);
} | @Override
public int hashCode() {
return Objects.hash(this.logLevel, this.name);
}
@Override
public String toString() {
return "LevelConfiguration [name=" + this.name + ", logLevel=" + this.logLevel + "]";
}
/**
* Create a new {@link LevelConfiguration} instance of the given {@link LogLevel}.
* @param logLevel the log level
* @return a new {@link LevelConfiguration} instance
*/
public static LevelConfiguration of(LogLevel logLevel) {
Assert.notNull(logLevel, "'logLevel' must not be null");
return new LevelConfiguration(logLevel.name(), logLevel);
}
/**
* Create a new {@link LevelConfiguration} instance for a custom level name.
* @param name the log level name
* @return a new {@link LevelConfiguration} instance
*/
public static LevelConfiguration ofCustom(String name) {
Assert.hasText(name, "'name' must not be empty");
return new LevelConfiguration(name, null);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\LoggerConfiguration.java | 1 |
请完成以下Java代码 | private static OAuth2Error createOAuth2Error(String reason) {
return new OAuth2Error(OAuth2ErrorCodes.INVALID_DPOP_PROOF, reason, null);
}
}
private static final class OAuth2AccessTokenClaims implements OAuth2Token, ClaimAccessor {
private final OAuth2Token accessToken;
private final Map<String, Object> claims;
private OAuth2AccessTokenClaims(OAuth2Token accessToken, Map<String, Object> claims) {
this.accessToken = accessToken;
this.claims = claims;
}
@Override
public String getTokenValue() {
return this.accessToken.getTokenValue(); | }
@Override
public Instant getIssuedAt() {
return this.accessToken.getIssuedAt();
}
@Override
public Instant getExpiresAt() {
return this.accessToken.getExpiresAt();
}
@Override
public Map<String, Object> getClaims() {
return this.claims;
}
}
} | repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\DPoPAuthenticationProvider.java | 1 |
请完成以下Java代码 | public class RichTextEditorDialog extends CDialog
{
/**
*
*/
private static final long serialVersionUID = -7306050007969338986L;
private Component field = null;
public RichTextEditorDialog(Component field, Frame owner, String title, String htmlText, boolean editable)
{
super(owner, "", true);
init(owner, title, htmlText, editable);
this.field = field;
}
public RichTextEditorDialog(Dialog owner, String title, String htmlText, boolean editable)
{
super(owner, "", true);
init(owner, title, htmlText, editable);
}
private void init(Window owner, String title, String htmlText, boolean editable)
{
if (title == null)
setTitle(Msg.getMsg(Env.getCtx(), "Editor"));
else
setTitle(title);
// General Layout
final CPanel mainPanel = new CPanel();
mainPanel.setLayout(new BorderLayout());
getContentPane().add(mainPanel, BorderLayout.CENTER);
mainPanel.add(editor, BorderLayout.CENTER);
editor.setPreferredSize(new Dimension(600, 600));
mainPanel.add(confirmPanel, BorderLayout.SOUTH);
confirmPanel.setActionListener(this);
//
setHtmlText(htmlText);
} // init
/** Logger */
private Logger log = LogManager.getLogger(getClass());
/** The HTML Text */
private String m_text;
private final RichTextEditor editor = new RichTextEditor();
private final ConfirmPanel confirmPanel = ConfirmPanel.newWithOKAndCancel();
private boolean m_isPressedOK = false;
@Override
public void actionPerformed(ActionEvent e)
{
log.debug("actionPerformed - Text:" + getHtmlText());
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
{
m_text = editor.getHtmlText(); | m_isPressedOK = true;
dispose();
}
else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
dispose();
}
}
public String getHtmlText()
{
String text = m_text;
// us315: check if is plain rext
if (field instanceof CTextPane)
{
if ("text/plain".equals(((CTextPane)field).getContentType()))
{
text = MADBoilerPlate.getPlainText(m_text);
log.info("Converted html to plain text: "+text);
}
}
return text;
}
public void setHtmlText(String htmlText)
{
m_text = htmlText;
editor.setHtmlText(htmlText);
}
public boolean isPressedOK()
{
return m_isPressedOK ;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\RichTextEditorDialog.java | 1 |
请完成以下Java代码 | public class ActiveMQConsumer {
public static void main(String[] args) throws JMSException {
// 创建连接
Connection connection = ActiveMQProducer.getConnection();
// 创建会话
final Session session = ActiveMQProducer.getSession(connection);
// 创建队列
Queue queue = ActiveMQProducer.getQueue(session);
// 创建 Consumer
MessageConsumer consumer = session.createConsumer(queue);
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println(String.format("[线程:%s][消息编号:%s][消息内容:%s]",
Thread.currentThread(), textMessage.getJMSMessageID(), textMessage.getText())); | } catch (JMSException e) {
throw new RuntimeException(e);
}
}
});
// 关闭
try {
TimeUnit.HOURS.sleep(1);
} catch (InterruptedException ignore) {
}
session.close();
connection.close();
}
} | repos\SpringBoot-Labs-master\lab-32\lab-32-activemq-native\src\main\java\cn\iocoder\springboot\lab32\activemqdemo\ActiveMQConsumer.java | 1 |
请完成以下Java代码 | public void deleteMobileAppById(TenantId tenantId, MobileAppId mobileAppId) {
log.trace("Executing deleteMobileAppById [{}]", mobileAppId.getId());
mobileAppDao.removeById(tenantId, mobileAppId.getId());
eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entityId(mobileAppId).build());
}
@Override
public MobileApp findMobileAppById(TenantId tenantId, MobileAppId mobileAppId) {
log.trace("Executing findMobileAppById [{}] [{}]", tenantId, mobileAppId);
return mobileAppDao.findById(tenantId, mobileAppId.getId());
}
@Override
public PageData<MobileApp> findMobileAppsByTenantId(TenantId tenantId, PlatformType platformType, PageLink pageLink) {
log.trace("Executing findMobileAppInfosByTenantId [{}]", tenantId);
return mobileAppDao.findByTenantId(tenantId, platformType, pageLink);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findMobileAppById(tenantId, new MobileAppId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(mobileAppDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override | @Transactional
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
deleteMobileAppById(tenantId, (MobileAppId) id);
}
@Override
public MobileApp findByBundleIdAndPlatformType(TenantId tenantId, MobileAppBundleId mobileAppBundleId, PlatformType platformType) {
log.trace("Executing findAndroidQrConfig, tenantId [{}], mobileAppBundleId [{}]", tenantId, mobileAppBundleId);
return mobileAppDao.findByBundleIdAndPlatformType(tenantId, mobileAppBundleId, platformType);
}
@Override
public MobileApp findMobileAppByPkgNameAndPlatformType(String pkgName, PlatformType platformType) {
log.trace("Executing findMobileAppByPkgNameAndPlatformType, pkgName [{}], platform [{}]", pkgName, platformType);
Validator.checkNotNull(platformType, PLATFORM_TYPE_IS_REQUIRED);
return mobileAppDao.findByPkgNameAndPlatformType(TenantId.SYS_TENANT_ID, pkgName, platformType);
}
@Override
public void deleteByTenantId(TenantId tenantId) {
log.trace("Executing deleteByTenantId, tenantId [{}]", tenantId);
mobileAppDao.deleteByTenantId(tenantId);
}
@Override
public EntityType getEntityType() {
return EntityType.MOBILE_APP;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\mobile\MobileAppServiceImpl.java | 1 |
请完成以下Java代码 | public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setStackabilityFactor (final int StackabilityFactor)
{
set_Value (COLUMNNAME_StackabilityFactor, StackabilityFactor);
}
@Override
public int getStackabilityFactor() | {
return get_ValueAsInt(COLUMNNAME_StackabilityFactor);
}
@Override
public void setWidth (final @Nullable BigDecimal Width)
{
set_Value (COLUMNNAME_Width, Width);
}
@Override
public BigDecimal getWidth()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PackingMaterial.java | 1 |
请完成以下Java代码 | private DocumentFilterDescriptorsProvider getFilterDescriptorsProvider()
{
return PackageableViewFilters.getDescriptors();
}
@Override
public PackageableView createView(final @NonNull CreateViewRequest request)
{
final ViewId viewId = request.getViewId();
viewId.assertWindowId(PickingConstantsV2.WINDOWID_PackageableView);
final DocumentFilterDescriptorsProvider filterDescriptors = getFilterDescriptorsProvider();
final PackageableRowsData rowsData = rowsRepo.newPackageableRowsData()
.filters(request.getFiltersUnwrapped(filterDescriptors))
.stickyFilters(request.getStickyFilters())
.build();
return PackageableView.builder()
.viewId(viewId)
.rowsData(rowsData)
.relatedProcessDescriptors(getRelatedProcessDescriptors())
.viewFilterDescriptors(filterDescriptors)
.build();
}
private Iterable<? extends RelatedProcessDescriptor> getRelatedProcessDescriptors()
{
return ImmutableList.of(
createProcessDescriptor(PackageablesView_OpenProductsToPick.class),
createProcessDescriptor(PackageablesView_UnlockFromLoggedUser.class),
createProcessDescriptor(PackageablesView_UnlockAll.class),
createProcessDescriptor(PackageablesView_PrintPicklist.class));
} | private RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass)
{
final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class);
final AdProcessId processId = adProcessDAO.retrieveProcessIdByClass(processClass);
if (processId == null)
{
throw new AdempiereException("No processId found for " + processClass);
}
return RelatedProcessDescriptor.builder()
.processId(processId)
.anyTable().anyWindow()
.displayPlace(DisplayPlace.ViewQuickActions)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\PackageableViewFactoryV2.java | 1 |
请完成以下Java代码 | public OffsetDateTime getPeakVisibilityTime() {
return peakVisibilityTime;
}
public void setPeakVisibilityTime(OffsetDateTime peakVisibilityTime) {
this.peakVisibilityTime = peakVisibilityTime;
}
public Integer getPeakVisibilityTimeOffset() {
return peakVisibilityTimeOffset;
}
public void setPeakVisibilityTimeOffset(Integer peakVisibilityTimeOffset) {
this.peakVisibilityTimeOffset = peakVisibilityTimeOffset;
}
public ZonedDateTime getNextExpectedAppearance() { | return nextExpectedAppearance;
}
public void setNextExpectedAppearance(ZonedDateTime nextExpectedAppearance) {
this.nextExpectedAppearance = nextExpectedAppearance;
}
public OffsetDateTime getLastRecordedSighting() {
return lastRecordedSighting;
}
public void setLastRecordedSighting(OffsetDateTime lastRecordedSighting) {
this.lastRecordedSighting = lastRecordedSighting;
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\timezonestorage\AstronomicalObservation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setPayWayName(String payWayName) {
this.payWayName = payWayName == null ? null : payWayName.trim();
}
public Date getPaySuccessTime() {
return paySuccessTime;
}
public void setPaySuccessTime(Date paySuccessTime) {
this.paySuccessTime = paySuccessTime;
}
public Date getCompleteTime() {
return completeTime;
}
public void setCompleteTime(Date completeTime) {
this.completeTime = completeTime;
}
public String getIsRefund() {
return isRefund;
}
public void setIsRefund(String isRefund) {
this.isRefund = isRefund == null ? null : isRefund.trim();
}
public Short getRefundTimes() { | return refundTimes;
}
public void setRefundTimes(Short refundTimes) {
this.refundTimes = refundTimes;
}
public BigDecimal getSuccessRefundAmount() {
return successRefundAmount;
}
public void setSuccessRefundAmount(BigDecimal successRefundAmount) {
this.successRefundAmount = successRefundAmount;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistakeScratchPool.java | 2 |
请完成以下Java代码 | private String writeMap(Map<String, Object> data) {
try {
return writeValueAsString(data);
}
catch (Exception ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
}
abstract String writeValueAsString(Map<String, Object> data) throws Exception;
}
/**
* Nested class to protect from getting {@link NoClassDefFoundError} when Jackson 2 is
* not on the classpath.
*
* @deprecated This is used to allow transition to Jackson 3. Use {@link Jackson3}
* instead.
*/
@Deprecated(forRemoval = true, since = "7.0")
private static final class Jackson2 {
private static ObjectMapper createObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
ClassLoader classLoader = Jackson2.class.getClassLoader();
List<Module> securityModules = SecurityJackson2Modules.getModules(classLoader);
objectMapper.registerModules(securityModules);
objectMapper.registerModule(new OAuth2AuthorizationServerJackson2Module());
return objectMapper;
} | }
/**
* Nested class used to get a common default instance of {@link JsonMapper}. It is in
* a nested class to protect from getting {@link NoClassDefFoundError} when Jackson 3
* is not on the classpath.
*/
private static final class Jackson3 {
private static JsonMapper createJsonMapper() {
List<JacksonModule> modules = SecurityJacksonModules.getModules(Jackson3.class.getClassLoader());
return JsonMapper.builder().addModules(modules).build();
}
}
static class JdbcRegisteredClientRepositoryRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.resources()
.registerResource(new ClassPathResource(
"org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql"));
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\client\JdbcRegisteredClientRepository.java | 1 |
请完成以下Java代码 | protected AutoDeploymentStrategy<CmmnEngine> getAutoDeploymentStrategy(final String mode) {
AutoDeploymentStrategy<CmmnEngine> result = new DefaultAutoDeploymentStrategy();
for (final AutoDeploymentStrategy<CmmnEngine> strategy : deploymentStrategies) {
if (strategy.handlesMode(mode)) {
result = strategy;
break;
}
}
return result;
}
public Collection<AutoDeploymentStrategy<CmmnEngine>> getDeploymentStrategies() {
return deploymentStrategies;
}
public void setDeploymentStrategies(Collection<AutoDeploymentStrategy<CmmnEngine>> deploymentStrategies) {
this.deploymentStrategies = deploymentStrategies;
}
@Override
public void start() {
synchronized (lifeCycleMonitor) {
if (!isRunning()) {
enginesBuild.forEach(name -> {
CmmnEngine cmmnEngine = CmmnEngines.getCmmnEngine(name);
cmmnEngine.startExecutors(); | autoDeployResources(cmmnEngine);
});
running = true;
}
}
}
@Override
public void stop() {
synchronized (lifeCycleMonitor) {
running = false;
}
}
@Override
public boolean isRunning() {
return running;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-spring\src\main\java\org\flowable\cmmn\spring\SpringCmmnEngineConfiguration.java | 1 |
请完成以下Java代码 | public class OptimizedRandomKeyTrackingMap<K, V> {
private final Map<K, V> delegate = new HashMap<>();
private final List<K> keys = new ArrayList<>();
private final Map<K, Integer> keyToIndex = new HashMap<>();
public void put(K key, V value) {
V previousValue = delegate.put(key, value);
if (previousValue == null) {
keys.add(key);
keyToIndex.put(key, keys.size() - 1);
}
}
public V remove(K key) {
V removedValue = delegate.remove(key);
if (removedValue != null) {
Integer index = keyToIndex.remove(key);
if (index != null) {
removeKeyAtIndex(index);
}
}
return removedValue;
}
private void removeKeyAtIndex(int index) {
int lastIndex = keys.size() - 1;
if (index == lastIndex) {
keys.remove(lastIndex);
return;
} | K lastKey = keys.get(lastIndex);
keys.set(index, lastKey);
keyToIndex.put(lastKey, index);
keys.remove(lastIndex);
}
public V getRandomValue() {
if (keys.isEmpty()) {
return null;
}
int randomIndex = ThreadLocalRandom.current().nextInt(keys.size());
K randomKey = keys.get(randomIndex);
return delegate.get(randomKey);
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps-9\src\main\java\com\baeldung\map\randommapkey\OptimizedRandomKeyTrackingMap.java | 1 |
请完成以下Java代码 | public void afterPropertiesSet() throws Exception {
if (this.taskScheduler != null) {
this.taskScheduler.afterPropertiesSet();
}
}
@Override
public void destroy() throws Exception {
if (this.taskScheduler != null) {
this.taskScheduler.shutdown();
}
}
/**
* Sets the {@link Clock} used when generating one-time token and checking token
* expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
/**
* The default {@code Function} that maps {@link OneTimeToken} to a {@code List} of
* {@link SqlParameterValue}.
*
* @author Max Batischev
* @since 6.4
*/
private static class OneTimeTokenParametersMapper implements Function<OneTimeToken, List<SqlParameterValue>> { | @Override
public List<SqlParameterValue> apply(OneTimeToken oneTimeToken) {
List<SqlParameterValue> parameters = new ArrayList<>();
parameters.add(new SqlParameterValue(Types.VARCHAR, oneTimeToken.getTokenValue()));
parameters.add(new SqlParameterValue(Types.VARCHAR, oneTimeToken.getUsername()));
parameters.add(new SqlParameterValue(Types.TIMESTAMP, Timestamp.from(oneTimeToken.getExpiresAt())));
return parameters;
}
}
/**
* The default {@link RowMapper} that maps the current row in
* {@code java.sql.ResultSet} to {@link OneTimeToken}.
*
* @author Max Batischev
* @since 6.4
*/
private static class OneTimeTokenRowMapper implements RowMapper<OneTimeToken> {
@Override
public OneTimeToken mapRow(ResultSet rs, int rowNum) throws SQLException {
String tokenValue = rs.getString("token_value");
String userName = rs.getString("username");
Instant expiresAt = rs.getTimestamp("expires_at").toInstant();
return new DefaultOneTimeToken(tokenValue, userName, expiresAt);
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\ott\JdbcOneTimeTokenService.java | 1 |
请完成以下Java代码 | public Long getLongValue() {
return longValue;
}
@Override
public void setLongValue(Long longValue) {
this.longValue = longValue;
}
@Override
public Double getDoubleValue() {
return doubleValue;
}
@Override
public void setDoubleValue(Double doubleValue) {
this.doubleValue = doubleValue;
}
public String getByteArrayValueId() {
return byteArrayField.getByteArrayId();
}
public void setByteArrayValueId(String byteArrayId) {
byteArrayField.setByteArrayId(byteArrayId);
}
@Override
public byte[] getByteArrayValue() {
return byteArrayField.getByteArrayValue();
}
@Override
public void setByteArrayValue(byte[] bytes) {
byteArrayField.setByteArrayValue(bytes);
}
public void setValue(TypedValue typedValue) {
typedValueField.setValue(typedValue);
}
public String getSerializerName() {
return typedValueField.getSerializerName();
}
public void setSerializerName(String serializerName) { | typedValueField.setSerializerName(serializerName);
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public void delete() {
byteArrayField.deleteByteArrayValue();
Context
.getCommandContext()
.getDbEntityManager()
.delete(this);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDecisionInputInstanceEntity.java | 1 |
请完成以下Java代码 | public int getExportedRowCount()
{
return exportedRowCount.intValue();
}
protected int incrementExportedRowCount()
{
return exportedRowCount.incrementAndGet();
}
@Override
public ExportStatus getExportStatus()
{
return exportStatus;
}
protected void setExportStatus(ExportStatus newStatus)
{
exportStatus = newStatus;
}
@Override
public Throwable getError()
{
return error;
}
@Override
public final void export(@NonNull final OutputStream out)
{
final IExportDataSource dataSource = getDataSource();
Check.assumeNotNull(dataSource, "dataSource not null");
Check.assume(ExportStatus.NotStarted.equals(getExportStatus()), "ExportStatus shall be " + ExportStatus.NotStarted + " and not {}", getExportStatus());
IExportDataDestination dataDestination = null;
try
{
// Init dataDestination
// NOTE: make sure we are doing this as first thing, because if anything fails, we need to close this "destination"
dataDestination = createDataDestination(out);
// Init status
error = null;
setExportStatus(ExportStatus.Running);
monitor.exportStarted(this);
while (dataSource.hasNext())
{
final List<Object> values = dataSource.next();
// for (int i = 1; i <= 3000; i++) // debugging
// {
appendRow(dataDestination, values);
incrementExportedRowCount();
// }
}
}
catch (Exception e)
{
final AdempiereException ex = new AdempiereException("Error while exporting line " + getExportedRowCount() + ": " + e.getLocalizedMessage(), e);
error = ex;
throw ex;
}
finally
{
close(dataSource);
close(dataDestination);
dataDestination = null;
setExportStatus(ExportStatus.Finished);
// Notify the monitor but discard all exceptions because we don't want to throw an "false" exception in finally block
try
{
monitor.exportFinished(this);
} | catch (Exception e)
{
logger.error("Error while invoking monitor(finish): " + e.getLocalizedMessage(), e);
}
}
logger.info("Exported " + getExportedRowCount() + " rows");
}
protected abstract void appendRow(IExportDataDestination dataDestination, List<Object> values) throws IOException;
protected abstract IExportDataDestination createDataDestination(OutputStream out) throws IOException;
/**
* Close {@link Closeable} object.
*
* NOTE: if <code>closeableObj</code> is not implementing {@link Closeable} or is null, nothing will happen
*
* @param closeableObj
*/
private static final void close(Object closeableObj)
{
if (closeableObj instanceof Closeable)
{
final Closeable closeable = (Closeable)closeableObj;
try
{
closeable.close();
}
catch (IOException e)
{
e.printStackTrace(); // NOPMD by tsa on 3/17/13 1:30 PM
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\AbstractExporter.java | 1 |
请完成以下Java代码 | private static final class FactAcctListener2ModelValidationEngineAdapter implements IFactAcctListener
{
public static final transient FactAcctListener2ModelValidationEngineAdapter instance = new FactAcctListener2ModelValidationEngineAdapter();
private FactAcctListener2ModelValidationEngineAdapter()
{
}
private final void fireDocValidate(final Object document, final int timing)
{
final Object model;
if (document instanceof IDocument)
{
model = ((IDocument)document).getDocumentModel();
}
else
{
model = document;
}
ModelValidationEngine.get().fireDocValidate(model, timing);
}
@Override
public void onBeforePost(final Object document)
{
fireDocValidate(document, ModelValidator.TIMING_BEFORE_POST); | }
@Override
public void onAfterPost(final Object document)
{
fireDocValidate(document, ModelValidator.TIMING_AFTER_POST);
}
// @Override
// public void onAfterUnpost(final Object document)
// {
// fireDocValidate(document, ModelValidator.TIMING_AFTER_UNPOST);
// }
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\impl\FactAcctListenersService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AuthController {
private final ClientRegistration registration;
private final AppProperties appProperties;
public AuthController(ClientRegistrationRepository registrations, AppProperties appProperties) {
this.registration = registrations.findByRegistrationId("oidc");
this.appProperties = appProperties;
}
//FIXME: use keycloak rest api to handle these
// @GetMapping("/change-password")
// public String changePwd(RedirectAttributes redirectAttributes, HttpServletRequest req, HttpServletResponse resp) {
// return getKeyCloakAccountUrl(redirectAttributes, req, resp) + "/#/security/signingin";
// }
//
// @GetMapping("/settings")
// public String settings(RedirectAttributes redirectAttributes, HttpServletRequest req, HttpServletResponse resp) {
// return getKeyCloakAccountUrl(redirectAttributes, req, resp);
// }
@GetMapping("/logout")
public String logout(HttpServletRequest request, @AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken) {
var logoutUrlSb = new StringBuilder(); | logoutUrlSb.append(this.registration.getProviderDetails().getConfigurationMetadata().get("end_session_endpoint").toString());
String originUrl = request.getHeader(HttpHeaders.ORIGIN);
if (!StringUtils.hasText(originUrl)) {
originUrl = appProperties.getWeb().getBaseUrl() + "?logout=true";
}
logoutUrlSb.append("?id_token_hint=").append(idToken.getTokenValue()).append("&post_logout_redirect_uri=").append(originUrl);
request.getSession().invalidate();
return "redirect:" + logoutUrlSb;
}
@GetMapping("/login")
public String login() {
return "redirect:/oauth2/authorization/oidc"; //this will redirect to login page
}
} | repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\web\mvc\AuthController.java | 2 |
请完成以下Java代码 | public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public RecordKey getRecordKey() {
return recordKey;
}
public void setRecordKey(RecordKey recordKey) {
this.recordKey = recordKey;
}
public KafkaPartition getPartition() {
return partition;
}
public void setPartition(KafkaPartition partition) {
this.partition = partition;
}
@JsonInclude(Include.NON_NULL)
public static class KafkaPartition {
protected String eventField;
protected String roundRobin;
protected String delegateExpression;
public String getEventField() {
return eventField;
}
public void setEventField(String eventField) {
this.eventField = eventField;
}
public String getRoundRobin() {
return roundRobin;
}
public void setRoundRobin(String roundRobin) {
this.roundRobin = roundRobin;
}
public String getDelegateExpression() {
return delegateExpression;
}
public void setDelegateExpression(String delegateExpression) {
this.delegateExpression = delegateExpression;
}
}
@JsonInclude(Include.NON_NULL)
public static class RecordKey {
protected String fixedValue; | protected String eventField;
protected String delegateExpression;
public String getFixedValue() {
return fixedValue;
}
public void setFixedValue(String fixedValue) {
this.fixedValue = fixedValue;
}
public String getEventField() {
return eventField;
}
public void setEventField(String eventField) {
this.eventField = eventField;
}
public String getDelegateExpression() {
return delegateExpression;
}
public void setDelegateExpression(String delegateExpression) {
this.delegateExpression = delegateExpression;
}
// backward compatibility
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static RecordKey fromFixedValue(String fixedValue) {
RecordKey recordKey = new RecordKey();
recordKey.setFixedValue(fixedValue);
return recordKey;
}
}
} | repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\KafkaOutboundChannelModel.java | 1 |
请完成以下Java代码 | public long getTaxJavaWay() {
return grossIncome * taxInPercents / 100;
}
@Formula("grossIncome * taxInPercents / 100")
private long tax;
@OneToMany
@JoinColumn(name = "employee_id")
@Where(clause = "deleted = false")
private Set<Phone> phones = new HashSet<>(0);
public Employee() {
}
public Employee(long grossIncome, int taxInPercents) {
this.grossIncome = grossIncome;
this.taxInPercents = taxInPercents;
}
public Integer getId() {
return id;
}
public long getGrossIncome() {
return grossIncome;
}
public int getTaxInPercents() {
return taxInPercents;
}
public long getTax() { | return tax;
}
public void setId(Integer id) {
this.id = id;
}
public void setGrossIncome(long grossIncome) {
this.grossIncome = grossIncome;
}
public void setTaxInPercents(int taxInPercents) {
this.taxInPercents = taxInPercents;
}
public boolean getDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public Set<Phone> getPhones() {
return phones;
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\pojo\Employee.java | 1 |
请完成以下Java代码 | public void markOccurrence(String name) {
markOccurrence(name, 1);
}
public void markOccurrence(String name, long times) {
markOccurrence(dbMeters, name, times);
markOccurrence(diagnosticsMeters, name, times);
}
public void markDiagnosticsOccurrence(String name, long times) {
markOccurrence(diagnosticsMeters, name, times);
}
protected void markOccurrence(Map<String, Meter> meters, String name, long times) {
Meter meter = meters.get(name);
if (meter != null) {
meter.markTimes(times);
}
}
/**
* Creates a meter for both database and diagnostics collection.
*/
public void createMeter(String name) { | Meter dbMeter = new Meter(name);
dbMeters.put(name, dbMeter);
Meter diagnosticsMeter = new Meter(name);
diagnosticsMeters.put(name, diagnosticsMeter);
}
/**
* Creates a meter only for database collection.
*/
public void createDbMeter(String name) {
Meter dbMeter = new Meter(name);
dbMeters.put(name, dbMeter);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\MetricsRegistry.java | 1 |
请完成以下Java代码 | public List<HistoricProcessInstance> call() throws Exception {
return new HistoricProcessInstanceQueryImpl().processInstanceIds(new HashSet<String>(processInstanceIds)).list();
}
});
if (failIfNotExists) {
if (processInstanceIds.size() == 1) {
ensureNotEmpty(BadUserRequestException.class, "No historic process instance found with id: " + processInstanceIds.get(0), "historicProcessInstanceIds",
instances);
} else {
ensureNotEmpty(BadUserRequestException.class, "No historic process instances found", "historicProcessInstanceIds", instances);
}
}
List<String> existingIds = new ArrayList<String>();
for (HistoricProcessInstance historicProcessInstance : instances) {
existingIds.add(historicProcessInstance.getId());
for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkDeleteHistoricProcessInstance(historicProcessInstance);
}
ensureNotNull(BadUserRequestException.class, "Process instance is still running, cannot delete historic process instance: " + historicProcessInstance, "instance.getEndTime()", historicProcessInstance.getEndTime());
}
if(failIfNotExists) {
ArrayList<String> nonExistingIds = new ArrayList<String>(processInstanceIds);
nonExistingIds.removeAll(existingIds);
if(nonExistingIds.size() != 0) {
throw new BadUserRequestException("No historic process instance found with id: " + nonExistingIds);
}
}
if(existingIds.size() > 0) { | commandContext.getHistoricProcessInstanceManager().deleteHistoricProcessInstanceByIds(existingIds);
}
writeUserOperationLog(commandContext, existingIds.size());
return null;
}
protected void writeUserOperationLog(CommandContext commandContext, int numInstances) {
List<PropertyChange> propertyChanges = new ArrayList<>();
propertyChanges.add(new PropertyChange("nrOfInstances", null, numInstances));
propertyChanges.add(new PropertyChange("async", null, false));
commandContext.getOperationLogManager()
.logProcessInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE_HISTORY,
null,
null,
null,
propertyChanges);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteHistoricProcessInstancesCmd.java | 1 |
请完成以下Java代码 | private static final class PropertiesIterator implements Iterator<Entry> {
private final Iterator<Map.Entry<Object, Object>> iterator;
private PropertiesIterator(Properties properties) {
this.iterator = properties.entrySet().iterator();
}
@Override
public boolean hasNext() {
return this.iterator.hasNext();
}
@Override
public Entry next() {
Map.Entry<Object, Object> entry = this.iterator.next();
return new Entry((String) entry.getKey(), (String) entry.getValue());
}
@Override
public void remove() {
throw new UnsupportedOperationException("InfoProperties are immutable.");
}
} | /**
* Property entry.
*/
public static final class Entry {
private final String key;
private final String value;
private Entry(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return this.key;
}
public String getValue() {
return this.value;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\InfoProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void fetchAuthorDtoReadWriteMode() {
AuthorDto authorDto = authorRepository.findTopByGenre("Anthology");
System.out.println("Author DTO: " + authorDto.getName() + ", " + authorDto.getAge());
org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext();
System.out.println("No of managed entities : " + persistenceContext.getNumberOfManagedEntities());
}
@Transactional(readOnly = true)
public void fetchAuthorDtoReadOnlyMode() {
AuthorDto authorDto = authorRepository.findTopByGenre("Anthology");
System.out.println("Author DTO: " + authorDto.getName() + ", " + authorDto.getAge());
org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext();
System.out.println("No of managed entities : " + persistenceContext.getNumberOfManagedEntities());
}
private org.hibernate.engine.spi.PersistenceContext getPersistenceContext() {
SharedSessionContractImplementor sharedSession = entityManager.unwrap(
SharedSessionContractImplementor.class
); | return sharedSession.getPersistenceContext();
}
private void displayInformation(String phase, Author author) {
System.out.println("\n-------------------------------------");
System.out.println("Phase:" + phase);
System.out.println("Entity: " + author);
System.out.println("-------------------------------------");
org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext();
System.out.println("Has only non read entities : " + persistenceContext.hasNonReadOnlyEntities());
EntityEntry entityEntry = persistenceContext.getEntry(author);
Object[] loadedState = entityEntry.getLoadedState();
Status status = entityEntry.getStatus();
System.out.println("Entity entry : " + entityEntry);
System.out.println("Status:" + status);
System.out.println("Loaded state: " + Arrays.toString(loadedState));
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootTransactionalReadOnlyMeaning\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | private String getSqlWithWhereClauseAndDocBaseTypeIfPresent(@NonNull final ExternalSystemScriptedExportConversionConfig config)
{
final String rootTableName = tableDAO.retrieveTableName(config.getAdTableId());
final String rootKeyColumnName = columnBL.getSingleKeyColumn(rootTableName);
return Optional.ofNullable(config.getDocBaseType())
.map(docBaseType -> "SELECT " + rootKeyColumnName +
" FROM " + rootTableName + " root" +
" WHERE " + config.getWhereClause() +
" AND root." + rootKeyColumnName + " = ?" +
" AND EXISTS (" +
" SELECT 1 FROM C_DocType targetType" +
" WHERE targetType.DocBaseType = '" + docBaseType.getCode() + "'" +
" AND targetType.C_DocType_ID = root.C_DocType_ID" +
")")
.orElseGet(() -> "SELECT " + rootKeyColumnName
+ " FROM " + rootTableName
+ " WHERE " + rootKeyColumnName + "=?"
+ " AND " + config.getWhereClause());
}
@NonNull
private String getOutboundProcessResponse(
@NonNull final ExternalSystemScriptedExportConversionConfig config,
@NonNull final Properties context,
@NonNull final String outboundDataProcessRecordId)
{
final String rootTableName = tableDAO.retrieveTableName(config.getAdTableId());
final String rootKeyColumnName = columnBL.getSingleKeyColumn(rootTableName);
final ProcessExecutor processExecutor = ProcessInfo.builder()
.setCtx(context)
.setRecord(TableRecordReference.of(config.getAdTableId(), StringUtils.toIntegerOrZero(outboundDataProcessRecordId)))
.setAD_Process_ID(config.getOutboundDataProcessId())
.addParameter(rootKeyColumnName, outboundDataProcessRecordId)
.buildAndPrepareExecution() | .executeSync();
final Resource resource = Optional.ofNullable(processExecutor.getResult())
.map(ProcessExecutionResult::getReportDataResource)
.orElse(null);
if (resource == null || !resource.exists())
{
throw new AdempiereException("Process did not return a valid Resource")
.appendParametersToMessage()
.setParameter("OutboundDataProcessId", config.getOutboundDataProcessId());
}
try (final InputStream in = resource.getInputStream())
{
return StreamUtils.copyToString(in, StandardCharsets.UTF_8);
}
catch (final IOException ex)
{
throw new AdempiereException("Failed to read process output Resource", ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\scriptedexportconversion\ExternalSystemScriptedExportConversionService.java | 1 |
请完成以下Java代码 | public boolean containsKey (final IValidationContext evalCtx, final Object key)
{
// linear search in p_data
final int size = getSize();
for (int i = 0; i < size; i++)
{
final Object oo = getElementAt(i);
if (oo != null && oo instanceof NamePair)
{
NamePair pp = (NamePair)oo;
if (pp.getID().equals(key))
return true;
}
}
return false;
} // containsKey
/**
* Get Object of Key Value
* @param key key
* @return Object or null
*/
@Override
public NamePair get (final IValidationContext evalCtx, Object key)
{
// linear search in m_data
final int size = getSize();
for (int i = 0; i < size; i++)
{
Object oo = getElementAt(i);
if (oo != null && oo instanceof NamePair)
{
NamePair pp = (NamePair)oo;
if (pp.getID().equals(key))
return pp;
}
}
return null;
} // get
/**
* Return data as sorted Array
* @param mandatory mandatory
* @param onlyValidated only validated
* @param onlyActive only active
* @param temporary force load for temporary display
* @return list of data
*/
@Override
public List<Object> getData (boolean mandatory,
boolean onlyValidated, boolean onlyActive, boolean temporary)
{
final int size = getSize();
final List<Object> list = new ArrayList<Object>(size);
for (int i = 0; i < size; i++)
{
final Object oo = getElementAt(i);
list.add(oo);
}
// Sort Data
if (m_keyColumn.endsWith("_ID"))
{
KeyNamePair p = KeyNamePair.EMPTY;
if (!mandatory)
list.add (p); | Collections.sort (list, p);
}
else
{
ValueNamePair p = ValueNamePair.EMPTY;
if (!mandatory)
list.add (p);
Collections.sort (list, p);
}
return list;
} // getArray
/**
* Refresh Values (nop)
* @return number of cache
*/
@Override
public int refresh()
{
return getSize();
} // refresh
@Override
public String getTableName()
{
if (Check.isEmpty(m_keyColumn, true))
{
return null;
}
return MQuery.getZoomTableName(m_keyColumn);
}
/**
* Get underlying fully qualified Table.Column Name
* @return column name
*/
@Override
public String getColumnName()
{
return m_keyColumn;
} // getColumnName
@Override
public String getColumnNameNotFQ()
{
return m_keyColumn;
}
} // XLookup | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\XLookup.java | 1 |
请完成以下Java代码 | public void log(@NonNull final DpdClientLogEvent event)
{
try
{
createLogRecord(event);
}
catch (final Exception ex)
{
logger.warn("Failed creating Dpd log record: {}", event, ex);
}
normalLogging(event);
}
private void normalLogging(final DpdClientLogEvent event)
{
if (!logger.isTraceEnabled())
{
return;
}
if (event.getResponseException() != null)
{
logger.trace("Dpd Send/Receive error: {}", event, event.getResponseException());
}
else
{
logger.trace("Dpd Send/Receive OK: {}", event);
}
} | private void createLogRecord(@NonNull final DpdClientLogEvent event)
{
final I_DPD_StoreOrder_Log logRecord = InterfaceWrapperHelper.newInstance(I_DPD_StoreOrder_Log.class);
logRecord.setConfigSummary(event.getConfigSummary());
logRecord.setDurationMillis((int)event.getDurationMillis());
logRecord.setDPD_StoreOrder_ID(event.getDeliveryOrderRepoId());
//noinspection ConstantConditions
logRecord.setRequestMessage(event.getRequestAsString());
if (event.getResponseException() != null)
{
logRecord.setIsError(true);
final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(event.getResponseException());
logRecord.setAD_Issue_ID(issueId.getRepoId());
}
else
{
logRecord.setIsError(false);
//noinspection ConstantConditions
logRecord.setResponseMessage(event.getResponseAsString());
}
InterfaceWrapperHelper.save(logRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java\de\metas\shipper\gateway\dpd\logger\DpdDatabaseClientLogger.java | 1 |
请完成以下Java代码 | public AdImage getById(@NonNull final AdImageId adImageId)
{
return cache.getOrLoad(adImageId, this::retrieveById);
}
private AdImage retrieveById(@NonNull final AdImageId adImageId)
{
final I_AD_Image record = InterfaceWrapperHelper.load(adImageId, I_AD_Image.class);
if (record == null)
{
throw new AdempiereException("No AD_Image found for " + adImageId);
}
return fromRecord(record);
} | public static AdImage fromRecord(@NonNull I_AD_Image record)
{
final String filename = record.getName();
return AdImage.builder()
.id(AdImageId.ofRepoId(record.getAD_Image_ID()))
.lastModified(record.getUpdated().toInstant())
.filename(filename)
.contentType(MimeType.getMimeType(filename))
.data(record.getBinaryData())
.clientAndOrgId(ClientAndOrgId.ofClientAndOrg(record.getAD_Client_ID(), record.getAD_Org_ID()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\image\AdImageRepository.java | 1 |
请完成以下Java代码 | public class RuleChainDebugEvent extends Event {
private static final long serialVersionUID = -386392236201116767L;
@Builder
private RuleChainDebugEvent(TenantId tenantId, UUID entityId, String serviceId, UUID id, long ts, String message, String error) {
super(tenantId, entityId, serviceId, id, ts);
this.message = message;
this.error = error;
}
@Getter
@Setter
private String message;
@Getter
@Setter
private String error; | @Override
public EventType getType() {
return EventType.DEBUG_RULE_CHAIN;
}
@Override
public EventInfo toInfo(EntityType entityType) {
EventInfo eventInfo = super.toInfo(entityType);
var json = (ObjectNode) eventInfo.getBody();
putNotNull(json, "message", message);
putNotNull(json, "error", error);
return eventInfo;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\event\RuleChainDebugEvent.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SupportIDType
{
@JsonCreator
public static SupportIDType of(final int valueAsInt)
{
return new SupportIDType(valueAsInt);
}
public static final int MAX_VALUE = 999999;
private final int valueAsInt;
private SupportIDType(final int valueAsInt)
{
if (valueAsInt < 1 || valueAsInt > MAX_VALUE)
{
throw new IllegalArgumentException("SupportID value shall be between 1 and " + MAX_VALUE + " but it was: " + valueAsInt); | }
this.valueAsInt = valueAsInt;
}
@JsonValue
public int toJson()
{
return valueAsInt;
}
public String getValueAsString()
{
return String.valueOf(getValueAsInt());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\order\SupportIDType.java | 2 |
请完成以下Java代码 | protected String doIt() throws Exception
{
final ApiRequestIterator apiRequestIterator = getSelectedRequests();
apiRequestReplayService.replayApiRequests(apiRequestIterator);
return MSG_OK;
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.getSelectionSize().isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@NonNull
private ApiRequestIterator getSelectedRequests()
{
final IQueryBuilder<I_API_Request_Audit> selectedApiRequestsQueryBuilder = retrieveSelectedRecordsQueryBuilder(I_API_Request_Audit.class); | if (isOnlyWithError)
{
selectedApiRequestsQueryBuilder.addEqualsFilter(I_API_Request_Audit.COLUMNNAME_Status, Status.ERROR.getCode());
}
final IQueryOrderBy orderBy = queryBL.createQueryOrderByBuilder(I_API_Request_Audit.class)
.addColumnAscending(I_API_Request_Audit.COLUMNNAME_Time)
.createQueryOrderBy();
final Iterator<I_API_Request_Audit> timeSortedApiRequests = selectedApiRequestsQueryBuilder.create()
.setOrderBy(orderBy)
.iterate(I_API_Request_Audit.class);
return ApiRequestIterator.of(timeSortedApiRequests, ApiRequestAuditRepository::recordToRequestAudit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\process\API_Audit_Repeat.java | 1 |
请完成以下Java代码 | public String toString()
{
return toStringSyntax();
}
public String toStringSyntax()
{
if (list.isEmpty())
{
return "";
}
return list.stream()
.map(DocumentQueryOrderBy::toStringSyntax)
.collect(Collectors.joining(","));
}
public ImmutableList<DocumentQueryOrderBy> toList()
{
return list;
}
public boolean isEmpty()
{
return list.isEmpty();
}
public static boolean equals(final DocumentQueryOrderByList list1, final DocumentQueryOrderByList list2)
{
return Objects.equals(list1, list2);
}
public Stream<DocumentQueryOrderBy> stream()
{
return list.stream();
}
public void forEach(@NonNull final Consumer<DocumentQueryOrderBy> consumer) | {
list.forEach(consumer);
}
public <T extends IViewRow> Comparator<T> toComparator(
@NonNull final FieldValueExtractor<T> fieldValueExtractor,
@NonNull final JSONOptions jsonOpts)
{
// used in case orderBys is empty or whatever else goes wrong
final Comparator<T> noopComparator = (o1, o2) -> 0;
return stream()
.map(orderBy -> orderBy.asComparator(fieldValueExtractor, jsonOpts))
.reduce(Comparator::thenComparing)
.orElse(noopComparator);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentQueryOrderByList.java | 1 |
请完成以下Java代码 | protected HistoricBatchEntity loadBatchEntity(BatchEntity batch) {
String batchId = batch.getId();
HistoricBatchEntity cachedEntity = findInCache(HistoricBatchEntity.class, batchId);
if(cachedEntity != null) {
return cachedEntity;
} else {
return newBatchEventEntity(batch);
}
}
/** find a cached entity by primary key */
protected <T extends HistoryEvent> T findInCache(Class<T> type, String id) {
return Context.getCommandContext() | .getDbEntityManager()
.getCachedEntity(type, id);
}
@Override
protected ProcessDefinitionEntity getProcessDefinitionEntity(String processDefinitionId) {
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionEntity entity = null;
if(commandContext != null) {
entity = commandContext
.getDbEntityManager()
.getCachedEntity(ProcessDefinitionEntity.class, processDefinitionId);
}
return (entity != null) ? entity : super.getProcessDefinitionEntity(processDefinitionId);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\CacheAwareHistoryEventProducer.java | 1 |
请完成以下Java代码 | private CloseStatus adaptCloseStatus(CloseStatus closeStatus) {
int code = closeStatus.getCode();
if (code > 2999 && code < 5000) {
return closeStatus;
}
switch (code) {
case 1000:
case 1001:
case 1002:
case 1003:
case 1007:
case 1008:
case 1009:
case 1010:
case 1011:
return closeStatus;
case 1004:
// Should not be used in a close frame
// RESERVED;
case 1005:
// Should not be used in a close frame
// return CloseStatus.NO_STATUS_CODE;
case 1006:
// Should not be used in a close frame
// return CloseStatus.NO_CLOSE_FRAME;
case 1012:
// Not in RFC6455
// return CloseStatus.SERVICE_RESTARTED;
case 1013:
// Not in RFC6455
// return CloseStatus.SERVICE_OVERLOAD;
case 1015:
// Should not be used in a close frame
// return CloseStatus.TLS_HANDSHAKE_FAILURE;
default:
return CloseStatus.PROTOCOL_ERROR;
}
}
@Override
public Mono<Void> handle(WebSocketSession proxySession) {
Mono<Void> serverClose = proxySession.closeStatus()
.filter(__ -> session.isOpen())
.map(this::adaptCloseStatus)
.flatMap(session::close);
Mono<Void> proxyClose = session.closeStatus() | .filter(__ -> proxySession.isOpen())
.map(this::adaptCloseStatus)
.flatMap(proxySession::close);
// Use retain() for Reactor Netty
Mono<Void> proxySessionSend = proxySession
.send(session.receive().doOnNext(WebSocketMessage::retain).doOnNext(webSocketMessage -> {
if (log.isTraceEnabled()) {
log.trace("proxySession(send from client): " + proxySession.getId()
+ ", corresponding session:" + session.getId() + ", packet: "
+ webSocketMessage.getPayloadAsText());
}
}));
// .log("proxySessionSend", Level.FINE);
Mono<Void> serverSessionSend = session
.send(proxySession.receive().doOnNext(WebSocketMessage::retain).doOnNext(webSocketMessage -> {
if (log.isTraceEnabled()) {
log.trace("session(send from backend): " + session.getId()
+ ", corresponding proxySession:" + proxySession.getId() + " packet: "
+ webSocketMessage.getPayloadAsText());
}
}));
// .log("sessionSend", Level.FINE);
// Ensure closeStatus from one propagates to the other
Mono.when(serverClose, proxyClose).subscribe();
// Complete when both sessions are done
return Mono.zip(proxySessionSend, serverSessionSend).then();
}
/**
* Copy subProtocols so they are available downstream.
* @return available subProtocols.
*/
@Override
public List<String> getSubProtocols() {
return ProxyWebSocketHandler.this.subProtocols;
}
});
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\WebsocketRoutingFilter.java | 1 |
请完成以下Spring Boot application配置 | spring:
config:
import: "optional:configserver:http://config-service:8088"
activate:
on-profile: docker
---
spring:
application:
name: gateway-ser | vice
config:
import: "optional:configserver:http://localhost:8088" | repos\sample-spring-microservices-new-master\gateway-service\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public String getSuperCaseInstanceId() {
return superCaseInstanceId;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public String getTenantId() {
return tenantId;
}
public Boolean getActive() {
return active;
}
public Boolean getCompleted() {
return completed;
}
public Boolean getTerminated() {
return terminated;
}
public Boolean getClosed() {
return closed;
}
public static HistoricCaseInstanceDto fromHistoricCaseInstance(HistoricCaseInstance historicCaseInstance) {
HistoricCaseInstanceDto dto = new HistoricCaseInstanceDto(); | dto.id = historicCaseInstance.getId();
dto.businessKey = historicCaseInstance.getBusinessKey();
dto.caseDefinitionId = historicCaseInstance.getCaseDefinitionId();
dto.caseDefinitionKey = historicCaseInstance.getCaseDefinitionKey();
dto.caseDefinitionName = historicCaseInstance.getCaseDefinitionName();
dto.createTime = historicCaseInstance.getCreateTime();
dto.closeTime = historicCaseInstance.getCloseTime();
dto.durationInMillis = historicCaseInstance.getDurationInMillis();
dto.createUserId = historicCaseInstance.getCreateUserId();
dto.superCaseInstanceId = historicCaseInstance.getSuperCaseInstanceId();
dto.superProcessInstanceId = historicCaseInstance.getSuperProcessInstanceId();
dto.tenantId = historicCaseInstance.getTenantId();
dto.active = historicCaseInstance.isActive();
dto.completed = historicCaseInstance.isCompleted();
dto.terminated = historicCaseInstance.isTerminated();
dto.closed = historicCaseInstance.isClosed();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricCaseInstanceDto.java | 1 |
请完成以下Java代码 | public de.metas.contracts.model.I_C_Flatrate_Term getC_Flatrate_Term()
{
return get_ValueAsPO(COLUMNNAME_C_Flatrate_Term_ID, de.metas.contracts.model.I_C_Flatrate_Term.class);
}
@Override
public void setC_Flatrate_Term(final de.metas.contracts.model.I_C_Flatrate_Term C_Flatrate_Term)
{
set_ValueFromPO(COLUMNNAME_C_Flatrate_Term_ID, de.metas.contracts.model.I_C_Flatrate_Term.class, C_Flatrate_Term);
}
@Override
public void setC_Flatrate_Term_ID (final int C_Flatrate_Term_ID)
{
if (C_Flatrate_Term_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Flatrate_Term_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Flatrate_Term_ID, C_Flatrate_Term_ID);
}
@Override
public int getC_Flatrate_Term_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Flatrate_Term_ID);
}
@Override
public void setC_OLCand_ID (final int C_OLCand_ID)
{
if (C_OLCand_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OLCand_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OLCand_ID, C_OLCand_ID);
}
@Override
public int getC_OLCand_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_ID);
}
/**
* DocStatus AD_Reference_ID=131
* Reference name: _Document Status
*/
public static final int DOCSTATUS_AD_Reference_ID=131;
/** Drafted = DR */ | public static final String DOCSTATUS_Drafted = "DR";
/** Completed = CO */
public static final String DOCSTATUS_Completed = "CO";
/** Approved = AP */
public static final String DOCSTATUS_Approved = "AP";
/** NotApproved = NA */
public static final String DOCSTATUS_NotApproved = "NA";
/** Voided = VO */
public static final String DOCSTATUS_Voided = "VO";
/** Invalid = IN */
public static final String DOCSTATUS_Invalid = "IN";
/** Reversed = RE */
public static final String DOCSTATUS_Reversed = "RE";
/** Closed = CL */
public static final String DOCSTATUS_Closed = "CL";
/** Unknown = ?? */
public static final String DOCSTATUS_Unknown = "??";
/** InProgress = IP */
public static final String DOCSTATUS_InProgress = "IP";
/** WaitingPayment = WP */
public static final String DOCSTATUS_WaitingPayment = "WP";
/** WaitingConfirmation = WC */
public static final String DOCSTATUS_WaitingConfirmation = "WC";
@Override
public void setDocStatus (final @Nullable java.lang.String DocStatus)
{
throw new IllegalArgumentException ("DocStatus is virtual column"); }
@Override
public java.lang.String getDocStatus()
{
return get_ValueAsString(COLUMNNAME_DocStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Contract_Term_Alloc.java | 1 |
请完成以下Java代码 | private static MailboxQuery mailboxQuery(final @NonNull UserNotificationsConfig notificationsConfig)
{
return MailboxQuery.builder()
.clientId(notificationsConfig.getClientId())
.orgId(notificationsConfig.getOrgId())
.build();
}
private String extractMailContent(final UserNotificationRequest request)
{
final body htmlBody = new body();
final String htmlBodyString = extractContentText(request, /* html */true);
if (!Check.isEmpty(htmlBodyString))
{
Splitter.on("\n")
.splitToList(htmlBodyString.trim())
.forEach(htmlLine -> htmlBody.addElement(new ClearElement(htmlLine)).addElement(new br()));
}
return new html().addElement(htmlBody).toString();
}
private NotificationMessageFormatter prepareMessageFormatter(final UserNotificationRequest request)
{
final NotificationMessageFormatter formatter = NotificationMessageFormatter.newInstance();
final TargetAction targetAction = request.getTargetAction();
if (targetAction instanceof TargetRecordAction)
{ | final TargetRecordAction targetRecordAction = TargetRecordAction.cast(targetAction);
final TableRecordReference targetRecord = targetRecordAction.getRecord();
final String targetRecordDisplayText = targetRecordAction.getRecordDisplayText();
if (!Check.isEmpty(targetRecordDisplayText))
{
formatter.recordDisplayText(targetRecord, targetRecordDisplayText);
}
final AdWindowId targetWindowId = targetRecordAction.getAdWindowId().orElse(null);
if (targetWindowId != null)
{
formatter.recordWindowId(targetRecord, targetWindowId);
}
}
else if (targetAction instanceof TargetViewAction)
{
final TargetViewAction targetViewAction = TargetViewAction.cast(targetAction);
final String viewURL = WebuiURLs.newInstance().getViewUrl(targetViewAction.getAdWindowId(), targetViewAction.getViewId());
formatter.bottomUrl(viewURL);
}
return formatter;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\NotificationSenderTemplate.java | 1 |
请完成以下Java代码 | private void reportFailedMethodExecution(TenantId tenantId, String method, long startTime, Throwable t, ProceedingJoinPoint joinPoint) {
if (t != null) {
if (ExceptionUtils.indexOfThrowable(t, JDBCConnectionException.class) >= 0) {
return;
}
if (StringUtils.containedByAny(DEADLOCK_DETECTED_ERROR, ExceptionUtils.getRootCauseMessage(t), ExceptionUtils.getMessage(t))) {
if (!batchSortEnabled) {
log.warn("Deadlock was detected for method {} (tenant: {}). You might need to enable 'sql.batch_sort' option.", method, tenantId);
} else {
log.error("Deadlock was detected for method {} (tenant: {}). Arguments passed: \n{}\n The error: ",
method, tenantId, join(joinPoint.getArgs(), System.lineSeparator()), t);
}
}
}
reportMethodExecution(tenantId, method, false, startTime);
}
private void reportSuccessfulMethodExecution(TenantId tenantId, String method, long startTime) {
reportMethodExecution(tenantId, method, true, startTime);
}
private void reportMethodExecution(TenantId tenantId, String method, boolean success, long startTime) {
statsMap.computeIfAbsent(tenantId, DbCallStats::new)
.onMethodCall(method, success, System.currentTimeMillis() - startTime);
}
TenantId getTenantId(MethodSignature signature, String methodName, Object[] args) {
if (args == null || args.length == 0) {
addAndLogInvalidMethods(methodName);
return null;
}
for (int i = 0; i < args.length; i++) { | Object arg = args[i];
if (arg instanceof TenantId) {
return (TenantId) arg;
} else if (arg instanceof UUID) {
if (signature.getParameterNames() != null && StringUtils.equals(signature.getParameterNames()[i], "tenantId")) {
log.trace("Method {} uses UUID for tenantId param instead of TenantId class", methodName);
return TenantId.fromUUID((UUID) arg);
}
}
}
if (ArrayUtils.contains(signature.getParameterTypes(), TenantId.class) ||
ArrayUtils.contains(signature.getParameterNames(), "tenantId")) {
log.debug("Null was submitted as tenantId to method {}. Args: {}", methodName, Arrays.toString(args));
} else {
addAndLogInvalidMethods(methodName);
}
return null;
}
private void addAndLogInvalidMethods(String methodName) {
invalidTenantDbCallMethods.add(methodName);
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\aspect\SqlDaoCallsAspect.java | 1 |
请完成以下Java代码 | public void setOrder(int order) {
this.order = order;
}
public Map<String, Object> getMetadata() {
return metadata;
}
public void setMetadata(Map<String, Object> metadata) {
this.metadata = metadata;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} | if (o == null || getClass() != o.getClass()) {
return false;
}
RouteDefinition that = (RouteDefinition) o;
return this.order == that.order && Objects.equals(this.id, that.id)
&& Objects.equals(this.predicates, that.predicates) && Objects.equals(this.filters, that.filters)
&& Objects.equals(this.uri, that.uri) && Objects.equals(this.metadata, that.metadata)
&& Objects.equals(this.enabled, that.enabled);
}
@Override
public int hashCode() {
return Objects.hash(this.id, this.predicates, this.filters, this.uri, this.metadata, this.order, this.enabled);
}
@Override
public String toString() {
return "RouteDefinition{" + "id='" + id + '\'' + ", predicates=" + predicates + ", filters=" + filters
+ ", uri=" + uri + ", order=" + order + ", metadata=" + metadata + ", enabled=" + enabled + '}';
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\route\RouteDefinition.java | 1 |
请完成以下Java代码 | public class User extends RepresentationModel<User> {
private Integer id;
private String name;
private String email;
private LocalDateTime createdAt;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public User(int id, String name, String email, LocalDateTime createdAt) {
this.id = id;
this.name = name;
this.email = email;
this.createdAt = createdAt;
}
} | repos\tutorials-master\spring-web-modules\spring-boot-rest-2\src\main\java\com\baeldung\hateoasvsswagger\model\User.java | 1 |
请完成以下Java代码 | public class AWindowSaveStateModel
{
private static final String ACTION_Name = "org.compiere.apps.AWindowSaveStateModel.action";
private static final Logger logger = LogManager.getLogger(AWindowSaveStateModel.class);
private static final CCache<UserId, Boolean> userId2enabled = new CCache<>(I_AD_Role.Table_Name, 5, 0);
public String getActionName()
{
return ACTION_Name;
}
public boolean isEnabled()
{
final Properties ctx = Env.getCtx();
final UserId loggedUserId = Env.getLoggedUserId(ctx);
return userId2enabled.getOrLoad(loggedUserId, this::retrieveEnabledNoFail);
}
private boolean retrieveEnabledNoFail(final UserId loggedUserId)
{
try
{
return retrieveEnabled(loggedUserId);
}
catch (Exception ex)
{
logger.error(ex.getLocalizedMessage(), ex);
return false;
}
}
private boolean retrieveEnabled(final UserId loggedUserId)
{
final AdWindowId windowId = AdWindowId.ofRepoIdOrNull(MTable.get(Env.getCtx(), I_AD_Field.Table_Name).getAD_Window_ID());
if (windowId == null)
{
return false;
}
final ClientId clientId = Env.getClientId();
final LocalDate date = Env.getLocalDate();
//
// Makes sure the logged in user has at least one role assigned which has read-write access to our window
return Services.get(IUserRolePermissionsDAO.class)
.matchUserRolesPermissionsForUser(
clientId,
loggedUserId, | date,
rolePermissions -> rolePermissions.checkWindowPermission(windowId).hasWriteAccess());
}
public void save(final GridTab gridTab)
{
Services.get(ITrxManager.class).runInNewTrx(() -> save0(gridTab));
}
private void save0(final GridTab gridTab)
{
Check.assumeNotNull(gridTab, "gridTab not null");
for (final GridField gridField : gridTab.getFields())
{
save(gridField);
}
}
private void save(final GridField gridField)
{
final GridFieldVO gridFieldVO = gridField.getVO();
final AdFieldId adFieldId = gridFieldVO.getAD_Field_ID();
if (adFieldId == null)
{
return;
}
final I_AD_Field adField = InterfaceWrapperHelper.load(adFieldId, I_AD_Field.class);
if (adField == null)
{
return;
}
adField.setIsDisplayedGrid(gridFieldVO.isDisplayedGrid());
adField.setSeqNoGrid(gridFieldVO.getSeqNoGrid());
adField.setColumnDisplayLength(gridFieldVO.getLayoutConstraints().getColumnDisplayLength());
InterfaceWrapperHelper.save(adField);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\AWindowSaveStateModel.java | 1 |
请完成以下Java代码 | public void setWebParam5 (String WebParam5)
{
set_Value (COLUMNNAME_WebParam5, WebParam5);
}
/** Get Web Parameter 5.
@return Web Site Parameter 5 (default footer center)
*/
public String getWebParam5 ()
{
return (String)get_Value(COLUMNNAME_WebParam5);
}
/** Set Web Parameter 6.
@param WebParam6
Web Site Parameter 6 (default footer right)
*/
public void setWebParam6 (String WebParam6)
{
set_Value (COLUMNNAME_WebParam6, WebParam6);
}
/** Get Web Parameter 6.
@return Web Site Parameter 6 (default footer right)
*/
public String getWebParam6 ()
{
return (String)get_Value(COLUMNNAME_WebParam6);
}
/** Set Web Store EMail.
@param WStoreEMail
EMail address used as the sender (From)
*/
public void setWStoreEMail (String WStoreEMail)
{
set_Value (COLUMNNAME_WStoreEMail, WStoreEMail);
}
/** Get Web Store EMail.
@return EMail address used as the sender (From)
*/
public String getWStoreEMail ()
{
return (String)get_Value(COLUMNNAME_WStoreEMail);
}
/** Set Web Store.
@param W_Store_ID
A Web Store of the Client
*/
public void setW_Store_ID (int W_Store_ID)
{
if (W_Store_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_Store_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_Store_ID, Integer.valueOf(W_Store_ID));
} | /** Get Web Store.
@return A Web Store of the Client
*/
public int getW_Store_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Store_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set WebStore User.
@param WStoreUser
User ID of the Web Store EMail address
*/
public void setWStoreUser (String WStoreUser)
{
set_Value (COLUMNNAME_WStoreUser, WStoreUser);
}
/** Get WebStore User.
@return User ID of the Web Store EMail address
*/
public String getWStoreUser ()
{
return (String)get_Value(COLUMNNAME_WStoreUser);
}
/** Set WebStore Password.
@param WStoreUserPW
Password of the Web Store EMail address
*/
public void setWStoreUserPW (String WStoreUserPW)
{
set_Value (COLUMNNAME_WStoreUserPW, WStoreUserPW);
}
/** Get WebStore Password.
@return Password of the Web Store EMail address
*/
public String getWStoreUserPW ()
{
return (String)get_Value(COLUMNNAME_WStoreUserPW);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Store.java | 1 |
请完成以下Java代码 | protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
final ExplainedOptional<CreateMatchInvoiceRequest> optionalRequest = createMatchInvoiceRequest();
if (!optionalRequest.isPresent())
{
return ProcessPreconditionsResolution.rejectWithInternalReason(optionalRequest.getExplanation());
}
final CreateMatchInvoicePlan plan = orderCostService.createMatchInvoiceSimulation(optionalRequest.get());
final Amount invoicedAmtDiff = plan.getInvoicedAmountDiff().toAmount(moneyService::getCurrencyCodeByCurrencyId);
return ProcessPreconditionsResolution.accept().withCaptionMapper(captionMapper(invoicedAmtDiff));
}
@Nullable
private ProcessPreconditionsResolution.ProcessCaptionMapper captionMapper(@Nullable final Amount invoicedAmtDiff)
{
if (invoicedAmtDiff == null || invoicedAmtDiff.isZero())
{
return null;
}
else
{
return originalProcessCaption -> TranslatableStrings.builder()
.append(originalProcessCaption)
.append(" (Diff: ").append(invoicedAmtDiff).append(")")
.build();
}
}
protected String doIt()
{
final CreateMatchInvoiceRequest request = createMatchInvoiceRequest().orElseThrow(); | orderCostService.createMatchInvoice(request);
invalidateView();
return MSG_OK;
}
private ExplainedOptional<CreateMatchInvoiceRequest> createMatchInvoiceRequest()
{
final ImmutableSet<InOutCostId> selectedInOutCostIds = getSelectedInOutCostIds();
if (selectedInOutCostIds.isEmpty())
{
return ExplainedOptional.emptyBecause("No selection");
}
return ExplainedOptional.of(
CreateMatchInvoiceRequest.builder()
.invoiceAndLineId(getView().getInvoiceLineId())
.inoutCostIds(selectedInOutCostIds)
.build());
}
private ImmutableSet<InOutCostId> getSelectedInOutCostIds()
{
final ImmutableList<InOutCostRow> rows = getSelectedRows();
return rows.stream().map(InOutCostRow::getInoutCostId).collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoice\match_inout_costs\InOutCostsView_CreateMatchInv.java | 1 |
请完成以下Java代码 | public BigDecimal getIncome() {
return income;
}
/** 平台账户入账金额 **/
public void setIncome(BigDecimal income) {
this.income = income;
}
/** 平台账户出款金额 **/
public BigDecimal getOutcome() {
return outcome;
}
/** 平台账户出款金额 **/
public void setOutcome(BigDecimal outcome) {
this.outcome = outcome;
}
/** 商户订单号 **/
public String getMerchantOrderNo() {
return merchantOrderNo;
}
/** 商户订单号 **/
public void setMerchantOrderNo(String merchantOrderNo) {
this.merchantOrderNo = merchantOrderNo;
}
/** 银行费率 **/
public BigDecimal getBankRate() {
return bankRate;
}
/** 银行费率 **/
public void setBankRate(BigDecimal bankRate) {
this.bankRate = bankRate;
}
/** 订单金额 **/
public BigDecimal getTotalFee() {
return totalFee;
}
/** 订单金额 **/
public void setTotalFee(BigDecimal totalFee) {
this.totalFee = totalFee;
}
/** 银行流水 **/ | public String getTradeNo() {
return tradeNo;
}
/** 银行流水 **/
public void setTradeNo(String tradeNo) {
this.tradeNo = tradeNo;
}
/** 交易类型 **/
public String getTransType() {
return transType;
}
/** 交易类型 **/
public void setTransType(String transType) {
this.transType = transType;
}
/** 交易时间 **/
public Date getTransDate() {
return transDate;
}
/** 交易时间 **/
public void setTransDate(Date transDate) {
this.transDate = transDate;
}
/** 银行(支付宝)该笔订单收取的手续费 **/
public BigDecimal getBankFee() {
return bankFee;
}
/** 银行(支付宝)该笔订单收取的手续费 **/
public void setBankFee(BigDecimal bankFee) {
this.bankFee = bankFee;
}
} | repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\vo\AlipayAccountLogVO.java | 1 |
请完成以下Java代码 | public class BalancedBinaryTree {
public static boolean isBalanced(Tree tree) {
return isBalancedRecursive(tree, -1).isBalanced;
}
private static Result isBalancedRecursive(Tree tree, int depth) {
if (tree == null) {
return new Result(true, -1);
}
Result leftSubtreeResult = isBalancedRecursive(tree.left(), depth + 1);
Result rightSubtreeResult = isBalancedRecursive(tree.right(), depth + 1);
boolean isBalanced = Math.abs(leftSubtreeResult.height - rightSubtreeResult.height) <= 1; | boolean subtreesAreBalanced = leftSubtreeResult.isBalanced && rightSubtreeResult.isBalanced;
int height = Math.max(leftSubtreeResult.height, rightSubtreeResult.height) + 1;
return new Result(isBalanced && subtreesAreBalanced, height);
}
private static final class Result {
private final boolean isBalanced;
private final int height;
private Result(boolean isBalanced, int height) {
this.isBalanced = isBalanced;
this.height = height;
}
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-5\src\main\java\com\baeldung\algorithms\balancedbinarytree\BalancedBinaryTree.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getAD_Find_ID()));
}
/** AndOr AD_Reference_ID=204 */
public static final int ANDOR_AD_Reference_ID=204;
/** And = A */
public static final String ANDOR_And = "A";
/** Or = O */
public static final String ANDOR_Or = "O";
/** Set And/Or.
@param AndOr
Logical operation: AND or OR
*/
public void setAndOr (String AndOr)
{
set_Value (COLUMNNAME_AndOr, AndOr);
}
/** Get And/Or.
@return Logical operation: AND or OR
*/
public String getAndOr ()
{
return (String)get_Value(COLUMNNAME_AndOr);
}
/** Set Find_ID.
@param Find_ID Find_ID */
public void setFind_ID (BigDecimal Find_ID)
{
set_Value (COLUMNNAME_Find_ID, Find_ID);
}
/** Get Find_ID.
@return Find_ID */
public BigDecimal getFind_ID ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Find_ID);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Operation AD_Reference_ID=205 */
public static final int OPERATION_AD_Reference_ID=205;
/** = = == */
public static final String OPERATION_Eq = "==";
/** >= = >= */
public static final String OPERATION_GtEq = ">=";
/** > = >> */
public static final String OPERATION_Gt = ">>";
/** < = << */
public static final String OPERATION_Le = "<<";
/** ~ = ~~ */
public static final String OPERATION_Like = "~~";
/** <= = <= */
public static final String OPERATION_LeEq = "<=";
/** |<x>| = AB */
public static final String OPERATION_X = "AB";
/** sql = SQ */
public static final String OPERATION_Sql = "SQ";
/** != = != */
public static final String OPERATION_NotEq = "!=";
/** Set Operation.
@param Operation
Compare Operation
*/
public void setOperation (String Operation) | {
set_Value (COLUMNNAME_Operation, Operation);
}
/** Get Operation.
@return Compare Operation
*/
public String getOperation ()
{
return (String)get_Value(COLUMNNAME_Operation);
}
/** 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);
}
/** Set Value To.
@param Value2
Value To
*/
public void setValue2 (String Value2)
{
set_Value (COLUMNNAME_Value2, Value2);
}
/** Get Value To.
@return Value To
*/
public String getValue2 ()
{
return (String)get_Value(COLUMNNAME_Value2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Find.java | 1 |
请完成以下Java代码 | public List<Map<String, Object>> execute() {
return decisionService.executeDecision(this);
}
@Override
public List<Map<String, Object>> executeDecision() {
return decisionService.executeDecision(this);
}
@Override
public Map<String, List<Map<String, Object>>> executeDecisionService() {
return decisionService.executeDecisionService(this);
}
@Override
public Map<String, Object> executeWithSingleResult() {
return decisionService.executeWithSingleResult(this);
}
@Override
public Map<String, Object> executeDecisionWithSingleResult() {
return decisionService.executeDecisionWithSingleResult(this);
}
@Override
public Map<String, Object> executeDecisionServiceWithSingleResult() {
return decisionService.executeDecisionServiceWithSingleResult(this);
}
@Override
public DecisionExecutionAuditContainer executeWithAuditTrail() {
return decisionService.executeWithAuditTrail(this);
}
@Override
public DecisionExecutionAuditContainer executeDecisionWithAuditTrail() {
return decisionService.executeDecisionWithAuditTrail(this);
}
@Override
public DecisionServiceExecutionAuditContainer executeDecisionServiceWithAuditTrail() {
return decisionService.executeDecisionServiceWithAuditTrail(this);
}
public String getDecisionKey() {
return decisionKey;
}
public String getParentDeploymentId() {
return parentDeploymentId;
}
public String getInstanceId() {
return instanceId;
} | public String getExecutionId() {
return executionId;
}
public String getActivityId() {
return activityId;
}
public String getScopeType() {
return scopeType;
}
public String getTenantId() {
return tenantId;
}
public boolean isFallbackToDefaultTenant() {
return this.fallbackToDefaultTenant;
}
public Map<String, Object> getVariables() {
return variables;
}
@Override
public ExecuteDecisionContext buildExecuteDecisionContext() {
ExecuteDecisionContext executeDecisionContext = new ExecuteDecisionContext();
executeDecisionContext.setDecisionKey(decisionKey);
executeDecisionContext.setParentDeploymentId(parentDeploymentId);
executeDecisionContext.setInstanceId(instanceId);
executeDecisionContext.setExecutionId(executionId);
executeDecisionContext.setActivityId(activityId);
executeDecisionContext.setScopeType(scopeType);
executeDecisionContext.setVariables(variables);
executeDecisionContext.setTenantId(tenantId);
executeDecisionContext.setFallbackToDefaultTenant(fallbackToDefaultTenant);
executeDecisionContext.setDisableHistory(disableHistory);
return executeDecisionContext;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\ExecuteDecisionBuilderImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SpringBeanJobFactory springBeanJobFactory() {
AutoWiringSpringBeanJobFactory jobFactory = new AutoWiringSpringBeanJobFactory();
logger.debug("Configuring Job factory");
jobFactory.setApplicationContext(applicationContext);
return jobFactory;
}
@Bean
public SchedulerFactoryBean scheduler(Trigger trigger, JobDetail job, DataSource quartzDataSource) {
SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
schedulerFactory.setConfigLocation(new ClassPathResource("quartz.properties"));
logger.debug("Setting the Scheduler up");
schedulerFactory.setJobFactory(springBeanJobFactory());
schedulerFactory.setJobDetails(job);
schedulerFactory.setTriggers(trigger);
// Comment the following line to use the default Quartz job store.
schedulerFactory.setDataSource(quartzDataSource);
return schedulerFactory;
}
@Bean
public JobDetailFactoryBean jobDetail() {
JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
jobDetailFactory.setJobClass(SampleJob.class);
jobDetailFactory.setName("Qrtz_Job_Detail"); | jobDetailFactory.setDescription("Invoke Sample Job service...");
jobDetailFactory.setDurability(true);
return jobDetailFactory;
}
@Bean
public SimpleTriggerFactoryBean trigger(JobDetail job) {
SimpleTriggerFactoryBean trigger = new SimpleTriggerFactoryBean();
trigger.setJobDetail(job);
int frequencyInSec = 10;
logger.info("Configuring trigger to fire every {} seconds", frequencyInSec);
trigger.setRepeatInterval(frequencyInSec * 1000);
trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
trigger.setName("Qrtz_Trigger");
return trigger;
}
@Bean
@QuartzDataSource
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource quartzDataSource() {
return DataSourceBuilder.create().build();
}
} | repos\tutorials-master\spring-quartz\src\main\java\org\baeldung\springquartz\basics\scheduler\SpringQrtzScheduler.java | 2 |
请完成以下Java代码 | public void setTcToken(String value) {
this.tcToken = value;
}
/**
* Gets the value of the insuranceDemandDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getInsuranceDemandDate() {
return insuranceDemandDate;
}
/**
* Sets the value of the insuranceDemandDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setInsuranceDemandDate(XMLGregorianCalendar value) {
this.insuranceDemandDate = value;
}
/**
* Gets the value of the insuranceDemandId property.
*
* @return
* possible object is
* {@link String }
*
*/ | public String getInsuranceDemandId() {
return insuranceDemandId;
}
/**
* Sets the value of the insuranceDemandId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInsuranceDemandId(String value) {
this.insuranceDemandId = value;
}
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ProcessingType.java | 1 |
请完成以下Java代码 | public class AmqpRejectAndDontRequeueException extends AmqpException {
private final boolean rejectManual;
/**
* Construct an instance with the supplied argument.
* @param message A message describing the problem.
*/
public AmqpRejectAndDontRequeueException(String message) {
this(message, false, null);
}
/**
* Construct an instance with the supplied argument.
* @param cause the cause.
*/
public AmqpRejectAndDontRequeueException(@Nullable Throwable cause) {
this(null, false, cause);
}
/**
* Construct an instance with the supplied arguments.
* @param message A message describing the problem.
* @param cause the cause.
*/
public AmqpRejectAndDontRequeueException(String message, @Nullable Throwable cause) { | this(message, false, cause);
}
/**
* Construct an instance with the supplied arguments.
* @param message A message describing the problem.
* @param rejectManual true to reject the message, even with Manual Acks if this is
* the top-level exception (e.g. thrown by an error handler).
* @param cause the cause.
* @since 2.1.9
*/
public AmqpRejectAndDontRequeueException(@Nullable String message, boolean rejectManual,
@Nullable Throwable cause) {
super(message, cause);
this.rejectManual = rejectManual;
}
/**
* True if the container should reject the message, even with manual acks.
* @return true to reject.
*/
public boolean isRejectManual() {
return this.rejectManual;
}
} | repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\AmqpRejectAndDontRequeueException.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public MobileSessionInfo getMobileSession(@RequestHeader(MOBILE_TOKEN_HEADER) String mobileToken,
@AuthenticationPrincipal SecurityUser user) {
return userService.findMobileSession(user.getTenantId(), user.getId(), mobileToken);
}
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@PostMapping("/user/mobile/session")
public void saveMobileSession(@RequestBody MobileSessionInfo sessionInfo,
@RequestHeader(MOBILE_TOKEN_HEADER) String mobileToken,
@AuthenticationPrincipal SecurityUser user) {
userService.saveMobileSession(user.getTenantId(), user.getId(), mobileToken, sessionInfo);
}
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@DeleteMapping("/user/mobile/session")
public void removeMobileSession(@RequestHeader(MOBILE_TOKEN_HEADER) String mobileToken,
@AuthenticationPrincipal SecurityUser user) {
userService.removeMobileSession(user.getTenantId(), mobileToken);
}
@ApiOperation(value = "Get Users By Ids (getUsersByIds)",
notes = "Requested users must be owned by tenant or assigned to customer which user is performing the request. ")
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@GetMapping(value = "/users", params = {"userIds"})
public List<User> getUsersByIds(
@Parameter(description = "A list of user ids, separated by comma ','", array = @ArraySchema(schema = @Schema(type = "string")), required = true)
@RequestParam("userIds") Set<UUID> userUUIDs) throws ThingsboardException {
TenantId tenantId = getCurrentUser().getTenantId(); | List<UserId> userIds = new ArrayList<>();
for (UUID userUUID : userUUIDs) {
userIds.add(new UserId(userUUID));
}
List<User> users = userService.findUsersByTenantIdAndIds(tenantId, userIds);
return filterUsersByReadPermission(users);
}
private List<User> filterUsersByReadPermission(List<User> users) {
return users.stream().filter(user -> {
try {
return accessControlService.hasPermission(getCurrentUser(), Resource.USER, Operation.READ, user.getId(), user);
} catch (ThingsboardException e) {
return false;
}
}).collect(Collectors.toList());
}
private void checkNotReserved(String strType, UserSettingsType type) throws ThingsboardException {
if (type.isReserved()) {
throw new ThingsboardException("Settings with type: " + strType + " are reserved for internal use!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\UserController.java | 2 |
请完成以下Java代码 | public void setRequestCache(RequestCache requestCache) {
Assert.notNull(requestCache, "requestCache cannot be null");
this.requestCache = requestCache;
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
final SavedRequest savedRequest = this.requestCache.getRequest(request, response);
final String redirectUrl = (savedRequest != null) ? savedRequest.getRedirectUrl()
: request.getContextPath() + "/";
this.requestCache.removeRequest(request, response);
this.converter.write(new AuthenticationSuccess(redirectUrl), MediaType.APPLICATION_JSON,
new ServletServerHttpResponse(response));
}
/**
* A response object used to write the JSON response for successful authentication.
*
* NOTE: We should be careful about writing {@link Authentication} or
* {@link Authentication#getPrincipal()} to the response since it contains
* credentials.
*/
public static final class AuthenticationSuccess {
private final String redirectUrl; | private AuthenticationSuccess(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
public String getRedirectUrl() {
return this.redirectUrl;
}
public boolean isAuthenticated() {
return true;
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\HttpMessageConverterAuthenticationSuccessHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void method01() {
// 查询订单
OrderDO order = orderMapper.selectById(1);
System.out.println(order);
// 查询用户
UserDO user = userMapper.selectById(1);
System.out.println(user);
}
@Transactional
public void method02() {
// 查询订单
OrderDO order = orderMapper.selectById(1);
System.out.println(order);
// 查询用户
UserDO user = userMapper.selectById(1);
System.out.println(user);
}
public void method03() {
// 查询订单
self().method031();
// 查询用户
self().method032();
}
@Transactional // 报错,因为此时获取的是 primary 对应的 DataSource ,即 users 。
public void method031() {
OrderDO order = orderMapper.selectById(1);
System.out.println(order);
}
@Transactional
public void method032() {
UserDO user = userMapper.selectById(1);
System.out.println(user);
}
public void method04() {
// 查询订单
self().method041();
// 查询用户
self().method042();
}
@Transactional
@DS(DBConstants.DATASOURCE_ORDERS)
public void method041() {
OrderDO order = orderMapper.selectById(1);
System.out.println(order);
}
@Transactional | @DS(DBConstants.DATASOURCE_USERS)
public void method042() {
UserDO user = userMapper.selectById(1);
System.out.println(user);
}
@Transactional
@DS(DBConstants.DATASOURCE_ORDERS)
public void method05() {
// 查询订单
OrderDO order = orderMapper.selectById(1);
System.out.println(order);
// 查询用户
self().method052();
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
@DS(DBConstants.DATASOURCE_USERS)
public void method052() {
UserDO user = userMapper.selectById(1);
System.out.println(user);
}
} | repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-baomidou-01\src\main\java\cn\iocoder\springboot\lab17\dynamicdatasource\service\OrderService.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.