instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public String getAssignee() {
return assignee;
}
public Date getStartTime() {
return startTime;
}
public Date getEndTime() {
return endTime;
}
public Long getDuration() {
return duration;
}
public String getTaskDefinitionKey() {
return taskDefinitionKey;
}
public int getPriority() {
return priority;
}
public Date getDue() {
return due;
}
public String getParentTaskId() {
return parentTaskId;
}
public Date getFollowUp() {
return followUp;
}
public String getTenantId() {
return tenantId;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
/**
* Returns task State of history tasks
*/
public String getTaskState() { return taskState; }
public static HistoricTaskInstanceDto fromHistoricTaskInstance(HistoricTaskInstance taskInstance) {
HistoricTaskInstanceDto dto = new HistoricTaskInstanceDto();
|
dto.id = taskInstance.getId();
dto.processDefinitionKey = taskInstance.getProcessDefinitionKey();
dto.processDefinitionId = taskInstance.getProcessDefinitionId();
dto.processInstanceId = taskInstance.getProcessInstanceId();
dto.executionId = taskInstance.getExecutionId();
dto.caseDefinitionKey = taskInstance.getCaseDefinitionKey();
dto.caseDefinitionId = taskInstance.getCaseDefinitionId();
dto.caseInstanceId = taskInstance.getCaseInstanceId();
dto.caseExecutionId = taskInstance.getCaseExecutionId();
dto.activityInstanceId = taskInstance.getActivityInstanceId();
dto.name = taskInstance.getName();
dto.description = taskInstance.getDescription();
dto.deleteReason = taskInstance.getDeleteReason();
dto.owner = taskInstance.getOwner();
dto.assignee = taskInstance.getAssignee();
dto.startTime = taskInstance.getStartTime();
dto.endTime = taskInstance.getEndTime();
dto.duration = taskInstance.getDurationInMillis();
dto.taskDefinitionKey = taskInstance.getTaskDefinitionKey();
dto.priority = taskInstance.getPriority();
dto.due = taskInstance.getDueDate();
dto.parentTaskId = taskInstance.getParentTaskId();
dto.followUp = taskInstance.getFollowUpDate();
dto.tenantId = taskInstance.getTenantId();
dto.removalTime = taskInstance.getRemovalTime();
dto.rootProcessInstanceId = taskInstance.getRootProcessInstanceId();
dto.taskState = taskInstance.getTaskState();
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricTaskInstanceDto.java
| 1
|
请完成以下Java代码
|
public static ProcessApplicationReference getCurrentProcessApplication() {
Deque<ProcessApplicationReference> stack = getStack(processApplicationContext);
if(stack.isEmpty()) {
return null;
} else {
return stack.peek();
}
}
public static void setCurrentProcessApplication(ProcessApplicationReference reference) {
Deque<ProcessApplicationReference> stack = getStack(processApplicationContext);
stack.push(reference);
}
public static void removeCurrentProcessApplication() {
Deque<ProcessApplicationReference> stack = getStack(processApplicationContext);
stack.pop();
}
/**
* Use {@link #executeWithinProcessApplication(Callable, ProcessApplicationReference, InvocationContext)}
* instead if an {@link InvocationContext} is available.
*/
public static <T> T executeWithinProcessApplication(Callable<T> callback, ProcessApplicationReference processApplicationReference) {
return executeWithinProcessApplication(callback, processApplicationReference, null);
}
public static <T> T executeWithinProcessApplication(Callable<T> callback, ProcessApplicationReference processApplicationReference, InvocationContext invocationContext) {
String paName = processApplicationReference.getName();
try {
ProcessApplicationInterface processApplication = processApplicationReference.getProcessApplication();
setCurrentProcessApplication(processApplicationReference);
try {
// wrap callback
|
ProcessApplicationClassloaderInterceptor<T> wrappedCallback = new ProcessApplicationClassloaderInterceptor<T>(callback);
// execute wrapped callback
return processApplication.execute(wrappedCallback, invocationContext);
} catch (Exception e) {
// unwrap exception
if(e.getCause() != null && e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}else {
throw new ProcessEngineException("Unexpected exeption while executing within process application ", e);
}
} finally {
removeCurrentProcessApplication();
}
} catch (ProcessApplicationUnavailableException e) {
throw new ProcessEngineException("Cannot switch to process application '"+paName+"' for execution: "+e.getMessage(), e);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\context\Context.java
| 1
|
请完成以下Java代码
|
static Object wrap(Object object) {
try {
if (object == null) {
return NULL;
}
if (
object instanceof JSONObject ||
object instanceof JSONArray ||
object instanceof Byte ||
object instanceof Character ||
object instanceof Short ||
object instanceof Integer ||
object instanceof Long ||
object instanceof Boolean ||
object instanceof Float ||
object instanceof Double ||
object instanceof String ||
NULL.equals(object)
) {
return object;
}
if (object instanceof Collection) {
return new JSONArray((Collection) object);
}
if (object.getClass().isArray()) {
return new JSONArray(object);
}
if (object instanceof Map) {
return new JSONObject((Map) object);
}
Package objectPackage = object.getClass().getPackage();
String objectPackageName = (objectPackage != null ? objectPackage.getName() : "");
if (
objectPackageName.startsWith("java.") ||
objectPackageName.startsWith("javax.") ||
object.getClass().getClassLoader() == null
) {
return object.toString();
}
return new JSONObject(object);
} catch (Exception exception) {
return null;
}
}
/**
* Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the signalData structure is acyclical.
*
* @return The writer.
* @throws JSONException
*/
|
public Writer write(Writer writer) throws JSONException {
try {
boolean b = false;
Iterator keys = keys();
writer.write('{');
while (keys.hasNext()) {
if (b) {
writer.write(',');
}
Object k = keys.next();
writer.write(quote(k.toString()));
writer.write(':');
Object v = this.map.get(k);
if (v instanceof JSONObject) {
((JSONObject) v).write(writer);
} else if (v instanceof JSONArray) {
((JSONArray) v).write(writer);
} else {
writer.write(valueToString(v));
}
b = true;
}
writer.write('}');
return writer;
} catch (IOException exception) {
throw new JSONException(exception);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\json\JSONObject.java
| 1
|
请完成以下Java代码
|
public class StartEventXMLConverter extends BaseBpmnXMLConverter {
@Override
public Class<? extends BaseElement> getBpmnElementType() {
return StartEvent.class;
}
@Override
protected String getXMLElementName() {
return ELEMENT_EVENT_START;
}
@Override
protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception {
String formKey = xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_FORM_FORMKEY);
StartEvent startEvent = null;
if (
StringUtils.isNotEmpty(formKey) &&
model.getStartEventFormTypes() != null &&
model.getStartEventFormTypes().contains(formKey)
) {
startEvent = new AlfrescoStartEvent();
}
if (startEvent == null) {
startEvent = new StartEvent();
}
BpmnXMLUtil.addXMLLocation(startEvent, xtr);
startEvent.setInitiator(xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_EVENT_START_INITIATOR));
boolean interrupting = true;
String interruptingAttribute = xtr.getAttributeValue(null, ATTRIBUTE_EVENT_START_INTERRUPTING);
if (ATTRIBUTE_VALUE_FALSE.equalsIgnoreCase(interruptingAttribute)) {
interrupting = false;
}
startEvent.setInterrupting(interrupting);
startEvent.setFormKey(formKey);
parseChildElements(getXMLElementName(), startEvent, model, xtr);
return startEvent;
}
@Override
protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
|
throws Exception {
StartEvent startEvent = (StartEvent) element;
writeQualifiedAttribute(ATTRIBUTE_EVENT_START_INITIATOR, startEvent.getInitiator(), xtw);
writeQualifiedAttribute(ATTRIBUTE_FORM_FORMKEY, startEvent.getFormKey(), xtw);
if (startEvent.getEventDefinitions() != null && startEvent.getEventDefinitions().size() > 0) {
writeDefaultAttribute(ATTRIBUTE_EVENT_START_INTERRUPTING, String.valueOf(startEvent.isInterrupting()), xtw);
}
}
@Override
protected boolean writeExtensionChildElements(
BaseElement element,
boolean didWriteExtensionStartElement,
XMLStreamWriter xtw
) throws Exception {
StartEvent startEvent = (StartEvent) element;
didWriteExtensionStartElement = writeFormProperties(startEvent, didWriteExtensionStartElement, xtw);
return didWriteExtensionStartElement;
}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
StartEvent startEvent = (StartEvent) element;
writeEventDefinitions(startEvent, startEvent.getEventDefinitions(), model, xtw);
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\StartEventXMLConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public R<IPage<Datasource>> list(Datasource datasource, Query query) {
IPage<Datasource> pages = datasourceService.page(Condition.getPage(query), Condition.getQueryWrapper(datasource));
return R.data(pages);
}
/**
* 新增 数据源配置表
*/
@PostMapping("/save")
@ApiOperationSupport(order = 4)
@Operation(summary = "新增", description = "传入datasource")
public R save(@Valid @RequestBody Datasource datasource) {
return R.status(datasourceService.save(datasource));
}
/**
* 修改 数据源配置表
*/
@PostMapping("/update")
@ApiOperationSupport(order = 5)
@Operation(summary = "修改", description = "传入datasource")
public R update(@Valid @RequestBody Datasource datasource) {
return R.status(datasourceService.updateById(datasource));
}
/**
* 新增或修改 数据源配置表
*/
@PostMapping("/submit")
@ApiOperationSupport(order = 6)
@Operation(summary = "新增或修改", description = "传入datasource")
public R submit(@Valid @RequestBody Datasource datasource) {
|
datasource.setUrl(datasource.getUrl().replace("&", "&"));
return R.status(datasourceService.saveOrUpdate(datasource));
}
/**
* 删除 数据源配置表
*/
@PostMapping("/remove")
@ApiOperationSupport(order = 7)
@Operation(summary = "逻辑删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
return R.status(datasourceService.deleteLogic(Func.toLongList(ids)));
}
/**
* 数据源列表
*/
@GetMapping("/select")
@ApiOperationSupport(order = 8)
@Operation(summary = "下拉数据源", description = "查询列表")
public R<List<Datasource>> select() {
List<Datasource> list = datasourceService.list();
return R.data(list);
}
}
|
repos\SpringBlade-master\blade-ops\blade-develop\src\main\java\org\springblade\develop\controller\DatasourceController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class DmnRestUrlBuilder {
protected String baseUrl = "";
protected DmnRestUrlBuilder() {
}
protected DmnRestUrlBuilder(String baseUrl) {
this.baseUrl = baseUrl;
}
public String getBaseUrl() {
return baseUrl;
}
public String buildUrl(String[] fragments, Object... arguments) {
return new StringBuilder(baseUrl).append("/").append(MessageFormat.format(StringUtils.join(fragments, '/'), arguments)).toString();
}
/** Uses baseUrl as the base URL */
public static DmnRestUrlBuilder usingBaseUrl(String baseUrl) {
if (baseUrl == null) {
throw new FlowableIllegalArgumentException("baseUrl can not be null");
|
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
}
return new DmnRestUrlBuilder(baseUrl);
}
/** Extracts the base URL from the request */
public static DmnRestUrlBuilder fromRequest(HttpServletRequest request) {
return usingBaseUrl(ServletUriComponentsBuilder.fromServletMapping(request).build().toUriString());
}
/** Extracts the base URL from current request */
public static DmnRestUrlBuilder fromCurrentRequest() {
return usingBaseUrl(ServletUriComponentsBuilder.fromCurrentServletMapping().build().toUriString());
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\DmnRestUrlBuilder.java
| 2
|
请完成以下Java代码
|
public String getCalledCaseInstanceId() {
return calledCaseInstanceId;
}
public String getTenantId() {
return tenantId;
}
public Date getCreateTime() {
return createTime;
}
public Date getEndTime() {
return endTime;
}
public Long getDurationInMillis() {
return durationInMillis;
}
public Boolean getRequired() {
return required;
}
public Boolean getAvailable() {
return available;
}
public Boolean getEnabled() {
return enabled;
}
public Boolean getDisabled() {
return disabled;
}
public Boolean getActive() {
return active;
}
public Boolean getCompleted() {
return completed;
}
public Boolean getTerminated() {
return terminated;
|
}
public static HistoricCaseActivityInstanceDto fromHistoricCaseActivityInstance(HistoricCaseActivityInstance historicCaseActivityInstance) {
HistoricCaseActivityInstanceDto dto = new HistoricCaseActivityInstanceDto();
dto.id = historicCaseActivityInstance.getId();
dto.parentCaseActivityInstanceId = historicCaseActivityInstance.getParentCaseActivityInstanceId();
dto.caseActivityId = historicCaseActivityInstance.getCaseActivityId();
dto.caseActivityName = historicCaseActivityInstance.getCaseActivityName();
dto.caseActivityType = historicCaseActivityInstance.getCaseActivityType();
dto.caseDefinitionId = historicCaseActivityInstance.getCaseDefinitionId();
dto.caseInstanceId = historicCaseActivityInstance.getCaseInstanceId();
dto.caseExecutionId = historicCaseActivityInstance.getCaseExecutionId();
dto.taskId = historicCaseActivityInstance.getTaskId();
dto.calledProcessInstanceId = historicCaseActivityInstance.getCalledProcessInstanceId();
dto.calledCaseInstanceId = historicCaseActivityInstance.getCalledCaseInstanceId();
dto.tenantId = historicCaseActivityInstance.getTenantId();
dto.createTime = historicCaseActivityInstance.getCreateTime();
dto.endTime = historicCaseActivityInstance.getEndTime();
dto.durationInMillis = historicCaseActivityInstance.getDurationInMillis();
dto.required = historicCaseActivityInstance.isRequired();
dto.available = historicCaseActivityInstance.isAvailable();
dto.enabled = historicCaseActivityInstance.isEnabled();
dto.disabled = historicCaseActivityInstance.isDisabled();
dto.active = historicCaseActivityInstance.isActive();
dto.completed = historicCaseActivityInstance.isCompleted();
dto.terminated = historicCaseActivityInstance.isTerminated();
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricCaseActivityInstanceDto.java
| 1
|
请完成以下Java代码
|
private boolean acceptTU(final I_M_HU tuHU)
{
//
// Check same BPartner
if (!BPartnerId.equals(IHandlingUnitsBL.extractBPartnerIdOrNull(tuHU), this.bpartnerId))
{
return false;
}
//
// Check same BPartner Location
if (!BPartnerLocationId.equals(IHandlingUnitsBL.extractBPartnerLocationIdOrNull(tuHU), this.bpartnerLocationId))
{
return false;
}
//
// Check same Locator
if (!LocatorId.equalsByRepoId(tuHU.getM_Locator_ID(), LocatorId.toRepoId(locatorId)))
{
return false;
}
//
// Check same HUStatus
final String huStatus = tuHU.getHUStatus();
if (!Objects.equals(huStatus, this.huStatus))
{
|
return false;
}
//
// Default: accept
return true;
}
void close()
{
final IAttributeStorage luAttributes = huContext.getHUAttributeStorageFactory().getAttributeStorage(luHU);
luAttributes.setSaveOnChange(true);
collectedAttributes.updateAggregatedValuesTo(luAttributes);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\LULoaderInstance.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
|
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" + "id=" + id + ", name='" + name + '\'' + '}';
}
}
|
repos\tutorials-master\persistence-modules\spring-data-yugabytedb\src\main\java\com\baeldung\User.java
| 2
|
请完成以下Java代码
|
public String getClearValue ()
{
return m_clearValue;
} // getClearValue
/**
* Set Clear Value
* @param clearValue The clearValue to set.
*/
public void setClearValue (String clearValue)
{
m_clearValue = clearValue;
m_obscuredValue = null;
} // setClearValue
/**
* Get Obscured Value
* @param clearValue The clearValue to set.
* @return Returns the obscuredValue.
*/
public String getObscuredValue (String clearValue)
{
setClearValue(clearValue);
return getObscuredValue();
} // getObscuredValue
/**
* Get Obscured Value
* @return Returns the obscuredValue.
*/
public String getObscuredValue ()
{
if (m_obscuredValue != null)
return m_obscuredValue;
if (m_clearValue == null || m_clearValue.length() == 0)
return m_clearValue;
//
boolean alpha = m_type.charAt(0) == 'A';
int clearStart = Integer.parseInt(m_type.substring(1,2));
int clearEnd = Integer.parseInt(m_type.substring(2));
//
char[] chars = m_clearValue.toCharArray();
int length = chars.length;
|
StringBuffer sb = new StringBuffer(length);
for (int i = 0; i < length; i++)
{
char c = chars[i];
if (i < clearStart)
sb.append(c);
else if (i >= length-clearEnd)
sb.append(c);
else
{
if (!alpha && !Character.isDigit(c))
sb.append(c);
else
sb.append('*');
}
}
m_obscuredValue = sb.toString();
return m_obscuredValue;
} // getObscuredValue
/**************************************************************************
* test
* @param args ignored
*/
public static void main (String[] args)
{
System.out.println (Obscure.obscure("1a2b3c4d5e6f7g8h9"));
} // main
} // Obscrure
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\Obscure.java
| 1
|
请完成以下Java代码
|
protected List<HalResource<?>> resolveCachedLinks(String[] linkedIds, Cache cache, List<String> notCachedLinkedIds) {
ArrayList<HalResource<?>> resolvedResources = new ArrayList<HalResource<?>>();
for (String linkedId : linkedIds) {
HalResource<?> resource = (HalResource<?>) cache.get(linkedId);
if (resource != null) {
resolvedResources.add(resource);
}
else {
notCachedLinkedIds.add(linkedId);
}
}
return resolvedResources;
}
/**
* Put a resource into the cache.
*/
protected void putIntoCache(List<HalResource<?>> notCachedResources) {
Cache cache = getCache();
for (HalResource<?> notCachedResource : notCachedResources) {
cache.put(getResourceId(notCachedResource), notCachedResource);
}
}
/**
* @return the class of the entity which is resolved
*/
protected abstract Class<?> getHalResourceClass();
/**
* @return a comparator for this HAL resource if not overridden sorting is skipped
*/
|
protected Comparator<HalResource<?>> getResourceComparator() {
return null;
}
/**
* @return the resolved resources which are currently not cached
*/
protected abstract List<HalResource<?>> resolveNotCachedLinks(String[] linkedIds, ProcessEngine processEngine);
/**
* @return the id which identifies a resource in the cache
*/
protected abstract String getResourceId(HalResource<?> resource);
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\cache\HalCachingLinkResolver.java
| 1
|
请完成以下Java代码
|
private static List<LU> mergeLists(final List<LU> list1, final List<LU> list2)
{
if (list2.isEmpty())
{
return list1;
}
if (list1.isEmpty())
{
return list2;
}
else
{
final HashMap<HuId, LU> lusNew = new HashMap<>();
list1.forEach(lu -> lusNew.put(lu.getId(), lu));
list2.forEach(lu -> lusNew.compute(lu.getId(), (luId, existingLU) -> existingLU == null ? lu : existingLU.mergeWith(lu)));
return ImmutableList.copyOf(lusNew.values());
|
}
}
public boolean containsAnyOfHUIds(final Collection<HuId> huIds)
{
if (huIds.isEmpty()) {return false;}
return huIds.contains(getId()) // LU matches
|| tus.containsAnyOfHUIds(huIds); // any of the TU matches
}
public void forEachAffectedHU(@NonNull final LUTUCUConsumer consumer)
{
tus.forEachAffectedHU(this, consumer);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\LUTUResult.java
| 1
|
请完成以下Java代码
|
public String getPassword() {
return password;
}
public UserDO setPassword(String password) {
this.password = password;
return this;
}
public Date getCreateTime() {
return createTime;
}
public UserDO setCreateTime(Date createTime) {
this.createTime = createTime;
return this;
}
public Integer getDeleted() {
return deleted;
}
public UserDO setDeleted(Integer deleted) {
|
this.deleted = deleted;
return this;
}
@Override
public String toString() {
return "UserDO{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", createTime=" + createTime +
", deleted=" + deleted +
'}';
}
}
|
repos\SpringBoot-Labs-master\lab-21\lab-21-cache-redis\src\main\java\cn\iocoder\springboot\lab21\cache\dataobject\UserDO.java
| 1
|
请完成以下Java代码
|
public void onSave(final ICalloutRecord calloutRecord)
{
final I_AD_User user = calloutRecord.getModel(I_AD_User.class);
if (!isMarketingChannelsUseEnforced(user.getAD_Client_ID(), user.getAD_Org_ID()))
{
return;
}
if (userDAO.isSystemUser(UserId.ofRepoId(user.getAD_User_ID())))
{
return;
}
boolean canBeSaved = true;
|
if (mktgChannelDao.retrieveMarketingChannelsCountForUser(UserId.ofRepoId(user.getAD_User_ID())) <= 0)
{
canBeSaved = false;
}
if (!canBeSaved)
{
throw new AdempiereException(MSG_CAN_NOT_REMOVE_CHANNEL).markAsUserValidationError();
}
}
private boolean isMarketingChannelsUseEnforced(int clientID, int orgID)
{
return sysConfigBL.getBooleanValue(SYS_CONFIG_MARKETING_CHANNELS_ENFORCED, false, clientID, orgID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\callout\AD_User_TabCallout.java
| 1
|
请完成以下Java代码
|
public String getExpressionString()
{
return expressionStr;
}
@Override
public String getFormatedExpressionString()
{
return expressionStr;
}
@Override
public Set<CtxName> getParameters()
{
return ImmutableSet.of();
}
@Override
public String evaluate(final Evaluatee ctx, final boolean ignoreUnparsable)
{
return expressionStr;
}
@Override
public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound)
|
{
return expressionStr;
}
public String getConstantValue()
{
return expressionStr;
}
@Override
public final IStringExpression resolvePartial(final Evaluatee ctx)
{
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\ConstantStringExpression.java
| 1
|
请完成以下Java代码
|
public void onAfterTabSave_WhenElementIdChanged(final I_AD_Tab tab)
{
updateTranslationsForElement(tab);
recreateElementLinkForTab(tab);
}
private void updateTabFromElement(final I_AD_Tab tab)
{
final IADElementDAO adElementDAO = Services.get(IADElementDAO.class);
final I_AD_Element tabElement = adElementDAO.getById(tab.getAD_Element_ID());
if (tabElement == null)
{
// nothing to do. It was not yet set
return;
}
tab.setName(tabElement.getName());
tab.setDescription(tabElement.getDescription());
tab.setHelp(tabElement.getHelp());
tab.setCommitWarning(tabElement.getCommitWarning());
tab.setEntityType(tab.getAD_Window().getEntityType());
}
private void recreateElementLinkForTab(final I_AD_Tab tab)
{
final AdTabId adTabId = AdTabId.ofRepoIdOrNull(tab.getAD_Tab_ID());
if (adTabId != null)
{
final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class);
elementLinksService.createADElementLinkForTabId(adTabId);
}
}
private void updateTranslationsForElement(final I_AD_Tab tab)
|
{
if (!IElementTranslationBL.DYNATTR_AD_Tab_UpdateTranslations.getValue(tab, true))
{
// do not copy translations from element to tab
return;
}
final AdElementId tabElementId = AdElementId.ofRepoIdOrNull(tab.getAD_Element_ID());
if (tabElementId == null)
{
// nothing to do. It was not yet set
return;
}
Services.get(IElementTranslationBL.class).updateTabTranslationsFromElement(tabElementId);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE })
public void onBeforeTabDelete(final I_AD_Tab tab)
{
final IADWindowDAO adWindowDAO = Services.get(IADWindowDAO.class);
final AdTabId adTabId = AdTabId.ofRepoId(tab.getAD_Tab_ID());
adWindowDAO.deleteFieldsByTabId(adTabId);
adWindowDAO.deleteUISectionsByTabId(adTabId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\tab\model\interceptor\AD_Tab.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class IncidentStatisticsResultDto {
protected String incidentType;
protected Integer incidentCount;
public IncidentStatisticsResultDto() {}
public String getIncidentType() {
return incidentType;
}
public void setIncidentType(String incidentType) {
this.incidentType = incidentType;
}
public Integer getIncidentCount() {
|
return incidentCount;
}
public void setIncidentCount(Integer incidentCount) {
this.incidentCount = incidentCount;
}
public static IncidentStatisticsResultDto fromIncidentStatistics(IncidentStatistics statistics) {
IncidentStatisticsResultDto dto = new IncidentStatisticsResultDto();
dto.setIncidentType(statistics.getIncidentType());
dto.setIncidentCount(statistics.getIncidentCount());
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\IncidentStatisticsResultDto.java
| 2
|
请完成以下Spring Boot application配置
|
server:
port: 8088
fdfs:
soTimeout: 1500
connectTimeout: 600
thumbImage: #thumbImage param
width: 150
height: 150
tra
|
ckerList: #TrackerList参数,支持多个
- 10.11.68.77:22122
|
repos\springboot-demo-master\fastdfs\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
public void setSecure(@Nullable Boolean secure) {
this.secure = secure;
}
public @Nullable Duration getMaxAge() {
return this.maxAge;
}
public void setMaxAge(@Nullable Duration maxAge) {
this.maxAge = maxAge;
}
public @Nullable SameSite getSameSite() {
return this.sameSite;
}
public void setSameSite(@Nullable SameSite sameSite) {
this.sameSite = sameSite;
}
public @Nullable Boolean getPartitioned() {
return this.partitioned;
}
public void setPartitioned(@Nullable Boolean partitioned) {
this.partitioned = partitioned;
}
/**
* SameSite values.
*/
public enum SameSite {
/**
* SameSite attribute will be omitted when creating the cookie.
|
*/
OMITTED(null),
/**
* SameSite attribute will be set to None. Cookies are sent in both first-party
* and cross-origin requests.
*/
NONE("None"),
/**
* SameSite attribute will be set to Lax. Cookies are sent in a first-party
* context, also when following a link to the origin site.
*/
LAX("Lax"),
/**
* SameSite attribute will be set to Strict. Cookies are only sent in a
* first-party context (i.e. not when following a link to the origin site).
*/
STRICT("Strict");
private @Nullable final String attributeValue;
SameSite(@Nullable String attributeValue) {
this.attributeValue = attributeValue;
}
public @Nullable String attributeValue() {
return this.attributeValue;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\Cookie.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
@ManyToOne
private Author author;
public Book(String title) {
this.title = title;
}
Book() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
|
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-exceptions-2\src\main\java\com\baeldung\hibernate\hibernateexception\Book.java
| 2
|
请完成以下Java代码
|
private IArchiveStorage getArchiveStorage(
final ClientId adClientId,
final StorageType storageType,
final AccessMode accessMode)
{
final ArchiveStorageKey key = ArchiveStorageKey.of(adClientId, storageType, accessMode);
return archiveStorages.getOrLoad(key, this::createArchiveStorage);
}
private IArchiveStorage createArchiveStorage(@NonNull final ArchiveStorageKey key)
{
final Class<? extends IArchiveStorage> storageClass = getArchiveStorageClass(key.getStorageType(), key.getAccessMode());
try
{
final IArchiveStorage storage = storageClass.newInstance();
storage.init(key.getClientId());
return storage;
}
catch (final Exception e)
{
throw AdempiereException.wrapIfNeeded(e)
.appendParametersToMessage()
.setParameter("storageClass", storageClass);
}
}
@Override
public IArchiveStorage getArchiveStorage(final Properties ctx, final StorageType storageType)
{
final ClientId adClientId = Env.getClientId(ctx);
final AccessMode accessMode = getAccessMode();
return getArchiveStorage(adClientId, storageType, accessMode);
}
|
@Override
public IArchiveStorage getArchiveStorage(final Properties ctx, final StorageType storageType, final AccessMode accessMode)
{
final ClientId adClientId = Env.getClientId(ctx);
return getArchiveStorage(adClientId, storageType, accessMode);
}
/**
* Remove all registered {@link IArchiveStorage} classes.
* <p>
* NOTE: to be used only in testing
*/
public void removeAllArchiveStorages()
{
storageClasses.clear();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\api\impl\ArchiveStorageFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class FlatrateConditionsExcludedProductsRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final CCache<Integer, FlatrateConditionsExcludedProducts> excludedProductsCache = CCache.<Integer, FlatrateConditionsExcludedProducts>builder()
.tableName(I_M_Product_Exclude_FlatrateConditions.Table_Name)
.build();
public boolean isProductExcludedFromFlatrateConditions(@NonNull final GroupTemplateId groupTemplateId, @NonNull final ProductId productId)
{
return getFlatrateConditionsExcludedProducts().isExcluded(groupTemplateId, productId);
}
private FlatrateConditionsExcludedProducts getFlatrateConditionsExcludedProducts()
{
return excludedProductsCache.getOrLoad(0, this::retrieveFlatrateConditionsExcludedProducts);
}
private FlatrateConditionsExcludedProducts retrieveFlatrateConditionsExcludedProducts()
{
|
final ImmutableSet<FlatrateConditionsExcludedProducts.GroupTemplateIdAndProductId> exclusions = queryBL
.createQueryBuilderOutOfTrx(I_M_Product_Exclude_FlatrateConditions.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(FlatrateConditionsExcludedProductsRepository::fromRecord)
.collect(ImmutableSet.toImmutableSet());
return new FlatrateConditionsExcludedProducts(exclusions);
}
private static FlatrateConditionsExcludedProducts.GroupTemplateIdAndProductId fromRecord(final I_M_Product_Exclude_FlatrateConditions record)
{
return FlatrateConditionsExcludedProducts.GroupTemplateIdAndProductId.of(
GroupTemplateId.ofRepoId(record.getC_CompensationGroup_Schema_ID()),
ProductId.ofRepoId(record.getM_Product_ID()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\FlatrateConditionsExcludedProductsRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
/* package */class LookupValue<KT extends Object> implements ILookupValue<KT>
{
private final ILookupTemplate<KT> lookupTemplate;
private final KT value;
private final boolean mandatoryLookup;
public LookupValue(final ILookupTemplate<KT> lookupTemplate, final KT value, final boolean mandatoryLookup)
{
this.lookupTemplate = lookupTemplate;
this.value = value;
this.mandatoryLookup = mandatoryLookup;
}
@Override
public ILookupTemplate<KT> getLookupTemplate()
{
|
return lookupTemplate;
}
@Override
public KT getValue()
{
return value;
}
@Override
public boolean isMandatoryLookup()
{
return mandatoryLookup;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\commons\api\impl\LookupValue.java
| 2
|
请完成以下Java代码
|
private Optional<String> getLookupTableName()
{
if (lookupTableName != null)
{
return lookupTableName;
}
else if (documentFieldBuilder != null)
{
return documentFieldBuilder.getLookupTableName();
}
else
{
return Optional.empty();
}
}
public Builder setFieldType(final FieldType fieldType)
{
this.fieldType = fieldType;
return this;
}
public boolean isRegularField()
{
return fieldType == null;
}
/**
* May be {@code null}, unless the field type is {@link FieldType#Tooltip}.
*/
public Builder setTooltipIconName(final String tooltipIconName)
{
this.tooltipIconName = tooltipIconName;
return this;
}
public Builder setPublicField(final boolean publicField)
{
this.publicField = publicField;
return this;
}
public boolean isPublicField()
{
return publicField;
}
private Builder setConsumed()
{
consumed = true;
return this;
}
public boolean isConsumed()
{
return consumed;
}
public Builder setListNullItemCaption(@NonNull final ITranslatableString listNullItemCaption)
{
this.listNullItemCaption = listNullItemCaption;
|
return this;
}
public Builder setEmptyFieldText(final ITranslatableString emptyFieldText)
{
this.emptyFieldText = emptyFieldText;
return this;
}
public Builder trackField(final DocumentFieldDescriptor.Builder field)
{
documentFieldBuilder = field;
return this;
}
public boolean isSpecialFieldToExcludeFromLayout()
{
return documentFieldBuilder != null && documentFieldBuilder.isSpecialFieldToExcludeFromLayout();
}
public Builder setDevices(@NonNull final DeviceDescriptorsList devices)
{
this._devices = devices;
return this;
}
private DeviceDescriptorsList getDevices()
{
return _devices;
}
public Builder setSupportZoomInto(final boolean supportZoomInto)
{
this.supportZoomInto = supportZoomInto;
return this;
}
private boolean isSupportZoomInto()
{
return supportZoomInto;
}
public Builder setForbidNewRecordCreation(final boolean forbidNewRecordCreation)
{
this.forbidNewRecordCreation = forbidNewRecordCreation;
return this;
}
private boolean isForbidNewRecordCreation()
{
return forbidNewRecordCreation;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementFieldDescriptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.headers(h -> h.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
.authorizeHttpRequests(ah -> ah
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.requestMatchers(AUTH_WHITELIST).permitAll()
.requestMatchers("/admin/**").hasAuthority(Constants.ROLE_ADMIN)
.requestMatchers("/user/**").hasAuthority(Constants.ROLE_USER)
.requestMatchers("/auth/login").permitAll()
.requestMatchers("/api/**").authenticated()//individual api will be secured differently
.anyRequest().authenticated()) //this one will catch the rest patterns
.csrf(AbstractHttpConfigurer::disable)
.oauth2Login(withDefaults())
.oauth2ResourceServer(o2 -> o2.jwt(withDefaults()))
.oauth2Client(withDefaults());
return http.build();
|
}
@Bean
JwtDecoder jwtDecoder(@Value("${spring.security.oauth2.client.provider.oidc.issuer-uri}") String issuerUri) {
return JwtDecoders.fromOidcIssuerLocation(issuerUri);
}
@Bean
public GrantedAuthoritiesMapper userAuthoritiesMapper() {
return authorities -> authorities.stream().filter(a -> a instanceof OidcUserAuthority)
.map(a -> (OidcUserAuthority) a)
.map(a -> SecurityUtils.extractAuthorityFromClaims(a.getUserInfo().getClaims()))
.flatMap(List::stream)
.collect(Collectors.toSet());
}
}
|
repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\config\security\SecurityConfig.java
| 2
|
请完成以下Java代码
|
public static boolean isPalindromeString(int number) {
String original = String.valueOf(number);
String reversed = new StringBuilder(original).reverse()
.toString();
return original.equals(reversed);
}
public static boolean isPalindromeRecursive(int number) {
return isPalindromeHelper(number, 0) == number;
}
private static int isPalindromeHelper(int number, int reversedNumber) {
if (number == 0) {
return reversedNumber;
}
reversedNumber = reversedNumber * 10 + number % 10;
return isPalindromeHelper(number / 10, reversedNumber);
}
public static boolean isPalindromeHalfReversal(int number) {
if (number < 0 || (number % 10 == 0 && number != 0)) {
return false;
}
int reversedNumber = 0;
while (number > reversedNumber) {
reversedNumber = reversedNumber * 10 + number % 10;
number /= 10;
}
return number == reversedNumber || number == reversedNumber / 10;
}
public static boolean isPalindromeDigitByDigit(int number) {
if (number < 0) {
return false;
|
}
int divisor = 1;
while (number / divisor >= 10) {
divisor *= 10;
}
while (number != 0) {
int leading = number / divisor;
int trailing = number % 10;
if (leading != trailing) {
return false;
}
number = (number % divisor) / 10;
divisor /= 100;
}
return true;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-numeric\src\main\java\com\baeldung\algorithms\palindrome\PalindromeNumber.java
| 1
|
请完成以下Java代码
|
protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException {
String jobExecutorThreadPoolName = THREAD_POOL_NAME.resolveModelAttribute(context, model).asString();
ServiceName jobExecutorThreadPoolServiceName = ServiceNames.forManagedThreadPool(jobExecutorThreadPoolName);
performRuntimeThreadPool(context, model, jobExecutorThreadPoolName, jobExecutorThreadPoolServiceName);
ServiceName serviceName = ServiceNames.forMscExecutorService();
ServiceBuilder<?> builder = context.getServiceTarget().addService(serviceName);
Consumer<ExecutorService> provider = builder.provides(serviceName);
Supplier<EnhancedQueueExecutor> supplier = builder.requires(jobExecutorThreadPoolServiceName);
MscExecutorService service = new MscExecutorService(supplier, provider);
builder.setInitialMode(ServiceController.Mode.ACTIVE);
builder.setInstance(service);
builder.install();
}
protected void performRuntimeThreadPool(OperationContext context,
ModelNode model,
String name,
ServiceName jobExecutorThreadPoolServiceName)
throws OperationFailedException {
ServiceTarget serviceTarget = context.getServiceTarget();
|
ThreadFactoryService threadFactory = new ThreadFactoryService();
threadFactory.setThreadGroupName(THREAD_POOL_GRP_NAME + name);
ServiceName threadFactoryServiceName = ServiceNames.forThreadFactoryService(name);
serviceTarget.addService(threadFactoryServiceName, threadFactory).install();
Builder executorBuilder = new Builder()
.setMaximumPoolSize(MAX_THREADS.resolveModelAttribute(context, model).asInt())
.setCorePoolSize(CORE_THREADS.resolveModelAttribute(context, model).asInt())
.setMaximumQueueSize(QUEUE_LENGTH.resolveModelAttribute(context, model).asInt())
.setKeepAliveTime(KEEPALIVE_TIME.resolveModelAttribute(context, model).asInt(), TimeUnit.SECONDS)
.allowCoreThreadTimeOut(ALLOW_CORE_TIMEOUT.resolveModelAttribute(context, model).asBoolean());
ServiceBuilder<EnhancedQueueExecutor> queueExecutorBuilder = serviceTarget.addService(jobExecutorThreadPoolServiceName, new EnhancedQueueExecutorService(executorBuilder));
queueExecutorBuilder.requires(threadFactoryServiceName);
queueExecutorBuilder.setInitialMode(ServiceController.Mode.ACTIVE).install();
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\extension\handler\JobExecutorAdd.java
| 1
|
请完成以下Java代码
|
public List<ProcessInstanceModificationInstructionDto> getStartInstructions() {
return startInstructions;
}
public void setStartInstructions(List<ProcessInstanceModificationInstructionDto> startInstructions) {
this.startInstructions = startInstructions;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public void setSkipCustomListeners(boolean skipCustomListeners) {
this.skipCustomListeners = skipCustomListeners;
}
public boolean isSkipIoMappings() {
|
return skipIoMappings;
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMappings = skipIoMappings;
}
public boolean isWithVariablesInReturn() {
return withVariablesInReturn;
}
public void setWithVariablesInReturn(boolean withVariablesInReturn) {
this.withVariablesInReturn = withVariablesInReturn;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\StartProcessInstanceDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public I_C_BPartner_QuickInput getById(@NonNull final BPartnerQuickInputId bpartnerQuickInputId)
{
final I_C_BPartner_QuickInput bpartnerQuickInput = InterfaceWrapperHelper.load(bpartnerQuickInputId, I_C_BPartner_QuickInput.class);
if (bpartnerQuickInput == null)
{
throw new AdempiereException("Not found " + I_C_BPartner_QuickInput.class.getSimpleName() + " for ID=" + bpartnerQuickInputId);
}
return bpartnerQuickInput;
}
public List<I_C_BPartner_Contact_QuickInput> retrieveContactsByQuickInputId(@NonNull final BPartnerQuickInputId bpartnerQuickInputId)
{
return queryBL
.createQueryBuilder(I_C_BPartner_Contact_QuickInput.class)
.addEqualsFilter(I_C_BPartner_Contact_QuickInput.COLUMNNAME_C_BPartner_QuickInput_ID, bpartnerQuickInputId)
.orderBy(I_C_BPartner_Contact_QuickInput.COLUMNNAME_C_BPartner_Contact_QuickInput_ID)
.create()
.list();
}
public List<I_C_BPartner_Location_QuickInput> retrieveLocationsByQuickInputId(final BPartnerQuickInputId bpartnerQuickInputId)
{
return queryBL
.createQueryBuilder(I_C_BPartner_Location_QuickInput.class)
.addEqualsFilter(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_QuickInput_ID, bpartnerQuickInputId)
.orderBy(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_Location_QuickInput_ID)
.create()
.list();
}
public List<I_C_BPartner_Location_QuickInput> retrieveBillToLocationsByQuickInputId(final BPartnerQuickInputId bpartnerQuickInputId)
{
return queryBL
.createQueryBuilder(I_C_BPartner_Location_QuickInput.class)
.addEqualsFilter(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_QuickInput_ID, bpartnerQuickInputId)
.orderBy(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_Location_QuickInput_ID)
|
.create()
.list();
}
public List<String> getOtherLocationNames(
final int bpartnerQuickInputRecordId,
final int bpartnerLocationQuickInputIdToExclude)
{
return queryBL
.createQueryBuilder(I_C_BPartner_Location_QuickInput.class)
.addEqualsFilter(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_QuickInput_ID, bpartnerQuickInputRecordId)
.addNotEqualsFilter(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_Location_QuickInput_ID, bpartnerLocationQuickInputIdToExclude)
.create()
.listDistinct(I_C_BPartner_Location_QuickInput.COLUMNNAME_Name, String.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\quick_input\service\BPartnerQuickInputRepository.java
| 2
|
请完成以下Java代码
|
public JsonHU withDisplayedAttributesOnly(@Nullable final List<String> displayedAttributeCodesOnly)
{
if (displayedAttributeCodesOnly == null || displayedAttributeCodesOnly.isEmpty())
{
return this;
}
final JsonHUAttributes attributes2New = attributes2.retainOnlyAttributesInOrder(displayedAttributeCodesOnly);
if (Objects.equals(attributes2New, this.attributes2))
{
return this;
}
return toBuilder()
.attributes2(attributes2New)
.attributes(attributes2New.toJsonHUAttributeCodeAndValues())
.build();
}
public JsonHU withLayoutSections(@Nullable List<String> layoutSections)
{
final ImmutableList<String> layoutSectionsNorm = layoutSections == null || layoutSections.isEmpty()
? null
|
: ImmutableList.copyOf(layoutSections);
if (Objects.equals(layoutSectionsNorm, this.layoutSections))
{
return this;
}
else
{
return toBuilder()
.layoutSections(layoutSectionsNorm)
.build();
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-manufacturing\src\main\java\de\metas\common\handlingunits\JsonHU.java
| 1
|
请完成以下Java代码
|
public void setK_IndexLog_ID (int K_IndexLog_ID)
{
if (K_IndexLog_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_IndexLog_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_IndexLog_ID, Integer.valueOf(K_IndexLog_ID));
}
/** Get Index Log.
@return Text search log
*/
public int getK_IndexLog_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_IndexLog_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** QuerySource AD_Reference_ID=391 */
public static final int QUERYSOURCE_AD_Reference_ID=391;
/** Collaboration Management = C */
public static final String QUERYSOURCE_CollaborationManagement = "C";
/** Java Client = J */
public static final String QUERYSOURCE_JavaClient = "J";
/** HTML Client = H */
public static final String QUERYSOURCE_HTMLClient = "H";
/** Self Service = W */
|
public static final String QUERYSOURCE_SelfService = "W";
/** Set Query Source.
@param QuerySource
Source of the Query
*/
public void setQuerySource (String QuerySource)
{
set_Value (COLUMNNAME_QuerySource, QuerySource);
}
/** Get Query Source.
@return Source of the Query
*/
public String getQuerySource ()
{
return (String)get_Value(COLUMNNAME_QuerySource);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_IndexLog.java
| 1
|
请完成以下Java代码
|
public Set<DocumentId> getAddedRowIds()
{
throw new IllegalArgumentException("changes are not recorded");
}
@Override
public void collectRemovedRowIds(final Collection<DocumentId> rowIds) {}
@Override
public Set<DocumentId> getRemovedRowIds()
{
throw new IllegalArgumentException("changes are not recorded");
}
@Override
public void collectChangedRowIds(final Collection<DocumentId> rowIds) {}
@Override
public Set<DocumentId> getChangedRowIds()
{
throw new IllegalArgumentException("changes are not recorded");
}
}
//
//
//
@ToString
public static class RecordingAddRemoveChangedRowIdsCollector extends AddRemoveChangedRowIdsCollector
{
private HashSet<DocumentId> addedRowIds;
private HashSet<DocumentId> removedRowIds;
private HashSet<DocumentId> changedRowIds;
private RecordingAddRemoveChangedRowIdsCollector() {}
@Override
public void collectAddedRowId(@NonNull final DocumentId rowId)
{
if (addedRowIds == null)
{
addedRowIds = new HashSet<>();
}
addedRowIds.add(rowId);
}
@Override
public Set<DocumentId> getAddedRowIds()
{
final HashSet<DocumentId> addedRowIds = this.addedRowIds;
return addedRowIds != null ? addedRowIds : ImmutableSet.of();
}
@Override
public boolean hasAddedRows()
{
final HashSet<DocumentId> addedRowIds = this.addedRowIds;
|
return addedRowIds != null && !addedRowIds.isEmpty();
}
@Override
public void collectRemovedRowIds(final Collection<DocumentId> rowIds)
{
if (removedRowIds == null)
{
removedRowIds = new HashSet<>(rowIds);
}
else
{
removedRowIds.addAll(rowIds);
}
}
@Override
public Set<DocumentId> getRemovedRowIds()
{
final HashSet<DocumentId> removedRowIds = this.removedRowIds;
return removedRowIds != null ? removedRowIds : ImmutableSet.of();
}
@Override
public void collectChangedRowIds(final Collection<DocumentId> rowIds)
{
if (changedRowIds == null)
{
changedRowIds = new HashSet<>(rowIds);
}
else
{
changedRowIds.addAll(rowIds);
}
}
@Override
public Set<DocumentId> getChangedRowIds()
{
final HashSet<DocumentId> changedRowIds = this.changedRowIds;
return changedRowIds != null ? changedRowIds : ImmutableSet.of();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\AddRemoveChangedRowIdsCollector.java
| 1
|
请完成以下Java代码
|
private static void applyPkce(OAuth2AuthorizationRequest.Builder builder) {
if (isPkceAlreadyApplied(builder)) {
return;
}
String codeVerifier = DEFAULT_SECURE_KEY_GENERATOR.generateKey();
builder.attributes((attrs) -> attrs.put(PkceParameterNames.CODE_VERIFIER, codeVerifier));
builder.additionalParameters((params) -> {
try {
String codeChallenge = createHash(codeVerifier);
params.put(PkceParameterNames.CODE_CHALLENGE, codeChallenge);
params.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256");
}
catch (NoSuchAlgorithmException ex) {
params.put(PkceParameterNames.CODE_CHALLENGE, codeVerifier);
}
});
}
|
private static boolean isPkceAlreadyApplied(OAuth2AuthorizationRequest.Builder builder) {
AtomicBoolean pkceApplied = new AtomicBoolean(false);
builder.additionalParameters((params) -> {
if (params.containsKey(PkceParameterNames.CODE_CHALLENGE)) {
pkceApplied.set(true);
}
});
return pkceApplied.get();
}
private static String createHash(String value) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(value.getBytes(StandardCharsets.US_ASCII));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestCustomizers.java
| 1
|
请完成以下Java代码
|
public IModelCopyHelper setFrom(final Object fromModel)
{
this._fromModel = fromModel;
this._fromModelAccessor = null;
return this;
}
private final IModelInternalAccessor getFromAccessor()
{
if (_fromModelAccessor == null)
{
return InterfaceWrapperHelper.getModelInternalAccessor(getFrom());
}
return _fromModelAccessor;
}
private Object getFrom()
{
Check.assumeNotNull(_fromModel, "_fromModel not null");
return _fromModel;
}
@Override
public IModelCopyHelper setTo(final Object toModel)
{
this._toModel = toModel;
this._toModelAccessor = null;
return this;
}
private final IModelInternalAccessor getToAccessor()
{
if (_toModelAccessor == null)
{
Check.assumeNotNull(_toModel, "_toModel not null");
_toModelAccessor = InterfaceWrapperHelper.getModelInternalAccessor(_toModel);
}
|
return _toModelAccessor;
}
public final boolean isSkipCalculatedColumns()
{
return _skipCalculatedColumns;
}
@Override
public IModelCopyHelper setSkipCalculatedColumns(boolean skipCalculatedColumns)
{
this._skipCalculatedColumns = skipCalculatedColumns;
return this;
}
@Override
public IModelCopyHelper addTargetColumnNameToSkip(final String columnName)
{
targetColumnNamesToSkip.add(columnName);
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\model\util\ModelCopyHelper.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class BPartnerLocationQuery
{
public enum Type
{
BILL_TO, SHIP_TO, REMIT_TO
}
@NonNull
BPartnerId bpartnerId;
@NonNull
Type type;
/**
* If {@code false}, then bpartner locations with the given type are preferred, but also a location with another type can be returned.
* {@code true} by default.
*/
@Default
boolean applyTypeStrictly = true;
/**
* If set, then return the bPartner relation which has this id as {@code C_BPartner_Location_ID} and if not found, fallback to initial location.
*/
@Nullable
BPartnerLocationId relationBPartnerLocationId;
@Nullable
String postalCode;
@Nullable
String city;
@Nullable
CountryId countryId;
public boolean applyLocationChecks()
{
return countryId != null;
}
}
|
BPGroupId getBPGroupIdByBPartnerId(BPartnerId bpartnerId);
Stream<BPartnerId> streamBPartnerIdsBySalesRepBPartnerId(BPartnerId parentPartnerId);
List<BPartnerId> getParentsUpToTheTopInTrx(BPartnerId bpartnerId);
boolean isCampaignPriceAllowed(BPartnerId bpartnerId);
boolean pricingSystemBelongsToCustomerForPriceMutation(PricingSystemId pricingSystemId);
Optional<BPartnerContactId> getBPartnerContactIdBy(BPartnerContactQuery query);
List<GeographicalCoordinatesWithBPartnerLocationId> getGeoCoordinatesByBPartnerIds(Collection<BPartnerId> bpartnerIds);
List<GeographicalCoordinatesWithBPartnerLocationId> getGeoCoordinatesByBPartnerLocationIds(Collection<Integer> bpartnerLocationRepoIds);
I_C_BPartner_Location retrieveCurrentBillLocationOrNull(BPartnerId partnerId);
BPartnerLocationId retrieveLastUpdatedLocation(BPartnerId bpartnerId);
List<I_C_BPartner> retrieveByIds(Set<BPartnerId> bpartnerIds);
BPartnerLocationId getCurrentLocation(final BPartnerLocationId locationId);
@NonNull
Optional<BPartnerLocationId> retrieveSingleBPartnerLocationIdBy(@NonNull GLNQuery query);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\IBPartnerDAO.java
| 2
|
请完成以下Java代码
|
public abstract class ForwardingScriptScanner implements IScriptScanner
{
protected abstract IScriptScanner getDelegate();
@Override
public void setScriptScannerFactory(final IScriptScannerFactory scriptScannerFactory)
{
getDelegate().setScriptScannerFactory(scriptScannerFactory);
}
@Override
public IScriptScannerFactory getScriptScannerFactory()
{
return getDelegate().getScriptScannerFactory();
}
@Override
public IScriptScannerFactory getScriptScannerFactoryToUse()
{
return getDelegate().getScriptScannerFactoryToUse();
}
@Override
public IScriptFactory getScriptFactory()
{
return getDelegate().getScriptFactory();
}
@Override
public void setScriptFactory(final IScriptFactory scriptFactory)
{
getDelegate().setScriptFactory(scriptFactory);
}
|
@Override
public IScriptFactory getScriptFactoryToUse()
{
return getDelegate().getScriptFactoryToUse();
}
@Override
public boolean hasNext()
{
return getDelegate().hasNext();
}
@Override
public IScript next()
{
return getDelegate().next();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\ForwardingScriptScanner.java
| 1
|
请完成以下Java代码
|
public int getMSV3_Server_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Server_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Warehouse_PickingGroup getM_Warehouse_PickingGroup() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Warehouse_PickingGroup_ID, org.compiere.model.I_M_Warehouse_PickingGroup.class);
}
@Override
public void setM_Warehouse_PickingGroup(org.compiere.model.I_M_Warehouse_PickingGroup M_Warehouse_PickingGroup)
{
set_ValueFromPO(COLUMNNAME_M_Warehouse_PickingGroup_ID, org.compiere.model.I_M_Warehouse_PickingGroup.class, M_Warehouse_PickingGroup);
}
/** Set Kommissionier-Lagergruppe .
@param M_Warehouse_PickingGroup_ID Kommissionier-Lagergruppe */
@Override
public void setM_Warehouse_PickingGroup_ID (int M_Warehouse_PickingGroup_ID)
{
if (M_Warehouse_PickingGroup_ID < 1)
|
set_Value (COLUMNNAME_M_Warehouse_PickingGroup_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_PickingGroup_ID, Integer.valueOf(M_Warehouse_PickingGroup_ID));
}
/** Get Kommissionier-Lagergruppe .
@return Kommissionier-Lagergruppe */
@Override
public int getM_Warehouse_PickingGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_PickingGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java-gen\de\metas\vertical\pharma\msv3\server\model\X_MSV3_Server.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_TreeNode[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_Tree getAD_Tree() throws RuntimeException
{
return (I_AD_Tree)MTable.get(getCtx(), I_AD_Tree.Table_Name)
.getPO(getAD_Tree_ID(), get_TrxName()); }
/** Set Tree.
@param AD_Tree_ID
Identifies a Tree
*/
public void setAD_Tree_ID (int AD_Tree_ID)
{
if (AD_Tree_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Tree_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Tree_ID, Integer.valueOf(AD_Tree_ID));
}
/** Get Tree.
@return Identifies a Tree
*/
public int getAD_Tree_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tree_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Node_ID.
@param Node_ID Node_ID */
public void setNode_ID (int Node_ID)
{
if (Node_ID < 0)
set_ValueNoCheck (COLUMNNAME_Node_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Node_ID, Integer.valueOf(Node_ID));
}
/** Get Node_ID.
@return Node_ID */
public int getNode_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Node_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Parent.
@param Parent_ID
Parent of Entity
*/
public void setParent_ID (int Parent_ID)
{
if (Parent_ID < 1)
set_Value (COLUMNNAME_Parent_ID, null);
else
|
set_Value (COLUMNNAME_Parent_ID, Integer.valueOf(Parent_ID));
}
/** Get Parent.
@return Parent of Entity
*/
public int getParent_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Parent_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_TreeNode.java
| 1
|
请完成以下Java代码
|
public FrontendPrinterDataItem toFrontendPrinterData()
{
return FrontendPrinterDataItem.builder()
.printer(printer)
.filename(suggestFilename())
.data(toByteArray())
.build();
}
private byte[] toByteArray()
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (final PrintingDataToPDFWriter pdfWriter = new PrintingDataToPDFWriter(baos))
{
for (PrintingDataAndSegment printingDataAndSegment : segments)
{
pdfWriter.addArchivePartToPDF(printingDataAndSegment.getPrintingData(), printingDataAndSegment.getSegment());
}
}
return baos.toByteArray();
}
private String suggestFilename()
{
final ImmutableSet<String> filenames = segments.stream()
|
.map(PrintingDataAndSegment::getDocumentFileName)
.collect(ImmutableSet.toImmutableSet());
return filenames.size() == 1 ? filenames.iterator().next() : "report.pdf";
}
}
@Value(staticConstructor = "of")
private static class PrintingDataAndSegment
{
@NonNull PrintingData printingData;
@NonNull PrintingSegment segment;
public String getDocumentFileName()
{
return printingData.getDocumentFileName();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\frontend\FrontendPrinter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PermissionIssuer
{
public static PermissionIssuer MANUAL = new PermissionIssuer("MANUAL");
public static PermissionIssuer AUTO_BP_HIERARCHY = new PermissionIssuer("AUTO_BP_HIERARCHY");
@JsonCreator
public static PermissionIssuer ofCode(final String code)
{
final PermissionIssuer permissionIssuer = cacheByCode.get(code);
if (permissionIssuer != null)
{
return permissionIssuer;
}
return new PermissionIssuer(code);
}
private static ImmutableMap<String, PermissionIssuer> cacheByCode = ImmutableMap.<String, PermissionIssuer> builder()
.put(MANUAL.getCode(), MANUAL)
.put(AUTO_BP_HIERARCHY.getCode(), AUTO_BP_HIERARCHY)
.build();
|
private final String code;
private PermissionIssuer(@NonNull final String code)
{
Check.assumeNotEmpty(code, "code is not empty");
this.code = code;
}
/**
* @deprecated use {@link #getCode()}
*/
@Deprecated
public String toString()
{
return getCode();
}
@JsonValue
public String getCode()
{
return code;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\record_access\PermissionIssuer.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Application {
private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
@Bean
CommandLineRunner customMybatisMapper(final ManagementService managementService) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
String processDefinitionId = managementService.executeCustomSql(new AbstractCustomSqlExecution<CustomMybatisMapper, String>(CustomMybatisMapper.class) {
@Override
public String execute(CustomMybatisMapper customMybatisMapper) {
return customMybatisMapper.loadProcessDefinitionIdByKey("waiter");
}
});
LOGGER.info("Process definition id = {}", processDefinitionId);
}
};
}
@Bean
CommandLineRunner customMybatisXmlMapper(final ManagementService managementService) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
String processDefinitionDeploymentId = managementService.executeCommand(new Command<String>() {
@Override
public String execute(CommandContext commandContext) {
|
return (String) CommandContextUtil.getDbSqlSession()
.selectOne("selectProcessDefinitionDeploymentIdByKey", "waiter");
}
});
LOGGER.info("Process definition deployment id = {}", processDefinitionDeploymentId);
}
};
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-samples\flowable-spring-boot-sample-custom-mybatis-mapper\src\main\java\flowable\Application.java
| 2
|
请完成以下Java代码
|
public String toString()
{
final StringBuilder sb = new StringBuilder(getClass().getName()).append("[");
if (isNoRestriction())
{
sb.append("NO_RESTRICTION");
}
else if (isDefault())
{
sb.append("DEFAULT");
}
else
{
sb.append(maxRows);
}
sb.append("]");
return sb.toString();
}
/**
* Gets the maximum rows allowed.
*
* The returned number makes sense only if it's not {@link #isDefault()} or {@link #isNoRestriction()}.
*
* @return max rows allowed.
*/
public int getMaxRows()
{
return maxRows;
}
|
/**
* @return true if this is a "no restrictions".
*/
public boolean isNoRestriction()
{
return this == NO_RESTRICTION;
}
/**
* @return true if this restriction asks that context defaults (i.e. defined on role level, tab level etc) to be applied.
*/
public boolean isDefault()
{
return this == DEFAULT;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\GridTabMaxRows.java
| 1
|
请完成以下Java代码
|
public class MTree_NodeCMS extends X_AD_TreeNodeCMS
{
/**
*
*/
private static final long serialVersionUID = -8092902713429554718L;
/**
* Get Tree
* @param ctx context
* @param AD_Tree_ID tree
* @param trxName transaction
* @return array of nodes
*/
public static MTree_NodeCMS[] getTree (Properties ctx, int AD_Tree_ID, String trxName)
{
ArrayList<MTree_NodeCMS> list = new ArrayList<MTree_NodeCMS>();
String sql = "SELECT * FROM AD_TreeNodeCMS WHERE AD_Tree_ID=? ORDER BY Node_ID";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, trxName);
pstmt.setInt (1, AD_Tree_ID);
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
{
list.add (new MTree_NodeCMS (ctx, rs, trxName));
}
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
s_log.error(sql, e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
MTree_NodeCMS[] retValue = new MTree_NodeCMS[list.size ()];
list.toArray (retValue);
return retValue;
} // getTree
/**
* Get Tree Node
* @param tree tree
* @param Node_ID node
* @return node or null
*/
public static MTree_NodeCMS get (MTree_Base tree, int Node_ID)
{
MTree_NodeCMS retValue = null;
String sql = "SELECT * FROM AD_TreeNodeCMS WHERE AD_Tree_ID=? AND Node_ID=?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, tree.get_TrxName());
pstmt.setInt (1, tree.getAD_Tree_ID());
pstmt.setInt (2, Node_ID);
ResultSet rs = pstmt.executeQuery ();
if (rs.next ())
retValue = new MTree_NodeCMS (tree.getCtx(), rs, tree.get_TrxName());
rs.close ();
pstmt.close ();
pstmt = null;
|
}
catch (Exception e)
{
s_log.error("get", e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
return retValue;
} // get
/** Static Logger */
private static Logger s_log = LogManager.getLogger(MTree_NodeCMS.class);
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MTree_NodeCMS (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MTree_NodeCMS
/**
* Full Constructor
* @param tree tree
* @param Node_ID node
*/
public MTree_NodeCMS (MTree_Base tree, int Node_ID)
{
super (tree.getCtx(), 0, tree.get_TrxName());
setClientOrg(tree);
setAD_Tree_ID (tree.getAD_Tree_ID());
setNode_ID(Node_ID);
// Add to root
setParent_ID(0);
setSeqNo (0);
} // MTree_NodeCMS
} // MTree_NodeCMS
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTree_NodeCMS.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private HUManagerProfilesMap retrieveMap()
{
final ImmutableListMultimap<HUManagerProfileId, AttributeId> displayedAttributeIdsInOrderByProfileId = retrieveDisplayedAttributeIdsInOrder();
final Map<HUManagerProfileId, HUManagerProfileLayoutSectionList> layoutSectionsByProfileId = retrieveLayoutSectionsInOrder();
return queryBL.createQueryBuilder(I_MobileUI_HUManager.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(record -> fromRecord(record, displayedAttributeIdsInOrderByProfileId, layoutSectionsByProfileId))
.collect(HUManagerProfilesMap.collect());
}
@NonNull
private ImmutableListMultimap<HUManagerProfileId, AttributeId> retrieveDisplayedAttributeIdsInOrder()
{
return queryBL.createQueryBuilder(I_MobileUI_HUManager_Attribute.class)
.addOnlyActiveRecordsFilter()
.orderBy(I_MobileUI_HUManager_Attribute.COLUMNNAME_MobileUI_HUManager_ID)
.orderBy(I_MobileUI_HUManager_Attribute.COLUMNNAME_SeqNo)
.orderBy(I_MobileUI_HUManager_Attribute.COLUMNNAME_MobileUI_HUManager_Attribute_ID)
.create()
.stream()
.collect(ImmutableListMultimap.toImmutableListMultimap(
record -> HUManagerProfileId.ofRepoId(record.getMobileUI_HUManager_ID()),
record -> AttributeId.ofRepoId(record.getM_Attribute_ID())
));
}
@NonNull
private static HUManagerProfile fromRecord(
@NonNull final I_MobileUI_HUManager record,
@NonNull final ImmutableListMultimap<HUManagerProfileId, AttributeId> displayedAttributeIdsInOrderByProfileId,
@NonNull final Map<HUManagerProfileId, HUManagerProfileLayoutSectionList> layoutSectionsByProfileId)
{
final HUManagerProfileId profileId = HUManagerProfileId.ofRepoId(record.getMobileUI_HUManager_ID());
|
return HUManagerProfile.builder()
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.displayedAttributeIdsInOrder(displayedAttributeIdsInOrderByProfileId.get(profileId))
.layoutSections(layoutSectionsByProfileId.getOrDefault(profileId, HUManagerProfileLayoutSectionList.DEFAULT))
.build();
}
@NonNull
private Map<HUManagerProfileId, HUManagerProfileLayoutSectionList> retrieveLayoutSectionsInOrder()
{
return queryBL.createQueryBuilder(I_MobileUI_HUManager_LayoutSection.class)
.addOnlyActiveRecordsFilter()
.orderBy(I_MobileUI_HUManager_LayoutSection.COLUMNNAME_MobileUI_HUManager_ID)
.orderBy(I_MobileUI_HUManager_LayoutSection.COLUMNNAME_SeqNo)
.orderBy(I_MobileUI_HUManager_LayoutSection.COLUMNNAME_MobileUI_HUManager_LayoutSection_ID)
.create()
.stream()
.collect(Collectors.groupingBy(
record -> HUManagerProfileId.ofRepoId(record.getMobileUI_HUManager_ID()),
Collectors.mapping(
HUManagerProfileRepository::fromRecord,
HUManagerProfileLayoutSectionList.collectOrDefault()
)
));
}
private static @NotNull HUManagerProfileLayoutSection fromRecord(final I_MobileUI_HUManager_LayoutSection record)
{
return HUManagerProfileLayoutSection.ofCode(record.getLayoutSection());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\mobileui\config\HUManagerProfileRepository.java
| 2
|
请完成以下Java代码
|
public ApiRequestAudit getById(@NonNull final ApiRequestAuditId apiRequestAuditId)
{
final I_API_Request_Audit record = InterfaceWrapperHelper.load(apiRequestAuditId, I_API_Request_Audit.class);
return recordToRequestAudit(record);
}
@NonNull
public ApiRequestIterator getByQuery(@NonNull final ApiRequestQuery query)
{
final IQueryBuilder<I_API_Request_Audit> apiRequestQueryBuilder = queryBL.createQueryBuilder(I_API_Request_Audit.class)
.addInArrayFilter(I_API_Request_Audit.COLUMNNAME_Status, query.getApiRequestStatusCodeSet());
if (query.getIsErrorAcknowledged() != null)
{
apiRequestQueryBuilder.addEqualsFilter(I_API_Request_Audit.COLUMNNAME_IsErrorAcknowledged, query.getIsErrorAcknowledged());
}
final IQuery<I_API_Request_Audit> apiRequestAuditQuery = apiRequestQueryBuilder.create();
final IQueryOrderByBuilder<I_API_Request_Audit> orderBy = queryBL.createQueryOrderByBuilder(I_API_Request_Audit.class);
if (query.isOrderByTimeAscending())
{
orderBy.addColumnAscending(I_API_Request_Audit.COLUMNNAME_Time);
}
else
{
orderBy.addColumnAscending(I_API_Request_Audit.COLUMNNAME_API_Request_Audit_ID);
}
apiRequestAuditQuery.setOrderBy(orderBy.createQueryOrderBy());
final int bufferSize = sysConfigBL.getIntValue(SYS_CONFIG_ITERATOR_BUFFER_SIZE, -1);
if (bufferSize > 0)
{
apiRequestAuditQuery.setOption(IQuery.OPTION_IteratorBufferSize, bufferSize);
}
final Iterator<I_API_Request_Audit> apiRequestRecordsIterator = apiRequestAuditQuery.iterate(I_API_Request_Audit.class);
return ApiRequestIterator.of(apiRequestRecordsIterator, ApiRequestAuditRepository::recordToRequestAudit);
}
public void deleteRequestAudit(@NonNull final ApiRequestAuditId apiRequestAuditId)
{
final I_API_Request_Audit record = InterfaceWrapperHelper.load(apiRequestAuditId, I_API_Request_Audit.class);
|
InterfaceWrapperHelper.deleteRecord(record);
}
@NonNull
public static ApiRequestAudit recordToRequestAudit(@NonNull final I_API_Request_Audit record)
{
return ApiRequestAudit.builder()
.apiRequestAuditId(ApiRequestAuditId.ofRepoId(record.getAPI_Request_Audit_ID()))
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.roleId(RoleId.ofRepoId(record.getAD_Role_ID()))
.userId(UserId.ofRepoId(record.getAD_User_ID()))
.apiAuditConfigId(ApiAuditConfigId.ofRepoId(record.getAPI_Audit_Config_ID()))
.status(Status.ofCode(record.getStatus()))
.isErrorAcknowledged(record.isErrorAcknowledged())
.body(record.getBody())
.method(HttpMethod.ofNullableCode(record.getMethod()))
.path(record.getPath())
.remoteAddress(record.getRemoteAddr())
.remoteHost(record.getRemoteHost())
.time(TimeUtil.asInstantNonNull(record.getTime()))
.httpHeaders(record.getHttpHeaders())
.requestURI(record.getRequestURI())
.uiTraceExternalId(UITraceExternalId.ofNullableString(record.getUI_Trace_ExternalId()))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\apirequest\request\ApiRequestAuditRepository.java
| 1
|
请完成以下Java代码
|
public void setQuery(AbstractQueryDto<?> query) {
this.query = query;
}
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
@JsonInclude(Include.NON_NULL)
public Long getItemCount() {
return itemCount;
}
public void setItemCount(Long itemCount) {
this.itemCount = itemCount;
}
public static FilterDto fromFilter(Filter filter) {
FilterDto dto = new FilterDto();
dto.id = filter.getId();
dto.resourceType = filter.getResourceType();
dto.name = filter.getName();
dto.owner = filter.getOwner();
if (EntityTypes.TASK.equals(filter.getResourceType())) {
|
dto.query = TaskQueryDto.fromQuery(filter.getQuery());
}
dto.properties = filter.getProperties();
return dto;
}
public void updateFilter(Filter filter, ProcessEngine engine) {
if (getResourceType() != null && !getResourceType().equals(filter.getResourceType())) {
throw new InvalidRequestException(Status.BAD_REQUEST, "Unable to update filter from resource type '" + filter.getResourceType() + "' to '" + getResourceType() + "'");
}
filter.setName(getName());
filter.setOwner(getOwner());
filter.setQuery(query.toQuery(engine));
filter.setProperties(getProperties());
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\FilterDto.java
| 1
|
请完成以下Java代码
|
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Issue Status.
@param R_IssueStatus_ID
Status of an Issue
*/
public void setR_IssueStatus_ID (int R_IssueStatus_ID)
|
{
if (R_IssueStatus_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_IssueStatus_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_IssueStatus_ID, Integer.valueOf(R_IssueStatus_ID));
}
/** Get Issue Status.
@return Status of an Issue
*/
public int getR_IssueStatus_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueStatus_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueStatus.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable Boolean getExcludeFieldsWithoutExposeAnnotation() {
return this.excludeFieldsWithoutExposeAnnotation;
}
public void setExcludeFieldsWithoutExposeAnnotation(@Nullable Boolean excludeFieldsWithoutExposeAnnotation) {
this.excludeFieldsWithoutExposeAnnotation = excludeFieldsWithoutExposeAnnotation;
}
public @Nullable Boolean getSerializeNulls() {
return this.serializeNulls;
}
public void setSerializeNulls(@Nullable Boolean serializeNulls) {
this.serializeNulls = serializeNulls;
}
public @Nullable Boolean getEnableComplexMapKeySerialization() {
return this.enableComplexMapKeySerialization;
}
public void setEnableComplexMapKeySerialization(@Nullable Boolean enableComplexMapKeySerialization) {
this.enableComplexMapKeySerialization = enableComplexMapKeySerialization;
}
public @Nullable Boolean getDisableInnerClassSerialization() {
return this.disableInnerClassSerialization;
}
public void setDisableInnerClassSerialization(@Nullable Boolean disableInnerClassSerialization) {
this.disableInnerClassSerialization = disableInnerClassSerialization;
}
public @Nullable LongSerializationPolicy getLongSerializationPolicy() {
return this.longSerializationPolicy;
}
public void setLongSerializationPolicy(@Nullable LongSerializationPolicy longSerializationPolicy) {
this.longSerializationPolicy = longSerializationPolicy;
}
public @Nullable FieldNamingPolicy getFieldNamingPolicy() {
return this.fieldNamingPolicy;
}
public void setFieldNamingPolicy(@Nullable FieldNamingPolicy fieldNamingPolicy) {
this.fieldNamingPolicy = fieldNamingPolicy;
}
public @Nullable Boolean getPrettyPrinting() {
return this.prettyPrinting;
}
public void setPrettyPrinting(@Nullable Boolean prettyPrinting) {
this.prettyPrinting = prettyPrinting;
}
public @Nullable Strictness getStrictness() {
return this.strictness;
}
public void setStrictness(@Nullable Strictness strictness) {
this.strictness = strictness;
}
public void setLenient(@Nullable Boolean lenient) {
setStrictness((lenient != null && lenient) ? Strictness.LENIENT : Strictness.STRICT);
}
public @Nullable Boolean getDisableHtmlEscaping() {
return this.disableHtmlEscaping;
}
public void setDisableHtmlEscaping(@Nullable Boolean disableHtmlEscaping) {
this.disableHtmlEscaping = disableHtmlEscaping;
}
|
public @Nullable String getDateFormat() {
return this.dateFormat;
}
public void setDateFormat(@Nullable String dateFormat) {
this.dateFormat = dateFormat;
}
/**
* Enumeration of levels of strictness. Values are the same as those on
* {@link com.google.gson.Strictness} that was introduced in Gson 2.11. To maximize
* backwards compatibility, the Gson enum is not used directly.
*/
public enum Strictness {
/**
* Lenient compliance.
*/
LENIENT,
/**
* Strict compliance with some small deviations for legacy reasons.
*/
LEGACY_STRICT,
/**
* Strict compliance.
*/
STRICT
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-gson\src\main\java\org\springframework\boot\gson\autoconfigure\GsonProperties.java
| 2
|
请完成以下Java代码
|
public void trigger(DelegateExecution execution, String triggerName, Object triggerData) {
ExecutionEntity executionEntity = deleteMessageEventSubScription(execution);
leaveIntermediateCatchEvent(executionEntity);
}
@Override
public void eventCancelledByEventGateway(DelegateExecution execution) {
deleteMessageEventSubScription(execution);
Context.getCommandContext()
.getExecutionEntityManager()
.deleteExecutionAndRelatedData((ExecutionEntity) execution, DeleteReason.EVENT_BASED_GATEWAY_CANCEL);
}
protected ExecutionEntity deleteMessageEventSubScription(DelegateExecution execution) {
ExecutionEntity executionEntity = (ExecutionEntity) execution;
// Should we use triggerName and triggerData, because message name expression can change?
String messageName = messageExecutionContext.getMessageName(execution);
EventSubscriptionEntityManager eventSubscriptionEntityManager =
Context.getCommandContext().getEventSubscriptionEntityManager();
List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions();
for (EventSubscriptionEntity eventSubscription : eventSubscriptions) {
if (
eventSubscription instanceof MessageEventSubscriptionEntity &&
eventSubscription.getEventName().equals(messageName)
|
) {
eventSubscriptionEntityManager.delete(eventSubscription);
}
}
return executionEntity;
}
public MessageEventDefinition getMessageEventDefinition() {
return messageEventDefinition;
}
public MessageExecutionContext getMessageExecutionContext() {
return messageExecutionContext;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\IntermediateCatchMessageEventActivityBehavior.java
| 1
|
请完成以下Java代码
|
public void addReview(BookReview review) {
this.reviews.add(review);
review.setBook(this);
}
public void removeReview(BookReview review) {
review.setBook(null);
this.reviews.remove(review);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
|
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public List<BookReview> getReviews() {
return reviews;
}
public void setReviews(List<BookReview> reviews) {
this.reviews = reviews;
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootDomainEvents\src\main\java\com\bookstore\entity\Book.java
| 1
|
请完成以下Java代码
|
public class MoneySourceAndAcct
{
@NonNull private final Money source;
@NonNull private final Money acct;
private MoneySourceAndAcct(@NonNull final Money source, @NonNull final Money acct)
{
this.source = source;
this.acct = acct;
}
public static MoneySourceAndAcct ofSourceAndAcct(@NonNull final Money source, @NonNull final Money acct)
{
return new MoneySourceAndAcct(source, acct);
}
public String toString()
{
return source + "/" + acct;
}
public int signum() {return source.signum();}
public CurrencyId getSourceCurrencyId() {return source.getCurrencyId();}
private MoneySourceAndAcct newOfSourceAndAcct(@NonNull final Money newSource, @NonNull final Money newAcct)
{
if (Money.equals(this.source, newSource) && Money.equals(this.acct, newAcct))
{
return this;
}
return ofSourceAndAcct(newSource, newAcct);
}
public MoneySourceAndAcct divide(@NonNull final MoneySourceAndAcct divisor, @NonNull final CurrencyPrecision precision)
{
return newOfSourceAndAcct(source.divide(divisor.source, precision), acct.divide(divisor.acct, precision));
|
}
public MoneySourceAndAcct multiply(@NonNull final BigDecimal multiplicand)
{
return newOfSourceAndAcct(source.multiply(multiplicand), acct.multiply(multiplicand));
}
public MoneySourceAndAcct negate()
{
return newOfSourceAndAcct(source.negate(), acct.negate());
}
public MoneySourceAndAcct negateIf(final boolean condition)
{
return condition ? negate() : this;
}
public MoneySourceAndAcct toZero()
{
return newOfSourceAndAcct(source.toZero(), acct.toZero());
}
public MoneySourceAndAcct roundIfNeeded(@NonNull final CurrencyPrecision sourcePrecision, @NonNull final CurrencyPrecision acctPrecision)
{
return newOfSourceAndAcct(source.roundIfNeeded(sourcePrecision), acct.roundIfNeeded(acctPrecision));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\MoneySourceAndAcct.java
| 1
|
请完成以下Java代码
|
public static Date addDate(Object startDate, Object years, Object months, Object days) {
LocalDate currentDate = new LocalDate(startDate);
currentDate = currentDate.plusYears(intValue(years));
currentDate = currentDate.plusMonths(intValue(months));
currentDate = currentDate.plusDays(intValue(days));
return currentDate.toDate();
}
public static Date subtractDate(Object startDate, Object years, Object months, Object days) {
LocalDate currentDate = new LocalDate(startDate);
currentDate = currentDate.minusYears(intValue(years));
currentDate = currentDate.minusMonths(intValue(months));
currentDate = currentDate.minusDays(intValue(days));
return currentDate.toDate();
|
}
public static Date now() {
return new LocalDate().toDate();
}
protected static Integer intValue(Object value) {
Integer intValue = null;
if (value instanceof Integer) {
intValue = (Integer) value;
} else {
intValue = Integer.valueOf(value.toString());
}
return intValue;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\el\util\DateUtil.java
| 1
|
请完成以下Java代码
|
public class ClientTlsVersionExamples {
public static CloseableHttpClient setViaSocketFactory() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
SSLContexts.createDefault(),
new String[] { "TLSv1.2", "TLSv1.3" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
public static CloseableHttpClient setTlsVersionPerConnection() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContexts.createDefault()) {
@Override
protected void prepareSocket(SSLSocket socket) {
String hostname = socket.getInetAddress().getHostName();
if (hostname.endsWith("internal.system.com")) {
socket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" });
} else {
socket.setEnabledProtocols(new String[] { "TLSv1.3" });
}
}
};
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
// To configure the TLS versions for the client, set the https.protocols system property during runtime.
// For example: java -Dhttps.protocols=TLSv1.1,TLSv1.2,TLSv1.3 -jar webClient.jar
public static CloseableHttpClient setViaSystemProperties() {
return HttpClients.createSystem();
|
// Alternatively:
// return HttpClients.custom().useSystemProperties().build();
}
public static void main(String[] args) throws IOException {
// Alternatively:
// CloseableHttpClient httpClient = setTlsVersionPerConnection();
// CloseableHttpClient httpClient = setViaSystemProperties();
try (CloseableHttpClient httpClient = setViaSocketFactory();
CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
}
}
}
|
repos\tutorials-master\apache-httpclient4\src\main\java\com\baeldung\tlsversion\ClientTlsVersionExamples.java
| 1
|
请完成以下Java代码
|
public UpdateProcessInstanceSuspensionStateBuilderImpl byProcessInstanceId(String processInstanceId) {
ensureNotNull("processInstanceId", processInstanceId);
this.processInstanceId = processInstanceId;
return this;
}
@Override
public UpdateProcessInstanceSuspensionStateBuilderImpl byProcessDefinitionId(String processDefinitionId) {
ensureNotNull("processDefinitionId", processDefinitionId);
this.processDefinitionId = processDefinitionId;
return this;
}
@Override
public UpdateProcessInstanceSuspensionStateBuilderImpl byProcessDefinitionKey(String processDefinitionKey) {
ensureNotNull("processDefinitionKey", processDefinitionKey);
this.processDefinitionKey = processDefinitionKey;
return this;
}
@Override
public UpdateProcessInstanceSuspensionStateBuilderImpl processDefinitionWithoutTenantId() {
this.processDefinitionTenantId = null;
this.isProcessDefinitionTenantIdSet = true;
return this;
}
@Override
public UpdateProcessInstanceSuspensionStateBuilderImpl processDefinitionTenantId(String tenantId) {
ensureNotNull("tenantId", tenantId);
this.processDefinitionTenantId = tenantId;
this.isProcessDefinitionTenantIdSet = true;
return this;
}
@Override
public void activate() {
validateParameters();
ActivateProcessInstanceCmd command = new ActivateProcessInstanceCmd(this);
commandExecutor.execute(command);
}
@Override
public void suspend() {
validateParameters();
SuspendProcessInstanceCmd command = new SuspendProcessInstanceCmd(this);
commandExecutor.execute(command);
}
protected void validateParameters() {
ensureOnlyOneNotNull("Need to specify either a process instance id, a process definition id or a process definition key.", processInstanceId, processDefinitionId, processDefinitionKey);
|
if (isProcessDefinitionTenantIdSet && (processInstanceId != null || processDefinitionId != null)) {
throw LOG.exceptionUpdateSuspensionStateForTenantOnlyByProcessDefinitionKey();
}
ensureNotNull("commandExecutor", commandExecutor);
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionTenantId() {
return processDefinitionTenantId;
}
public boolean isProcessDefinitionTenantIdSet() {
return isProcessDefinitionTenantIdSet;
}
public String getProcessInstanceId() {
return processInstanceId;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\runtime\UpdateProcessInstanceSuspensionStateBuilderImpl.java
| 1
|
请完成以下Java代码
|
public XhtmlFrameSetDocument appendBody(Element value)
{
body.addElement(value);
return(this);
}
/**
Append to the body element for this XhtmlFrameSetDocument container.
@param value adds to the value between the body tags
*/
public XhtmlFrameSetDocument appendBody(String value)
{
body.addElement(value);
return(this);
}
/**
Get the title element for this XhtmlFrameSetDocument container.
*/
public title getTitle()
{
return(title);
}
/**
Set the title element for this XhtmlFrameSetDocument container.
*/
public XhtmlFrameSetDocument setTitle(title set_title)
{
this.title = set_title;
return(this);
}
/**
Append to the title element for this XhtmlFrameSetDocument container.
@param value adds to the value between the title tags
*/
public XhtmlFrameSetDocument appendTitle(Element value)
{
title.addElement(value);
return(this);
}
/**
Append to the title element for this XhtmlFrameSetDocument container.
@param value adds to the value between the title tags
*/
public XhtmlFrameSetDocument appendTitle(String value)
{
title.addElement(value);
return(this);
}
/**
* Sets the codeset for this XhtmlFrameSetDocument
*/
public void setCodeset ( String codeset )
{
this.codeset = codeset;
}
/**
* Gets the codeset for this XhtmlFrameSetDocument
*
* @return the codeset
*/
public String getCodeset()
{
return this.codeset;
}
/**
Write the container to the OutputStream
*/
public void output(OutputStream out)
{
// XhtmlFrameSetDocument is just a convient wrapper for html call html.output
html.output(out);
}
/**
Write the container to the PrinteWriter
|
*/
public void output(PrintWriter out)
{
// XhtmlFrameSetDocument is just a convient wrapper for html call html.output
html.output(out);
}
/**
Override the toString() method so that it prints something meaningful.
*/
public final String toString()
{
if ( getCodeset() != null )
return (html.toString(getCodeset()));
else
return(html.toString());
}
/**
Override the toString() method so that it prints something meaningful.
*/
public final String toString(String codeset)
{
return(html.toString(codeset));
}
/**
Allows the XhtmlFrameSetDocument to be cloned. Doesn't return an instanceof XhtmlFrameSetDocument returns instance of html.
*/
public Object clone()
{
return(html.clone());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\XhtmlFrameSetDocument.java
| 1
|
请完成以下Java代码
|
public final String getName()
{
final Object nameObj = getValue(Action.NAME);
return nameObj == null ? "" : nameObj.toString();
}
public final KeyStroke getAccelerator()
{
return (KeyStroke)getValue(ACCELERATOR_KEY);
}
/**
* Install the action and the key bindings to given component.
*
* @param comp
* @param inputMapCondition one of WHEN_IN_FOCUSED_WINDOW, WHEN_FOCUSED, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
*/
public final void installTo(final JComponent comp, final int inputMapCondition)
{
if (comp == null)
{
return;
|
}
final String actionName = getName();
final ActionMap actionMap = comp.getActionMap();
actionMap.put(actionName, this);
final KeyStroke accelerator = getAccelerator();
if (accelerator != null)
{
final InputMap inputMap = comp.getInputMap(inputMapCondition);
inputMap.put(accelerator, actionName);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VEditorAction.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public AppDeploymentQueryImpl deploymentWithoutTenantId() {
this.withoutTenantId = true;
return this;
}
@Override
public AppDeploymentQueryImpl latest() {
if (key == null) {
throw new FlowableIllegalArgumentException("latest can only be used together with a deployment key");
}
this.latest = true;
return this;
}
// sorting ////////////////////////////////////////////////////////
@Override
public AppDeploymentQuery orderByDeploymentId() {
return orderBy(AppDeploymentQueryProperty.DEPLOYMENT_ID);
}
@Override
public AppDeploymentQuery orderByDeploymentTime() {
return orderBy(AppDeploymentQueryProperty.DEPLOY_TIME);
}
@Override
public AppDeploymentQuery orderByDeploymentName() {
return orderBy(AppDeploymentQueryProperty.DEPLOYMENT_NAME);
}
@Override
public AppDeploymentQuery orderByTenantId() {
return orderBy(AppDeploymentQueryProperty.DEPLOYMENT_TENANT_ID);
}
// results ////////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getAppDeploymentEntityManager(commandContext).findDeploymentCountByQueryCriteria(this);
}
@Override
public List<AppDeployment> executeList(CommandContext commandContext) {
return CommandContextUtil.getAppDeploymentEntityManager(commandContext).findDeploymentsByQueryCriteria(this);
}
// getters ////////////////////////////////////////////////////////
public String getDeploymentId() {
return deploymentId;
}
public List<String> getDeploymentIds() {
return deploymentIds;
|
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getCategory() {
return category;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getKey() {
return key;
}
public boolean isLatest() {
return latest;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDeploymentQueryImpl.java
| 2
|
请完成以下Java代码
|
public OAuth2AuthorizationRequest deserialize(JsonParser parser, DeserializationContext context) {
JsonNode root = context.readTree(parser);
return deserialize(parser, context, root);
}
private OAuth2AuthorizationRequest deserialize(JsonParser parser, DeserializationContext context, JsonNode root) {
AuthorizationGrantType authorizationGrantType = convertAuthorizationGrantType(
JsonNodeUtils.findObjectNode(root, "authorizationGrantType"));
Builder builder = getBuilder(parser, authorizationGrantType);
builder.authorizationUri(JsonNodeUtils.findStringValue(root, "authorizationUri"));
builder.clientId(JsonNodeUtils.findStringValue(root, "clientId"));
builder.redirectUri(JsonNodeUtils.findStringValue(root, "redirectUri"));
builder.scopes(JsonNodeUtils.findValue(root, "scopes", JsonNodeUtils.STRING_SET, context));
builder.state(JsonNodeUtils.findStringValue(root, "state"));
builder.additionalParameters(
JsonNodeUtils.findValue(root, "additionalParameters", JsonNodeUtils.STRING_OBJECT_MAP, context));
builder.authorizationRequestUri(JsonNodeUtils.findStringValue(root, "authorizationRequestUri"));
builder.attributes(JsonNodeUtils.findValue(root, "attributes", JsonNodeUtils.STRING_OBJECT_MAP, context));
return builder.build();
}
private Builder getBuilder(JsonParser parser, AuthorizationGrantType authorizationGrantType) {
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(authorizationGrantType)) {
|
return OAuth2AuthorizationRequest.authorizationCode();
}
throw new InvalidFormatException(parser, "Invalid authorizationGrantType", authorizationGrantType,
AuthorizationGrantType.class);
}
private static AuthorizationGrantType convertAuthorizationGrantType(JsonNode jsonNode) {
String value = JsonNodeUtils.findStringValue(jsonNode, "value");
if (AuthorizationGrantType.AUTHORIZATION_CODE.getValue().equalsIgnoreCase(value)) {
return AuthorizationGrantType.AUTHORIZATION_CODE;
}
return null;
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\jackson\OAuth2AuthorizationRequestDeserializer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class DefaultFetchCurrentChargesService implements FetchCurrentChargesService {
@Override
public CurrentChargesResponse fetch(CurrentChargesRequest request) {
List<String> subscriptions = request.getSubscriptionIds();
if (subscriptions == null || subscriptions.isEmpty()) {
System.out.println("Fetching ALL charges for customer: " + request.getCustomerId());
subscriptions = mockSubscriptions();
} else {
System.out.println(format("Fetching charges for customer: %s and subscriptions: %s", request.getCustomerId(), subscriptions));
}
CurrentChargesResponse charges = mockCharges(request.getCustomerId(), subscriptions, request.isItemized());
System.out.println("Fetched charges...");
return charges;
}
private CurrentChargesResponse mockCharges(String customerId, List<String> subscriptions, boolean itemized) {
List<LineItem> lineItems = mockLineItems(subscriptions);
BigDecimal amountDue = lineItems
.stream()
.map(li -> li.getAmount())
.reduce(new BigDecimal("0"), BigDecimal::add);
return CurrentChargesResponse
.builder()
.customerId(customerId)
.lineItems(itemized ? lineItems : emptyList())
.amountDue(amountDue)
.build();
}
|
private List<LineItem> mockLineItems(List<String> subscriptions) {
return subscriptions
.stream()
.map(subscription -> LineItem.builder()
.subscriptionId(subscription)
.quantity(current().nextInt(20))
.amount(new BigDecimal(current().nextDouble(1_000)))
.build())
.collect(toList());
}
private List<String> mockSubscriptions() {
String[] subscriptions = new String[5];
fill(subscriptions, UUID.randomUUID().toString());
return asList(subscriptions);
}
}
|
repos\tutorials-master\libraries-cli\src\main\java\com\baeldung\jcommander\usagebilling\service\DefaultFetchCurrentChargesService.java
| 2
|
请完成以下Java代码
|
public Group createNewGroup(String groupId) {
GroupEntity groupEntity = dataManager.create();
groupEntity.setId(groupId);
groupEntity.setRevision(0); // Needed as groups can be transient and not save when they are returned
return groupEntity;
}
@Override
public void delete(String groupId) {
GroupEntity group = dataManager.findById(groupId);
if (group != null) {
getMembershipEntityManager().deleteMembershipByGroupId(groupId);
if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(FlowableIdmEventBuilder.createMembershipEvent(FlowableIdmEventType.MEMBERSHIPS_DELETED, groupId, null),
engineConfiguration.getEngineCfgKey());
}
delete(group);
}
}
@Override
public GroupQuery createNewGroupQuery() {
return new GroupQueryImpl(getCommandExecutor());
}
@Override
public List<Group> findGroupByQueryCriteria(GroupQueryImpl query) {
return dataManager.findGroupByQueryCriteria(query);
}
@Override
public long findGroupCountByQueryCriteria(GroupQueryImpl query) {
return dataManager.findGroupCountByQueryCriteria(query);
}
@Override
public List<Group> findGroupsByUser(String userId) {
return dataManager.findGroupsByUser(userId);
|
}
@Override
public List<Group> findGroupsByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findGroupsByNativeQuery(parameterMap);
}
@Override
public long findGroupCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findGroupCountByNativeQuery(parameterMap);
}
@Override
public boolean isNewGroup(Group group) {
return ((GroupEntity) group).getRevision() == 0;
}
@Override
public List<Group> findGroupsByPrivilegeId(String privilegeId) {
return dataManager.findGroupsByPrivilegeId(privilegeId);
}
protected MembershipEntityManager getMembershipEntityManager() {
return engineConfiguration.getMembershipEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\GroupEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
private static @NonNull ImmutableSet<TriggerTiming> extractTimings(final I_AD_BusinessRule_Trigger record)
{
final ImmutableSet.Builder<TriggerTiming> timings = ImmutableSet.builder();
if (record.isOnNew())
{
timings.add(TriggerTiming.NEW);
}
if (record.isOnUpdate())
{
timings.add(TriggerTiming.UPDATE);
}
if (record.isOnDelete())
{
timings.add(TriggerTiming.DELETE);
}
return timings.build();
}
@Nullable
private static Validation extractCondition(final I_AD_BusinessRule_Trigger record)
{
return StringUtils.trimBlankToOptional(record.getConditionSQL())
|
.map(Validation::sql)
.orElse(null);
}
private static BusinessRuleWarningTarget fromRecord(@NonNull final I_AD_BusinessRule_WarningTarget record)
{
final String lookupSQL = StringUtils.trimBlankToNull(record.getLookupSQL());
if (lookupSQL == null)
{
throw new FillMandatoryException(I_AD_BusinessRule_WarningTarget.COLUMNNAME_LookupSQL);
}
return BusinessRuleWarningTarget.sqlLookup(
AdTableId.ofRepoId(record.getAD_Table_ID()),
lookupSQL
);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\descriptor\BusinessRuleLoader.java
| 1
|
请完成以下Java代码
|
private static final class OAuth2DeviceCodeGenerator implements OAuth2TokenGenerator<OAuth2DeviceCode> {
private final StringKeyGenerator deviceCodeGenerator = new Base64StringKeyGenerator(
Base64.getUrlEncoder().withoutPadding(), 96);
@Nullable
@Override
public OAuth2DeviceCode generate(OAuth2TokenContext context) {
if (context.getTokenType() == null
|| !OAuth2ParameterNames.DEVICE_CODE.equals(context.getTokenType().getValue())) {
return null;
}
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt
.plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive());
return new OAuth2DeviceCode(this.deviceCodeGenerator.generateKey(), issuedAt, expiresAt);
}
}
private static final class UserCodeStringKeyGenerator implements StringKeyGenerator {
// @formatter:off
private static final char[] VALID_CHARS = {
'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Z'
};
// @formatter:on
private final BytesKeyGenerator keyGenerator = KeyGenerators.secureRandom(8);
@Override
public String generateKey() {
byte[] bytes = this.keyGenerator.generateKey();
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
int offset = Math.abs(b % 20);
|
sb.append(VALID_CHARS[offset]);
}
sb.insert(4, '-');
return sb.toString();
}
}
private static final class OAuth2UserCodeGenerator implements OAuth2TokenGenerator<OAuth2UserCode> {
private final StringKeyGenerator userCodeGenerator = new UserCodeStringKeyGenerator();
@Nullable
@Override
public OAuth2UserCode generate(OAuth2TokenContext context) {
if (context.getTokenType() == null
|| !OAuth2ParameterNames.USER_CODE.equals(context.getTokenType().getValue())) {
return null;
}
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt
.plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive());
return new OAuth2UserCode(this.userCodeGenerator.generateKey(), issuedAt, expiresAt);
}
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2DeviceAuthorizationRequestAuthenticationProvider.java
| 1
|
请完成以下Java代码
|
protected IAllocationResult loadRemaining(final IAllocationRequest request)
{
// nothing at this level
return AllocationUtils.nullResult();
}
public final AbstractProducerDestination setM_HU_LUTU_Configuration(final I_M_HU_LUTU_Configuration lutuConfiguration)
{
assertConfigurable();
_lutuConfiguration = lutuConfiguration;
return this;
}
public final I_M_HU_LUTU_Configuration getM_HU_LUTU_Configuration()
{
return _lutuConfiguration;
}
@Override
public final IHUProducerAllocationDestination setIsHUPlanningReceiptOwnerPM(boolean isHUPlanningReceiptOwnerPM)
{
this._isHUPlanningReceiptOwnerPM = isHUPlanningReceiptOwnerPM;
return this;
}
public final boolean isHUPlanningReceiptOwnerPM()
{
return _isHUPlanningReceiptOwnerPM;
}
/**
* Sets this producer in "non-configurable" state. No further configuration to this producer will be allowed after calling this method.
*/
protected final void setNotConfigurable()
{
_configurable = false;
}
/**
* Makes sure producer is in configurable state. If not, and exception will be thrown.
*/
protected final void assertConfigurable()
{
if (!_configurable)
{
throw new HUException("This producer is not configurable anymore: " + this);
}
}
|
@Override
public final IHUProducerAllocationDestination setHUClearanceStatusInfo(final ClearanceStatusInfo huClearanceStatusInfo)
{
assertConfigurable();
_huClearanceStatusInfo = huClearanceStatusInfo;
return this;
}
public final ClearanceStatusInfo getHUClearanceStatusInfo()
{
return _huClearanceStatusInfo;
}
private void destroyCurrentHU(final HUListCursor currentHUCursor, final IHUContext huContext)
{
final I_M_HU hu = currentHUCursor.current();
if (hu == null)
{
return; // shall not happen
}
currentHUCursor.closeCurrent(); // close the current position of this cursor
// since _createdNonAggregateHUs is just a subset of _createdHUs, we don't know if 'hu' was in there to start with. All we care is that it's not in _createdNonAggregateHUs after this method.
_createdNonAggregateHUs.remove(hu);
final boolean removedFromCreatedHUs = _createdHUs.remove(hu);
Check.assume(removedFromCreatedHUs, "Cannot destroy {} because it wasn't created by us", hu);
// Delete only those HUs which were internally created by THIS producer
if (DYNATTR_Producer.getValue(hu) == this)
{
final Supplier<IAutoCloseable> getDontDestroyParentLUClosable = () -> {
final I_M_HU lu = handlingUnitsBL.getLoadingUnitHU(hu);
return lu != null
? huContext.temporarilyDontDestroyHU(HuId.ofRepoId(lu.getM_HU_ID()))
: () -> {
};
};
try (final IAutoCloseable ignored = getDontDestroyParentLUClosable.get())
{
handlingUnitsBL.destroyIfEmptyStorage(huContext, hu);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AbstractProducerDestination.java
| 1
|
请完成以下Java代码
|
public class BigDecimalRestVariableConverter implements RestVariableConverter {
@Override
public String getRestTypeName() {
return "bigDecimal";
}
@Override
public Class<?> getVariableType() {
return BigDecimal.class;
}
@Override
public Object getVariableValue(EngineRestVariable result) {
if (result.getValue() != null) {
return new BigDecimal(result.getValue().toString());
}
return null;
|
}
@Override
public void convertVariableValue(Object variableValue, EngineRestVariable result) {
if (variableValue != null) {
if (!(variableValue instanceof BigDecimal)) {
throw new FlowableIllegalArgumentException("Converter can only convert big decimal values");
}
result.setValue(((BigDecimal) variableValue).toPlainString());
} else {
result.setValue(null);
}
}
}
|
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\variable\BigDecimalRestVariableConverter.java
| 1
|
请完成以下Java代码
|
public String getAccountStatus() {
return accountStatus;
}
public void setAccountStatus(String accountStatus) {
this.accountStatus = accountStatus;
}
public Long getBalanceBegin() {
return balanceBegin;
}
public void setBalanceBegin(Long balanceBegin) {
this.balanceBegin = balanceBegin;
}
public Long getBalanceEnd() {
return balanceEnd;
}
public void setBalanceEnd(Long balanceEnd) {
this.balanceEnd = balanceEnd;
}
|
public String getCreateDateBegin() {
return createDateBegin;
}
public void setCreateDateBegin(String createDateBegin) {
this.createDateBegin = createDateBegin;
}
public String getCreateDateEnd() {
return createDateEnd;
}
public void setCreateDateEnd(String createDateEnd) {
this.createDateEnd = createDateEnd;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
repos\spring-boot-leaning-master\2.x_data\2-4 MongoDB 支持动态 SQL、分页方案\spring-boot-mongodb-page\src\main\java\com\neo\param\AccountPageParam.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PrometheusCustomMonitor {
private Counter requestErrorCount;
private Counter orderCount;
private DistributionSummary amountSum;
private AtomicInteger failCaseNum;
private final MeterRegistry registry;
@Autowired
public PrometheusCustomMonitor(MeterRegistry registry) {
this.registry = registry;
}
@PostConstruct
private void init() {
requestErrorCount = registry.counter("requests_error_total", "status", "error");
orderCount = registry.counter("order_request_count", "order", "test-svc");
amountSum = registry.summary("order_amount_sum", "orderAmount", "test-svc");
|
failCaseNum = registry.gauge("fail_case_num", new AtomicInteger(0));
}
public Counter getRequestErrorCount() {
return requestErrorCount;
}
public Counter getOrderCount() {
return orderCount;
}
public DistributionSummary getAmountSum() {
return amountSum;
}
public AtomicInteger getFailCaseNum() {
return failCaseNum;
}
}
|
repos\springboot-demo-master\prometheus\src\main\java\com\et\prometheus\monitor\PrometheusCustomMonitor.java
| 2
|
请完成以下Java代码
|
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Integer getFactoryStatus() {
return factoryStatus;
}
public void setFactoryStatus(Integer factoryStatus) {
this.factoryStatus = factoryStatus;
}
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
|
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getBigPic() {
return bigPic;
}
public void setBigPic(String bigPic) {
this.bigPic = bigPic;
}
public String getBrandStory() {
return brandStory;
}
public void setBrandStory(String brandStory) {
this.brandStory = brandStory;
}
}
|
repos\mall-master\mall-demo\src\main\java\com\macro\mall\demo\dto\PmsBrandDto.java
| 1
|
请完成以下Java代码
|
private static class AuthorizationHandshakeInterceptor implements HandshakeInterceptor
{
private static final Logger logger = LogManager.getLogger(AuthorizationHandshakeInterceptor.class);
@Override
public boolean beforeHandshake(@NonNull final ServerHttpRequest request, final @NonNull ServerHttpResponse response, final @NonNull WebSocketHandler wsHandler, final @NonNull Map<String, Object> attributes)
{
final UserSession userSession = UserSession.getCurrentOrNull();
if (userSession == null)
{
logger.warn("Websocket connection not allowed (missing userSession)");
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return false;
}
if (!userSession.isLoggedIn())
{
|
logger.warn("Websocket connection not allowed (not logged in) - userSession={}", userSession);
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return false;
}
return true;
}
@Override
public void afterHandshake(final @NonNull ServerHttpRequest request, final @NonNull ServerHttpResponse response, final @NonNull WebSocketHandler wsHandler, final Exception exception)
{
// nothing
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\websocket\WebsocketConfig.java
| 1
|
请完成以下Java代码
|
public UUID getUuidId() {
if (id != null) {
return id.getId();
}
return null;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@SuppressWarnings("rawtypes")
@Override
|
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IdBased other = (IdBased) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\id\IdBased.java
| 1
|
请完成以下Java代码
|
public void cancelCellEditing()
{
if (!canStopEditing())
{
return ;
}
clearCurrentEditing();
super.cancelCellEditing();
}
private void clearCurrentEditing()
{
// metas: reset editing coordinates
|
editingRowIndexModel = -1;
editingColumnIndexModel = -1;
editingKeyId = -100;
if (m_editor instanceof VLookup)
{
((VLookup)m_editor).setStopEditing(true);
}
}
public void setActionListener(final ActionListener listener)
{
actionListener = listener;
}
} // VCellEditor
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VCellEditor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Duration getStep() {
return this.step;
}
public void setStep(Duration step) {
this.step = step;
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Duration getConnectTimeout() {
return this.connectTimeout;
}
public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
|
public Duration getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
}
public Integer getBatchSize() {
return this.batchSize;
}
public void setBatchSize(Integer batchSize) {
this.batchSize = batchSize;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\properties\PushRegistryProperties.java
| 2
|
请完成以下Java代码
|
private static File getNewShapeFile() {
String filePath = new File(".").getAbsolutePath() + FILE_NAME;
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
chooser.setDialogTitle("Save shapefile");
chooser.setSelectedFile(new File(filePath));
int returnVal = chooser.showSaveDialog(null);
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
System.exit(0);
}
return chooser.getSelectedFile();
}
private static ShapefileDataStore setDataStoreParams(ShapefileDataStoreFactory dataStoreFactory, Map<String, Serializable> params, File shapeFile, SimpleFeatureType CITY) throws Exception {
params.put("url", shapeFile.toURI()
.toURL());
params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
dataStore.createSchema(CITY);
return dataStore;
}
private static void writeToFile(ShapefileDataStore dataStore, DefaultFeatureCollection collection) throws Exception {
// If you decide to use the TYPE type and create a Data Store with it,
// You will need to uncomment this line to set the Coordinate Reference System
// newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
Transaction transaction = new DefaultTransaction("create");
String typeName = dataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
|
featureStore.setTransaction(transaction);
try {
featureStore.addFeatures(collection);
transaction.commit();
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
} finally {
transaction.close();
}
System.exit(0); // success!
} else {
System.out.println(typeName + " does not support read/write access");
System.exit(1);
}
}
}
|
repos\tutorials-master\geotools\src\main\java\com\baeldung\geotools\ShapeFile.java
| 1
|
请完成以下Java代码
|
public class MultipleTbCallback implements TbCallback {
@Getter
private final UUID id;
private final AtomicInteger counter;
private final TbCallback callback;
public MultipleTbCallback(int count, TbCallback callback) {
id = UUID.randomUUID();
this.counter = new AtomicInteger(count);
this.callback = callback;
}
@Override
public void onSuccess() {
onSuccess(1);
|
}
public void onSuccess(int number) {
log.trace("[{}][{}] onSuccess({})", id, callback.getId(), number);
if (counter.addAndGet(-number) <= 0) {
log.trace("[{}][{}] Done.", id, callback.getId());
callback.onSuccess();
}
}
@Override
public void onFailure(Throwable t) {
log.warn("[{}][{}] onFailure.", id, callback.getId(), t);
callback.onFailure(t);
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\calculatedField\MultipleTbCallback.java
| 1
|
请完成以下Java代码
|
public Integer getRegistryPort() {
return registryPort;
}
public void setRegistryPort(Integer registryPort) {
this.registryPort = registryPort;
}
public String getServiceUrlPath() {
return serviceUrlPath;
}
public void setServiceUrlPath(String serviceUrlPath) {
this.serviceUrlPath = serviceUrlPath;
}
public Integer getConnectorPort() {
return connectorPort;
}
public void setConnectorPort(Integer connectorPort) {
this.connectorPort = connectorPort;
}
@Override
public void beforeInit(AbstractEngineConfiguration engineConfiguration) {
|
// nothing to do
}
@Override
public void configure(AbstractEngineConfiguration engineConfiguration) {
try {
this.processEngineConfig = (ProcessEngineConfiguration) engineConfiguration;
if (!disabled) {
managementAgent = new DefaultManagementAgent(this);
managementAgent.doStart();
managementAgent.findAndRegisterMbeans();
}
} catch (Exception e) {
LOGGER.warn("error in initializing jmx. Continue with partial or no JMX configuration", e);
}
}
}
|
repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\JMXConfigurator.java
| 1
|
请完成以下Java代码
|
public class OAuthClientCredentialsFeignManager {
private static final Logger logger = LoggerFactory.getLogger(OAuthClientCredentialsFeignManager.class);
private final OAuth2AuthorizedClientManager manager;
private final Authentication principal;
private final ClientRegistration clientRegistration;
public OAuthClientCredentialsFeignManager(OAuth2AuthorizedClientManager manager, ClientRegistration clientRegistration) {
this.manager = manager;
this.clientRegistration = clientRegistration;
this.principal = createPrincipal();
}
private Authentication createPrincipal() {
return new Authentication() {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.emptySet();
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getDetails() {
return null;
}
@Override
public Object getPrincipal() {
return this;
}
@Override
public boolean isAuthenticated() {
return false;
|
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
}
@Override
public String getName() {
return clientRegistration.getClientId();
}
};
}
public String getAccessToken() {
try {
OAuth2AuthorizeRequest oAuth2AuthorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(clientRegistration.getRegistrationId())
.principal(principal)
.build();
OAuth2AuthorizedClient client = manager.authorize(oAuth2AuthorizeRequest);
if (isNull(client)) {
throw new IllegalStateException("client credentials flow on " + clientRegistration.getRegistrationId() + " failed, client is null");
}
return client.getAccessToken().getTokenValue();
} catch (Exception exp) {
logger.error("client credentials error " + exp.getMessage());
}
return null;
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-openfeign\src\main\java\com\baeldung\cloud\openfeign\oauthfeign\OAuthClientCredentialsFeignManager.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Double getPrice() {
return price;
}
|
public void setPrice(Double price) {
this.price = price;
}
public CustomerOrder getCustomerOrder() {
return customerOrder;
}
public void setCustomerOrder(CustomerOrder co) {
this.customerOrder = co;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="customerorder_id", nullable = false)
private CustomerOrder customerOrder;
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\entities\Product.java
| 1
|
请完成以下Java代码
|
public class Message implements Serializable {
private static final long serialVersionUID = 6678420965611108427L;
private String from;
private String message;
public Message() {
}
public Message(String from, String message) {
this.from = from;
this.message = message;
}
@Override
public String toString() {
return "Message{" +
"from='" + from + '\'' +
|
", message='" + message + '\'' +
'}';
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
repos\SpringAll-master\54.Spring-Boot-Kafka\src\main\java\com\example\demo\domain\Message.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
ApplicationRunner geography(ReactiveRedisTemplate <String, String> template){
return args -> {
var sicily = "Sicily";
var geoTemplate = template.opsForGeo();
var mapOfPoints = Map.of(
"Arigento", new Point(13.3619389, 38.11555556),
"Catania", new Point(15.0876269, 37.502669),
"Palermo", new Point(13.5833333, 37.316667));
Flux.fromIterable(mapOfPoints.entrySet())
.flatMap(e -> geoTemplate.add(sicily, e.getValue(), e.getKey()))
.thenMany(geoTemplate.radius(sicily, new Circle(
new Point(13.583333, 37.31667),
new Distance(10, RedisGeoCommands.DistanceUnit.KILOMETERS)
)))
.map(GeoResult::getContent)
.map(RedisGeoCommands.GeoLocation::getName)
.doOnNext(System.out::println)
.subscribe();
};
}
@Bean
ApplicationRunner list (ReactiveRedisTemplate <String, String> template) {
//
|
return args -> {
var listTemplate = template.opsForList();
var listName = "spring-team";
var push = listTemplate.leftPushAll(listName, "Madhura", "Stephana", "Dr.Syer", "Yuxin", "Olga", "Violetta");
push
.thenMany(listTemplate.leftPop(listName))
.doOnNext(System.out::println)
.thenMany(listTemplate.leftPop(listName))
.doOnNext(System.out::println)
.subscribe();
};
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-9.1. SpringReactive-Redis-Projects\Project-1 SpringReactiveRedis\ReactiveRedisProject\src\main\java\uz\reactiveredis\pro\reactiveredisproject\ReactiveRedisProjectApplication.java
| 2
|
请完成以下Java代码
|
public TimerJobEntityManager getTimerJobEntityManager() {
return getSession(TimerJobEntityManager.class);
}
public SuspendedJobEntityManager getSuspendedJobEntityManager() {
return getSession(SuspendedJobEntityManager.class);
}
public DeadLetterJobEntityManager getDeadLetterJobEntityManager() {
return getSession(DeadLetterJobEntityManager.class);
}
public AttachmentEntityManager getAttachmentEntityManager() {
return getSession(AttachmentEntityManager.class);
}
public TableDataManager getTableDataManager() {
return getSession(TableDataManager.class);
}
public CommentEntityManager getCommentEntityManager() {
return getSession(CommentEntityManager.class);
}
public PropertyEntityManager getPropertyEntityManager() {
return getSession(PropertyEntityManager.class);
}
public EventSubscriptionEntityManager getEventSubscriptionEntityManager() {
return getSession(EventSubscriptionEntityManager.class);
}
public Map<Class<?>, SessionFactory> getSessionFactories() {
return sessionFactories;
}
|
public HistoryManager getHistoryManager() {
return getSession(HistoryManager.class);
}
// getters and setters //////////////////////////////////////////////////////
public TransactionContext getTransactionContext() {
return transactionContext;
}
public Command<?> getCommand() {
return command;
}
public Map<Class<?>, Session> getSessions() {
return sessions;
}
public Throwable getException() {
return exception;
}
public FailedJobCommandFactory getFailedJobCommandFactory() {
return failedJobCommandFactory;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public FlowableEventDispatcher getEventDispatcher() {
return processEngineConfiguration.getEventDispatcher();
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public Date getCreateTime() {
return createTime;
}
@Override
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String getLockOwner() {
return lockOwner;
}
@Override
public void setLockOwner(String claimedBy) {
this.lockOwner = claimedBy;
}
@Override
public Date getLockExpirationTime() {
return lockExpirationTime;
}
@Override
public void setLockExpirationTime(Date claimedUntil) {
this.lockExpirationTime = claimedUntil;
}
@Override
public String getScopeType() {
|
return scopeType;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
protected String getJobByteArrayRefAsString(ByteArrayRef jobByteArrayRef) {
if (jobByteArrayRef == null) {
return null;
}
return jobByteArrayRef.asString(getEngineType());
}
protected String getEngineType() {
if (StringUtils.isNotEmpty(scopeType)) {
return scopeType;
} else {
return ScopeTypes.BPMN;
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoryJobEntity[").append("id=").append(id)
.append(", jobHandlerType=").append(jobHandlerType);
if (scopeType != null) {
sb.append(", scopeType=").append(scopeType);
}
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\HistoryJobEntityImpl.java
| 2
|
请完成以下Java代码
|
public String getColumnName()
{
return attributeName;
}
@Override
public boolean isMandatory()
{
return mandatory;
}
public Object readValue(final I_M_AttributeInstance ai)
{
return readMethod.apply(ai);
}
private void writeValue(final I_M_AttributeInstance ai, final IDocumentFieldView field)
{
writeMethod.accept(ai, field);
}
private static void writeValueFromLookup(final I_M_AttributeInstance ai, final IDocumentFieldView field, boolean isNumericKey)
{
final LookupValue lookupValue = isNumericKey
? field.getValueAs(IntegerLookupValue.class)
: field.getValueAs(StringLookupValue.class);
final AttributeValueId attributeValueId = field.getDescriptor().getLookupDescriptor()
.orElseThrow(() -> new AdempiereException("No lookup defined for " + field))
.cast(ASILookupDescriptor.class)
.getAttributeValueId(lookupValue);
ai.setValueNumber(lookupValue != null && isNumericKey ? BigDecimal.valueOf(lookupValue.getIdAsInt()) : null); // IMPORTANT: always setValueNumber before setValue because setValueNumber is overriden and set the Value string too. wtf?!
ai.setValue(lookupValue == null ? null : lookupValue.getIdAsString());
ai.setM_AttributeValue_ID(AttributeValueId.toRepoId(attributeValueId));
|
}
public I_M_AttributeInstance createAndSaveM_AttributeInstance(final I_M_AttributeSetInstance asiRecord, final IDocumentFieldView asiField)
{
final I_M_AttributeInstance aiRecord = InterfaceWrapperHelper.newInstance(I_M_AttributeInstance.class, asiRecord);
aiRecord.setM_AttributeSetInstance(asiRecord);
aiRecord.setM_Attribute_ID(attributeId.getRepoId());
writeValue(aiRecord, asiField);
InterfaceWrapperHelper.save(aiRecord);
return aiRecord;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASIDescriptorFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class FileUploadController {
private final StorageService storageService;
@Autowired
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
}
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("files", storageService
.loadAll()
.map(path ->
MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString())
.collect(Collectors.toList()));
return "uploadForm";
}
@GetMapping("/files/{filename:.+}")
@ResponseBody
public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
Resource file = storageService.loadAsResource(filename);
return ResponseEntity
.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+file.getFilename()+"\"")
.body(file);
|
}
@PostMapping("/")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
storageService.store(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
return "redirect:/";
}
@ExceptionHandler(StorageFileNotFoundException.class)
public ResponseEntity handleStorageFileNotFound(StorageFileNotFoundException exc) {
return ResponseEntity.notFound().build();
}
}
|
repos\SpringBootLearning-master\springboot-upload-file\src\main\java\com\forezp\web\FileUploadController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonProperties {
private String host;
private int port;
private boolean resend;
private List<String> topics;
private LinkedHashMap<String, ?> sender;
public LinkedHashMap<String, ?> getSender() {
return sender;
}
public void setSender(LinkedHashMap<String, ?> sender) {
this.sender = sender;
}
public List<String> getTopics() {
return topics;
}
public void setTopics(List<String> topics) {
this.topics = topics;
}
public int getPort() {
|
return port;
}
public void setPort(int port) {
this.port = port;
}
public boolean isResend() {
return resend;
}
public void setResend(boolean resend) {
this.resend = resend;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-properties-3\src\main\java\com\baeldung\properties\json\JsonProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
class StockAvailabilityWebServiceImpl
{
private static final Logger logger = LoggerFactory.getLogger(StockAvailabilityWebServiceImpl.class);
private final MSV3ServerAuthenticationService authService;
private final StockAvailabilityService stockAvailabilityService;
private final StockAvailabilityServerJAXBConverters jaxbConverters;
@Builder
private StockAvailabilityWebServiceImpl(
@NonNull final MSV3ServerAuthenticationService authService,
@NonNull final StockAvailabilityService stockAvailabilityService,
@NonNull final StockAvailabilityServerJAXBConverters jaxbConverters)
{
this.authService = authService;
this.stockAvailabilityService = stockAvailabilityService;
this.jaxbConverters = jaxbConverters;
}
public JAXBElement<?> getStockAvailability(@RequestPayload final JAXBElement<?> jaxbRequest)
{
logXML("getStockAvailability - request", jaxbRequest);
final Object soapRequest = jaxbRequest.getValue();
final ClientSoftwareId clientSoftwareId = jaxbConverters.getClientSoftwareIdFromClientRequest(soapRequest);
authService.assertValidClientSoftwareId(clientSoftwareId);
final BPartnerId bpartnerId = authService.getCurrentBPartner();
final StockAvailabilityQuery stockAvailabilityQuery = jaxbConverters.decodeRequestFromClient(soapRequest, bpartnerId);
final StockAvailabilityResponse stockAvailabilityResponse = stockAvailabilityService.checkAvailability(stockAvailabilityQuery);
|
final JAXBElement<?> jaxbResponse = jaxbConverters.encodeResponseToClient(stockAvailabilityResponse);
logXML("getStockAvailability - response", jaxbResponse);
return jaxbResponse;
}
private static void logXML(final String name, final JAXBElement<?> element)
{
if (!logger.isDebugEnabled())
{
return;
}
logger.debug("{}: {}", name, JAXBUtils.toXml(element));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\stockAvailability\StockAvailabilityWebServiceImpl.java
| 2
|
请完成以下Java代码
|
public void sendHtmlMail(
String to, String subject, String content
) {
//使用MimeMessage,MIME协议
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
//MimeMessageHelper帮助我们设置更丰富的内容
try {
helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);//true代表支持html
mailSender.send(message);
logger.info("发送HTML邮件成功");
} catch (MessagingException e) {
e.printStackTrace();
logger.error("发送HTML邮件失败:", e);
}
}
/**
* 发送带附件的邮件
*
* @param to 收件人
* @param subject 主体
* @param content 内容
* @param filePath 附件路径
*/
public void sendAttachmentMail(
String to, String subject,
String content, String filePath
) {
// 日志
logger.info("发送带附件邮件开始:{},{},{},{}", to, subject, content, filePath);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(message, true);
//true代表支持多组件,如附件,图片等
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
|
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = file.getFilename();
helper.addAttachment(fileName, file);//添加附件,可多次调用该方法添加多个附件
mailSender.send(message);
logger.info("发送带附件邮件成功");
} catch (MessagingException e) {
logger.error("发送带附件邮件失败", e);
}
}
/**
* 发送带图片的邮件
*
* @param to 收件人
* @param subject 主体
* @param content 内容
* @param rscPath 图片路径
* @param rscId rscId 图片ID,用于在<img\>标签中使用,从而显示图片
*/
public void sendInlineResourceMail(
String to, String subject, String content,
String rscPath, String rscId) {
// 日志
logger.info("发送带图片邮件开始:{},{},{},{},{}", to, subject, content, rscPath, rscId);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);//重复使用添加多个图片
mailSender.send(message);
logger.info("发送带图片邮件成功");
} catch (MessagingException e) {
logger.error("发送带图片邮件失败", e);
}
}
}
|
repos\springboot-demo-master\mail\src\main\java\com\et\mail\util\MailUtils.java
| 1
|
请完成以下Java代码
|
public void inValidateScheds(final I_C_BPartner bpartner)
{
//
// Services
final IShipmentSchedulePA shipmentSchedulesRepo = Services.get(IShipmentSchedulePA.class);
final IBPartnerBL bpartnerBL = Services.get(IBPartnerBL.class);
final boolean isBPAllowConsolidateInOut = bpartnerBL.isAllowConsolidateInOutEffective(bpartner, SOTrx.SALES);
final BPartnerId bpartnerId = BPartnerId.ofRepoId(bpartner.getC_BPartner_ID());
shipmentSchedulesRepo
.streamUnprocessedByPartnerIdAndAllowConsolidateInOut(bpartnerId, !isBPAllowConsolidateInOut)
.forEach(sched -> setAllowConsolidateInOutAndSave(sched, isBPAllowConsolidateInOut));
}
private void setAllowConsolidateInOutAndSave(final I_M_ShipmentSchedule sched, final boolean allowConsolidateInOut)
|
{
if (sched.isAllowConsolidateInOut() == allowConsolidateInOut)
{
return;
}
sched.setAllowConsolidateInOut(allowConsolidateInOut);
InterfaceWrapperHelper.saveRecord(sched);
// note that we do not need to invalidate the current sched explicitly..
// it will be updated as part of the segment, unless it has delivery rule force..
// and if it has that rule, then the partner change makes no difference to it, anyways.
Services.get(IShipmentScheduleInvalidateBL.class).notifySegmentChangedForShipmentSchedule(sched);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\C_BPartner_ShipmentSchedule.java
| 1
|
请完成以下Java代码
|
public void setLengthInCm (int LengthInCm)
{
set_Value (COLUMNNAME_LengthInCm, Integer.valueOf(LengthInCm));
}
/** Get Length In Cm.
@return Length In Cm */
@Override
public int getLengthInCm ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LengthInCm);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Package getM_Package()
{
return get_ValueAsPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class);
}
@Override
public void setM_Package(org.compiere.model.I_M_Package M_Package)
{
set_ValueFromPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class, M_Package);
}
/** Set Packstück.
@param M_Package_ID
Shipment Package
*/
@Override
public void setM_Package_ID (int M_Package_ID)
{
if (M_Package_ID < 1)
set_Value (COLUMNNAME_M_Package_ID, null);
else
set_Value (COLUMNNAME_M_Package_ID, Integer.valueOf(M_Package_ID));
}
/** Get Packstück.
@return Shipment Package
*/
@Override
public int getM_Package_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Package_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Package Content.
@param PackageContent Package Content */
@Override
|
public void setPackageContent (java.lang.String PackageContent)
{
set_Value (COLUMNNAME_PackageContent, PackageContent);
}
/** Get Package Content.
@return Package Content */
@Override
public java.lang.String getPackageContent ()
{
return (java.lang.String)get_Value(COLUMNNAME_PackageContent);
}
/** Set Weight In Kg.
@param WeightInKg Weight In Kg */
@Override
public void setWeightInKg (int WeightInKg)
{
set_Value (COLUMNNAME_WeightInKg, Integer.valueOf(WeightInKg));
}
/** Get Weight In Kg.
@return Weight In Kg */
@Override
public int getWeightInKg ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_WeightInKg);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Width In Cm.
@param WidthInCm Width In Cm */
@Override
public void setWidthInCm (int WidthInCm)
{
set_Value (COLUMNNAME_WidthInCm, Integer.valueOf(WidthInCm));
}
/** Get Width In Cm.
@return Width In Cm */
@Override
public int getWidthInCm ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_WidthInCm);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_StoreOrderLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
@Nullable DateTimeFormatter getDateFormatter() {
return this.dateFormatter;
}
@Nullable String getDatePattern() {
return this.datePattern;
}
@Nullable DateTimeFormatter getTimeFormatter() {
return this.timeFormatter;
}
@Nullable DateTimeFormatter getDateTimeFormatter() {
return this.dateTimeFormatter;
}
boolean isCustomized() {
return this.dateFormatter != null || this.timeFormatter != null || this.dateTimeFormatter != null;
}
|
private static @Nullable DateTimeFormatter formatter(@Nullable String pattern) {
return StringUtils.hasText(pattern)
? DateTimeFormatter.ofPattern(pattern).withResolverStyle(ResolverStyle.SMART) : null;
}
private static boolean isIso(@Nullable String pattern) {
return "iso".equalsIgnoreCase(pattern);
}
private static boolean isIsoOffset(@Nullable String pattern) {
return "isooffset".equalsIgnoreCase(pattern) || "iso-offset".equalsIgnoreCase(pattern);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\format\DateTimeFormatters.java
| 2
|
请完成以下Java代码
|
public class JsonKPIFieldLayout
{
public static JsonKPIFieldLayout field(final KPIField kpiField, final KPIJsonOptions jsonOpts)
{
final boolean isOffsetField = false;
return new JsonKPIFieldLayout(kpiField, isOffsetField, jsonOpts);
}
public static JsonKPIFieldLayout offsetField(final KPIField kpiField, final KPIJsonOptions jsonOpts)
{
final boolean isOffsetField = true;
return new JsonKPIFieldLayout(kpiField, isOffsetField, jsonOpts);
}
@JsonProperty("caption")
private final String caption;
@JsonProperty("description")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private final String description;
@JsonProperty("unit")
private final String unit;
@JsonProperty("fieldName")
private final String fieldName;
// NOTE: not needed because we are providing a separate groupByField in JsonKPILayout
// @JsonProperty("groupBy")
// private final boolean groupBy;
@JsonProperty("dataType")
private final String dataType;
@JsonProperty("color")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private final String color;
|
public JsonKPIFieldLayout(final KPIField kpiField, final boolean isOffsetField, final KPIJsonOptions jsonOpts)
{
final String adLanguage = jsonOpts.getAdLanguage();
// Caption
if (isOffsetField)
{
caption = kpiField.getOffsetCaption(adLanguage);
}
else
{
caption = kpiField.getCaption(adLanguage);
}
// FieldName
if (isOffsetField)
{
fieldName = kpiField.getOffsetFieldName();
}
else
{
fieldName = kpiField.getFieldName();
}
description = kpiField.getDescription(adLanguage);
unit = kpiField.getUnit(adLanguage).orElse(null);
// groupBy = kpiField.isGroupBy();
dataType = kpiField.getValueType().toJson();
color = kpiField.getColor();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\json\JsonKPIFieldLayout.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static ApiAuditConfigsMap ofList(@NonNull final List<ApiAuditConfig> list)
{
return !list.isEmpty() ? new ApiAuditConfigsMap(list) : EMPTY;
}
private static final ApiAuditConfigsMap EMPTY = new ApiAuditConfigsMap();
private final ImmutableList<ApiAuditConfig> configs;
private final ImmutableMap<ApiAuditConfigId, ApiAuditConfig> byId;
private ApiAuditConfigsMap(@NonNull final List<ApiAuditConfig> list)
{
configs = ImmutableList.copyOf(list);
byId = Maps.uniqueIndex(list, ApiAuditConfig::getApiAuditConfigId);
}
private ApiAuditConfigsMap()
{
configs = ImmutableList.of();
byId = ImmutableMap.of();
}
|
public ImmutableList<ApiAuditConfig> getActiveConfigsByOrgId(@NonNull final OrgId orgId)
{
return configs.stream()
.filter(ApiAuditConfig::isActive)
.filter(config -> config.getOrgId().isAny()
|| OrgId.equals(config.getOrgId(), orgId))
.collect(ImmutableList.toImmutableList());
}
@NonNull
public ApiAuditConfig getConfigById(@NonNull final ApiAuditConfigId id)
{
final ApiAuditConfig config = byId.get(id);
if (config == null)
{
throw new AdempiereException("No config found for " + id);
}
return config;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\config\ApiAuditConfigsMap.java
| 2
|
请完成以下Java代码
|
public void setSystemStatus (final java.lang.String SystemStatus)
{
set_Value (COLUMNNAME_SystemStatus, SystemStatus);
}
@Override
public java.lang.String getSystemStatus()
{
return get_ValueAsString(COLUMNNAME_SystemStatus);
}
@Override
public void setUserAgent (final @Nullable java.lang.String UserAgent)
{
set_Value (COLUMNNAME_UserAgent, UserAgent);
}
@Override
public java.lang.String getUserAgent()
{
return get_ValueAsString(COLUMNNAME_UserAgent);
}
@Override
public void setUserName (final java.lang.String UserName)
{
|
set_ValueNoCheck (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return get_ValueAsString(COLUMNNAME_UserName);
}
@Override
public void setVersion (final java.lang.String Version)
{
set_ValueNoCheck (COLUMNNAME_Version, Version);
}
@Override
public java.lang.String getVersion()
{
return get_ValueAsString(COLUMNNAME_Version);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Issue.java
| 1
|
请完成以下Java代码
|
public class Travel {
private ArrayList<City> travel = new ArrayList<>();
private ArrayList<City> previousTravel = new ArrayList<>();
public Travel(int numberOfCities) {
for (int i = 0; i < numberOfCities; i++) {
travel.add(new City());
}
}
public void generateInitialTravel() {
if (travel.isEmpty()) {
new Travel(10);
}
Collections.shuffle(travel);
}
public void swapCities() {
int a = generateRandomIndex();
int b = generateRandomIndex();
previousTravel = new ArrayList<>(travel);
City x = travel.get(a);
City y = travel.get(b);
travel.set(a, y);
travel.set(b, x);
}
public void revertSwap() {
travel = previousTravel;
}
|
private int generateRandomIndex() {
return (int) (Math.random() * travel.size());
}
public City getCity(int index) {
return travel.get(index);
}
public int getDistance() {
int distance = 0;
for (int index = 0; index < travel.size(); index++) {
City starting = getCity(index);
City destination;
if (index + 1 < travel.size()) {
destination = getCity(index + 1);
} else {
destination = getCity(0);
}
distance += starting.distanceToCity(destination);
}
return distance;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\annealing\Travel.java
| 1
|
请完成以下Java代码
|
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DataStore.class, BPMN_ELEMENT_DATA_STORE)
.namespaceUri(BPMN20_NS)
.extendsType(RootElement.class)
.instanceProvider(new ModelTypeInstanceProvider<DataStore>() {
public DataStore newInstance(ModelTypeInstanceContext instanceContext) {
return new DataStoreImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME)
.build();
capacityAttribute = typeBuilder.integerAttribute(BPMN_ATTRIBUTE_CAPACITY)
.build();
isUnlimitedAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_IS_UNLIMITED)
.defaultValue(true)
.build();
itemSubjectRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ITEM_SUBJECT_REF)
.qNameAttributeReference(ItemDefinition.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
dataStateChild = sequenceBuilder.element(DataState.class)
.build();
typeBuilder.build();
}
public DataStoreImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
@Override
public String getName() {
return nameAttribute.getValue(this);
}
@Override
public void setName(String name) {
nameAttribute.setValue(this, name);
}
|
@Override
public Integer getCapacity() {
return capacityAttribute.getValue(this);
}
@Override
public void setCapacity(Integer capacity) {
capacityAttribute.setValue(this, capacity);
}
@Override
public Boolean isUnlimited() {
return isUnlimitedAttribute.getValue(this);
}
@Override
public void setUnlimited(Boolean isUnlimited) {
isUnlimitedAttribute.setValue(this, isUnlimited);
}
@Override
public ItemDefinition getItemSubject() {
return itemSubjectRefAttribute.getReferenceTargetElement(this);
}
@Override
public void setItemSubject(ItemDefinition itemSubject) {
itemSubjectRefAttribute.setReferenceTargetElement(this, itemSubject);
}
@Override
public DataState getDataState() {
return dataStateChild.getChild(this);
}
@Override
public void setDataState(DataState dataState) {
dataStateChild.setChild(this, dataState);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DataStoreImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public SampleOidEntity create(Request request, Response response) {
SampleOidEntity entity = request.getBodyAs(SampleOidEntity.class, "Resource details not provided");
SampleOidEntity saved = service.create(entity);
// Construct the response for create...
response.setResponseCreated();
// Include the Location header...
String locationPattern = request.getNamedUrl(HttpMethod.GET, Constants.Routes.SINGLE_OID_SAMPLE);
response.addLocationHeader(LOCATION_BUILDER.build(locationPattern, new DefaultTokenResolver()));
// Return the newly-created resource...
return saved;
}
public SampleOidEntity read(Request request, Response response) {
String id = request.getHeader(Constants.Url.SAMPLE_ID, "No resource ID supplied");
SampleOidEntity entity = service.read(Identifiers.MONGOID.parse(id));
return entity;
}
public List<SampleOidEntity> readAll(Request request, Response response) {
QueryFilter filter = QueryFilters.parseFrom(request);
QueryOrder order = QueryOrders.parseFrom(request);
QueryRange range = QueryRanges.parseFrom(request, 20);
List<SampleOidEntity> entities = service.readAll(filter, range, order);
long count = service.count(filter);
response.setCollectionResponse(range, entities.size(), count);
return entities;
}
|
public void update(Request request, Response response) {
String id = request.getHeader(Constants.Url.SAMPLE_ID, "No resource ID supplied");
SampleOidEntity entity = request.getBodyAs(SampleOidEntity.class, "Resource details not provided");
entity.setId(Identifiers.MONGOID.parse(id));
service.update(entity);
response.setResponseNoContent();
}
public void delete(Request request, Response response) {
String id = request.getHeader(Constants.Url.SAMPLE_ID, "No resource ID supplied");
service.delete(Identifiers.MONGOID.parse(id));
response.setResponseNoContent();
}
}
|
repos\tutorials-master\microservices-modules\rest-express\src\main\java\com\baeldung\restexpress\objectid\SampleOidEntityController.java
| 2
|
请完成以下Java代码
|
public class SubrangeMethodArgumentResolver<P> implements HandlerMethodArgumentResolver {
private final CursorStrategy<P> cursorStrategy;
public SubrangeMethodArgumentResolver(CursorStrategy<P> cursorStrategy) {
Assert.notNull(cursorStrategy, "CursorStrategy is required");
this.cursorStrategy = cursorStrategy;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return (parameter.getParameterType().equals(Subrange.class) &&
this.cursorStrategy.supports(parameter.nested().getNestedParameterType()));
}
@Override
public Object resolveArgument(MethodParameter parameter, DataFetchingEnvironment environment) throws Exception {
boolean forward = true;
String cursor = environment.getArgument("after");
Integer count = environment.getArgument("first");
if (cursor == null && count == null) {
cursor = environment.getArgument("before");
|
count = environment.getArgument("last");
if (cursor != null || count != null) {
forward = false;
}
}
P pos = (cursor != null) ? this.cursorStrategy.fromCursor(cursor) : null;
return createSubrange(pos, count, forward);
}
/**
* Allows subclasses to create an extension of {@link Subrange}.
* @param pos the position in the subrange
* @param count the number of elements in the subrange
* @param forward whether the scroll direction is forward or backward from this position
*/
protected Subrange<P> createSubrange(@Nullable P pos, @Nullable Integer count, boolean forward) {
return new Subrange<>(pos, count, forward);
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\method\annotation\support\SubrangeMethodArgumentResolver.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
application:
name: spring-boot-actuator
server:
port: 8080
logging:
pattern:
level: ${spring.application.name:},%X{traceId:-},%X{spanId:-}
management:
# server:
# port: 8088
# address: 127.0.0.1
endpoints:
jmx:
exposure:
include: health,info
web:
discovery:
enabled: true
base-path: /actuator
path-mapping:
health: health
exposure:
include: "*"
exclude: threaddump
cors:
allowed-origins: "*"
allowed-m
|
ethods: "GET,POST"
observations:
key-values:
application: ${spring.application.name}
tracing:
sampling:
probability: 1.0
prometheus:
metrics:
export:
pushgateway:
enabled: true
|
repos\spring-boot-best-practice-master\spring-boot-actuator\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
private static Object combineValue(@Nullable final Object target, @Nullable final Object source)
{
if (source instanceof Map)
{
//noinspection unchecked
final Map<String, Object> sourceMap = (Map<String, Object>)source;
final LinkedHashMap<String, Object> result = new LinkedHashMap<>();
if (target instanceof Map)
{
//noinspection unchecked
final Map<String, Object> targetMap = (Map<String, Object>)target;
deepCopyInto(result, targetMap);
deepCopyInto(result, sourceMap);
return result;
}
else
{
|
deepCopyInto(result, sourceMap);
return result;
}
}
else
{
return source;
}
}
public JsonMessages toJson()
{
return JsonMessages.builder()
.language(adLanguage)
.messages(map)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\AdMessagesTree.java
| 1
|
请完成以下Java代码
|
private static OrderAndLineId extractOrderAndLineId(final I_C_OrderLine record) {return OrderAndLineId.ofRepoIds(record.getC_Order_ID(), record.getC_OrderLine_ID());}
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE)
public void onBeforeChange(final I_C_OrderLine record)
{
final OrderCostDetailOrderLinePart orderLineInfo = extractOrderLineInfoIfHasChanges(record);
if (orderLineInfo != null)
{
orderCostService.updateOrderCostsOnOrderLineChanged(orderLineInfo);
}
}
@Nullable
private static OrderCostDetailOrderLinePart extractOrderLineInfoIfHasChanges(final I_C_OrderLine record)
{
final I_C_OrderLine recordBeforeChanges = InterfaceWrapperHelper.createOld(record, I_C_OrderLine.class);
final OrderCostDetailOrderLinePart lineInfoBeforeChanges = OrderCostDetailOrderLinePart.ofOrderLine(recordBeforeChanges);
final OrderCostDetailOrderLinePart lineInfo = OrderCostDetailOrderLinePart.ofOrderLine(record);
if (lineInfo.equals(lineInfoBeforeChanges))
|
{
return null; // no changes
}
return lineInfo;
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void onBeforeDelete(final I_C_OrderLine record)
{
if (InterfaceWrapperHelper.isUIAction(record))
{
orderCostService.deleteByCreatedOrderLineId(extractOrderAndLineId(record));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\interceptor\C_OrderLine.java
| 1
|
请完成以下Java代码
|
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getIndexName() {
return this.indexName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
public int getMaxAttempts() {
return this.maxAttempts;
}
public void setMaxAttempts(int maxAttempts) {
this.maxAttempts = maxAttempts;
}
|
public String getUri() {
return this.uri;
}
public void setUri(String uri) {
this.uri = cleanUri(uri);
}
private static String cleanUri(String contextPath) {
if (StringUtils.hasText(contextPath) && contextPath.endsWith("/")) {
return contextPath.substring(0, contextPath.length() - 1);
}
return contextPath;
}
}
}
|
repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\stat\StatsProperties.java
| 1
|
请完成以下Java代码
|
public int getA_Depreciation_Table_Header_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Depreciation_Table_Header_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getA_Depreciation_Table_Header_ID()));
}
/** A_Table_Rate_Type AD_Reference_ID=53255 */
public static final int A_TABLE_RATE_TYPE_AD_Reference_ID=53255;
/** Amount = AM */
public static final String A_TABLE_RATE_TYPE_Amount = "AM";
/** Rate = RT */
public static final String A_TABLE_RATE_TYPE_Rate = "RT";
/** Set Type.
@param A_Table_Rate_Type Type */
public void setA_Table_Rate_Type (String A_Table_Rate_Type)
{
set_Value (COLUMNNAME_A_Table_Rate_Type, A_Table_Rate_Type);
}
/** Get Type.
@return Type */
public String getA_Table_Rate_Type ()
{
return (String)get_Value(COLUMNNAME_A_Table_Rate_Type);
}
/** A_Term AD_Reference_ID=53256 */
public static final int A_TERM_AD_Reference_ID=53256;
/** Period = PR */
public static final String A_TERM_Period = "PR";
/** Yearly = YR */
public static final String A_TERM_Yearly = "YR";
/** Set Period/Yearly.
@param A_Term Period/Yearly */
public void setA_Term (String A_Term)
{
set_Value (COLUMNNAME_A_Term, A_Term);
}
/** Get Period/Yearly.
@return Period/Yearly */
public String getA_Term ()
{
return (String)get_Value(COLUMNNAME_A_Term);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
|
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Table_Header.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.