instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public static String getWhereClause(final Object[] rowData, final List<GridField> gridFields)
{
final int size = gridFields.size();
StringBuilder singleRowWHERE = null;
StringBuilder multiRowWHERE = null;
for (int col = 0; col < size; col++)
{
final GridField field = gridFields.get(col);
if (field.isKey())
{
final String columnName = field.getColumnName();
final Object value = rowData[col];
if (value == null)
{
log.warn("PK data is null - {}", columnName);
return null;
}
if (columnName.endsWith("_ID"))
{
singleRowWHERE = new StringBuilder(columnName)
.append("=").append(value);
}
else
{
singleRowWHERE = new StringBuilder(columnName)
.append("=").append(DB.TO_STRING(value.toString()));
}
}
else if (field.isParentColumn())
{
final String columnName = field.getColumnName();
final Object value = rowData[col];
if (value == null)
{
log.warn("FK data is null - {}", columnName);
continue;
}
//
if (multiRowWHERE == null)
{
multiRowWHERE = new StringBuilder();
}
else
{
multiRowWHERE.append(" AND ");
}
//
if (columnName.endsWith("_ID"))
{
multiRowWHERE.append(columnName)
.append("=").append(value);
}
else
{
multiRowWHERE.append(columnName)
.append("=").append(DB.TO_STRING(value.toString()));
}
}
} // for all columns
if (singleRowWHERE != null)
{
return singleRowWHERE.toString();
}
if (multiRowWHERE != null)
{
return multiRowWHERE.toString();
}
log.warn("No key Found. Returning NULL.");
return null;
}
private static Object decrypt(final Object encryptedValue)
{
if (encryptedValue == null)
{ | return null;
}
return SecureEngine.decrypt(encryptedValue);
}
public static boolean isValueChanged(Object oldValue, Object value)
{
if (isNotNullAndIsEmpty(oldValue))
{
oldValue = null;
}
if (isNotNullAndIsEmpty(value))
{
value = null;
}
boolean bChanged = oldValue == null && value != null
|| oldValue != null && value == null;
if (!bChanged && oldValue != null)
{
if (oldValue.getClass().equals(value.getClass()))
{
if (oldValue instanceof Comparable<?>)
{
bChanged = ((Comparable<Object>)oldValue).compareTo(value) != 0;
}
else
{
bChanged = !oldValue.equals(value);
}
}
else if (value != null)
{
bChanged = !oldValue.toString().equals(value.toString());
}
}
return bChanged;
}
private static boolean isNotNullAndIsEmpty(final Object value)
{
if (value != null
&& value instanceof String
&& value.toString().equals(""))
{
return true;
}
else
{
return false;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTableUtils.java | 1 |
请完成以下Java代码 | public void setIcon(String icon) {
this.icon = icon;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public boolean isSameDeployment() {
return sameDeployment;
}
public void setSameDeployment(boolean sameDeployment) {
this.sameDeployment = sameDeployment;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public List<String> getCandidateUsers() { | return candidateUsers;
}
public void setCandidateUsers(List<String> candidateUsers) {
this.candidateUsers = candidateUsers;
}
public List<String> getCandidateGroups() {
return candidateGroups;
}
public void setCandidateGroups(List<String> candidateGroups) {
this.candidateGroups = candidateGroups;
}
@Override
public CasePageTask clone() {
CasePageTask clone = new CasePageTask();
clone.setValues(this);
return clone;
}
public void setValues(CasePageTask otherElement) {
super.setValues(otherElement);
setType(otherElement.getType());
setFormKey(otherElement.getFormKey());
setSameDeployment(otherElement.isSameDeployment());
setLabel(otherElement.getLabel());
setIcon(otherElement.getIcon());
setAssignee(otherElement.getAssignee());
setOwner(otherElement.getOwner());
setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups()));
setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers()));
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\CasePageTask.java | 1 |
请完成以下Java代码 | public GridField getField()
{
return m_mField;
}
/**
* Set Enabled
*
* @param enabled enabled
*/
@Override
public void setEnabled(boolean enabled)
{
super.setEnabled(enabled);
m_text.setEnabled(enabled);
m_button.setReadWrite(enabled && m_readWrite);
} // setEnabled
@Override
public void addActionListener(ActionListener l)
{
listenerList.add(ActionListener.class, l);
} // addActionListener
@Override
public void setBackground(final Color bg)
{
m_text.setBackground(bg);
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
// metas
@Override
public void addMouseListener(final MouseListener l)
{
m_text.addMouseListener(l);
} | @Override
public void addKeyListener(final KeyListener l)
{
m_text.addKeyListener(l);
}
public int getCaretPosition()
{
return m_text.getCaretPosition();
}
public void setCaretPosition(final int position)
{
m_text.setCaretPosition(position);
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
@Override
protected final boolean processKeyBinding(final KeyStroke ks, final KeyEvent e, final int condition, final boolean pressed)
{
// Forward all key events on this component to the text field.
// We have to do this for the case when we are embedding this editor in a JTable and the JTable is forwarding the key strokes to editing component.
// Effect of NOT doing this: when in JTable, user presses a key (e.g. a digit) to start editing but the first key he pressed gets lost here.
if (m_text != null && condition == WHEN_FOCUSED)
{
if (m_text.processKeyBinding(ks, e, condition, pressed))
{
return true;
}
}
//
// Fallback to super
return super.processKeyBinding(ks, e, condition, pressed);
}
} // VDate | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VDate.java | 1 |
请完成以下Java代码 | public int getRepoId()
{
return repoId;
}
public static boolean equals(final HuPackingInstructionsId o1, final HuPackingInstructionsId o2)
{
return Objects.equals(o1, o2);
}
public boolean isTemplate()
{
return isTemplateRepoId(repoId);
}
public static boolean isTemplateRepoId(final int repoId)
{
return repoId == TEMPLATE.repoId;
}
public boolean isVirtual()
{
return isVirtualRepoId(repoId);
}
public static boolean isVirtualRepoId(final int repoId) | {
return repoId == VIRTUAL.repoId;
}
public boolean isRealPackingInstructions()
{
return isRealPackingInstructionsRepoId(repoId);
}
public static boolean isRealPackingInstructionsRepoId(final int repoId)
{
return repoId > 0
&& !isTemplateRepoId(repoId)
&& !isVirtualRepoId(repoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\handlingunits\HuPackingInstructionsId.java | 1 |
请完成以下Java代码 | public void setIsPackagingMaterial(final I_C_InvoiceLine invoiceLine)
{
if (invoiceLine.getC_OrderLine() == null)
{
// in case the c_orderline_id is removed, make sure the flag is on false. The user can set it on true, manually
invoiceLine.setIsPackagingMaterial(false);
return;
}
final de.metas.interfaces.I_C_OrderLine ol = InterfaceWrapperHelper.create(invoiceLine.getC_OrderLine(), de.metas.interfaces.I_C_OrderLine.class);
invoiceLine.setIsPackagingMaterial(ol.isPackagingMaterial());
}
/**
* If we have a not-yet-processed invoice line in a verification-set, then allow to delete that line.
*/
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE })
public void deleteVerificationData(final I_C_InvoiceLine invoiceLine)
{
queryBL.createQueryBuilder(I_C_Invoice_Verification_SetLine.class) | .addEqualsFilter(I_C_Invoice_Verification_SetLine.COLUMNNAME_C_InvoiceLine_ID, invoiceLine.getC_InvoiceLine_ID())
.create()
.delete();
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_C_InvoiceLine.COLUMNNAME_M_Product_ID })
public void checkExcludedProducts(final I_C_InvoiceLine invoiceLine)
{
final org.compiere.model.I_C_Invoice invoice = invoiceBL.getById(InvoiceId.ofRepoId(invoiceLine.getC_Invoice_ID()));
//Product should always be set, but we can't make it mandatory in db because of existing cases
final ProductId productId = ProductId.ofRepoId(invoiceLine.getM_Product_ID());
final BPartnerId partnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID());
final SOTrx soTrx = SOTrx.ofBooleanNotNull(invoice.isSOTrx());
partnerProductBL.assertNotExcludedFromTransaction(soTrx, productId, partnerId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\interceptor\C_InvoiceLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigInteger getProgressNumberDifference() {
return progressNumberDifference;
}
/**
* Sets the value of the progressNumberDifference property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setProgressNumberDifference(BigInteger value) {
this.progressNumberDifference = value;
}
/**
* Gets the value of the kanbanID property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the kanbanID property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getKanbanID().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getKanbanID() {
if (kanbanID == null) {
kanbanID = new ArrayList<String>(); | }
return this.kanbanID;
}
/**
* The classification of the product/service in free-text form.Gets the value of the classification property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the classification property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getClassification().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ClassificationType }
*
*
*/
public List<ClassificationType> getClassification() {
if (classification == null) {
classification = new ArrayList<ClassificationType>();
}
return this.classification;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AdditionalLineItemInformationType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ProxyExchangeWebfluxProperties {
/**
* Properties prefix.
*/
public static final String PREFIX = "spring.cloud.gateway.proxy-exchange.webflux";
/**
* Contains headers that are considered case-sensitive by default.
*/
public static Set<String> DEFAULT_SENSITIVE = Set.of("cookie", "authorization");
/**
* Contains headers that are skipped by default.
*/
public static Set<String> DEFAULT_SKIPPED = Set.of("content-length", "host");
/**
* Fixed header values that will be added to all downstream requests.
*/
private Map<String, String> headers = new LinkedHashMap<>();
/**
* A set of header names that should be sent downstream by default.
*/
private Set<String> autoForward = new HashSet<>();
/**
* A set of sensitive header names that will not be sent downstream by default.
*/
private Set<String> sensitive = DEFAULT_SENSITIVE;
/**
* A set of header names that will not be sent downstream because they could be
* problematic.
*/
private Set<String> skipped = DEFAULT_SKIPPED;
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public Set<String> getAutoForward() {
return autoForward;
}
public void setAutoForward(Set<String> autoForward) {
this.autoForward = autoForward; | }
public Set<String> getSensitive() {
return sensitive;
}
public void setSensitive(Set<String> sensitive) {
this.sensitive = sensitive;
}
public Set<String> getSkipped() {
return skipped;
}
public void setSkipped(Set<String> skipped) {
this.skipped = skipped;
}
public HttpHeaders convertHeaders() {
HttpHeaders headers = new HttpHeaders();
for (String key : this.headers.keySet()) {
headers.set(key, this.headers.get(key));
}
return headers;
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webflux\src\main\java\org\springframework\cloud\gateway\webflux\config\ProxyExchangeWebfluxProperties.java | 2 |
请完成以下Java代码 | private String cleanValue(String value)
{
char[] chars = value.toCharArray();
StringBuilder sb = new StringBuilder();
for (char c : chars)
{
char ch = c;
ch = Character.toLowerCase(ch);
if ((ch >= '0' && ch <= '9') // digits
|| (ch >= 'a' && ch <= 'z'))
{
sb.append(ch);
}
}
return sb.toString();
} // cleanValue
/**
* Get First/Last Name
*
* @param name name
* @param getFirst if true first name is returned
* @return first/last name
*/
private String getName(String name, boolean getFirst)
{
if (name == null || name.length() == 0)
{
return "";
}
String first = null;
String last = null;
// Janke, Jorg R - Jorg R Janke
// double names not handled gracefully nor titles
// nor (former) aristrocratic world de/la/von
boolean lastFirst = name.indexOf(',') != -1;
StringTokenizer st = null;
if (lastFirst)
{
st = new StringTokenizer(name, ",");
}
else
{
st = new StringTokenizer(name, " ");
}
while (st.hasMoreTokens())
{
String s = st.nextToken().trim();
if (lastFirst)
{
if (last == null)
{
last = s;
}
else if (first == null)
{
first = s;
}
}
else
{
if (first == null)
{
first = s;
}
else
{
last = s;
}
}
}
if (getFirst)
{ | if (first == null)
{
return "";
}
return first.trim();
}
if (last == null)
{
return "";
}
return last.trim();
} // getName
/**
* String Representation
*
* @return Info
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder("MUser[")
.append(get_ID())
.append(",Name=").append(getName())
.append(",EMail=").append(getEMail())
.append("]");
return sb.toString();
} // toString
/**
* Set EMail - reset validation
*
* @param EMail email
*/
@Override
public void setEMail(String EMail)
{
super.setEMail(EMail);
setEMailVerifyDate(null);
} // setEMail
/**
* Before Save
*
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave(boolean newRecord)
{
// New Address invalidates verification
if (!newRecord && is_ValueChanged("EMail"))
{
setEMailVerifyDate(null);
}
if (newRecord || super.getValue() == null || is_ValueChanged("Value"))
{
setValue(super.getValue());
}
return true;
} // beforeSave
} // MUser | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MUser.java | 1 |
请完成以下Java代码 | public PInstanceId getQueryOnlySelectionId()
{
return queryOnlySelectionId;
}
public IQueryFilter<T> getMainFilter()
{
return mainFilter;
}
public ICompositeQueryFilter<T> getMainFilterAsComposite()
{
return (ICompositeQueryFilter<T>)mainFilter;
}
public ICompositeQueryFilter<T> getMainFilterAsCompositeOrNull()
{
return mainFilter instanceof ICompositeQueryFilter ? (ICompositeQueryFilter<T>)mainFilter : null;
}
public IQueryOrderBy getQueryOrderBy()
{
return queryOrderBy;
} | public QueryLimit getQueryLimit()
{
return queryLimit;
}
public void setQueryLimit(@NonNull final QueryLimit queryLimit)
{
this.queryLimit = queryLimit;
}
public boolean isExplodeORJoinsToUnions()
{
return explodeORJoinsToUnions;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\AbstractQueryBuilderDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private ConditionOutcome getMatchOutcome(String[] locations) {
if (!isJndiAvailable()) {
return ConditionOutcome
.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).notAvailable("JNDI environment"));
}
if (locations.length == 0) {
return ConditionOutcome
.match(ConditionMessage.forCondition(ConditionalOnJndi.class).available("JNDI environment"));
}
JndiLocator locator = getJndiLocator(locations);
String location = locator.lookupFirstLocation();
String details = "(" + StringUtils.arrayToCommaDelimitedString(locations) + ")";
if (location != null) {
return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnJndi.class, details)
.foundExactly("\"" + location + "\""));
}
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class, details)
.didNotFind("any matching JNDI location")
.atAll());
}
protected boolean isJndiAvailable() {
return JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable();
}
protected JndiLocator getJndiLocator(String[] locations) {
return new JndiLocator(locations);
} | protected static class JndiLocator extends JndiLocatorSupport {
private final String[] locations;
public JndiLocator(String[] locations) {
this.locations = locations;
}
public @Nullable String lookupFirstLocation() {
for (String location : this.locations) {
try {
lookup(location);
return location;
}
catch (NamingException ex) {
// Swallow and continue
}
}
return null;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\OnJndiCondition.java | 2 |
请完成以下Java代码 | public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
protected void setEntity(ENTITY_TYPE entity) {
this.entity = entity;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder
.append("RuntimeEventImpl [id=")
.append(id)
.append(", timestamp=")
.append(timestamp)
.append(", processInstanceId=")
.append(processInstanceId)
.append(", processDefinitionId=")
.append(processDefinitionId)
.append(", processDefinitionKey=")
.append(processDefinitionKey)
.append(", processDefinitionVersion=")
.append(processDefinitionVersion)
.append(", businessKey=")
.append(businessKey)
.append(", parentProcessInstanceId=")
.append(parentProcessInstanceId)
.append(", entity=")
.append(entity)
.append("]");
return builder.toString();
}
@Override
public int hashCode() {
return Objects.hash(
businessKey,
entity,
id,
parentProcessInstanceId,
processDefinitionId,
processDefinitionKey,
processDefinitionVersion,
processInstanceId,
timestamp,
getEventType()
); | }
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
RuntimeEventImpl other = (RuntimeEventImpl) obj;
return (
Objects.equals(businessKey, other.businessKey) &&
Objects.equals(entity, other.entity) &&
Objects.equals(id, other.id) &&
Objects.equals(parentProcessInstanceId, other.parentProcessInstanceId) &&
Objects.equals(processDefinitionId, other.processDefinitionId) &&
Objects.equals(processDefinitionKey, other.processDefinitionKey) &&
Objects.equals(processDefinitionVersion, other.processDefinitionVersion) &&
Objects.equals(processInstanceId, other.processInstanceId) &&
Objects.equals(timestamp, other.timestamp)
);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-model-shared-impl\src\main\java\org\activiti\api\runtime\event\impl\RuntimeEventImpl.java | 1 |
请完成以下Java代码 | public EngineResource getResourceEntity() {
return resourceEntity;
}
public void setResourceEntity(EngineResource resourceEntity) {
this.resourceEntity = resourceEntity;
}
public CmmnParseResult(EngineDeployment deployment) {
this.deployment = deployment;
}
public EngineDeployment getDeployment() {
return deployment;
}
public CmmnModel getCmmnModel() {
return cmmnModel;
}
public void setCmmnModel(CmmnModel cmmnModel) {
this.cmmnModel = cmmnModel;
}
public void addCaseDefinition(CaseDefinitionEntity caseDefinitionEntity) {
definitions.add(caseDefinitionEntity);
}
public List<CaseDefinitionEntity> getAllCaseDefinitions() {
return definitions;
}
public void addCaseDefinition(CaseDefinitionEntity caseDefinitionEntity, EngineResource resourceEntity, CmmnModel cmmnModel) { | definitions.add(caseDefinitionEntity);
mapDefinitionsToResources.put(caseDefinitionEntity, resourceEntity);
mapDefinitionsToCmmnModel.put(caseDefinitionEntity, cmmnModel);
}
public EngineResource getResourceForCaseDefinition(CaseDefinitionEntity caseDefinition) {
return mapDefinitionsToResources.get(caseDefinition);
}
public CmmnModel getCmmnModelForCaseDefinition(CaseDefinitionEntity caseDefinition) {
return mapDefinitionsToCmmnModel.get(caseDefinition);
}
public Case getCmmnCaseForCaseDefinition(CaseDefinitionEntity caseDefinition) {
CmmnModel model = getCmmnModelForCaseDefinition(caseDefinition);
return (model == null ? null : model.getCaseById(caseDefinition.getKey()));
}
public void merge(CmmnParseResult cmmnParseResult) {
if (deployment == null) {
throw new FlowableException("Cannot merge from a parse result without a deployment entity");
}
if (cmmnParseResult.getDeployment() != null && !deployment.equals(cmmnParseResult.getDeployment())) {
throw new FlowableException("Cannot merge parse results with different deployment entities");
}
for (CaseDefinitionEntity caseDefinitionEntity : cmmnParseResult.getAllCaseDefinitions()) {
addCaseDefinition(caseDefinitionEntity,
cmmnParseResult.getResourceForCaseDefinition(caseDefinitionEntity),
cmmnParseResult.getCmmnModelForCaseDefinition(caseDefinitionEntity));
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\parser\CmmnParseResult.java | 1 |
请完成以下Java代码 | private void createAndSubmitWorkpackage(
@NonNull final IWorkPackageQueue workPackageQueue,
@NonNull final Collection<Object> modelsToEnqueue,
@Nullable final AsyncBatchId asyncBatchId)
{
workPackageQueue.newWorkPackage()
.setUserInChargeId(userIdInCharge)
.parameters(parameters)
.addElements(modelsToEnqueue)
.setAsyncBatchId(asyncBatchId)
.buildAndEnqueue();
}
private void createAndSubmitWorkpackagesByAsyncBatch(@NonNull final IWorkPackageQueue workPackageQueue)
{
for (final Map.Entry<AsyncBatchId, List<Object>> entry : batchId2Models.entrySet())
{
final AsyncBatchId key = entry.getKey();
final List<Object> value = entry.getValue();
createAndSubmitWorkpackage(workPackageQueue, value, AsyncBatchId.toAsyncBatchIdOrNull(key));
}
}
private boolean hasNoModels()
{
return isCreateOneWorkpackagePerAsyncBatch() ? batchId2Models.isEmpty() : models.isEmpty();
}
}
private static final class ModelsScheduler<ModelType> extends WorkpackagesOnCommitSchedulerTemplate<ModelType>
{
private final Class<ModelType> modelType;
private final boolean collectModels;
public ModelsScheduler(final Class<? extends IWorkpackageProcessor> workpackageProcessorClass, final Class<ModelType> modelType, final boolean collectModels)
{
super(workpackageProcessorClass);
this.modelType = modelType; | this.collectModels = collectModels;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("collectModels", collectModels)
.add("workpackageProcessorClass", getWorkpackageProcessorClass())
.add("modelType", modelType)
.toString();
}
@Override
protected Properties extractCtxFromItem(final ModelType item)
{
return InterfaceWrapperHelper.getCtx(item);
}
@Override
protected String extractTrxNameFromItem(final ModelType item)
{
return InterfaceWrapperHelper.getTrxName(item);
}
@Nullable
@Override
protected Object extractModelToEnqueueFromItem(final Collector collector, final ModelType item)
{
return collectModels ? item : null;
}
@Override
protected boolean isEnqueueWorkpackageWhenNoModelsEnqueued()
{
return !collectModels;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\WorkpackagesOnCommitSchedulerTemplate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getHeaderDescription() {
return headerDescription;
}
/**
* Sets the value of the headerDescription property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHeaderDescription(String value) {
this.headerDescription = value;
}
/**
* A list of different line items. Used to group line items of a certain kind together.Gets the value of the itemList property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the itemList property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getItemList().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ItemListType }
*
*
*/
public List<ItemListType> getItemList() {
if (itemList == null) { | itemList = new ArrayList<ItemListType>();
}
return this.itemList;
}
/**
* A free-text footer description with suceeds the details section.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFooterDescription() {
return footerDescription;
}
/**
* Sets the value of the footerDescription property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFooterDescription(String value) {
this.footerDescription = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DetailsType.java | 2 |
请完成以下Java代码 | public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
}
public void setProcessDefinitionTenantId(String processDefinitionTenantId) {
this.processDefinitionTenantId = processDefinitionTenantId;
}
public void setProcessDefinitionWithoutTenantId(boolean processDefinitionWithoutTenantId) {
this.processDefinitionWithoutTenantId = processDefinitionWithoutTenantId;
}
@Override
public void updateSuspensionState(ProcessEngine engine) {
int params = (jobDefinitionId != null ? 1 : 0)
+ (processDefinitionId != null ? 1 : 0)
+ (processDefinitionKey != null ? 1 : 0);
if (params > 1) {
String message = "Only one of jobDefinitionId, processDefinitionId or processDefinitionKey should be set to update the suspension state.";
throw new InvalidRequestException(Status.BAD_REQUEST, message);
} else if (params == 0) {
String message = "Either jobDefinitionId, processDefinitionId or processDefinitionKey should be set to update the suspension state.";
throw new InvalidRequestException(Status.BAD_REQUEST, message);
}
UpdateJobDefinitionSuspensionStateBuilder updateSuspensionStateBuilder = createUpdateSuspensionStateBuilder(engine);
if (executionDate != null && !executionDate.equals("")) {
Date delayedExecutionDate = DateTimeUtil.parseDate(executionDate);
updateSuspensionStateBuilder.executionDate(delayedExecutionDate);
}
updateSuspensionStateBuilder.includeJobs(includeJobs); | if (getSuspended()) {
updateSuspensionStateBuilder.suspend();
} else {
updateSuspensionStateBuilder.activate();
}
}
protected UpdateJobDefinitionSuspensionStateBuilder createUpdateSuspensionStateBuilder(ProcessEngine engine) {
UpdateJobDefinitionSuspensionStateSelectBuilder selectBuilder = engine.getManagementService().updateJobDefinitionSuspensionState();
if (jobDefinitionId != null) {
return selectBuilder.byJobDefinitionId(jobDefinitionId);
} else if (processDefinitionId != null) {
return selectBuilder.byProcessDefinitionId(processDefinitionId);
} else {
UpdateJobDefinitionSuspensionStateTenantBuilder tenantBuilder = selectBuilder.byProcessDefinitionKey(processDefinitionKey);
if (processDefinitionTenantId != null) {
tenantBuilder.processDefinitionTenantId(processDefinitionTenantId);
} else if (processDefinitionWithoutTenantId) {
tenantBuilder.processDefinitionWithoutTenantId();
}
return tenantBuilder;
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\management\JobDefinitionSuspensionStateDto.java | 1 |
请完成以下Java代码 | public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public void setActivityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getTenantId() {
return tenantId;
} | public static VariableInstanceDto fromVariableInstance(VariableInstance variableInstance) {
VariableInstanceDto dto = new VariableInstanceDto();
dto.id = variableInstance.getId();
dto.name = variableInstance.getName();
dto.processDefinitionId = variableInstance.getProcessDefinitionId();
dto.processInstanceId = variableInstance.getProcessInstanceId();
dto.executionId = variableInstance.getExecutionId();
dto.caseExecutionId = variableInstance.getCaseExecutionId();
dto.caseInstanceId = variableInstance.getCaseInstanceId();
dto.taskId = variableInstance.getTaskId();
dto.batchId = variableInstance.getBatchId();
dto.activityInstanceId = variableInstance.getActivityInstanceId();
dto.tenantId = variableInstance.getTenantId();
if(variableInstance.getErrorMessage() == null) {
VariableValueDto.fromTypedValue(dto, variableInstance.getTypedValue());
}
else {
dto.errorMessage = variableInstance.getErrorMessage();
dto.type = VariableValueDto.toRestApiTypeName(variableInstance.getTypeName());
}
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\VariableInstanceDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<Map<String,Object>> queryTreeListForDeptRole(@RequestParam(name="departId",required=true) String departId,HttpServletRequest request) {
Result<Map<String,Object>> result = new Result<>();
//全部权限ids
List<String> ids = new ArrayList<>();
try {
List<SysPermission> list = sysPermissionService.queryDepartPermissionList(departId);
for(SysPermission sysPer : list) {
ids.add(sysPer.getId());
}
List<TreeModel> treeList = new ArrayList<>();
getTreeModelList(treeList, list, null);
Map<String,Object> resMap = new HashMap(5);
//全部树节点数据
resMap.put("treeList", treeList);
//全部树ids
resMap.put("ids", ids);
result.setResult(resMap);
result.setSuccess(true);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return result;
}
private void getTreeModelList(List<TreeModel> treeList, List<SysPermission> metaList, TreeModel temp) {
for (SysPermission permission : metaList) {
String tempPid = permission.getParentId();
TreeModel tree = new TreeModel(permission.getId(), tempPid, permission.getName(),permission.getRuleFlag(), permission.isLeaf()); | if(temp==null && oConvertUtils.isEmpty(tempPid)) {
treeList.add(tree);
if(!tree.getIsLeaf()) {
getTreeModelList(treeList, metaList, tree);
}
}else if(temp!=null && tempPid!=null && tempPid.equals(temp.getKey())){
temp.getChildren().add(tree);
if(!tree.getIsLeaf()) {
getTreeModelList(treeList, metaList, tree);
}
}
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysDepartPermissionController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class RestClientBuilderConfigurer {
private final ClientHttpRequestFactoryBuilder<?> requestFactoryBuilder;
private final HttpClientSettings clientSettings;
private final List<RestClientCustomizer> customizers;
public RestClientBuilderConfigurer() {
this(ClientHttpRequestFactoryBuilder.detect(), HttpClientSettings.defaults(), Collections.emptyList());
}
RestClientBuilderConfigurer(ClientHttpRequestFactoryBuilder<?> requestFactoryBuilder,
HttpClientSettings clientSettings, List<RestClientCustomizer> customizers) {
this.requestFactoryBuilder = requestFactoryBuilder;
this.clientSettings = clientSettings;
this.customizers = customizers;
}
/**
* Configure the specified {@link Builder RestClient.Builder}. The builder can be | * further tuned and default settings can be overridden.
* @param builder the {@link Builder RestClient.Builder} instance to configure
* @return the configured builder
*/
public RestClient.Builder configure(RestClient.Builder builder) {
builder.requestFactory(this.requestFactoryBuilder.build(this.clientSettings));
applyCustomizers(builder);
return builder;
}
private void applyCustomizers(RestClient.Builder builder) {
for (RestClientCustomizer customizer : this.customizers) {
customizer.customize(builder);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-restclient\src\main\java\org\springframework\boot\restclient\autoconfigure\RestClientBuilderConfigurer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.headers()
.frameOptions()
.disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/books/purchase/**").authenticated() | .antMatchers("/api/register").permitAll()
.antMatchers("/api/activate").permitAll()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/account/reset-password/init").permitAll()
.antMatchers("/api/account/reset-password/finish").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/info").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.and()
.apply(securityConfigurerAdapter());
}
private JWTConfigurer securityConfigurerAdapter() {
return new JWTConfigurer(tokenProvider);
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\config\SecurityConfiguration.java | 2 |
请完成以下Java代码 | public <T> T[] toArray(T[] ts) {
return cookieMap.values().toArray(ts);
}
@Override
public boolean add(Cookie cookie) {
if (cookie == null) {
return false;
}
cookieMap.put(cookie.getName(), cookie);
return true;
}
@Override
public boolean remove(Object o) {
if (o instanceof String) {
return cookieMap.remove((String)o) != null;
}
if (o instanceof Cookie) {
Cookie c = (Cookie)o;
return cookieMap.remove(c.getName()) != null;
}
return false;
}
public Cookie get(String name) {
return cookieMap.get(name);
}
@Override
public boolean containsAll(Collection<?> collection) {
for(Object o : collection) {
if (!contains(o)) {
return false;
}
}
return true;
}
@Override
public boolean addAll(Collection<? extends Cookie> collection) {
boolean result = false;
for(Cookie cookie : collection) {
result|= add(cookie);
}
return result; | }
@Override
public boolean removeAll(Collection<?> collection) {
boolean result = false;
for(Object cookie : collection) {
result|= remove(cookie);
}
return result;
}
@Override
public boolean retainAll(Collection<?> collection) {
boolean result = false;
Iterator<Map.Entry<String, Cookie>> it = cookieMap.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<String, Cookie> e = it.next();
if (!collection.contains(e.getKey()) && !collection.contains(e.getValue())) {
it.remove();
result = true;
}
}
return result;
}
@Override
public void clear() {
cookieMap.clear();
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\security\oauth2\CookieCollection.java | 1 |
请完成以下Java代码 | private Object getRandomBytes() {
byte[] bytes = new byte[16];
getSource().nextBytes(bytes);
return HexFormat.of().withLowerCase().formatHex(bytes);
}
/**
* Add a {@link RandomValuePropertySource} to the given {@link Environment}.
* @param environment the environment to add the random property source to
*/
public static void addToEnvironment(ConfigurableEnvironment environment) {
addToEnvironment(environment, logger);
}
/**
* Add a {@link RandomValuePropertySource} to the given {@link Environment}.
* @param environment the environment to add the random property source to
* @param logger logger used for debug and trace information
* @since 4.0.0
*/
public static void addToEnvironment(ConfigurableEnvironment environment, Log logger) {
MutablePropertySources sources = environment.getPropertySources();
PropertySource<?> existing = sources.get(RANDOM_PROPERTY_SOURCE_NAME);
if (existing != null) {
logger.trace("RandomValuePropertySource already present");
return;
}
RandomValuePropertySource randomSource = new RandomValuePropertySource(RANDOM_PROPERTY_SOURCE_NAME);
if (sources.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME) != null) {
sources.addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, randomSource);
}
else {
sources.addLast(randomSource);
}
logger.trace("RandomValuePropertySource add to Environment");
}
static final class Range<T extends Number> {
private final String value;
private final T min;
private final T max;
private Range(String value, T min, T max) {
this.value = value;
this.min = min;
this.max = max; | }
T getMin() {
return this.min;
}
T getMax() {
return this.max;
}
@Override
public String toString() {
return this.value;
}
static <T extends Number & Comparable<T>> Range<T> of(String value, Function<String, T> parse) {
T zero = parse.apply("0");
String[] tokens = StringUtils.commaDelimitedListToStringArray(value);
T min = parse.apply(tokens[0]);
if (tokens.length == 1) {
Assert.state(min.compareTo(zero) > 0, "Bound must be positive.");
return new Range<>(value, zero, min);
}
T max = parse.apply(tokens[1]);
Assert.state(min.compareTo(max) < 0, "Lower bound must be less than upper bound.");
return new Range<>(value, min, max);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\RandomValuePropertySource.java | 1 |
请完成以下Java代码 | public int getPickFrom_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_Order_ID);
}
/**
* PickStatus AD_Reference_ID=540919
* Reference name: M_Picking_Candidate_PickStatus
*/
public static final int PICKSTATUS_AD_Reference_ID=540919;
/** ToBePicked = ? */
public static final String PICKSTATUS_ToBePicked = "?";
/** Picked = P */
public static final String PICKSTATUS_Picked = "P";
/** WillNotBePicked = N */
public static final String PICKSTATUS_WillNotBePicked = "N";
/** Packed = A */
public static final String PICKSTATUS_Packed = "A";
@Override
public void setPickStatus (final java.lang.String PickStatus)
{
set_Value (COLUMNNAME_PickStatus, PickStatus);
}
@Override
public java.lang.String getPickStatus()
{
return get_ValueAsString(COLUMNNAME_PickStatus);
}
@Override
public void setQtyPicked (final BigDecimal QtyPicked)
{
set_Value (COLUMNNAME_QtyPicked, QtyPicked);
}
@Override
public BigDecimal getQtyPicked()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPicked);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyReject (final BigDecimal QtyReject)
{
set_Value (COLUMNNAME_QtyReject, QtyReject);
}
@Override
public BigDecimal getQtyReject()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReject);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyReview (final @Nullable BigDecimal QtyReview)
{
set_Value (COLUMNNAME_QtyReview, QtyReview);
}
@Override
public BigDecimal getQtyReview()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReview);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* RejectReason AD_Reference_ID=541422
* Reference name: QtyNotPicked RejectReason
*/
public static final int REJECTREASON_AD_Reference_ID=541422;
/** NotFound = N */
public static final String REJECTREASON_NotFound = "N";
/** Damaged = D */
public static final String REJECTREASON_Damaged = "D"; | @Override
public void setRejectReason (final @Nullable java.lang.String RejectReason)
{
set_Value (COLUMNNAME_RejectReason, RejectReason);
}
@Override
public java.lang.String getRejectReason()
{
return get_ValueAsString(COLUMNNAME_RejectReason);
}
/**
* Status AD_Reference_ID=540734
* Reference name: M_Picking_Candidate_Status
*/
public static final int STATUS_AD_Reference_ID=540734;
/** Closed = CL */
public static final String STATUS_Closed = "CL";
/** InProgress = IP */
public static final String STATUS_InProgress = "IP";
/** Processed = PR */
public static final String STATUS_Processed = "PR";
/** Voided = VO */
public static final String STATUS_Voided = "VO";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Candidate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void startAllRoutes()
{
getRoutes()
.stream()
.filter(CustomRouteController::isReadyToStart)
.sorted(Comparator.comparing(Route::getStartupOrder, Comparator.nullsFirst(Comparator.naturalOrder())))
.forEach(this::start);
}
public void stopAllRoutes()
{
getRoutes()
.stream()
.filter(CustomRouteController::canBeStopped)
.forEach(this::stop);
}
public void startAlwaysRunningRoutes()
{
getRoutes()
.stream()
.filter(CustomRouteController::isAlwaysRunning)
.forEach(this::start);
}
private void start(final Route route)
{
try
{
getRouteController().startRoute(route.getRouteId());
}
catch (final Exception e)
{
throw new RuntimeException("Exception caught when trying to start route=" + route.getRouteId(), e);
}
}
private void stop(final Route route)
{
try
{
getRouteController().stopRoute(route.getRouteId(), 100, TimeUnit.MILLISECONDS);
}
catch (final Exception e)
{
throw new RuntimeException("Exception caught when trying to suspend route=" + route.getRouteId(), e);
}
}
@NonNull
private List<Route> getRoutes()
{
return camelContext.getRoutes();
} | @NonNull
private RouteController getRouteController()
{
return camelContext.getRouteController();
}
private static boolean isReadyToStart(@NonNull final Route route)
{
final boolean isStartOnDemand = CamelRoutesGroup.ofCodeOptional(route.getGroup())
.map(CamelRoutesGroup::isStartOnDemand)
.orElse(false);
return !isStartOnDemand;
}
private static boolean canBeStopped(@NonNull final Route route)
{
return !isAlwaysRunning(route);
}
private static boolean isAlwaysRunning(@NonNull final Route route)
{
return CamelRoutesGroup.ofCodeOptional(route.getGroup())
.map(CamelRoutesGroup::isAlwaysOn)
.orElse(false);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\CustomRouteController.java | 2 |
请完成以下Java代码 | public static SupplierApproval ofNullableCode(@Nullable final String code)
{
return code != null ? ofCode(code) : null;
}
public static SupplierApproval ofCode(@NonNull final String code)
{
SupplierApproval type = typesByCode.get(code);
if (type == null)
{
throw new AdempiereException("No " + SupplierApproval.class + " found for code: " + code);
}
return type;
}
public static String toCodeOrNull(final SupplierApproval type)
{
return type != null ? type.getCode() : null;
} | private static final ImmutableMap<String, SupplierApproval> typesByCode = Maps.uniqueIndex(Arrays.asList(values()), SupplierApproval::getCode);
public boolean isOneYear()
{
return this == OneYear;
}
public boolean isTwoYears()
{
return this == TwoYears;
}
public boolean isThreeYears()
{
return this == ThreeYears;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\SupplierApproval.java | 1 |
请完成以下Java代码 | public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public List<ProcessDefinition> getDeployedProcessDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(ProcessDefinitionEntity.class);
}
@Override
public List<CaseDefinition> getDeployedCaseDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(CaseDefinitionEntity.class);
}
@Override
public List<DecisionDefinition> getDeployedDecisionDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(DecisionDefinitionEntity.class);
}
@Override
public List<DecisionRequirementsDefinition> getDeployedDecisionRequirementsDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(DecisionRequirementsDefinitionEntity.class);
} | @Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", name=" + name
+ ", resources=" + resources
+ ", deploymentTime=" + deploymentTime
+ ", validatingSchema=" + validatingSchema
+ ", isNew=" + isNew
+ ", source=" + source
+ ", tenantId=" + tenantId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\DeploymentEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExecutionResponse {
protected String id;
protected String url;
protected String parentId;
protected String parentUrl;
protected String superExecutionId;
protected String superExecutionUrl;
protected String processInstanceId;
protected String processInstanceUrl;
protected boolean suspended;
protected String activityId;
protected String tenantId;
@ApiModelProperty(example = "5")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@ApiModelProperty(example = "http://localhost:8182/runtime/executions/5")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "null")
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
@ApiModelProperty(example = "null")
public String getParentUrl() {
return parentUrl;
}
public void setParentUrl(String parentUrl) {
this.parentUrl = parentUrl;
}
@ApiModelProperty(example = "null")
public String getSuperExecutionId() {
return superExecutionId;
}
public void setSuperExecutionId(String superExecutionId) {
this.superExecutionId = superExecutionId;
}
@ApiModelProperty(example = "null")
public String getSuperExecutionUrl() {
return superExecutionUrl;
}
public void setSuperExecutionUrl(String superExecutionUrl) {
this.superExecutionUrl = superExecutionUrl; | }
@ApiModelProperty(example = "5")
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@ApiModelProperty(example = "http://localhost:8182/runtime/process-instances/5")
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
public boolean isSuspended() {
return suspended;
}
public void setSuspended(boolean suspended) {
this.suspended = suspended;
}
@ApiModelProperty(example = "null")
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ExecutionResponse.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class UnacquireOwnedJobsCmd implements Command<Void> {
private static final Logger LOGGER = LoggerFactory.getLogger(UnacquireOwnedJobsCmd.class);
protected final JobServiceConfiguration jobServiceConfiguration;
protected final String lockOwner;
protected final String tenantId;
public UnacquireOwnedJobsCmd(String lockOwner, String tenantId, JobServiceConfiguration jobServiceConfiguration) {
this.lockOwner = lockOwner;
this.tenantId = tenantId;
this.jobServiceConfiguration = jobServiceConfiguration;
}
@Override
public Void execute(CommandContext commandContext) {
JobQueryImpl jobQuery = new JobQueryImpl(commandContext, jobServiceConfiguration);
jobQuery.lockOwner(lockOwner);
// The tenantId is only used if it has been explicitly set
if (tenantId != null) {
if (!tenantId.isEmpty()) {
jobQuery.jobTenantId(tenantId);
} else {
jobQuery.jobWithoutTenantId();
}
} | List<Job> jobs = jobServiceConfiguration.getJobEntityManager().findJobsByQueryCriteria(jobQuery);
for (Job job : jobs) {
try {
jobServiceConfiguration.getJobManager().unacquire(job);
logJobUnlocking(job);
} catch (Exception e) {
/*
* Not logging the exception. The engine is shutting down, so not much can be done at this point.
*
* Furthermore: some exceptions can be expected here: if the job was picked up and put in the queue when
* the shutdown was triggered, the job can still be executed as the threadpool doesn't shut down immediately.
*
* This would then throw an NPE for data related to the job queried here (e.g. the job itself or related executions).
* That is also why the exception is catched here and not higher-up (e.g. at the flush, but the flush won't be reached for an NPE)
*/
}
}
return null;
}
protected void logJobUnlocking(Job job) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Unacquired job {} with owner {} and tenantId {}", job, lockOwner, tenantId);
}
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\UnacquireOwnedJobsCmd.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static String clean(String s) {
String ss;
ss = s.replace(".", " ").replace(",", " ").replace(";", " ").replace("*", " ").replace("#", " ").replace("-", " ");
return ss;
}
public static double editDistanceWord(String s1, String s2) {
String[] w1 = clean(s1).split("\\s+");
String[] w2 = clean(s2).split("\\s+");
for (int i = 0; i < w1.length; i++) {
for (int j = 0; j < w2.length; j++)
if (w1[i].toLowerCase().equals(w2[j].toLowerCase())) {
w1[i] = "";
w2[j] = "";
break;
}
}
double d = 0.0;
int count = 0;
int w1l = w1.length>0?w1.length:1;
int w2l = w2.length>0?w2.length:1;
for (int i = 0; i < w1.length; i++)
for (int j = 0; j < w2.length; j++) {
if (!w1[i].isEmpty() && !w2[j].isEmpty())
d = d + editDistance(w1[i].toLowerCase(), w2[j].toLowerCase()) / max(w1[i].length(), w2[j].length());
else
if (w1[i].isEmpty() && w2[j].isEmpty());
else
if (w1[i].isEmpty())
d = d + 1.0 / w1l;
else
if (w2[j].isEmpty())
d = d + 1.0 / w2l;
count++; | }
if (count == 0)
count = 1;
return Math.round(d / count * 100);
}
public static double similarity2(String s1, String s2) {
return editDistanceWord(s1, s2);
}
@Override
public int compare(Address o1, Address o2) {
double f1 = similarity2(o1.getAddr(), baseToCompare);
double f2 = similarity2(o2.getAddr(), baseToCompare);
if (f1 > f2)
return 1;
else
if (Math.abs(f1 - f2) < 0.000001)
return 0;
else
return -1;
}
} | repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\service\taxiMaster\StringSimilarity.java | 2 |
请完成以下Java代码 | public abstract class AbstractManager {
protected DmnEngineConfiguration dmnEngineConfiguration;
public AbstractManager(DmnEngineConfiguration dmnEngineConfiguration) {
this.dmnEngineConfiguration = dmnEngineConfiguration;
}
// Command scoped
protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected <T> T getSession(Class<T> sessionClass) {
return getCommandContext().getSession(sessionClass);
}
// Engine scoped
protected DmnEngineConfiguration getDmnEngineConfiguration() { | return dmnEngineConfiguration;
}
protected DmnDeploymentEntityManager getDeploymentEntityManager() {
return getDmnEngineConfiguration().getDeploymentEntityManager();
}
protected DecisionEntityManager getDecisionTableEntityManager() {
return getDmnEngineConfiguration().getDecisionEntityManager();
}
protected HistoricDecisionExecutionEntityManager getHistoricDecisionExecutionEntityManager() {
return getDmnEngineConfiguration().getHistoricDecisionExecutionEntityManager();
}
protected DmnResourceEntityManager getResourceEntityManager() {
return getDmnEngineConfiguration().getResourceEntityManager();
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\AbstractManager.java | 1 |
请完成以下Java代码 | protected CEditor createCheckboxEditor(final String label)
{
final VCheckBox cb = new VCheckBox();
cb.setText(label);
cb.setSelected(true);
cb.setFocusable(false);
cb.setRequestFocusEnabled(false);
cb.addVetoableChangeListener(fieldChangedListener);
return cb;
}
@Override
protected CEditor createLookupEditor(final String columnName, final Lookup lookup, final Object defaultValue)
{
final VLookup vl = new VLookup(columnName, false, false, true, lookup);
vl.setName(columnName);
if (defaultValue != null)
{
vl.setValue(defaultValue);
}
vl.addVetoableChangeListener(fieldChangedListener);
return vl;
}
@Override
protected CEditor createStringEditor(final String defaultValue)
{
final VString field = new VString();
field.setBackground(AdempierePLAF.getInfoBackground());
if (defaultValue != null)
{
field.setText(defaultValue);
} | field.addVetoableChangeListener(fieldChangedListener);
return field;
}
@Override
protected CEditor createNumberEditor(final String columnName, final String title, final int displayType)
{
final VNumber vn = new VNumber(columnName, false, false, true, displayType, title);
vn.setName(columnName);
vn.addVetoableChangeListener(fieldChangedListener);
return vn;
}
@Override
protected CEditor createDateEditor(final String columnName, final String title, final int displayType)
{
final VDate vd = new VDate(columnName, false, false, true, displayType, title);
vd.setName(columnName);
vd.addVetoableChangeListener(fieldChangedListener);
return vd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\InfoQueryCriteriaGeneral.java | 1 |
请完成以下Java代码 | private void stopScheduledFuture()
{
if (scheduledFuture == null)
{
return;
}
try
{
scheduledFuture.cancel(true);
}
catch (final Exception ex)
{
logger.warn("{}: Failed stopping scheduled future: {}. Ignored and considering it as stopped", this, scheduledFuture, ex);
}
scheduledFuture = null;
}
private void pollAndPublish()
{
if (onPollingEventsSupplier == null)
{
return;
}
try
{
final List<?> events = onPollingEventsSupplier.produceEvents(); | if (events != null && !events.isEmpty())
{
for (final Object event : events)
{
websocketSender.convertAndSend(topicName, event);
logger.trace("Event sent to {}: {}", topicName, event);
}
}
else
{
logger.trace("Got no events from {}", onPollingEventsSupplier);
}
}
catch (final Exception ex)
{
logger.warn("Failed producing event for {}. Ignored.", this, ex);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\producers\WebSocketProducersRegistry.java | 1 |
请完成以下Java代码 | private static int skipBackward(final boolean[] pagesCovered,
final int pageTo,
final int limit)
{
int pageToFinal = pageTo;
for (int i = pageTo; i >= limit; i--)
{
if (!pagesCovered[i - 1])
{
break;
}
pageToFinal = i - 1;
}
return pageToFinal;
}
private static int skipForward(final boolean[] pagesCovered,
final int pageFrom,
final int limit)
{
final int limitToUse = Math.min(limit, pagesCovered.length);
int pageFromFinal = pageFrom;
for (int i = pageFrom; i <= limitToUse; i++)
{
if (!pagesCovered[i - 1])
{
break;
}
pageFromFinal = i + 1;
}
return pageFromFinal;
}
private static void markCovered(final boolean[] pagesCovered,
final int pageFrom,
final int pageTo)
{
for (int i = pageFrom; i <= pageTo; i++)
{
pagesCovered[i - 1] = true;
}
}
public boolean hasData()
{
return data != null;
}
public int getNumberOfPages()
{
Integer numberOfPages = this._numberOfPages;
if (numberOfPages == null)
{
numberOfPages = this._numberOfPages = computeNumberOfPages();
}
return numberOfPages;
}
private int computeNumberOfPages()
{
if (!hasData())
{
return 0;
}
PdfReader reader = null;
try
{
reader = new PdfReader(getData());
return reader.getNumberOfPages();
}
catch (final IOException e)
{
throw new AdempiereException("Cannot get number of pages for C_Printing_Queue_ID=" + printingQueueItemId.getRepoId(), e);
}
finally
{
if (reader != null)
{
try
{
reader.close();
} | catch (final Exception ignored)
{
}
}
}
}
public PrintingData onlyWithType(@NonNull final OutputType outputType)
{
final ImmutableList<PrintingSegment> filteredSegments = segments.stream()
.filter(segment -> segment.isMatchingOutputType(outputType))
.collect(ImmutableList.toImmutableList());
return toBuilder()
.clearSegments()
.segments(filteredSegments)
.adjustSegmentPageRanges(false)
.build();
}
public PrintingData onlyQueuedForExternalSystems()
{
final ImmutableList<PrintingSegment> filteredSegments = segments.stream()
.filter(PrintingSegment::isQueuedForExternalSystems)
.collect(ImmutableList.toImmutableList());
return toBuilder()
.clearSegments()
.segments(filteredSegments)
.adjustSegmentPageRanges(false)
.build();
}
public boolean hasSegments() {return !getSegments().isEmpty();}
public int getSegmentsCount() {return getSegments().size();}
public ImmutableSet<String> getPrinterNames()
{
return segments.stream()
.map(segment -> segment.getPrinter().getName())
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingData.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class PaymentTermConverter
{
@NonNull
public static PaymentTerm fromRecord(
@NonNull final I_C_PaymentTerm record,
@NonNull final List<I_C_PaymentTerm_Break> breakRecords,
@NonNull final List<I_C_PaySchedule> payScheduleRecords)
{
return PaymentTerm.builder()
.id(extractId(record))
.clientId(ClientId.ofRepoId(record.getAD_Client_ID()))
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.value(record.getValue())
.name(record.getName())
.description(record.getDescription())
.discount(Percent.of(record.getDiscount()))
.discount2(Percent.of(record.getDiscount2()))
.discountDays(record.getDiscountDays())
.discountDays2(record.getDiscountDays2())
.netDay(record.getNetDay())
.netDays(record.getNetDays())
.graceDays(record.getGraceDays())
.isDefault(record.isDefault())
.isActive(record.isActive())
.breaks(breakRecords.stream()
.filter(I_C_PaymentTerm_Break::isActive)
.map(PaymentTermBreakConverter::fromRecord)
.collect(ImmutableList.toImmutableList()))
.paySchedules(payScheduleRecords.stream()
.filter(I_C_PaySchedule::isActive)
.map(PayScheduleConverter::fromRecord)
.collect(ImmutableList.toImmutableList())) | .build();
}
@NonNull
public static PaymentTermId extractId(@NonNull final I_C_PaymentTerm record)
{
return PaymentTermId.ofRepoId(record.getC_PaymentTerm_ID());
}
public static void updateRecord(final I_C_PaymentTerm record, final @NonNull PaymentTerm paymentTerm)
{
record.setIsComplex(paymentTerm.isComplex());
record.setIsValid(paymentTerm.isValid());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\paymentterm\repository\impl\PaymentTermConverter.java | 2 |
请完成以下Java代码 | public void setAssetValueAmt (BigDecimal AssetValueAmt)
{
set_Value (COLUMNNAME_AssetValueAmt, AssetValueAmt);
}
/** Get Asset value.
@return Book Value of the asset
*/
public BigDecimal getAssetValueAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssetValueAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_C_InvoiceLine getC_InvoiceLine() throws RuntimeException
{
return (I_C_InvoiceLine)MTable.get(getCtx(), I_C_InvoiceLine.Table_Name)
.getPO(getC_InvoiceLine_ID(), get_TrxName()); }
/** Set Invoice Line.
@param C_InvoiceLine_ID
Invoice Detail Line
*/
public void setC_InvoiceLine_ID (int C_InvoiceLine_ID)
{ | if (C_InvoiceLine_ID < 1)
set_Value (COLUMNNAME_C_InvoiceLine_ID, null);
else
set_Value (COLUMNNAME_C_InvoiceLine_ID, Integer.valueOf(C_InvoiceLine_ID));
}
/** Get Invoice Line.
@return Invoice Detail Line
*/
public int getC_InvoiceLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_InvoiceLine_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_A_Asset_Retirement.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void exportUser(@Parameter(hidden = true) @RequestParam Map<String, Object> user, BladeUser bladeUser, HttpServletResponse response) {
QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user, User.class);
if (!SecureUtil.isAdministrator()) {
queryWrapper.lambda().eq(User::getTenantId, bladeUser.getTenantId());
}
queryWrapper.lambda().eq(User::getIsDeleted, BladeConstant.DB_NOT_DELETED);
List<UserExcel> list = userService.exportUser(queryWrapper);
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
String fileName = URLEncoder.encode("用户数据导出", StandardCharsets.UTF_8);
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
FastExcel.write(response.getOutputStream(), UserExcel.class).sheet("用户数据表").doWrite(list);
}
/**
* 导出模板
*/
@SneakyThrows
@GetMapping("export-template")
@ApiOperationSupport(order = 14)
@Operation(summary = "导出模板")
public void exportUser(HttpServletResponse response) {
List<UserExcel> list = new ArrayList<>();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
String fileName = URLEncoder.encode("用户数据模板", StandardCharsets.UTF_8);
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
FastExcel.write(response.getOutputStream(), UserExcel.class).sheet("用户数据表").doWrite(list);
} | /**
* 第三方注册用户
*/
@PostMapping("/register-guest")
@ApiOperationSupport(order = 15)
@Operation(summary = "第三方注册用户", description = "传入user")
public R registerGuest(User user, Long oauthId) {
return R.status(userService.registerGuest(user, oauthId));
}
/**
* 用户解锁
*/
@PostMapping("/unlock")
@ApiOperationSupport(order = 16)
@Operation(summary = "账号解锁")
@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
public R unlock(String userIds) {
if (StringUtil.isBlank(userIds)) {
return R.fail("请至少选择一个用户");
}
List<User> userList = userService.list(Wrappers.<User>lambdaQuery().in(User::getId, Func.toLongList(userIds)));
userList.forEach(user -> bladeRedis.del(CacheNames.tenantKey(user.getTenantId(), CacheNames.USER_FAIL_KEY, user.getAccount())));
return R.success("操作成功");
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\UserController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getParcelLabelNumber() {
return parcelLabelNumber;
}
/**
* Sets the value of the parcelLabelNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setParcelLabelNumber(String value) {
this.parcelLabelNumber = value;
}
/**
* Gets the value of the dpdReference property.
*
* @return
* possible object is
* {@link String } | *
*/
public String getDpdReference() {
return dpdReference;
}
/**
* Sets the value of the dpdReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDpdReference(String value) {
this.dpdReference = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ParcelInformationType.java | 2 |
请完成以下Java代码 | public int getHUCapacity()
{
if (X_M_HU_Item.ITEMTYPE_HUAggregate.equals(item.getItemType()))
{
return Quantity.QTY_INFINITE.intValue();
}
return Services.get(IHandlingUnitsBL.class).getPIItem(item).getQty().intValueExact();
}
@Override
public IProductStorage getProductStorage(final ProductId productId, final I_C_UOM uom, final ZonedDateTime date)
{
return new HUItemProductStorage(this, productId, uom, date);
}
@Override
public List<IProductStorage> getProductStorages(final ZonedDateTime date)
{
final List<I_M_HU_Item_Storage> storages = dao.retrieveItemStorages(item);
final List<IProductStorage> result = new ArrayList<>(storages.size());
for (final I_M_HU_Item_Storage storage : storages)
{
final ProductId productId = ProductId.ofRepoId(storage.getM_Product_ID());
final I_C_UOM uom = extractUOM(storage);
final HUItemProductStorage productStorage = new HUItemProductStorage(this, productId, uom, date);
result.add(productStorage);
}
return result;
}
private I_C_UOM extractUOM(final I_M_HU_Item_Storage storage)
{
return Services.get(IUOMDAO.class).getById(storage.getC_UOM_ID());
}
@Override
public boolean isEmpty()
{ | final List<I_M_HU_Item_Storage> storages = dao.retrieveItemStorages(item);
for (final I_M_HU_Item_Storage storage : storages)
{
if (!isEmpty(storage))
{
return false;
}
}
return true;
}
private boolean isEmpty(final I_M_HU_Item_Storage storage)
{
final BigDecimal qty = storage.getQty();
if (qty.signum() != 0)
{
return false;
}
return true;
}
@Override
public boolean isEmpty(final ProductId productId)
{
final I_M_HU_Item_Storage storage = dao.retrieveItemStorage(item, productId);
if (storage == null)
{
return true;
}
return isEmpty(storage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUItemStorage.java | 1 |
请完成以下Java代码 | public class NonBlockingServer {
private static final int PORT = 6000;
public static void main(String[] args) throws IOException {
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.bind(new InetSocketAddress(PORT));
serverChannel.configureBlocking(false);
Selector selector = Selector.open();
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Non-blocking Server listening on port " + PORT);
while (true) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iter = keys.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
iter.remove();
if (key.isAcceptable()) {
SocketChannel client = serverChannel.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
System.out.println("New client connected");
}
else if (key.isReadable()) {
SocketChannel client = (SocketChannel) key.channel();
try {
MyObject obj = receiveObject(client);
if (obj != null) {
System.out.println("Received: " + obj.getName() + ", " + obj.getAge());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
client.close(); | }
}
}
}
}
private static MyObject receiveObject(SocketChannel channel)
throws IOException, ClassNotFoundException {
ByteBuffer buffer = ByteBuffer.allocate(1024);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = channel.read(buffer)) > 0) {
buffer.flip();
byteStream.write(buffer.array(), 0, buffer.limit());
buffer.clear();
}
if (bytesRead == -1) {
channel.close();
return null;
}
byte[] bytes = byteStream.toByteArray();
try (ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
return (MyObject) objIn.readObject();
}
}
} | repos\tutorials-master\core-java-modules\core-java-nio-3\src\main\java\com\baeldung\socketchannel\NonBlockingServer.java | 1 |
请完成以下Java代码 | public void createDisposeCandidates(
@NonNull final HuId huId,
@NonNull final QtyRejectedReasonCode reasonCode)
{
trxManager.runInThreadInheritedTrx(() -> createDisposeCandidatesInTrx(huId, reasonCode));
}
public void createDisposeCandidatesInTrx(
@NonNull final HuId huId,
@NonNull final QtyRejectedReasonCode reasonCode)
{
final I_M_HU hu = handlingUnitsBL.getById(huId);
if (!huStatusBL.isQtyOnHand(hu.getHUStatus()))
{
throw new AdempiereException("Invalid HU status: " + hu.getHUStatus());
}
final ImmutableMap<ProductId, I_M_Inventory_Candidate> existingRecords = Maps.uniqueIndex(
queryByHuIdAndNotProcessed(huId).create().list(),
record -> ProductId.ofRepoId(record.getM_Product_ID()));
handlingUnitsBL.getStorageFactory()
.getStorage(hu)
.getProductStorages()
.forEach(huProductStorage -> {
final I_M_Inventory_Candidate existingRecord = existingRecords.get(huProductStorage.getProductId());
createOrUpdateDisposeCandidate(huProductStorage, reasonCode, existingRecord);
});
}
private void createOrUpdateDisposeCandidate(
@NonNull final IHUProductStorage huProductStorage,
@NonNull final QtyRejectedReasonCode reasonCode,
@Nullable final I_M_Inventory_Candidate existingRecord)
{
final I_M_Inventory_Candidate record;
if (existingRecord == null)
{ | record = InterfaceWrapperHelper.newInstance(I_M_Inventory_Candidate.class);
record.setM_HU_ID(huProductStorage.getHuId().getRepoId());
record.setM_Product_ID(huProductStorage.getProductId().getRepoId());
}
else
{
record = existingRecord;
}
final Quantity qty = huProductStorage.getQty();
record.setC_UOM_ID(qty.getUomId().getRepoId());
record.setQtyToDispose(qty.toBigDecimal());
record.setIsWholeHU(true);
record.setDisposeReason(reasonCode.getCode());
InterfaceWrapperHelper.save(record);
}
private IQueryBuilder<I_M_Inventory_Candidate> queryByHuIdAndNotProcessed(final @NonNull HuId huId)
{
return queryBL.createQueryBuilder(I_M_Inventory_Candidate.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_Inventory_Candidate.COLUMNNAME_M_HU_ID, huId)
.addEqualsFilter(I_M_Inventory_Candidate.COLUMNNAME_Processed, false);
}
public boolean isDisposalPending(final @NonNull HuId huId)
{
return queryByHuIdAndNotProcessed(huId)
.addNotNull(I_M_Inventory_Candidate.COLUMNNAME_DisposeReason)
.create()
.anyMatch();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inventory\InventoryCandidateService.java | 1 |
请完成以下Java代码 | public static LocalDateTime toLocalDateTime(final XMLGregorianCalendar xml)
{
if (xml == null)
{
return null;
}
return xml.toGregorianCalendar().toZonedDateTime().toLocalDateTime();
}
public static ZonedDateTime toZonedDateTime(final XMLGregorianCalendar xml)
{
if (xml == null)
{
return null;
}
return xml.toGregorianCalendar().toZonedDateTime();
} | public static java.util.Date toDate(final XMLGregorianCalendar xml)
{
return xml == null ? null : xml.toGregorianCalendar().getTime();
}
public static Timestamp toTimestamp(final XMLGregorianCalendar xmlGregorianCalendar)
{
final Date date = toDate(xmlGregorianCalendar);
if (date == null)
{
return null;
}
return new Timestamp(date.getTime());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\util\JAXBDateUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DictController {
private final DictService dictService;
private static final String ENTITY_NAME = "dict";
@ApiOperation("导出字典数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('dict:list')")
public void exportDict(HttpServletResponse response, DictQueryCriteria criteria) throws IOException {
dictService.download(dictService.queryAll(criteria), response);
}
@ApiOperation("查询字典")
@GetMapping(value = "/all")
@PreAuthorize("@el.check('dict:list')")
public ResponseEntity<List<DictDto>> queryAllDict(){
return new ResponseEntity<>(dictService.queryAll(new DictQueryCriteria()),HttpStatus.OK);
}
@ApiOperation("查询字典")
@GetMapping
@PreAuthorize("@el.check('dict:list')")
public ResponseEntity<PageResult<DictDto>> queryDict(DictQueryCriteria resources, Pageable pageable){
return new ResponseEntity<>(dictService.queryAll(resources,pageable),HttpStatus.OK);
}
@Log("新增字典")
@ApiOperation("新增字典")
@PostMapping | @PreAuthorize("@el.check('dict:add')")
public ResponseEntity<Object> createDict(@Validated @RequestBody Dict resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
dictService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改字典")
@ApiOperation("修改字典")
@PutMapping
@PreAuthorize("@el.check('dict:edit')")
public ResponseEntity<Object> updateDict(@Validated(Dict.Update.class) @RequestBody Dict resources){
dictService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除字典")
@ApiOperation("删除字典")
@DeleteMapping
@PreAuthorize("@el.check('dict:del')")
public ResponseEntity<Object> deleteDict(@RequestBody Set<Long> ids){
dictService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\DictController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean availableBalanceIsEnough(BigDecimal amount) {
return this.getAvailableBalance().compareTo(amount) >= 0;
}
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo == null ? null : accountNo.trim();
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public BigDecimal getUnbalance() {
return unbalance;
}
public void setUnbalance(BigDecimal unbalance) {
this.unbalance = unbalance;
}
public BigDecimal getSecurityMoney() {
return securityMoney;
}
public void setSecurityMoney(BigDecimal securityMoney) {
this.securityMoney = securityMoney;
}
public BigDecimal getTotalIncome() {
return totalIncome;
}
public void setTotalIncome(BigDecimal totalIncome) {
this.totalIncome = totalIncome;
}
public BigDecimal getTotalExpend() {
return totalExpend;
} | public void setTotalExpend(BigDecimal totalExpend) {
this.totalExpend = totalExpend;
}
public BigDecimal getTodayIncome() {
return todayIncome;
}
public void setTodayIncome(BigDecimal todayIncome) {
this.todayIncome = todayIncome;
}
public BigDecimal getTodayExpend() {
return todayExpend;
}
public void setTodayExpend(BigDecimal todayExpend) {
this.todayExpend = todayExpend;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType == null ? null : accountType.trim();
}
public BigDecimal getSettAmount() {
return settAmount;
}
public void setSettAmount(BigDecimal settAmount) {
this.settAmount = settAmount;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpAccount.java | 2 |
请完成以下Java代码 | protected I_M_Material_Tracking getMaterialTrackingFromDocumentLineASI(final DocumentLineType documentLine)
{
final IMaterialTrackingAttributeBL materialTrackingAttributeBL = Services.get(IMaterialTrackingAttributeBL.class);
final AttributeSetInstanceId asiId = getM_AttributeSetInstance(documentLine);
final I_M_Material_Tracking materialTracking = materialTrackingAttributeBL.getMaterialTrackingOrNull(asiId);
return materialTracking;
}
/**
*
* @param document
* @return true if given document is eligible to be linked to a material tracking via a new <code>M_Material_Tracking_Ref</code> record.
*/
protected abstract boolean isEligibleForMaterialTracking(DocumentType document); | /**
*
* @param document
* @return document lines
*/
protected abstract List<DocumentLineType> retrieveDocumentLines(final DocumentType document);
/**
*
* @param documentLine
* @return ASI from document line
*/
protected abstract AttributeSetInstanceId getM_AttributeSetInstance(final DocumentLineType documentLine);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\validator\MaterialTrackableDocumentByASIInterceptor.java | 1 |
请完成以下Java代码 | public class ConfigFileContext implements IContext
{
private final Properties properties;
public ConfigFileContext()
{
String configFilename = System.getProperty("config");
// Fallback: use config.properties
if (configFilename == null || configFilename.trim().isEmpty())
{
configFilename = new File(".", "config.properties").getAbsolutePath();
}
properties = new Properties();
//
// Load file
InputStream in = null;
try
{
in = new FileInputStream(configFilename);
properties.load(in);
}
catch (final IOException e)
{
throw new RuntimeException("Failed loading config file: " + configFilename + ", start client with -Dconfig=<filename> so specify a particualr file", e);
}
finally | {
Util.close(in);
in = null;
}
}
@Override
public String getProperty(final String name)
{
final String property = properties.getProperty(name);
if (property != null)
{
// we don't want things to be screwed up by trailing white spaces in our properties file, so we trim.
// further reading: https://docs.oracle.com/cd/E23095_01/Platform.93/ATGProgGuide/html/s0204propertiesfileformat01.html
// "The property value is generally terminated by the end of the line. White space following the property value is not ignored, and is treated as part of the property value."
return property.trim();
}
return property;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\ConfigFileContext.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
} | public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-runtime\src\main\java\com\baeldung\sampleapp\web\dto\HeavyResource.java | 1 |
请完成以下Java代码 | public Task getTask() {
return associationManager.getTask();
}
/**
* Returns the currently associated execution or 'null'
*/
public Execution getExecution() {
return associationManager.getExecution();
}
/**
* @see #getExecution()
*/
public String getExecutionId() {
Execution e = getExecution();
return e != null ? e.getId() : null;
}
/**
* Returns the {@link ProcessInstance} currently associated or 'null'
*
* @throws FlowableCdiException if no {@link Execution} is associated. Use {@link #isAssociated()} to check whether an association exists.
*/
public ProcessInstance getProcessInstance() {
Execution execution = getExecution();
if (execution != null && !(execution.getProcessInstanceId().equals(execution.getId()))) {
return processEngine.getRuntimeService().createProcessInstanceQuery().processInstanceId(execution.getProcessInstanceId()).singleResult();
}
return (ProcessInstance) execution;
}
// internal implementation
// //////////////////////////////////////////////////////////
protected void assertAssociated() {
if (associationManager.getExecution() == null) {
throw new FlowableCdiException("No execution associated. Call businessProcess.associateExecutionById() or businessProcess.startTask() first."); | }
}
protected void assertTaskAssociated() {
if (associationManager.getTask() == null) {
throw new FlowableCdiException("No task associated. Call businessProcess.startTask() first.");
}
}
protected Map<String, Object> getCachedVariables() {
return associationManager.getCachedVariables();
}
protected Map<String, Object> getAndClearCachedVariables() {
Map<String, Object> beanStore = getCachedVariables();
Map<String, Object> copy = new HashMap<>(beanStore);
beanStore.clear();
return copy;
}
} | repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\BusinessProcess.java | 1 |
请完成以下Java代码 | public OutboundEventProcessingPipelineBuilder eventProcessingPipeline() {
return new OutboundEventProcessingPipelineBuilderImpl(outboundChannelDefinitionBuilder, kafkaChannel);
}
}
public static class OutboundEventProcessingPipelineBuilderImpl implements OutboundEventProcessingPipelineBuilder {
protected OutboundChannelDefinitionBuilderImpl outboundChannelDefinitionBuilder;
protected OutboundChannelModel outboundChannel;
public OutboundEventProcessingPipelineBuilderImpl(OutboundChannelDefinitionBuilderImpl outboundChannelDefinitionBuilder,
OutboundChannelModel outboundChannel) {
this.outboundChannelDefinitionBuilder = outboundChannelDefinitionBuilder;
this.outboundChannel = outboundChannel;
}
@Override
public OutboundChannelModelBuilder jsonSerializer() {
this.outboundChannel.setSerializerType("json");
return outboundChannelDefinitionBuilder;
}
@Override
public OutboundChannelModelBuilder xmlSerializer() {
this.outboundChannel.setSerializerType("xml");
return outboundChannelDefinitionBuilder;
} | @Override
public OutboundChannelModelBuilder delegateExpressionSerializer(String delegateExpression) {
this.outboundChannel.setSerializerType("expression");
this.outboundChannel.setSerializerDelegateExpression(delegateExpression);
return outboundChannelDefinitionBuilder;
}
@Override
public OutboundChannelModelBuilder eventProcessingPipeline(String delegateExpression) {
this.outboundChannel.setPipelineDelegateExpression(delegateExpression);
return outboundChannelDefinitionBuilder;
}
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\model\OutboundChannelDefinitionBuilderImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProductService
{
@NonNull private final IProductBL productBL = Services.get(IProductBL.class);
@NonNull private final IAttributeSetInstanceBL attributeSetInstanceBL = Services.get(IAttributeSetInstanceBL.class);
@NonNull final IAttributeDAO attributeDAO = Services.get(IAttributeDAO.class);
public boolean isValidEAN13Product(final @NonNull EAN13 ean13, @NonNull final ProductId lineProductId)
{
return productBL.isValidEAN13Product(ean13, lineProductId);
}
public ProductsLoadingCache newProductsLoadingCache()
{
return ProductsLoadingCache.builder()
.productBL(productBL)
.build();
}
public ASILoadingCache newASILoadingCache()
{
return ASILoadingCache.builder()
.attributeSetInstanceBL(attributeSetInstanceBL)
.build();
}
public AttributeSetInstanceId createASI(@NonNull ProductId productId, @NonNull final Map<AttributeCode, String> attributes)
{
if (attributes.isEmpty()) | {
return AttributeSetInstanceId.NONE;
}
return attributeSetInstanceBL.addAttributes(
AddAttributesRequest.builder()
.productId(productId)
.attributeInstanceBasicInfos(attributes.entrySet()
.stream()
.map(entry -> CreateAttributeInstanceReq.builder()
.attributeCode(entry.getKey())
.value(entry.getValue())
.build())
.collect(Collectors.toList()))
.build()
);
}
public @NonNull Attribute getAttribute(final AttributeCode attributeCode)
{
return attributeDAO.getAttributeByCode(attributeCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\deps\products\ProductService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | boolean isAlreadyIncluded(@NonNull final AddToResultGroupRequest request)
{
// assume it's matching
// if (!isMatchting(request))
// {
// return false; // only matching requests were ever included
// }
if (request.getBpartner().isSpecificBPartner())
{
return false;
}
final ArrayKey key = request.computeKey();
if (!includedRequestKeys.containsKey(key))
{
return false;
}
final DateAndSeqNo dateAndSeq = includedRequestKeys.get(key); | // if our bpartnerless request is "earlier" than the latest request (with same key) that we already added, then the quantity of the bpartnerless request is contained within that other request which we already added
return DateAndSeqNo.ofAddToResultGroupRequest(request).isBefore(dateAndSeq);
}
public void addQty(@NonNull final AddToResultGroupRequest request)
{
qty = qty.add(request.getQty());
final ArrayKey computeKey = request.computeKey();
final DateAndSeqNo oldTimeAndSeqNo = includedRequestKeys.get(computeKey);
final DateAndSeqNo latest = DateAndSeqNo.ofAddToResultGroupRequest(request).max(oldTimeAndSeqNo);
includedRequestKeys.put(computeKey, latest);
}
boolean isZeroQty()
{
return getQty().signum() == 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\atp\AvailableToPromiseResultGroupBuilder.java | 2 |
请完成以下Java代码 | private void updateFlatrateTermsPartner()
{
final List<I_C_Flatrate_Term> flatrateTermsToChange = getFlatrateTermsToChange();
flatrateTermsToChange.forEach(this::updateFlatrateTermPartner);
}
private void updateFlatrateTermPartner(final I_C_Flatrate_Term term)
{
final ImmutableList<I_C_Flatrate_Term> nextTerms = flatrateBL.retrieveNextFlatrateTerms(term);
updateFlatrateTermBillBPartner(term);
nextTerms.forEach(this::updateFlatrateTermBillBPartner);
}
private void updateFlatrateTermBillBPartner(final I_C_Flatrate_Term term)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoId(p_billBPartnerId);
final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoId(p_billBPartnerId, p_billLocationId); | final BPartnerContactId bPartnerContactId = BPartnerContactId.ofRepoIdOrNull(p_billBPartnerId, p_billUserId);
final boolean termHasInvoices = C_Flatrate_Term_Change_ProcessHelper.termHasInvoices(term);
final FlatrateTermBillPartnerRequest request = FlatrateTermBillPartnerRequest.builder()
.flatrateTermId(FlatrateTermId.ofRepoId(term.getC_Flatrate_Term_ID()))
.billBPartnerId(bPartnerId)
.billLocationId(bPartnerLocationId)
.billUserId(bPartnerContactId)
.termHasInvoices(termHasInvoices)
.build();
flatrateBL.updateFlatrateTermBillBPartner(request);
}
protected abstract ImmutableList<I_C_Flatrate_Term> getFlatrateTermsToChange();
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_Change_BillPartner_Base.java | 1 |
请完成以下Java代码 | public static class War implements Layout {
private static final Map<LibraryScope, String> SCOPE_LOCATION;
static {
Map<LibraryScope, String> locations = new HashMap<>();
locations.put(LibraryScope.COMPILE, "WEB-INF/lib/");
locations.put(LibraryScope.CUSTOM, "WEB-INF/lib/");
locations.put(LibraryScope.RUNTIME, "WEB-INF/lib/");
locations.put(LibraryScope.PROVIDED, "WEB-INF/lib-provided/");
SCOPE_LOCATION = Collections.unmodifiableMap(locations);
}
@Override
public String getLauncherClassName() {
return "org.springframework.boot.loader.launch.WarLauncher";
}
@Override
public @Nullable String getLibraryLocation(String libraryName, @Nullable LibraryScope scope) {
return SCOPE_LOCATION.get(scope);
}
@Override
public String getClassesLocation() {
return "WEB-INF/classes/";
} | @Override
public String getClasspathIndexFileLocation() {
return "WEB-INF/classpath.idx";
}
@Override
public String getLayersIndexFileLocation() {
return "WEB-INF/layers.idx";
}
@Override
public boolean isExecutable() {
return true;
}
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\Layouts.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ServerRunner implements CommandLineRunner {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final SocketIOServer server;
// 下载地址,版本2.1.1:https://bitbucket.org/ariya/phantomjs/downloads/
private static final String PHANTOM_PATH = "phantomjs";
@Resource
private MyProperties p;
@Autowired
public ServerRunner(SocketIOServer server) {
this.server = server;
}
@Override
public void run(String... args) {
logger.info("ServerRunner 开始启动啦...");
server.start();
logger.info("SocketServer 启动成功!");
logger.info("点击打开首页: http://localhost:9075");
// 启动socker服务器后,通过phantomjs启动浏览器网页客户端 | // openHtml(p.getLoadJs());
// logger.info("Phantomjs 启动成功!");
}
// private void openHtml(String loadJs) {
// String cmdStr = PHANTOM_PATH + " " + loadJs + " " + "http://localhost:9075";
// logger.info("cmdStr=" + cmdStr);
// Runtime rt = Runtime.getRuntime();
// try {
// rt.exec(cmdStr);
// } catch (IOException e) {
// logger.error("执行phantomjs的指令失败!PhantomJs详情参考这里:http://phantomjs.org", e);
// }
// }
} | repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\echarts\common\ServerRunner.java | 2 |
请完成以下Java代码 | public I_C_BP_BankAccount retrieveSEPABankAccount(I_C_BPartner bPartner)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(bPartner);
final String trxName = InterfaceWrapperHelper.getTrxName(bPartner);
final String whereClause = I_C_BP_BankAccount.COLUMNNAME_C_BPartner_ID + "=?";
final List<Object> params = new ArrayList<>();
params.add(bPartner.getC_BPartner_ID());
return new Query(ctx, I_C_BP_BankAccount.Table_Name, whereClause, trxName)
.setParameters(params)
.setOrderBy(I_C_BP_BankAccount.COLUMNNAME_IsDefault + " DESC")
.setOnlyActiveRecords(true)
.first(I_C_BP_BankAccount.class);
}
@Override
public List<I_SEPA_Export_Line> retrieveLines(@NonNull final I_SEPA_Export doc)
{
return queryBL.createQueryBuilder(I_SEPA_Export_Line.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_SEPA_Export_Line.COLUMNNAME_IsError, false)
.addEqualsFilter(I_SEPA_Export_Line.COLUMNNAME_SEPA_Export_ID, doc.getSEPA_Export_ID())
.orderBy()
.addColumn(I_SEPA_Export_Line.COLUMNNAME_C_Currency_ID)
.addColumn(I_SEPA_Export_Line.COLUMNNAME_SEPA_Export_Line_ID).endOrderBy()
.create() | .list();
}
@Override
public List<I_SEPA_Export_Line> retrieveLinesChangeRule(Properties ctx, String trxName)
{
//
// Placeholder for future functionality.
return Collections.emptyList();
}
@NonNull
public List<I_SEPA_Export_Line_Ref> retrieveLineReferences(@NonNull final I_SEPA_Export_Line line)
{
return toLineRefSqlQuery(line)
.list();
}
@NonNull
private IQuery<I_SEPA_Export_Line_Ref> toLineRefSqlQuery(@NonNull final I_SEPA_Export_Line line)
{
return queryBL.createQueryBuilder(I_SEPA_Export_Line_Ref.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_SEPA_Export_Line_Ref.COLUMNNAME_SEPA_Export_Line_ID, line.getSEPA_Export_Line_ID())
.addEqualsFilter(I_SEPA_Export_Line_Ref.COLUMNNAME_SEPA_Export_ID, line.getSEPA_Export_ID())
.create();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\SEPADocumentDAO.java | 1 |
请完成以下Java代码 | public OAuth2 tokenEndpointUri(String uri) {
this.oAuth2Settings.tokenEndpointUri(uri);
return this;
}
public OAuth2 clientId(String clientId) {
this.oAuth2Settings.clientId(clientId);
return this;
}
public OAuth2 clientSecret(String clientSecret) {
this.oAuth2Settings.clientSecret(clientSecret);
return this;
}
public OAuth2 grantType(String grantType) {
this.oAuth2Settings.grantType(grantType);
return this;
}
public OAuth2 parameter(String name, String value) {
this.oAuth2Settings.parameter(name, value);
return this;
}
public OAuth2 shared(boolean shared) {
this.oAuth2Settings.shared(shared);
return this;
}
public OAuth2 sslContext(SSLContext sslContext) {
this.oAuth2Settings.tls().sslContext(sslContext);
return this;
}
}
public static final class Recovery { | private final ConnectionBuilder.RecoveryConfiguration recoveryConfiguration;
private Recovery(ConnectionBuilder.RecoveryConfiguration recoveryConfiguration) {
this.recoveryConfiguration = recoveryConfiguration;
}
public Recovery activated(boolean activated) {
this.recoveryConfiguration.activated(activated);
return this;
}
public Recovery backOffDelayPolicy(BackOffDelayPolicy backOffDelayPolicy) {
this.recoveryConfiguration.backOffDelayPolicy(backOffDelayPolicy);
return this;
}
public Recovery topology(boolean activated) {
this.recoveryConfiguration.topology(activated);
return this;
}
}
} | repos\spring-amqp-main\spring-rabbitmq-client\src\main\java\org\springframework\amqp\rabbitmq\client\SingleAmqpConnectionFactory.java | 1 |
请完成以下Java代码 | public DeliveryOrder save(final DeliveryOrder order)
{
final I_GO_DeliveryOrder orderPO = toDeliveryOrderPO(order);
InterfaceWrapperHelper.save(orderPO);
saveAssignedPackageIds(orderPO.getGO_DeliveryOrder_ID(), GOUtils.getSingleDeliveryPosition(order).getPackageIds());
return order.toBuilder()
.id(DeliveryOrderId.ofRepoId(orderPO.getGO_DeliveryOrder_ID()))
.build();
}
private I_GO_DeliveryOrder retrieveGODeliveryOrderPOById(@NonNull final OrderId orderId)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_GO_DeliveryOrder.class)
.addEqualsFilter(I_GO_DeliveryOrder.COLUMN_GO_AX4Number, orderId.getOrderIdAsString())
.create()
.firstOnly(I_GO_DeliveryOrder.class);
}
private void saveAssignedPackageIds(final int deliveryOrderRepoId, final Set<PackageId> packageIds)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final Set<PackageId> prevPackageIds = retrieveGODeliveryOrderPackageIds(deliveryOrderRepoId);
final Set<PackageId> packageIdsToDelete = Sets.difference(prevPackageIds, packageIds);
if (!packageIdsToDelete.isEmpty())
{
queryBL.createQueryBuilder(I_GO_DeliveryOrder_Package.class)
.addEqualsFilter(I_GO_DeliveryOrder_Package.COLUMN_GO_DeliveryOrder_ID, deliveryOrderRepoId)
.addInArrayFilter(I_GO_DeliveryOrder_Package.COLUMN_M_Package_ID, packageIdsToDelete)
.create()
.delete();
}
final Set<PackageId> packageIdsToAdd = Sets.difference(packageIds, prevPackageIds);
packageIdsToAdd.forEach(packageId -> createGODeliveryOrderPackage(deliveryOrderRepoId, packageId.getRepoId()));
}
private Set<PackageId> retrieveGODeliveryOrderPackageIds(final int deliveryOrderRepoId)
{
if (deliveryOrderRepoId <= 0)
{
return ImmutableSet.of(); | }
final List<Integer> mpackageIds = Services.get(IQueryBL.class)
.createQueryBuilder(I_GO_DeliveryOrder_Package.class)
.addEqualsFilter(I_GO_DeliveryOrder_Package.COLUMN_GO_DeliveryOrder_ID, deliveryOrderRepoId)
.create()
.listDistinct(I_GO_DeliveryOrder_Package.COLUMNNAME_M_Package_ID, Integer.class);
final ImmutableSet<PackageId> packageIds = mpackageIds.stream()
.map(PackageId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
return packageIds;
}
private void createGODeliveryOrderPackage(final int deliveryOrderRepoId, final int packageId)
{
final I_GO_DeliveryOrder_Package orderPackagePO = InterfaceWrapperHelper.newInstance(I_GO_DeliveryOrder_Package.class);
orderPackagePO.setGO_DeliveryOrder_ID(deliveryOrderRepoId);
orderPackagePO.setM_Package_ID(packageId);
InterfaceWrapperHelper.save(orderPackagePO);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java\de\metas\shipper\gateway\go\GODeliveryOrderRepository.java | 1 |
请完成以下Java代码 | public void insertElementAt(Object obj, int index)
{
}
@Override
public void addElement(Object obj)
{
}
};
public MutableComboBoxModelProxy()
{
super();
}
public MutableComboBoxModelProxy(final MutableComboBoxModel delegate)
{
super();
setDelegate(delegate);
}
private final MutableComboBoxModel getDelegateToUse()
{
if (delegate == null)
{
return COMBOBOXMODEL_NULL;
}
return delegate;
}
public void setDelegate(final MutableComboBoxModel delegateNew)
{
if (this.delegate == delegateNew)
{
// nothing changed
return;
}
// Unregister listeners on old lookup
final MutableComboBoxModel delegateOld = this.delegate;
if (delegateOld != null)
{
for (ListDataListener l : listenerList.getListeners(ListDataListener.class))
{
delegateOld.removeListDataListener(l);
}
}
//
// Setup new Lookup
this.delegate = delegateNew;
// Register listeners on new lookup
if (this.delegate != null)
{
for (ListDataListener l : listenerList.getListeners(ListDataListener.class))
{
this.delegate.addListDataListener(l);
}
}
}
@Override
public void addListDataListener(final ListDataListener l)
{
listenerList.add(ListDataListener.class, l);
if (delegate != null)
{
delegate.addListDataListener(l);
}
}
@Override
public void removeListDataListener(final ListDataListener l)
{
listenerList.remove(ListDataListener.class, l);
if (delegate != null)
{
delegate.removeListDataListener(l);
}
} | @Override
public int getSize()
{
return getDelegateToUse().getSize();
}
@Override
public Object getElementAt(int index)
{
return getDelegateToUse().getElementAt(index);
}
@Override
public void setSelectedItem(Object anItem)
{
getDelegateToUse().setSelectedItem(anItem);
}
@Override
public Object getSelectedItem()
{
return getDelegateToUse().getSelectedItem();
}
@Override
public void addElement(Object obj)
{
getDelegateToUse().addElement(obj);
}
@Override
public void removeElement(Object obj)
{
getDelegateToUse().removeElement(obj);
}
@Override
public void insertElementAt(Object obj, int index)
{
getDelegateToUse().insertElementAt(obj, index);
}
@Override
public void removeElementAt(int index)
{
getDelegateToUse().removeElementAt(index);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\MutableComboBoxModelProxy.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getNameOfDriver() {
return nameOfDriver;
}
/**
* Sets the value of the nameOfDriver property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNameOfDriver(String value) {
this.nameOfDriver = value;
}
/**
* The license plate number of the vehicle performing the delivery.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransportVehicleLicenseNumber() {
return transportVehicleLicenseNumber;
}
/**
* Sets the value of the transportVehicleLicenseNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/ | public void setTransportVehicleLicenseNumber(String value) {
this.transportVehicleLicenseNumber = value;
}
/**
* Gets the value of the deliveryDetailsExtension property.
*
* @return
* possible object is
* {@link DeliveryDetailsExtensionType }
*
*/
public DeliveryDetailsExtensionType getDeliveryDetailsExtension() {
return deliveryDetailsExtension;
}
/**
* Sets the value of the deliveryDetailsExtension property.
*
* @param value
* allowed object is
* {@link DeliveryDetailsExtensionType }
*
*/
public void setDeliveryDetailsExtension(DeliveryDetailsExtensionType value) {
this.deliveryDetailsExtension = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DeliveryDetailsType.java | 2 |
请完成以下Java代码 | public <T> T getInstance(final String name, final Class<T> interfaceClazz)
{
final Object value = get(name);
if (value == null)
{
throw new RuntimeException("No class of " + interfaceClazz + " found for property " + name);
}
else if (value instanceof String)
{
final String classname = value.toString();
return Util.getInstance(classname, interfaceClazz);
}
else if (value instanceof Class)
{
final Class<?> clazz = (Class<?>)value;
if (interfaceClazz.isAssignableFrom(clazz))
{
try
{
@SuppressWarnings("unchecked")
final T obj = (T)clazz.newInstance();
return obj;
}
catch (final Exception e)
{
throw new RuntimeException(e);
}
}
else
{
throw new RuntimeException("Invalid object " + value + " for property " + name + " (expected class: " + interfaceClazz + ")");
}
}
else if (interfaceClazz.isAssignableFrom(value.getClass()))
{
@SuppressWarnings("unchecked")
final T obj = (T)value;
return obj;
}
else
{
throw new RuntimeException("Invalid object " + value + " for property " + name + " (expected class: " + interfaceClazz + ")");
} | }
public <T> T get(final String name)
{
if (props.containsKey(name))
{
@SuppressWarnings("unchecked")
final T value = (T)props.get(name);
return value;
}
// Check other sources
for (final IContext source : sources)
{
final String valueStr = source.getProperty(name);
if (valueStr != null)
{
@SuppressWarnings("unchecked")
final T value = (T)valueStr;
return value;
}
}
// Check defaults
@SuppressWarnings("unchecked")
final T value = (T)defaults.get(name);
return value;
}
@Override
public String toString()
{
return "Context["
+ "sources=" + sources
+ ", properties=" + props
+ ", defaults=" + defaults
+ "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\Context.java | 1 |
请完成以下Java代码 | public static PaymentReservationStatus ofCode(@NonNull final String code)
{
PaymentReservationStatus type = typesByCode.get(code);
if (type == null)
{
throw new AdempiereException("No " + PaymentReservationStatus.class + " found for code: " + code);
}
return type;
}
private static final ImmutableMap<String, PaymentReservationStatus> typesByCode = ReferenceListAwareEnums.indexByCode(values());
public boolean isCompleted()
{
return this == COMPLETED;
}
public boolean isVoided()
{
return this == VOIDED;
}
public boolean isApprovedByPayer()
{
return this == APPROVED_BY_PAYER;
}
public void assertApprovedByPayer()
{
assertEquals(APPROVED_BY_PAYER);
}
public void assertCompleted()
{
assertEquals(COMPLETED);
} | public void assertEquals(@NonNull final PaymentReservationStatus expected)
{
if (!this.equals(expected))
{
throw new AdempiereException("Invalid reservation status. Expected " + expected + " but got " + this);
}
}
public boolean isWaitingForPayerApproval()
{
return this == WAITING_PAYER_APPROVAL;
}
public void assertWaitingForPayerApproval()
{
assertEquals(WAITING_PAYER_APPROVAL);
}
public boolean isWaitingToComplete()
{
return isWaitingForPayerApproval()
|| isApprovedByPayer();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\reservation\PaymentReservationStatus.java | 1 |
请完成以下Java代码 | public class AuthorizeTokenFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(AuthorizeTokenFilter.class);
private final OAuth2AuthorizedClientManager clientManager;
public AuthorizeTokenFilter(OAuth2AuthorizedClientManager clientManager) {
this.clientManager = clientManager;
}
@Override
protected void doFilterInternal(@Nonnull HttpServletRequest request,
@Nonnull HttpServletResponse response,
@Nonnull FilterChain filterChain) throws ServletException, IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof OAuth2AuthenticationToken) {
var token = (OAuth2AuthenticationToken) authentication;
authorizeToken(token, request, response);
}
filterChain.doFilter(request, response);
}
protected boolean hasTokenExpired(OAuth2Token token) {
return token.getExpiresAt() == null || ClockUtil.now().after(Date.from(token.getExpiresAt()));
}
protected void clearContext(HttpServletRequest request) {
SecurityContextHolder.clearContext();
try {
request.getSession().invalidate();
} catch (Exception ignored) {
}
}
protected void authorizeToken(OAuth2AuthenticationToken token,
HttpServletRequest request,
HttpServletResponse response) {
// @formatter:off
var authRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(token.getAuthorizedClientRegistrationId())
.principal(token)
.attributes(attrs -> {
attrs.put(HttpServletRequest.class.getName(), request); | attrs.put(HttpServletResponse.class.getName(), response);
}).build();
// @formatter:on
var name = token.getName();
try {
var res = clientManager.authorize(authRequest);
if (res == null || hasTokenExpired(res.getAccessToken())) {
logger.warn("Authorize failed for '{}': could not re-authorize expired access token", name);
clearContext(request);
} else {
logger.debug("Authorize successful for '{}', access token expiry: {}", name, res.getAccessToken().getExpiresAt());
}
} catch (OAuth2AuthorizationException e) {
logger.warn("Authorize failed for '{}': {}", name, e.getMessage());
clearContext(request);
}
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\impl\AuthorizeTokenFilter.java | 1 |
请完成以下Java代码 | public String toString() {
if (isCaseInstanceExecution()) {
return "CaseInstance[" + getToStringIdentity() + "]";
} else {
return "CmmnExecution["+getToStringIdentity() + "]";
}
}
protected String getToStringIdentity() {
return Integer.toString(System.identityHashCode(this));
}
public String getId() {
return String.valueOf(System.identityHashCode(this));
}
public ProcessEngineServices getProcessEngineServices() { | throw LOG.unsupportedTransientOperationException(ProcessEngineServicesAware.class.getName());
}
public ProcessEngine getProcessEngine() {
throw LOG.unsupportedTransientOperationException(ProcessEngineServicesAware.class.getName());
}
public CmmnElement getCmmnModelElementInstance() {
throw LOG.unsupportedTransientOperationException(CmmnModelExecutionContext.class.getName());
}
public CmmnModelInstance getCmmnModelInstance() {
throw LOG.unsupportedTransientOperationException(CmmnModelExecutionContext.class.getName());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\execution\CaseExecutionImpl.java | 1 |
请完成以下Java代码 | default LocalDate getPreviousBusinessDay(@NonNull final LocalDate date, final int targetWorkingDays)
{
Check.assumeGreaterOrEqualToZero(targetWorkingDays, "targetWorkingDays");
LocalDate currentDate = date;
// Skip until we find the first business day
while (!isBusinessDay(currentDate))
{
currentDate = currentDate.minusDays(1);
}
if (targetWorkingDays == 0)
{
return currentDate;
}
int workingDays = 0;
while (true) | {
currentDate = currentDate.minusDays(1);
final boolean isBusinessDay = isBusinessDay(currentDate);
if (isBusinessDay)
{
workingDays++;
}
if (workingDays >= targetWorkingDays && isBusinessDay)
{
return currentDate;
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\calendar\IBusinessDayMatcher.java | 1 |
请完成以下Java代码 | public void setField (GridField mField)
{
m_mField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField() {
return m_mField;
}
/**
* Feature Request [1707462]
* Set VFormat
* @param strMask mask
* @author fer_luck
*/
public void setVFormat (String strMask)
{
m_VFormat = strMask;
//Get the actual caret from the field, if there's no
//caret then just catch the exception and continue
//creating the new caret.
try{
CaretListener [] cl = this.getCaretListeners();
this.removeCaretListener(cl[0]);
} catch(ClassCastException ex ){
log.debug("VString.setVFormat - No caret Listeners");
}
//hengsin: [ adempiere-Bugs-1891037 ], preserve current data before change of format
String s = getText();
setDocument(new MDocString(m_VFormat, m_fieldLength, this));
setText(s);
} // setVFormat
/**
* Set Text (optionally obscured)
* @param text text
*/
@Override
public void setText (String text)
{
if (m_obscure != null && !m_infocus)
{
super.setFont(m_obscureFont);
super.setText (m_obscure.getObscuredValue(text));
super.setForeground(Color.gray);
}
else
{
if (m_stdFont != null)
{
super.setFont(m_stdFont);
super.setForeground(AdempierePLAF.getTextColor_Normal());
}
super.setText (text);
}
} // setText
/**
* Get Text (clear)
* @return text
*/
@Override
public String getText ()
{
String text = super.getText();
if (m_obscure != null && text != null && text.length() > 0)
{
if (text.equals(m_obscure.getObscuredValue()))
text = m_obscure.getClearValue(); | }
return text;
} // getText
/**
* Feature Request [1707462]
* Get VFormat
* @return strMask mask
* @author fer_luck
*/
public String getVFormat ()
{
return this.m_VFormat;
} // getVFormat
/**
* Focus Gained.
* Enabled with Obscure
* @param e event
*/
@Override
public void focusGained (FocusEvent e)
{
m_infocus = true;
setText(getText()); // clear
} // focusGained
/**
* Focus Lost
* Enabled with Obscure
* @param e event
*/
@Override
public void focusLost (FocusEvent e)
{
m_infocus = false;
setText(getText()); // obscure
} // focus Lost
@Override
public void setFont(Font f) {
super.setFont(f);
m_stdFont = f;
m_obscureFont = new Font("SansSerif", Font.ITALIC, m_stdFont.getSize());
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
} // VString | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VString.java | 1 |
请完成以下Java代码 | private void assertQtyToIssueToleranceIsRespected_LowerBound(final Quantity qtyIssuedOrReceivedActual)
{
if (issuingToleranceSpec == null)
{
return;
}
final Quantity qtyIssuedOrReceivedActualMin = issuingToleranceSpec.subtractFrom(qtyRequired);
if (qtyIssuedOrReceivedActual.compareTo(qtyIssuedOrReceivedActualMin) < 0)
{
final ITranslatableString qtyStr = TranslatableStrings.builder()
.appendQty(qtyIssuedOrReceivedActualMin.toBigDecimal(), qtyIssuedOrReceivedActualMin.getUOMSymbol())
.append(" (")
.appendQty(qtyRequired.toBigDecimal(), qtyRequired.getUOMSymbol())
.append(" - ")
.append(issuingToleranceSpec.toTranslatableString())
.append(")")
.build();
throw new AdempiereException(MSG_CannotIssueLessThan, qtyStr)
.markAsUserValidationError();
}
}
private void assertQtyToIssueToleranceIsRespected_UpperBound(final Quantity qtyIssuedOrReceivedActual)
{
if (issuingToleranceSpec == null)
{
return;
}
final Quantity qtyIssuedOrReceivedActualMax = issuingToleranceSpec.addTo(qtyRequired);
if (qtyIssuedOrReceivedActual.compareTo(qtyIssuedOrReceivedActualMax) > 0)
{
final ITranslatableString qtyStr = TranslatableStrings.builder()
.appendQty(qtyIssuedOrReceivedActualMax.toBigDecimal(), qtyIssuedOrReceivedActualMax.getUOMSymbol())
.append(" (")
.appendQty(qtyRequired.toBigDecimal(), qtyRequired.getUOMSymbol())
.append(" + ")
.append(issuingToleranceSpec.toTranslatableString())
.append(")")
.build();
throw new AdempiereException(MSG_CannotIssueMoreThan, qtyStr)
.markAsUserValidationError(); | }
}
@NonNull
public OrderBOMLineQuantities convertQuantities(@NonNull final UnaryOperator<Quantity> converter)
{
return toBuilder()
.qtyRequired(converter.apply(qtyRequired))
.qtyRequiredBeforeClose(converter.apply(qtyRequiredBeforeClose))
.qtyIssuedOrReceived(converter.apply(qtyIssuedOrReceived))
.qtyIssuedOrReceivedActual(converter.apply(qtyIssuedOrReceivedActual))
.qtyReject(converter.apply(qtyReject))
.qtyScrap(converter.apply(qtyScrap))
.qtyUsageVariance(converter.apply(qtyUsageVariance))
.qtyPost(converter.apply(qtyPost))
.qtyReserved(converter.apply(qtyReserved))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\OrderBOMLineQuantities.java | 1 |
请完成以下Java代码 | private static CarrierProduct fromProductRecord(@NotNull final I_Carrier_Product product)
{
return CarrierProduct.builder()
.id(CarrierProductId.ofRepoId(product.getCarrier_Product_ID()))
.code(product.getExternalId())
.name(product.getName())
.build();
}
@NonNull
public CarrierProduct getOrCreateCarrierProduct(@NonNull final ShipperId shipperId, @NonNull final String code, @NonNull final String name)
{
final CarrierProduct cachedShipperProductByCode = getCachedShipperProductByCode(shipperId, code);
if (cachedShipperProductByCode != null)
{
return cachedShipperProductByCode;
}
return createShipperProduct(shipperId, code, name);
}
@Nullable
private CarrierProduct getCachedShipperProductByCode(@NonNull final ShipperId shipperId, @Nullable final String code)
{
if (code == null)
{
return null;
}
return carrierProductsByExternalId.getOrLoad(shipperId + code, () ->
queryBL.createQueryBuilder(I_Carrier_Product.class)
.addEqualsFilter(I_Carrier_Product.COLUMNNAME_M_Shipper_ID, shipperId)
.addEqualsFilter(I_Carrier_Product.COLUMNNAME_ExternalId, code)
.firstOptional() | .map(CarrierProductRepository::fromProductRecord)
.orElse(null));
}
@Nullable
public CarrierProduct getCachedShipperProductById(@Nullable final CarrierProductId productId)
{
if (productId == null)
{
return null;
}
return carrierProductsById.getOrLoad(productId.toString(), () ->
queryBL.createQueryBuilder(I_Carrier_Product.class)
.addEqualsFilter(I_Carrier_Product.COLUMNNAME_Carrier_Product_ID, productId)
.firstOptional()
.map(CarrierProductRepository::fromProductRecord)
.orElse(null));
}
@NonNull
private CarrierProduct createShipperProduct(@NonNull final ShipperId shipperId, @NonNull final String code, @NonNull final String name)
{
final I_Carrier_Product po = InterfaceWrapperHelper.newInstance(I_Carrier_Product.class);
po.setM_Shipper_ID(shipperId.getRepoId());
po.setExternalId(code);
po.setName(name);
InterfaceWrapperHelper.saveRecord(po);
return fromProductRecord(po);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\CarrierProductRepository.java | 1 |
请完成以下Java代码 | public static int getPrecision(Properties ctx, int C_UOM_ID)
{
if(C_UOM_ID <= 0)
{
return 2;
}
return Services.get(IUOMDAO.class)
.getStandardPrecision(UomId.ofRepoId(C_UOM_ID))
.toInt();
} // getPrecision
/**
* Load All UOMs
*
* @param ctx context
*/
private static void loadUOMs(Properties ctx)
{
List<MUOM> list = new Query(ctx, Table_Name, "IsActive='Y'", null)
.setRequiredAccess(Access.READ)
.list(MUOM.class);
//
for (MUOM uom : list)
{
s_cache.put(uom.get_ID(), uom);
}
} // loadUOMs | public MUOM(Properties ctx, int C_UOM_ID, String trxName)
{
super(ctx, C_UOM_ID, trxName);
if (is_new())
{
// setName (null);
// setX12DE355 (null);
setIsDefault(false);
setStdPrecision(2);
setCostingPrecision(6);
}
} // UOM
public MUOM(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // UOM
} // MUOM | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MUOM.java | 1 |
请完成以下Java代码 | public void setEnabled(boolean enabled)
{
super.setEnabled(enabled);
m_text.setEnabled(enabled);
m_button.setReadWrite(enabled && m_readWrite);
} // setEnabled
@Override
public void addActionListener(ActionListener l)
{
listenerList.add(ActionListener.class, l);
} // addActionListener
@Override
public void setBackground(final Color bg)
{
m_text.setBackground(bg);
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
// metas
@Override
public void addMouseListener(final MouseListener l)
{
m_text.addMouseListener(l);
}
@Override
public void addKeyListener(final KeyListener l)
{
m_text.addKeyListener(l);
} | public int getCaretPosition()
{
return m_text.getCaretPosition();
}
public void setCaretPosition(final int position)
{
m_text.setCaretPosition(position);
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
@Override
protected final boolean processKeyBinding(final KeyStroke ks, final KeyEvent e, final int condition, final boolean pressed)
{
// Forward all key events on this component to the text field.
// We have to do this for the case when we are embedding this editor in a JTable and the JTable is forwarding the key strokes to editing component.
// Effect of NOT doing this: when in JTable, user presses a key (e.g. a digit) to start editing but the first key he pressed gets lost here.
if (m_text != null && condition == WHEN_FOCUSED)
{
if (m_text.processKeyBinding(ks, e, condition, pressed))
{
return true;
}
}
//
// Fallback to super
return super.processKeyBinding(ks, e, condition, pressed);
}
} // VDate | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VDate.java | 1 |
请完成以下Java代码 | final class SecurityInfo {
static final SecurityInfo NONE = new SecurityInfo(null, null);
private final Certificate[][] certificateLookups;
private final CodeSigner[][] codeSignerLookups;
private SecurityInfo(Certificate[][] entryCertificates, CodeSigner[][] entryCodeSigners) {
this.certificateLookups = entryCertificates;
this.codeSignerLookups = entryCodeSigners;
}
Certificate[] getCertificates(ZipContent.Entry contentEntry) {
return (this.certificateLookups != null) ? clone(this.certificateLookups[contentEntry.getLookupIndex()]) : null;
}
CodeSigner[] getCodeSigners(ZipContent.Entry contentEntry) {
return (this.codeSignerLookups != null) ? clone(this.codeSignerLookups[contentEntry.getLookupIndex()]) : null;
}
private <T> T[] clone(T[] array) {
return (array != null) ? array.clone() : null;
}
/**
* Get the {@link SecurityInfo} for the given {@link ZipContent}.
* @param content the zip content
* @return the security info
*/
static SecurityInfo get(ZipContent content) {
if (!content.hasJarSignatureFile()) {
return NONE;
}
try {
return load(content);
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
/**
* Load security info from the jar file. We need to use {@link JarInputStream} to
* obtain the security info since we don't have an actual real file to read. This
* isn't that fast, but hopefully doesn't happen too often and the result is cached.
* @param content the zip content
* @return the security info
* @throws IOException on I/O error
*/
@SuppressWarnings("resource") | private static SecurityInfo load(ZipContent content) throws IOException {
int size = content.size();
boolean hasSecurityInfo = false;
Certificate[][] entryCertificates = new Certificate[size][];
CodeSigner[][] entryCodeSigners = new CodeSigner[size][];
try (JarEntriesStream entries = new JarEntriesStream(content.openRawZipData().asInputStream())) {
JarEntry entry = entries.getNextEntry();
while (entry != null) {
ZipContent.Entry relatedEntry = content.getEntry(entry.getName());
if (relatedEntry != null && entries.matches(relatedEntry.isDirectory(),
relatedEntry.getUncompressedSize(), relatedEntry.getCompressionMethod(),
() -> relatedEntry.openContent().asInputStream())) {
Certificate[] certificates = entry.getCertificates();
CodeSigner[] codeSigners = entry.getCodeSigners();
if (certificates != null || codeSigners != null) {
hasSecurityInfo = true;
entryCertificates[relatedEntry.getLookupIndex()] = certificates;
entryCodeSigners[relatedEntry.getLookupIndex()] = codeSigners;
}
}
entry = entries.getNextEntry();
}
}
return (!hasSecurityInfo) ? NONE : new SecurityInfo(entryCertificates, entryCodeSigners);
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\jar\SecurityInfo.java | 1 |
请完成以下Java代码 | public long getSequenceCounter() {
return sequenceCounter;
}
public void setSequenceCounter(long sequenceCounter) {
this.sequenceCounter = sequenceCounter;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
// persistent object implementation ///////////////
public Object getPersistentState() {
// events are immutable
return HistoryEvent.class;
}
// state inspection
public boolean isEventOfType(HistoryEventType type) {
return type.getEventName().equals(eventType); | }
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", processInstanceId=" + processInstanceId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", removalTime=" + removalTime
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoryEvent.java | 1 |
请完成以下Java代码 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
int width = 57;// 图像宽度
int height = 21;// 图像高度
// 定义输出格式
response.setContentType("image/jpeg");
ServletOutputStream out = response.getOutputStream();
// 准备缓冲图像,不支持表单
BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Random r = new Random();
// 获取图形上下文环境
Graphics gc = bimg.getGraphics();
// 设定背景色并进行填充
gc.setColor(getRandColor(200, 250));
gc.fillRect(0, 0, width, height);
// 设置图形上下文环境字体
gc.setFont(new Font("Times New Roman", Font.PLAIN, 18));
// 随机产生200条干扰线条,使图像中的认证码不易被其他分析程序探测到
gc.setColor(getRandColor(160, 200));
for (int i = 0; i < 200; i++) {
int x1 = r.nextInt(width);
int y1 = r.nextInt(height);
int x2 = r.nextInt(15);
int y2 = r.nextInt(15);
gc.drawLine(x1, y1, x1 + x2, y1 + y2);
}
// 随机产生100个干扰点,使图像中的验证码不易被其他分析程序探测到
gc.setColor(getRandColor(120, 240));
for (int i = 0; i < 100; i++) {
int x = r.nextInt(width);
int y = r.nextInt(height);
gc.drawOval(x, y, 0, 0);
}
// 随机产生4个数字的验证码
String rs = "";
String rn = "";
for (int i = 0; i < 4; i++) {
rn = String.valueOf(r.nextInt(10));
rs += rn;
gc.setColor(new Color(20 + r.nextInt(110), 20 + r.nextInt(110), 20 + r.nextInt(110)));
gc.drawString(rn, 13 * i + 1, 16);
}
// 释放图形上下文环境
gc.dispose(); | request.getSession().setAttribute("rcCaptcha", rs);
ImageIO.write(bimg, "jpeg", out);
try {
out.flush();
} finally {
out.close();
}
}
public Color getRandColor(int fc, int bc) {
Random r = new Random();
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int red = fc + r.nextInt(bc - fc);// 红
int green = fc + r.nextInt(bc - fc);// 绿
int blue = fc + r.nextInt(bc - fc);// 蓝
return new Color(red, green, blue);
}
} | repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\shiro\filter\RcCaptchaFilter.java | 1 |
请完成以下Java代码 | public void setCamundaCandidateUsersList(List<String> camundaCandidateUsersList) {
String candidateUsers = StringUtil.joinCommaSeparatedList(camundaCandidateUsersList);
camundaCandidateUsersAttribute.setValue(this, candidateUsers);
}
public String getCamundaDueDate() {
return camundaDueDateAttribute.getValue(this);
}
public void setCamundaDueDate(String camundaDueDate) {
camundaDueDateAttribute.setValue(this, camundaDueDate);
}
public String getCamundaFollowUpDate() {
return camundaFollowUpDateAttribute.getValue(this);
}
public void setCamundaFollowUpDate(String camundaFollowUpDate) {
camundaFollowUpDateAttribute.setValue(this, camundaFollowUpDate);
}
public String getCamundaFormHandlerClass() {
return camundaFormHandlerClassAttribute.getValue(this);
}
public void setCamundaFormHandlerClass(String camundaFormHandlerClass) {
camundaFormHandlerClassAttribute.setValue(this, camundaFormHandlerClass);
}
public String getCamundaFormKey() {
return camundaFormKeyAttribute.getValue(this);
}
public void setCamundaFormKey(String camundaFormKey) {
camundaFormKeyAttribute.setValue(this, camundaFormKey);
}
public String getCamundaFormRef() { | return camundaFormRefAttribute.getValue(this);
}
public void setCamundaFormRef(String camundaFormRef) {
camundaFormRefAttribute.setValue(this, camundaFormRef);
}
public String getCamundaFormRefBinding() {
return camundaFormRefBindingAttribute.getValue(this);
}
public void setCamundaFormRefBinding(String camundaFormRefBinding) {
camundaFormRefBindingAttribute.setValue(this, camundaFormRefBinding);
}
public String getCamundaFormRefVersion() {
return camundaFormRefVersionAttribute.getValue(this);
}
public void setCamundaFormRefVersion(String camundaFormRefVersion) {
camundaFormRefVersionAttribute.setValue(this, camundaFormRefVersion);
}
public String getCamundaPriority() {
return camundaPriorityAttribute.getValue(this);
}
public void setCamundaPriority(String camundaPriority) {
camundaPriorityAttribute.setValue(this, camundaPriority);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\UserTaskImpl.java | 1 |
请完成以下Java代码 | public <ModelType> IAggregationKeyBuilder<ModelType> getDefaultAggregationKeyBuilderOrNull(final Properties ctx, final Class<ModelType> modelClass, final Boolean isSOTrx, final String aggregationUsageLevel)
{
final IAggregationDAO aggregationDAO = Services.get(IAggregationDAO.class);
//
// Load it from database
{
final Aggregation aggregation = aggregationDAO.retrieveDefaultAggregationOrNull(ctx, modelClass, isSOTrx, aggregationUsageLevel);
if (aggregation != null)
{
return createAggregationKeyBuilder(modelClass, aggregation);
}
}
//
// Check programmatically registered default
{
final ArrayKey key = mkDefaultAggregationKey(modelClass, aggregationUsageLevel);
@SuppressWarnings("unchecked") final IAggregationKeyBuilder<ModelType> aggregationKeyBuilder = (IAggregationKeyBuilder<ModelType>)defaultAggregationKeyBuilders.get(key);
return aggregationKeyBuilder;
}
}
@Override
public <ModelType> void setDefaultAggregationKeyBuilder(
final Class<? extends ModelType> modelClass,
final String aggregationUsageLevel,
final IAggregationKeyBuilder<ModelType> aggregationKeyBuilder)
{
Check.assumeNotNull(modelClass, "modelClass not null");
Check.assumeNotEmpty(aggregationUsageLevel, "aggregationUsageLevel not empty");
Check.assumeNotNull(aggregationKeyBuilder, "aggregationKeyBuilder not null"); | final ArrayKey key = mkDefaultAggregationKey(modelClass, aggregationUsageLevel);
defaultAggregationKeyBuilders.put(key, aggregationKeyBuilder);
}
private final ArrayKey mkDefaultAggregationKey(final Class<?> modelClass, final String aggregationUsageLevel)
{
final String tableName = InterfaceWrapperHelper.getTableName(modelClass);
return Util.mkKey(tableName, aggregationUsageLevel);
}
private final <ModelType> IAggregationKeyBuilder<ModelType> createAggregationKeyBuilder(
final Class<ModelType> modelClass,
final Aggregation aggregation)
{
final GenericAggregationKeyBuilder<ModelType> aggregationKeyBuilder = new GenericAggregationKeyBuilder<>(modelClass, aggregation);
return aggregationKeyBuilder;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\api\impl\AggregationFactory.java | 1 |
请完成以下Java代码 | public void setRequestBody (final @Nullable java.lang.String RequestBody)
{
set_ValueNoCheck (COLUMNNAME_RequestBody, RequestBody);
}
@Override
public java.lang.String getRequestBody()
{
return get_ValueAsString(COLUMNNAME_RequestBody);
}
@Override
public void setRequestHeaders (final @Nullable java.lang.String RequestHeaders)
{
set_ValueNoCheck (COLUMNNAME_RequestHeaders, RequestHeaders);
}
@Override
public java.lang.String getRequestHeaders()
{
return get_ValueAsString(COLUMNNAME_RequestHeaders);
}
@Override
public void setRequestMethod (final @Nullable java.lang.String RequestMethod)
{
set_ValueNoCheck (COLUMNNAME_RequestMethod, RequestMethod);
}
@Override
public java.lang.String getRequestMethod()
{
return get_ValueAsString(COLUMNNAME_RequestMethod);
}
@Override
public void setRequestPath (final @Nullable java.lang.String RequestPath)
{
set_ValueNoCheck (COLUMNNAME_RequestPath, RequestPath);
}
@Override
public java.lang.String getRequestPath()
{
return get_ValueAsString(COLUMNNAME_RequestPath);
}
@Override
public void setResponseBody (final @Nullable java.lang.String ResponseBody)
{
set_ValueNoCheck (COLUMNNAME_ResponseBody, ResponseBody);
}
@Override | public java.lang.String getResponseBody()
{
return get_ValueAsString(COLUMNNAME_ResponseBody);
}
@Override
public void setResponseCode (final int ResponseCode)
{
set_ValueNoCheck (COLUMNNAME_ResponseCode, ResponseCode);
}
@Override
public int getResponseCode()
{
return get_ValueAsInt(COLUMNNAME_ResponseCode);
}
@Override
public void setResponseHeaders (final @Nullable java.lang.String ResponseHeaders)
{
set_ValueNoCheck (COLUMNNAME_ResponseHeaders, ResponseHeaders);
}
@Override
public java.lang.String getResponseHeaders()
{
return get_ValueAsString(COLUMNNAME_ResponseHeaders);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java-gen\de\metas\payment\paypal\model\X_PayPal_Log.java | 1 |
请完成以下Java代码 | public void dnsStart(Call call, String domainName) {
logTimedEvent("dnsStart");
}
@Override
public void dnsEnd(Call call, String domainName, List<InetAddress> inetAddressList) {
logTimedEvent("dnsEnd");
}
@Override
public void connectStart(Call call, InetSocketAddress inetSocketAddress, Proxy proxy) {
logTimedEvent("connectStart");
}
@Override
public void secureConnectStart(Call call) {
logTimedEvent("secureConnectStart");
}
@Override
public void secureConnectEnd(Call call, Handshake handshake) {
logTimedEvent("secureConnectEnd");
}
@Override
public void connectEnd(Call call, InetSocketAddress inetSocketAddress, Proxy proxy, Protocol protocol) {
logTimedEvent("connectEnd");
}
@Override
public void connectFailed(Call call, InetSocketAddress inetSocketAddress, Proxy proxy, Protocol protocol, IOException ioe) {
logTimedEvent("connectFailed");
}
@Override
public void connectionAcquired(Call call, Connection connection) {
logTimedEvent("connectionAcquired");
}
@Override
public void connectionReleased(Call call, Connection connection) {
logTimedEvent("connectionReleased");
}
@Override
public void requestHeadersStart(Call call) {
logTimedEvent("requestHeadersStart");
}
@Override
public void requestHeadersEnd(Call call, Request request) {
logTimedEvent("requestHeadersEnd");
}
@Override
public void requestBodyStart(Call call) {
logTimedEvent("requestBodyStart");
}
@Override
public void requestBodyEnd(Call call, long byteCount) {
logTimedEvent("requestBodyEnd");
} | @Override
public void requestFailed(Call call, IOException ioe) {
logTimedEvent("requestFailed");
}
@Override
public void responseHeadersStart(Call call) {
logTimedEvent("responseHeadersStart");
}
@Override
public void responseHeadersEnd(Call call, Response response) {
logTimedEvent("responseHeadersEnd");
}
@Override
public void responseBodyStart(Call call) {
logTimedEvent("responseBodyStart");
}
@Override
public void responseBodyEnd(Call call, long byteCount) {
logTimedEvent("responseBodyEnd");
}
@Override
public void responseFailed(Call call, IOException ioe) {
logTimedEvent("responseFailed");
}
@Override
public void callEnd(Call call) {
logTimedEvent("callEnd");
}
@Override
public void callFailed(Call call, IOException ioe) {
logTimedEvent("callFailed");
}
@Override
public void canceled(Call call) {
logTimedEvent("canceled");
}
} | repos\tutorials-master\libraries-http-2\src\main\java\com\baeldung\okhttp\events\EventTimer.java | 1 |
请完成以下Spring Boot application配置 | spring:
datasource:
driverClassName: org.h2.Driver
url: jdbc:h2:mem:shedlock_db;INIT=CREATE SCHEMA IF NOT EXISTS shedlock;DATABASE_TO_UPPER=false;DB | _CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
username: sa
password: | repos\tutorials-master\spring-boot-modules\spring-boot-libraries\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public Mono<Void> transferGatesReactive(String fromId, String toId, int gatesToTransfer,
RuntimeException exceptionToThrow) {
return Mono.deferContextual(ctx -> {
AirlineGates fromAirlineGates = template.findById(AirlineGates.class).one(fromId);
AirlineGates toAirlineGates = template.findById(AirlineGates.class).one(toId);
toAirlineGates.gates += gatesToTransfer;
fromAirlineGates.gates -= gatesToTransfer;
template.save(fromAirlineGates);
if (exceptionToThrow != null) {
throw exceptionToThrow;
}
return reactiveTemplate.save(toAirlineGates).then();
});
}
// This does not have the @Transactional annotation therefore is not executed in a transaction
public AirlineGates save(AirlineGates airlineGates) {
return template.save(airlineGates);
} | // This does not have the @Transactional annotation therefore is not executed in a transaction
public AirlineGates findById(String id) {
return template.findById(AirlineGates.class).one(id);
}
// This does not have the @Transactional annotation therefore is not executed in a transaction
public AirlineGates saveRepo(AirlineGates airlineGates) {
return airlineGatesRepository.save(airlineGates);
}
// This does not have the @Transactional annotation therefore is not executed in a transaction
public AirlineGates findByIdRepo(String id) {
return airlineGatesRepository.findById(id).orElse(null);
}
} | repos\spring-data-examples-main\couchbase\transactions\src\main\java\com\example\demo\AirlineGatesService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult add(@RequestBody MemberProductCollection productCollection) {
int count = memberCollectionService.add(productCollection);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("删除商品收藏")
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(Long productId) {
int count = memberCollectionService.delete(productId);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("显示当前用户商品收藏列表")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody | public CommonResult<CommonPage<MemberProductCollection>> list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
Page<MemberProductCollection> page = memberCollectionService.list(pageNum,pageSize);
return CommonResult.success(CommonPage.restPage(page));
}
@ApiOperation("显示商品收藏详情")
@RequestMapping(value = "/detail", method = RequestMethod.GET)
@ResponseBody
public CommonResult<MemberProductCollection> detail(@RequestParam Long productId) {
MemberProductCollection memberProductCollection = memberCollectionService.detail(productId);
return CommonResult.success(memberProductCollection);
}
@ApiOperation("清空当前用户商品收藏列表")
@RequestMapping(value = "/clear", method = RequestMethod.POST)
@ResponseBody
public CommonResult clear() {
memberCollectionService.clear();
return CommonResult.success(null);
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\MemberProductCollectionController.java | 2 |
请完成以下Java代码 | public static void processInParameters(List<IOParameter> inParameters, VariableContainer sourceContainer, Map<String, Object> targetContainer,
ExpressionManager expressionManager) {
processParameters(inParameters, sourceContainer, targetContainer::put, targetContainer::put, expressionManager, "In");
}
public static void processOutParameters(List<IOParameter> outParameters, VariableContainer sourceContainer, VariableContainer targetContainer,
ExpressionManager expressionManager) {
processParameters(outParameters, sourceContainer, targetContainer::setVariable, targetContainer::setTransientVariable, expressionManager, "Out");
}
protected static void processParameters(List<IOParameter> parameters, VariableContainer sourceContainer, BiConsumer<String, Object> targetVariableConsumer,
BiConsumer<String, Object> targetTransientVariableConsumer, ExpressionManager expressionManager, String parameterType) {
if (parameters == null || parameters.isEmpty()) {
return;
}
for (IOParameter parameter : parameters) {
Object value;
if (StringUtils.isNotEmpty(parameter.getSourceExpression())) {
Expression expression = expressionManager.createExpression(parameter.getSourceExpression().trim());
value = expression.getValue(sourceContainer);
} else {
value = sourceContainer.getVariable(parameter.getSource());
}
if (value != null) {
value = JsonUtil.deepCopyIfJson(value);
} | String variableName = null;
if (StringUtils.isNotEmpty(parameter.getTargetExpression())) {
Expression expression = expressionManager.createExpression(parameter.getTargetExpression());
Object variableNameValue = expression.getValue(sourceContainer);
if (variableNameValue != null) {
variableName = variableNameValue.toString();
} else {
LOGGER.warn("{} parameter target expression {} did not resolve to a variable name, this is most likely a programmatic error",
parameterType, parameter.getTargetExpression());
}
} else if (StringUtils.isNotEmpty(parameter.getTarget())) {
variableName = parameter.getTarget();
}
if (parameter.isTransient()) {
targetTransientVariableConsumer.accept(variableName, value);
} else {
targetVariableConsumer.accept(variableName, value);
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\IOParameterUtil.java | 1 |
请完成以下Java代码 | public final class RfQWorkDatesUtil
{
private RfQWorkDatesUtil()
{
}
/**
* If needed, sets DateWorkStart or DateWorkComplete or DeliveryDays based on the other fields.
*
* @param workDatesAware
*/
public static void updateWorkDates(final IRfQWorkDatesAware workDatesAware)
{
// Calculate Complete Date (also used to verify)
final Timestamp dateWorkStart = workDatesAware.getDateWorkStart();
final Timestamp dateWorkComplete = workDatesAware.getDateWorkComplete();
final int deliveryDays = workDatesAware.getDeliveryDays();
if (dateWorkStart != null && deliveryDays != 0)
{
setDateWorkComplete(workDatesAware);
}
// Calculate Delivery Days
else if (dateWorkStart != null && deliveryDays == 0 && dateWorkComplete != null)
{
setDeliveryDays(workDatesAware);
}
// Calculate Start Date
else if (dateWorkStart == null && deliveryDays != 0 && dateWorkComplete != null)
{
setDateWorkStart(workDatesAware);
}
}
public static void updateFromDateWorkStart(final IRfQWorkDatesAware workDatesAware)
{
final Timestamp dateWorkStart = workDatesAware.getDateWorkStart();
if(dateWorkStart == null)
{
return;
}
setDateWorkComplete(workDatesAware);
}
public static void updateFromDateWorkComplete(final IRfQWorkDatesAware workDatesAware)
{
final Timestamp dateWorkComplete = workDatesAware.getDateWorkComplete(); | if(dateWorkComplete == null)
{
return;
}
setDeliveryDays(workDatesAware);
}
public static void updateFromDeliveryDays(final IRfQWorkDatesAware workDatesAware)
{
final Timestamp dateWorkStart = workDatesAware.getDateWorkStart();
if(dateWorkStart == null)
{
return;
}
setDateWorkComplete(workDatesAware);
}
public static void setDateWorkStart(final IRfQWorkDatesAware workDatesAware)
{
final Timestamp dateWorkStart = TimeUtil.addDays(workDatesAware.getDateWorkComplete(), workDatesAware.getDeliveryDays() * -1);
workDatesAware.setDateWorkStart(dateWorkStart);
}
public static void setDeliveryDays(final IRfQWorkDatesAware workDatesAware)
{
final int deliveryDays = TimeUtil.getDaysBetween(workDatesAware.getDateWorkStart(), workDatesAware.getDateWorkComplete());
workDatesAware.setDeliveryDays(deliveryDays);
}
public static void setDateWorkComplete(final IRfQWorkDatesAware workDatesAware)
{
final Timestamp dateWorkComplete = TimeUtil.addDays(workDatesAware.getDateWorkStart(), workDatesAware.getDeliveryDays());
workDatesAware.setDateWorkComplete(dateWorkComplete);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\util\RfQWorkDatesUtil.java | 1 |
请完成以下Java代码 | private Set<DocumentId> retrieveRowIdsByWhereClause(final SqlViewRowsWhereClause sqlWhereClause)
{
if (sqlWhereClause.isNoRecords())
{
return ImmutableSet.of();
}
final SqlViewKeyColumnNamesMap keyColumnNamesMap = sqlViewBinding.getSqlViewKeyColumnNamesMap();
final SqlAndParams sql = SqlAndParams.builder()
.append("SELECT ").append(keyColumnNamesMap.getKeyColumnNamesCommaSeparated())
.append("\n FROM " + getTableName())
.append("\n WHERE (\n").append(sqlWhereClause.toSqlAndParams()).append("\n)")
.build();
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql.getSql(), ITrx.TRXNAME_ThreadInherited);
DB.setParameters(pstmt, sql.getSqlParams());
rs = pstmt.executeQuery();
final HashSet<DocumentId> rowIds = new HashSet<>();
while (rs.next())
{
final DocumentId rowId = keyColumnNamesMap.retrieveRowId(rs);
if (rowId != null)
{
rowIds.add(rowId);
}
}
return rowIds;
}
catch (final Exception ex)
{
throw new DBException(ex, sql.getSql(), sql.getSqlParams());
}
finally | {
DB.close(rs, pstmt);
}
}
@Override
public List<Object> retrieveFieldValues(
@NonNull final ViewEvaluationCtx viewEvalCtx,
@NonNull final String selectionId,
@NonNull final String fieldName,
final int limit)
{
final SqlViewRowFieldLoader fieldLoader = sqlViewBinding.getFieldLoader(fieldName);
final SqlAndParams sql = sqlViewBinding.getSqlViewSelect().selectFieldValues(viewEvalCtx, selectionId, fieldName, limit);
final String adLanguage = viewEvalCtx.getAdLanguage();
return DB.retrieveRows(
sql.getSql(),
sql.getSqlParams(),
rs -> fieldLoader.retrieveValue(rs, adLanguage));
}
public boolean isQueryIfNoFilters() {return sqlViewBinding.isQueryIfNoFilters();}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\SqlViewDataRepository.java | 1 |
请完成以下Java代码 | public void setValueFromPO(final String idPropertyName, final Class<?> parameterType, final Object value)
{
po.set_ValueFromPO(idPropertyName, parameterType, value);
}
@Override
public boolean invokeEquals(final Object[] methodArgs)
{
if (methodArgs == null || methodArgs.length != 1)
{
throw new IllegalArgumentException("Invalid method arguments to be used for equals(): " + methodArgs);
}
return po.equals(methodArgs[0]);
}
@Override | public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception
{
return method.invoke(po, methodArgs);
}
@Override
public boolean isCalculated(final String columnName)
{
return getPOInfo().isCalculated(columnName);
}
@Override
public boolean hasColumnName(final String columnName)
{
return getPOInfo().hasColumnName(columnName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POModelInternalAccessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class StockChangeDetail implements BusinessCaseDetail
{
@Nullable
CandidateStockChangeDetailId candidateStockChangeDetailId;
@Nullable
CandidateId candidateId;
@Nullable
Integer freshQuantityOnHandRepoId;
@Nullable
Integer freshQuantityOnHandLineRepoId;
@Nullable
InventoryId inventoryId;
@Nullable
InventoryLineId inventoryLineId;
@Nullable
Boolean isReverted;
@NonNull
Instant eventDate;
@Override
public CandidateBusinessCase getCandidateBusinessCase()
{
return CandidateBusinessCase.STOCK_CHANGE;
}
@Override | public BigDecimal getQty()
{
throw new AdempiereException("StockChangeDetail doesn't carry Qty!");
}
@Nullable
public static StockChangeDetail castOrNull(@Nullable final BusinessCaseDetail businessCaseDetail)
{
if (!(businessCaseDetail instanceof StockChangeDetail))
{
return null;
}
return cast(businessCaseDetail);
}
@NonNull
public static StockChangeDetail cast(@NonNull final BusinessCaseDetail businessCaseDetail)
{
return (StockChangeDetail)businessCaseDetail;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\businesscase\StockChangeDetail.java | 2 |
请完成以下Java代码 | protected final I_C_DocType retrieveCounterDocTypeOrNull(IDocument document)
{
final IDocumentBL docActionBL = Services.get(IDocumentBL.class);
final I_C_DocType docType = docActionBL.getDocTypeOrNull(document);
if (docType == null)
{
return null;
}
if (!docType.isCreateCounter())
{
return null;
}
int C_DocTypeTarget_ID = 0;
MDocTypeCounter counterDT = MDocTypeCounter.getCounterDocType(document.getCtx(), docType.getC_DocType_ID());
if (counterDT != null)
{
logger.debug(counterDT.toString());
if (counterDT.isCreateCounter() && counterDT.isValid())
{
return counterDT.getCounter_C_DocType();
}
}
else
// indirect
{
C_DocTypeTarget_ID = MDocTypeCounter.getCounterDocType_ID(document.getCtx(), docType.getC_DocType_ID());
logger.debug("Indirect C_DocTypeTarget_ID=" + C_DocTypeTarget_ID);
if (C_DocTypeTarget_ID > 0)
{
return InterfaceWrapperHelper.create(document.getCtx(), C_DocTypeTarget_ID, I_C_DocType.class, document.get_TrxName());
}
}
return null;
}
protected final I_C_BPartner retrieveCounterPartnerOrNull(IDocument document)
{
// our own org's bpartner would be the the counter document's C_BPartner.
MOrg org = MOrg.get(document.getCtx(), document.getAD_Org_ID()); | int counterC_BPartner_ID = org.getLinkedC_BPartner_ID(document.get_TrxName());
if (counterC_BPartner_ID > 0)
{
return InterfaceWrapperHelper.create(document.getCtx(), counterC_BPartner_ID, I_C_BPartner.class, document.get_TrxName());
}
return null;
}
protected final I_AD_Org retrieveCounterOrgOrNull(IDocument document)
{
final IBPartnerAware bpartnerAware = InterfaceWrapperHelper.asColumnReferenceAwareOrNull(document, IBPartnerAware.class);
if (bpartnerAware.getC_BPartner_ID() > 0 && bpartnerAware.getC_BPartner().getAD_OrgBP_ID() > 0)
{
return InterfaceWrapperHelper.create(document.getCtx(), bpartnerAware.getC_BPartner().getAD_OrgBP_ID(), I_AD_Org.class, document.get_TrxName());
}
// document's BPartner is not linked to any (counter-)org
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\document\spi\CounterDocumentHandlerAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PostgRESTConfigId implements RepoIdAware
{
@JsonCreator
public static PostgRESTConfigId ofRepoId(final int repoId)
{
return new PostgRESTConfigId(repoId);
}
@Nullable
@JsonCreator
public static PostgRESTConfigId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId!= null && repoId > 0 ? new PostgRESTConfigId(repoId) : null;
}
public static int toRepoId(@Nullable final PostgRESTConfigId postgRESTConfigId)
{
return postgRESTConfigId != null ? postgRESTConfigId.getRepoId() : -1; | }
int repoId;
private PostgRESTConfigId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "S_PostgREST_Config_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\postgrest\config\PostgRESTConfigId.java | 2 |
请完成以下Java代码 | public <ID extends RepoIdAware> ID getId(@NonNull final Class<ID> idType)
{
final RepoIdAware id = getId();
return id != null ? idType.cast(id) : null;
}
public UomId getUomId()
{
return getCostPrice().getUomId();
}
@NonNull
public static UomId extractUniqueUomId(@NonNull final Collection<BOMCostElementPrice> list)
{
return CollectionUtils.extractSingleElement(list, BOMCostElementPrice::getUomId);
} | public void clearOwnCostPrice()
{
setCostPrice(getCostPrice().withZeroOwnCostPrice());
}
public void clearComponentsCostPrice()
{
setCostPrice(getCostPrice().withZeroComponentsCostPrice());
}
public void setComponentsCostPrice(CostAmount componentsCostPrice)
{
setCostPrice(getCostPrice().withComponentsCostPrice(componentsCostPrice));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\costing\BOMCostElementPrice.java | 1 |
请完成以下Java代码 | public SpinJsonException unableToCreateNode(String objectType) {
return new SpinJsonPropertyException(exceptionMessage("005", "Unable to create node for object of type '{}'", objectType));
}
public SpinJsonException unableToDeserialize(JsonNode jsonNode, JavaType type, Exception cause) {
return new SpinJsonException(
exceptionMessage("006", "Cannot deserialize '{}...' to java type '{}'",
jsonNode.toString().substring(0, 10), type), cause);
}
public SpinJsonDataFormatException unableToConstructJavaType(String fromString, Exception cause) {
return new SpinJsonDataFormatException(
exceptionMessage("007", "Cannot construct java type from string '{}'", fromString), cause);
}
public SpinJsonDataFormatException unableToDetectCanonicalType(Object parameter) {
return new SpinJsonDataFormatException(exceptionMessage("008", "Cannot detect canonical data type for parameter '{}'", parameter));
}
public SpinJsonDataFormatException unableToMapInput(Object input, Exception cause) {
return new SpinJsonDataFormatException(exceptionMessage("009", "Unable to map object '{}' to json node", input), cause);
}
public SpinJsonException unableToModifyNode(String nodeName) {
return new SpinJsonException(exceptionMessage("010", "Unable to modify node of type '{}'. Node is not a list.", nodeName));
}
public SpinJsonException unableToGetIndex(String nodeName) {
return new SpinJsonException(exceptionMessage("011", "Unable to get index from '{}'. Node is not a list.", nodeName));
}
public IndexOutOfBoundsException indexOutOfBounds(Integer index, Integer size) {
return new IndexOutOfBoundsException(exceptionMessage("012", "Index is out of bound! Index: '{}', Size: '{}'", index, size));
}
public SpinJsonPathException unableToEvaluateJsonPathExpressionOnNode(SpinJsonNode node, Exception cause) {
return new SpinJsonPathException( | exceptionMessage("013", "Unable to evaluate JsonPath expression on element '{}'", node.getClass().getName()), cause);
}
public SpinJsonPathException unableToCompileJsonPathExpression(String expression, Exception cause) {
return new SpinJsonPathException(
exceptionMessage("014", "Unable to compile '{}'!", expression), cause);
}
public SpinJsonPathException unableToCastJsonPathResultTo(Class<?> castClass, Exception cause) {
return new SpinJsonPathException(
exceptionMessage("015", "Unable to cast JsonPath expression to '{}'", castClass.getName()), cause);
}
public SpinJsonPathException invalidJsonPath(Class<?> castClass, Exception cause) {
return new SpinJsonPathException(
exceptionMessage("017", "Invalid json path to '{}'", castClass.getName()), cause);
}
} | repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\JacksonJsonLogger.java | 1 |
请完成以下Java代码 | public class Employee implements Serializable {
private static final long serialVersionUID = -2454619097207585825L;
private int id;
private String name;
private int age;
public Employee() {
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public Employee(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getAge() {
return age;
} | public int getId() {
return id;
}
public void setAge(int age) {
this.age = age;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced\src\main\java\com\baeldung\arraycopy\model\Employee.java | 1 |
请完成以下Java代码 | public boolean isLiteralText() {
return true;
}
@Override
public boolean isLeftValue() {
return false;
}
@Override
public boolean isMethodInvocation() {
return false;
}
@Override
public Class<?> getType(Bindings bindings, ELContext context) {
return null;
}
@Override
public boolean isReadOnly(Bindings bindings, ELContext context) {
return true;
}
@Override
public void setValue(Bindings bindings, ELContext context, Object value) {
throw new ELException(LocalMessages.get("error.value.set.rvalue", getStructuralId(bindings)));
}
@Override
public ValueReference getValueReference(Bindings bindings, ELContext context) {
return null;
}
@Override
public Object eval(Bindings bindings, ELContext context) {
return value;
}
@Override
public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) {
return null;
} | @Override
public Object invoke(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] paramValues) {
return returnType == null ? value : bindings.convert(value, returnType);
}
@Override
public String toString() {
return "\"" + value + "\"";
}
@Override
public void appendStructure(StringBuilder b, Bindings bindings) {
int end = value.length() - 1;
for (int i = 0; i < end; i++) {
char c = value.charAt(i);
if ((c == '#' || c == '$') && value.charAt(i + 1) == '{') {
b.append('\\');
}
b.append(c);
}
if (end >= 0) {
b.append(value.charAt(end));
}
}
@Override
public int getCardinality() {
return 0;
}
@Override
public AstNode getChild(int i) {
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\de\odysseus\el\tree\impl\ast\AstText.java | 1 |
请完成以下Java代码 | public Class<? extends ModelEntity> getManagedEntityClass() {
return ModelEntityImpl.class;
}
@Override
public ModelEntity create() {
return new ModelEntityImpl();
}
@Override
@SuppressWarnings("unchecked")
public List<Model> findModelsByQueryCriteria(ModelQueryImpl query, Page page) {
return getDbSqlSession().selectList("selectModelsByQueryCriteria", query, page);
}
@Override
public long findModelCountByQueryCriteria(ModelQueryImpl query) {
return (Long) getDbSqlSession().selectOne("selectModelCountByQueryCriteria", query); | }
@Override
@SuppressWarnings("unchecked")
public List<Model> findModelsByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
return getDbSqlSession().selectListWithRawParameter(
"selectModelByNativeQuery",
parameterMap,
firstResult,
maxResults
);
}
@Override
public long findModelCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectModelCountByNativeQuery", parameterMap);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisModelDataManager.java | 1 |
请完成以下Java代码 | public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entity Type.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** ReplicationType AD_Reference_ID=126 */
public static final int REPLICATIONTYPE_AD_Reference_ID=126;
/** Local = L */
public static final String REPLICATIONTYPE_Local = "L";
/** Merge = M */
public static final String REPLICATIONTYPE_Merge = "M";
/** Reference = R */
public static final String REPLICATIONTYPE_Reference = "R";
/** Broadcast = B */
public static final String REPLICATIONTYPE_Broadcast = "B";
/** Set Replication Type.
@param ReplicationType
Type of Data Replication | */
public void setReplicationType (String ReplicationType)
{
set_Value (COLUMNNAME_ReplicationType, ReplicationType);
}
/** Get Replication Type.
@return Type of Data Replication
*/
public String getReplicationType ()
{
return (String)get_Value(COLUMNNAME_ReplicationType);
}
public I_EXP_Format getEXP_Format() throws RuntimeException
{
return (I_EXP_Format)MTable.get(getCtx(), I_EXP_Format.Table_Name)
.getPO(getEXP_Format_ID(), get_TrxName());
}
public void setEXP_Format_ID (int EXP_Format_ID)
{
if (EXP_Format_ID < 1)
set_ValueNoCheck (COLUMNNAME_EXP_Format_ID, null);
else
set_ValueNoCheck (COLUMNNAME_EXP_Format_ID, Integer.valueOf(EXP_Format_ID));
}
public int getEXP_Format_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_EXP_Format_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_AD_ReplicationTable.java | 1 |
请完成以下Java代码 | public class GitIgnore {
private final GitIgnoreSection general = new GitIgnoreSection(null);
private final GitIgnoreSection sts = new GitIgnoreSection("STS");
private final GitIgnoreSection intellijIdea = new GitIgnoreSection("IntelliJ IDEA");
private final GitIgnoreSection netBeans = new GitIgnoreSection("NetBeans");
private final GitIgnoreSection vscode = new GitIgnoreSection("VS Code");
private final List<GitIgnoreSection> sections = new ArrayList<>(
Arrays.asList(this.general, this.sts, this.intellijIdea, this.netBeans, this.vscode));
public void write(PrintWriter writer) throws IOException {
for (GitIgnoreSection section : this.sections) {
section.write(writer);
}
}
public void addSection(GitIgnoreSection section) {
GitIgnoreSection existingSection = getSection(section.name);
Assert.state(existingSection == null, () -> "Section with name '%s' already exists".formatted(section.name));
this.sections.add(section);
}
/**
* Adds a section if it doesn't already exist.
* @param sectionName the name of the section
* @return the newly added section or the existing one
*/
public GitIgnoreSection addSectionIfAbsent(String sectionName) {
GitIgnoreSection section = getSection(sectionName);
if (section != null) {
return section;
}
section = new GitIgnoreSection(sectionName);
addSection(section);
return section;
}
public GitIgnoreSection getSection(String sectionName) {
if ("general".equalsIgnoreCase(sectionName)) {
return this.general;
}
else {
return this.sections.stream()
.filter((section) -> section.name != null && section.name.equalsIgnoreCase(sectionName))
.findAny()
.orElse(null);
}
}
public boolean isEmpty() {
return this.sections.stream().allMatch((section) -> section.items.isEmpty());
}
public GitIgnoreSection getGeneral() {
return this.general;
}
public GitIgnoreSection getSts() {
return this.sts;
}
public GitIgnoreSection getIntellijIdea() {
return this.intellijIdea;
}
public GitIgnoreSection getNetBeans() {
return this.netBeans; | }
public GitIgnoreSection getVscode() {
return this.vscode;
}
/**
* Representation of a section of a {@code .gitignore} file.
*/
public static class GitIgnoreSection implements Section {
private final String name;
private final LinkedList<String> items;
public GitIgnoreSection(String name) {
this.name = name;
this.items = new LinkedList<>();
}
public void add(String... items) {
this.items.addAll(Arrays.asList(items));
}
public LinkedList<String> getItems() {
return this.items;
}
@Override
public void write(PrintWriter writer) {
if (!this.items.isEmpty()) {
if (this.name != null) {
writer.println();
writer.println(String.format("### %s ###", this.name));
}
this.items.forEach(writer::println);
}
}
}
} | repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\scm\git\GitIgnore.java | 1 |
请完成以下Java代码 | public Object resolveProperty(String name) {
Object originalValue = delegate.getProperty(name);
if (!(originalValue instanceof String)) {
//Because we read the original property every time, if it isn't a String,
// there's no point in caching it.
return originalValue;
}
CachedValue cachedValue = cache.get(name);
if (cachedValue != null && Objects.equals(originalValue, cachedValue.originValue)) {
// If the original property has not changed, it is safe to return the cached result.
return cachedValue.resolvedValue;
}
//originalValue must be String here
if (filter.shouldInclude(delegate, name)) {
String originStringValue = (String) originalValue;
String resolved = resolver.resolvePropertyValue(originStringValue);
CachedValue newCachedValue = new CachedValue(originStringValue, resolved);
//If the mapping relationship in the cache changes during
// the calculation process, then ignore it directly.
if (cachedValue == null) {
cache.putIfAbsent(name, newCachedValue); | } else {
cache.replace(name, cachedValue, newCachedValue);
}
//return the result calculated this time
return resolved;
}
return originalValue;
}
/**
* <p>Refresh the cache.</p>
*/
public void refresh() {
log.info("CachingResolver cache refreshed");
cache.clear();
}
@AllArgsConstructor
static class CachedValue {
private final String originValue;
private final String resolvedValue;
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\caching\CachingResolver.java | 1 |
请完成以下Java代码 | public String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
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 |
请完成以下Java代码 | public ApplicationServerDto getApplicationServer() {
return applicationServer;
}
public void setApplicationServer(ApplicationServerDto applicationServer) {
this.applicationServer = applicationServer;
}
public Map<String, CommandDto> getCommands() {
return commands;
}
public void setCommands(Map<String, CommandDto> commands) {
this.commands = commands;
}
public Map<String, MetricDto> getMetrics() {
return metrics;
}
public void setMetrics(Map<String, MetricDto> metrics) {
this.metrics = metrics;
}
public JdkDto getJdk() {
return jdk;
}
public void setJdk(JdkDto jdk) {
this.jdk = jdk;
}
public Set<String> getCamundaIntegration() {
return camundaIntegration;
}
public void setCamundaIntegration(Set<String> camundaIntegration) {
this.camundaIntegration = camundaIntegration;
}
public LicenseKeyDataDto getLicenseKey() {
return licenseKey;
}
public void setLicenseKey(LicenseKeyDataDto licenseKey) {
this.licenseKey = licenseKey;
}
public Set<String> getWebapps() {
return webapps;
} | public void setWebapps(Set<String> webapps) {
this.webapps = webapps;
}
public Date getDataCollectionStartDate() {
return dataCollectionStartDate;
}
public void setDataCollectionStartDate(Date dataCollectionStartDate) {
this.dataCollectionStartDate = dataCollectionStartDate;
}
public static InternalsDto fromEngineDto(Internals other) {
LicenseKeyData licenseKey = other.getLicenseKey();
InternalsDto dto = new InternalsDto(
DatabaseDto.fromEngineDto(other.getDatabase()),
ApplicationServerDto.fromEngineDto(other.getApplicationServer()),
licenseKey != null ? LicenseKeyDataDto.fromEngineDto(licenseKey) : null,
JdkDto.fromEngineDto(other.getJdk()));
dto.dataCollectionStartDate = other.getDataCollectionStartDate();
dto.commands = new HashMap<>();
other.getCommands().forEach((name, command) -> dto.commands.put(name, new CommandDto(command.getCount())));
dto.metrics = new HashMap<>();
other.getMetrics().forEach((name, metric) -> dto.metrics.put(name, new MetricDto(metric.getCount())));
dto.setWebapps(other.getWebapps());
dto.setCamundaIntegration(other.getCamundaIntegration());
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\InternalsDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private boolean validateSign(HttpServletRequest request) {
String requestSign = request.getParameter("sign");//获得请求签名,如sign=19e907700db7ad91318424a97c54ed57
if (StringUtils.isEmpty(requestSign)) {
return false;
}
List<String> keys = new ArrayList<String>(request.getParameterMap().keySet());
keys.remove("sign");//排除sign参数
Collections.sort(keys);//排序
StringBuilder sb = new StringBuilder();
for (String key : keys) {
sb.append(key).append("=").append(request.getParameter(key)).append("&");//拼接字符串
}
String linkString = sb.toString();
linkString = StringUtils.substring(linkString, 0, linkString.length() - 1);//去除最后一个'&'
String secret = "Potato";//密钥,自己修改
String sign = DigestUtils.md5Hex(linkString + secret);//混合密钥md5
return StringUtils.equals(sign, requestSign);//比较
}
private String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP"); | }
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// 如果是多级代理,那么取第一个ip为客户端ip
if (ip != null && ip.indexOf(",") != -1) {
ip = ip.substring(0, ip.indexOf(",")).trim();
}
return ip;
}
} | repos\spring-boot-api-project-seed-master\src\main\java\com\company\project\configurer\WebMvcConfigurer.java | 2 |
请完成以下Java代码 | public List<Deployment> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getDeploymentManager()
.findDeploymentsByQueryCriteria(this, page);
}
//getters ////////////////////////////////////////////////////////
public String getDeploymentId() {
return deploymentId;
}
public String getName() {
return name;
}
public String getNameLike() { | return nameLike;
}
public boolean isSourceQueryParamEnabled() {
return sourceQueryParamEnabled;
}
public String getSource() {
return source;
}
public Date getDeploymentBefore() {
return deploymentBefore;
}
public Date getDeploymentAfter() {
return deploymentAfter;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\DeploymentQueryImpl.java | 1 |
请完成以下Java代码 | public I_I_Datev_Payment retrieveImportRecord(final Properties ctx, final ResultSet rs) throws SQLException
{
return new X_I_Datev_Payment(ctx, rs, ITrx.TRXNAME_ThreadInherited);
}
@Override
protected ImportRecordResult importRecord(@NonNull final IMutable<Object> state,
@NonNull final I_I_Datev_Payment importRecord,
final boolean isInsertOnly) throws Exception
{
return importDatevPayment(importRecord, isInsertOnly);
}
private ImportRecordResult importDatevPayment(@NonNull final I_I_Datev_Payment importRecord, final boolean isInsertOnly)
{
final ImportRecordResult schemaImportResult;
final boolean paymentExists = importRecord.getC_Payment_ID() > 0;
if (paymentExists && isInsertOnly)
{
// do not update
return ImportRecordResult.Nothing;
}
final I_C_Payment payment;
if (!paymentExists)
{
payment = createNewPayment(importRecord);
schemaImportResult = ImportRecordResult.Inserted;
}
else
{
payment = importRecord.getC_Payment();
schemaImportResult = ImportRecordResult.Updated;
}
ModelValidationEngine.get().fireImportValidate(this, importRecord, payment,
IImportInterceptor.TIMING_AFTER_IMPORT);
InterfaceWrapperHelper.save(payment); | importRecord.setC_Payment_ID(payment.getC_Payment_ID());
InterfaceWrapperHelper.save(importRecord);
return schemaImportResult;
}
private I_C_Payment createNewPayment(@NonNull final I_I_Datev_Payment importRecord)
{
final LocalDate date = TimeUtil.asLocalDate(importRecord.getDateTrx());
final IPaymentBL paymentsService = Services.get(IPaymentBL.class);
return paymentsService.newBuilderOfInvoice(importRecord.getC_Invoice())
//.receipt(importRecord.isReceipt())
.adOrgId(OrgId.ofRepoId(importRecord.getAD_Org_ID()))
.bpartnerId(BPartnerId.ofRepoId(importRecord.getC_BPartner_ID()))
.payAmt(importRecord.getPayAmt())
.discountAmt(importRecord.getDiscountAmt())
.tenderType(TenderType.DirectDeposit)
.dateAcct(date)
.dateTrx(date)
.description("Import for debitorId/creditorId" + importRecord.getBPartnerValue())
.createAndProcess();
}
@Override
protected void markImported(@NonNull final I_I_Datev_Payment importRecord)
{
importRecord.setI_IsImported(X_I_Datev_Payment.I_ISIMPORTED_Imported);
importRecord.setProcessed(true);
InterfaceWrapperHelper.save(importRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impexp\DatevPaymentImportProcess.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorize -> authorize.anyRequest()
.authenticated())
.formLogin(Customizer.withDefaults());
return http.build();
}
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient mcpClient = RegisteredClient.withId(UUID.randomUUID()
.toString())
.clientId("mcp-client")
.clientSecret("{noop}mcp-secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.redirectUri("http://localhost:8080/authorize/oauth2/code/authserver")
.redirectUri("http://127.0.0.1:8080/authorize/oauth2/code/authserver")
.postLogoutRedirectUri("http://localhost:8080/")
// Standard OAuth2/OIDC scopes
.scope(OidcScopes.OPENID) | .scope(OidcScopes.PROFILE)
// Custom MCP scopes
.scope("mcp.read")
.scope("mcp.write")
.clientSettings(ClientSettings.builder()
.requireAuthorizationConsent(false)
.requireProofKey(false)
.build())
.tokenSettings(TokenSettings.builder()
.accessTokenTimeToLive(Duration.ofHours(1))
.refreshTokenTimeToLive(Duration.ofDays(1))
.reuseRefreshTokens(false)
.build())
.build();
return new InMemoryRegisteredClientRepository(mcpClient);
}
@Bean
public AuthorizationServerSettings authorizationServerSettings() {
return AuthorizationServerSettings.builder()
.issuer("http://localhost:9000")
.build();
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-mcp-oauth\oauth2-authorization-server\src\main\java\com\baeldung\mcp\oauth2authorizationserver\config\AuthorizationServerConfig.java | 2 |
请完成以下Spring Boot application配置 | server:
port: 8088
spring:
mvc:
contentnegotiation:
#favor-path-extension: true # header accept
favor-parameter: true # url ?format=x | ml or format=json
media-types:
json: application/json | repos\springboot-demo-master\ContentNegotiation\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | private static String normalizeValue(@Nullable final String value)
{
return StringUtils.trimBlankToNull(value);
}
@JsonCreator
public static POSOrderExternalId ofString(@NonNull final String value)
{
return new POSOrderExternalId(value);
}
public static Set<POSOrderExternalId> ofCommaSeparatedString(@Nullable final String string)
{
return CollectionUtils.ofCommaSeparatedSet(string, POSOrderExternalId::ofString);
}
public static Set<String> toStringSet(@NonNull final Collection<POSOrderExternalId> collection) | {
return collection.stream()
.map(POSOrderExternalId::getAsString)
.collect(ImmutableSet.toImmutableSet());
}
@Override
@Deprecated
public String toString() {return value;}
@JsonValue
public String getAsString() {return value;}
public static boolean equals(@Nullable final POSOrderExternalId id1, @Nullable final POSOrderExternalId id2) {return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrderExternalId.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.