instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public boolean isPlannedForActivationInMigration() {
return plannedForActivationInMigration;
}
@Override
public void setPlannedForActivationInMigration(boolean plannedForActivationInMigration) {
this.plannedForActivationInMigration = plannedForActivationInMigration;
}
@Override
public boolean isStateChangeUnprocessed() {
return stateChangeUnprocessed;
}
@Override
public void setStateChangeUnprocessed(boolean stateChangeUnprocessed) {
this.stateChangeUnprocessed = stateChangeUnprocessed;
}
@Override
public Map<String, Object> getPlanItemInstanceLocalVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (VariableInstance variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getSubScopeId() != null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
@Override
public List<VariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new VariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<VariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder(); | stringBuilder.append("PlanItemInstance with id: ")
.append(id);
if (getName() != null) {
stringBuilder.append(", name: ").append(getName());
}
stringBuilder.append(", definitionId: ")
.append(planItemDefinitionId)
.append(", state: ")
.append(state);
if (elementId != null) {
stringBuilder.append(", elementId: ").append(elementId);
}
stringBuilder
.append(", caseInstanceId: ")
.append(caseInstanceId)
.append(", caseDefinitionId: ")
.append(caseDefinitionId);
if (StringUtils.isNotEmpty(tenantId)) {
stringBuilder.append(", tenantId=").append(tenantId);
}
return stringBuilder.toString();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\PlanItemInstanceEntityImpl.java | 1 |
请完成以下Java代码 | /* package */abstract class AbstractProductionMaterial implements IProductionMaterial
{
// Services
private final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
protected final UOMConversionContext getUOMConversionContext()
{
final UOMConversionContext conversionCtx = UOMConversionContext.of(getM_Product());
return conversionCtx;
}
@Override
public final BigDecimal getQty(@NonNull final I_C_UOM uomTo)
{
final BigDecimal qty = getQty();
final I_C_UOM qtyUOM = getC_UOM();
final UOMConversionContext conversionCtx = getUOMConversionContext();
final BigDecimal qtyInUOMTo = uomConversionBL.convertQty(conversionCtx, qty, qtyUOM, uomTo);
return qtyInUOMTo;
} | @Override
public final BigDecimal getQM_QtyDeliveredAvg(@NonNull final I_C_UOM uomTo)
{
final UOMConversionContext conversionCtx = getUOMConversionContext();
final BigDecimal qty = getQM_QtyDeliveredAvg();
final I_C_UOM qtyUOM = getC_UOM();
final BigDecimal qtyInUOMTo = uomConversionBL.convertQty(conversionCtx, qty, qtyUOM, uomTo);
return qtyInUOMTo;
}
@Override
public boolean isByProduct()
{
return getComponentType() != null && getComponentType().isByProduct();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\AbstractProductionMaterial.java | 1 |
请完成以下Java代码 | public Map<Integer, BigDecimal> retrieveIolAndQty(final PPOrderId ppOrderId)
{
final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class);
final IPPCostCollectorDAO ppCostCollectorDAO = Services.get(IPPCostCollectorDAO.class);
final IHUAssignmentDAO huAssignmentDAO = Services.get(IHUAssignmentDAO.class);
final IHUInOutDAO huInOutDAO = Services.get(IHUInOutDAO.class);
final Map<Integer, BigDecimal> iolMap = new HashMap<>();
final List<I_PP_Cost_Collector> costCollectors = ppCostCollectorDAO.getByOrderId(ppOrderId);
for (final I_PP_Cost_Collector costCollector : costCollectors)
{
if (!ppCostCollectorBL.isAnyComponentIssueOrCoProduct(costCollector))
{
continue;
}
final List<I_M_HU_Assignment> huAssignmentsForModel = huAssignmentDAO.retrieveTopLevelHUAssignmentsForModel(costCollector);
final Map<Integer, I_M_InOutLine> id2iol = new HashMap<>();
for (final I_M_HU_Assignment assignment : huAssignmentsForModel)
{
final I_M_HU hu = assignment.getM_HU();
final I_M_InOutLine inoutLine = huInOutDAO.retrieveCompletedReceiptLineOrNull(hu);
if (inoutLine == null || !inoutLine.getM_InOut().isProcessed())
{
// there is no iol
// or it's not processed (which should not happen)
continue;
}
id2iol.put(inoutLine.getM_InOutLine_ID(), inoutLine);
} | BigDecimal qtyToAllocate = ppCostCollectorBL.getMovementQtyInStockingUOM(costCollector).toBigDecimal();
for (final I_M_InOutLine inoutLine : id2iol.values())
{
final BigDecimal qty = qtyToAllocate.min(inoutLine.getMovementQty());
iolMap.put(inoutLine.getM_InOutLine_ID(), qty);
qtyToAllocate = qtyToAllocate.subtract(inoutLine.getMovementQty()).max(BigDecimal.ZERO);
}
if (qtyToAllocate.signum() > 0)
{
Loggables.addLog("PROBLEM: PP_Cost_Collector {0} of PP_Order {1} has a remaining unallocated qty of {2}!", costCollector, ppOrderId, qtyToAllocate);
}
}
return iolMap;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\spi\impl\PPOrderMInOutLineRetrievalService.java | 1 |
请完成以下Java代码 | public List<String> getCandidateStarterGroups() {
return candidateStarterGroups;
}
public void setCandidateStarterGroups(List<String> candidateStarterGroups) {
this.candidateStarterGroups = candidateStarterGroups;
}
public boolean isAsync() {
return async;
}
public void setAsync(boolean async) {
this.async = async;
}
public Map<String, CaseElement> getAllCaseElements() {
return allCaseElements;
}
public void setAllCaseElements(Map<String, CaseElement> allCaseElements) {
this.allCaseElements = allCaseElements;
}
public <T extends PlanItemDefinition> List<T> findPlanItemDefinitionsOfType(Class<T> type) {
return planModel.findPlanItemDefinitionsOfType(type, true);
}
public ReactivateEventListener getReactivateEventListener() {
return reactivateEventListener; | }
public void setReactivateEventListener(ReactivateEventListener reactivateEventListener) {
this.reactivateEventListener = reactivateEventListener;
}
@Override
public List<FlowableListener> getLifecycleListeners() {
return this.lifecycleListeners;
}
@Override
public void setLifecycleListeners(List<FlowableListener> lifecycleListeners) {
this.lifecycleListeners = lifecycleListeners;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Case.java | 1 |
请完成以下Java代码 | public Optional<Boolean> getBooleanValue() {
return Optional.ofNullable(null);
}
@Override
public Optional<Double> getDoubleValue() {
return Optional.ofNullable(null);
}
@Override
public Optional<String> getJsonValue() {
return Optional.ofNullable(null);
}
@Override
public boolean equals(Object o) {
if (this == o) return true; | if (!(o instanceof BasicKvEntry)) return false;
BasicKvEntry that = (BasicKvEntry) o;
return Objects.equals(key, that.key);
}
@Override
public int hashCode() {
return Objects.hash(key);
}
@Override
public String toString() {
return "BasicKvEntry{" +
"key='" + key + '\'' +
'}';
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\BasicKvEntry.java | 1 |
请完成以下Java代码 | public class Dest {
private String name;
private int age;
public Dest() {
}
public Dest(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name; | }
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
} | repos\tutorials-master\libraries-data\src\main\java\com\baeldung\dozer\Dest.java | 1 |
请完成以下Java代码 | public void setC_UOM(org.compiere.model.I_C_UOM C_UOM)
{
set_ValueFromPO(COLUMNNAME_C_UOM_ID, org.compiere.model.I_C_UOM.class, C_UOM);
}
/** Set Maßeinheit.
@param C_UOM_ID
Maßeinheit
*/
@Override
public void setC_UOM_ID (int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, Integer.valueOf(C_UOM_ID));
}
/** Get Maßeinheit.
@return Maßeinheit
*/
@Override
public int getC_UOM_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_UOM_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Berechnete Menge.
@param InvoicedQty
The quantity invoiced
*/
@Override
public void setInvoicedQty (java.math.BigDecimal InvoicedQty)
{
set_Value (COLUMNNAME_InvoicedQty, InvoicedQty);
}
/** Get Berechnete Menge.
@return The quantity invoiced
*/
@Override
public java.math.BigDecimal getInvoicedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_InvoicedQty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Zeilennetto.
@param LineNetAmt
Nettowert Zeile (Menge * Einzelpreis) ohne Fracht und Gebühren
*/
@Override
public void setLineNetAmt (java.math.BigDecimal LineNetAmt)
{
set_Value (COLUMNNAME_LineNetAmt, LineNetAmt);
}
/** Get Zeilennetto.
@return Nettowert Zeile (Menge * Einzelpreis) ohne Fracht und Gebühren
*/
@Override
public java.math.BigDecimal getLineNetAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_LineNetAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Position.
@param LineNo
Zeile Nr.
*/
@Override
public void setLineNo (int LineNo)
{ | set_Value (COLUMNNAME_LineNo, Integer.valueOf(LineNo));
}
/** Get Position.
@return Zeile Nr.
*/
@Override
public int getLineNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LineNo);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Customs_Invoice_Line.java | 1 |
请完成以下Java代码 | public DecisionEntity findDecisionByDeploymentAndKey(String deploymentId, String DefinitionKey) {
return dataManager.findDecisionByDeploymentAndKey(deploymentId, DefinitionKey);
}
@Override
public DecisionEntity findDecisionByDeploymentAndKeyAndTenantId(String deploymentId, String decisionKey, String tenantId) {
return dataManager.findDecisionByDeploymentAndKeyAndTenantId(deploymentId, decisionKey, tenantId);
}
@Override
public DecisionEntity findDecisionByKeyAndVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) {
if (tenantId == null || DmnEngineConfiguration.NO_TENANT_ID.equals(tenantId)) {
return dataManager.findDecisionByKeyAndVersion(definitionKey, definitionVersion);
} else {
return dataManager.findDecisionByKeyAndVersionAndTenantId(definitionKey, definitionVersion, tenantId);
}
} | @Override
public List<DmnDecision> findDecisionsByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findDecisionsByNativeQuery(parameterMap);
}
@Override
public long findDecisionCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findDecisionCountByNativeQuery(parameterMap);
}
@Override
public void updateDecisionTenantIdForDeployment(String deploymentId, String newTenantId) {
dataManager.updateDecisionTenantIdForDeployment(deploymentId, newTenantId);
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\DefinitionEntityManagerImpl.java | 1 |
请完成以下Java代码 | public ResourceList<Role> findAll(QuerySpec querySpec) {
return querySpec.apply(roleRepository.findAll());
}
@Override
public ResourceList<Role> findAll(Iterable<Long> ids, QuerySpec querySpec) {
return querySpec.apply(roleRepository.findAllById(ids));
}
@Override
public <S extends Role> S save(S entity) {
return roleRepository.save(entity);
}
@Override | public void delete(Long id) {
roleRepository.deleteById(id);
}
@Override
public Class<Role> getResourceClass() {
return Role.class;
}
@Override
public <S extends Role> S create(S entity) {
return save(entity);
}
} | repos\tutorials-master\spring-katharsis\src\main\java\com\baeldung\persistence\katharsis\RoleResourceRepository.java | 1 |
请完成以下Java代码 | public class StringPermutation {
public static boolean isPermutationWithSorting(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;
}
char[] s1CharArray = s1.toCharArray();
char[] s2CharArray = s2.toCharArray();
Arrays.sort(s1CharArray);
Arrays.sort(s2CharArray);
return Arrays.equals(s1CharArray, s2CharArray);
}
public static boolean isPermutationWithOneCounter(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;
}
int[] counter = new int[256];
for (int i = 0; i < s1.length(); i++) {
counter[s1.charAt(i)]++;
counter[s2.charAt(i)]--;
}
for (int count : counter) {
if (count != 0) {
return false;
}
}
return true;
}
public static boolean isPermutationWithTwoCounters(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;
}
int[] counter1 = new int[256];
int[] counter2 = new int[256];
for (int i = 0; i < s1.length(); i++) {
counter1[s1.charAt(i)]++;
}
for (int i = 0; i < s2.length(); i++) {
counter2[s2.charAt(i)]++;
}
return Arrays.equals(counter1, counter2);
} | public static boolean isPermutationWithMap(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;
}
Map<Character, Integer> charsMap = new HashMap<>();
for (int i = 0; i < s1.length(); i++) {
charsMap.merge(s1.charAt(i), 1, Integer::sum);
}
for (int i = 0; i < s2.length(); i++) {
if (!charsMap.containsKey(s2.charAt(i)) || charsMap.get(s2.charAt(i)) == 0) {
return false;
}
charsMap.merge(s2.charAt(i), -1, Integer::sum);
}
return true;
}
public static boolean isPermutationInclusion(String s1, String s2) {
int ns1 = s1.length(), ns2 = s2.length();
if (ns1 < ns2) {
return false;
}
int[] s1Count = new int[26];
int[] s2Count = new int[26];
for (char ch : s2.toCharArray()) {
s2Count[ch - 'a']++;
}
for (int i = 0; i < ns1; ++i) {
s1Count[s1.charAt(i) - 'a']++;
if (i >= ns2) {
s1Count[s1.charAt(i - ns2) - 'a']--;
}
if (Arrays.equals(s2Count, s1Count)) {
return true;
}
}
return false;
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-9\src\main\java\com\baeldung\algorithms\permutation\StringPermutation.java | 1 |
请完成以下Java代码 | public void onNewAsUserAction(final I_M_PickingSlot_HU pickingSlotHU)
{
final PickingSlotId pickingSlotId = PickingSlotId.ofRepoId(pickingSlotHU.getM_PickingSlot_ID());
final HuId huId = HuId.ofRepoId(pickingSlotHU.getM_HU_ID());
final IHUPickingSlotBL.IQueueActionResult result = pickingSlotBL.addToPickingSlotQueue(pickingSlotId, huId);
final I_M_PickingSlot_Trx pickingSlotTrx = Check.assumeNotNull(result.getM_PickingSlot_Trx(),
"The result of addToPickingSlotQueue contains a M_PickingSlot_Trx for {} and {} ", pickingSlotId, huId);
pickingSlotTrx.setIsUserAction(true);
InterfaceWrapperHelper.save(pickingSlotTrx);
}
/**
* If a picking-slot-hu is deleted by a user, then remove it from the picking-slot-hu and update the respective {@link I_M_PickingSlot_Trx} to <code>IsUserAction='Y'</code>. | */
@ModelChange(timings = { ModelValidator.TYPE_AFTER_DELETE }, ifUIAction = true)
public void onDeleteAsUserAction(final I_M_PickingSlot_HU pickingSlotHU)
{
final PickingSlotId pickingSlotId = PickingSlotId.ofRepoId(pickingSlotHU.getM_PickingSlot_ID());
final HuId huId = HuId.ofRepoId(pickingSlotHU.getM_HU_ID());
final IHUPickingSlotBL.IQueueActionResult result = pickingSlotBL.removeFromPickingSlotQueue(pickingSlotId, huId);
final I_M_PickingSlot_Trx pickingSlotTrx = Check.assumeNotNull(result.getM_PickingSlot_Trx(),
"The result of addToPickingSlotQueue contains a M_PickingSlot_Trx for {} and {} ", pickingSlotId, huId);
pickingSlotTrx.setIsUserAction(true);
InterfaceWrapperHelper.save(pickingSlotTrx);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_PickingSlot_HU.java | 1 |
请完成以下Java代码 | public <ET> QueryResultPage<ET> loadPage(
@NonNull final Class<ET> clazz,
@NonNull final String pageIdentifier)
{
final PageDescriptor currentPageDescriptor = pageDescriptorRepository.getBy(pageIdentifier);
if (currentPageDescriptor == null)
{
throw new UnknownPageIdentifierException(pageIdentifier);
}
return loadPage(clazz, currentPageDescriptor);
}
private <ET> QueryResultPage<ET> loadPage(
@NonNull final Class<ET> clazz,
@NonNull final PageDescriptor currentPageDescriptor)
{
final TypedSqlQuery<ET> query = QuerySelectionHelper.createUUIDSelectionQuery(
PlainContextAware.newWithThreadInheritedTrx(),
clazz,
currentPageDescriptor.getPageIdentifier().getSelectionUid());
final int currentPageSize = currentPageDescriptor.getPageSize();
final List<ET> items = query
.addWhereClause(
true /* joinByAnd */,
QuerySelectionHelper.SELECTION_LINE_ALIAS + " > " + currentPageDescriptor.getOffset())
.setLimit(currentPageSize)
.list(clazz);
final int actualPageSize = items.size();
logger.debug("Loaded next page: bufferSize={}, offset={} -> {} records",
currentPageSize, currentPageDescriptor.getOffset(), actualPageSize); | // True when buffer contains as much data as was required. If this flag is false then it's a good indicator that we are on last page.
final boolean pageFullyLoaded = actualPageSize >= currentPageSize;
final PageDescriptor nextPageDescriptor;
if (pageFullyLoaded)
{
nextPageDescriptor = currentPageDescriptor.createNext();
pageDescriptorRepository.save(nextPageDescriptor);
}
else
{
nextPageDescriptor = null;
}
return new QueryResultPage<ET>(
currentPageDescriptor,
nextPageDescriptor,
currentPageDescriptor.getTotalSize(),
currentPageDescriptor.getSelectionTime(),
ImmutableList.copyOf(items));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\selection\pagination\PaginationService.java | 1 |
请完成以下Java代码 | public Pointcut getPointcut() {
return this.pointcut;
}
@Override
public Advice getAdvice() {
synchronized (this.adviceMonitor) {
if (this.interceptor == null) {
Assert.notNull(this.adviceBeanName, "'adviceBeanName' must be set for use with bean factory lookup.");
Assert.state(this.beanFactory != null, "BeanFactory must be set to resolve 'adviceBeanName'");
this.interceptor = this.beanFactory.getBean(this.adviceBeanName, MethodInterceptor.class);
}
return this.interceptor;
}
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
this.adviceMonitor = new Object(); | this.attributeSource = this.beanFactory.getBean(this.metadataSourceBeanName,
MethodSecurityMetadataSource.class);
}
class MethodSecurityMetadataSourcePointcut extends StaticMethodMatcherPointcut implements Serializable {
@Override
public boolean matches(Method m, Class<?> targetClass) {
MethodSecurityMetadataSource source = MethodSecurityMetadataSourceAdvisor.this.attributeSource;
return !CollectionUtils.isEmpty(source.getAttributes(m, targetClass));
}
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\aopalliance\MethodSecurityMetadataSourceAdvisor.java | 1 |
请完成以下Java代码 | public I_C_UOM getC_UOM()
{
return uom;
}
@Override
public void setC_UOM(final I_C_UOM uom)
{
this.uom = uom;
}
@Override
public BigDecimal getQty()
{
return qty;
}
@Override
public void setQty(final BigDecimal qty)
{
this.qty = qty;
}
@Override
public BigDecimal getQtyProjected()
{
return qtyProjected;
}
@Override
public void setQtyProjected(final BigDecimal qtyProjected)
{
this.qtyProjected = qtyProjected;
}
@Override
public BigDecimal getPercentage()
{
return percentage;
}
@Override
public void setPercentage(final BigDecimal percentage)
{
this.percentage = percentage;
}
@Override
public boolean isNegateQtyInReport()
{
return negateQtyInReport;
}
@Override
public void setNegateQtyInReport(final boolean negateQtyInReport)
{
this.negateQtyInReport = negateQtyInReport; | }
@Override
public String getComponentType()
{
return componentType;
}
@Override
public void setComponentType(final String componentType)
{
this.componentType = componentType;
}
@Override
public String getVariantGroup()
{
return variantGroup;
}
@Override
public void setVariantGroup(final String variantGroup)
{
this.variantGroup = variantGroup;
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfo()
{
return handlingUnitsInfo;
}
@Override
public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo)
{
this.handlingUnitsInfo = handlingUnitsInfo;
}
@Override
public void setHandlingUnitsInfoProjected(final IHandlingUnitsInfo handlingUnitsInfo)
{
handlingUnitsInfoProjected = handlingUnitsInfo;
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfoProjected()
{
return handlingUnitsInfoProjected;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLine.java | 1 |
请完成以下Java代码 | private Properties getCtx()
{
return Env.getCtx();
}
private JPopupMenu getPopupMenu()
{
final Properties ctx = getCtx();
final List<SwingRelatedProcessDescriptor> processes = model.fetchProcesses(ctx, parent.getCurrentTab());
if (processes.isEmpty())
{
return null;
}
final String adLanguage = Env.getAD_Language(ctx);
final JPopupMenu popup = new JPopupMenu("ProcessMenu");
processes.stream()
.map(process -> createProcessMenuItem(process, adLanguage))
.sorted(Comparator.comparing(CMenuItem::getText))
.forEach(mi -> popup.add(mi));
return popup;
}
public void showPopup()
{
final JPopupMenu popup = getPopupMenu();
if (popup == null)
{
return;
}
final AbstractButton button = action.getButton();
if (button.isShowing())
{
popup.show(button, 0, button.getHeight()); // below button
}
}
private CMenuItem createProcessMenuItem(final SwingRelatedProcessDescriptor process, final String adLanguage)
{
final CMenuItem mi = new CMenuItem(process.getCaption(adLanguage));
mi.setIcon(process.getIcon());
mi.setToolTipText(process.getDescription(adLanguage));
if (process.isEnabled())
{
mi.setEnabled(true); | mi.addActionListener(event -> startProcess(process));
}
else
{
mi.setEnabled(false);
mi.setToolTipText(process.getDisabledReason(adLanguage));
}
return mi;
}
private void startProcess(final SwingRelatedProcessDescriptor process)
{
final String adLanguage = Env.getAD_Language(getCtx());
final VButton button = new VButton(
"StartProcess", // columnName,
false, // mandatory,
false, // isReadOnly,
true, // isUpdateable,
process.getCaption(adLanguage),
process.getDescription(adLanguage),
process.getHelp(adLanguage),
process.getAD_Process_ID());
// Invoke action
parent.actionButton(button);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\AProcess.java | 1 |
请完成以下Java代码 | public void onUserLogin(final int AD_Org_ID_IGNORED, final int AD_Role_ID_IGNORED, final int AD_User_ID_IGNORED)
{
logCustomizerConfig();
}
private void logCustomizerConfig()
{
final String customizerConfig = LogManager.dumpCustomizerConfig();
// try to get the current log level for this interceptor's logger
final String logLevelBkp = LogManager.getLoggerLevelName(logger);
if (Check.isEmpty(logLevelBkp))
{
System.err.println("Unable to log the customizer config to logger=" + logger);
System.err.println("Writing the customizer config to std-err instead"); | // there is a problem, but still try to output the information.
System.err.println(customizerConfig);
return;
}
// this is the normal case. Make sure that we are loglevel info, log the information and set the logger back to its former level.
try
{
LogManager.setLoggerLevel(logger, Level.INFO);
logger.info(customizerConfig);
}
finally
{
LogManager.setLoggerLevel(logger, logLevelBkp);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\model\interceptor\LoggingModuleInterceptor.java | 1 |
请完成以下Java代码 | public String getDeleteReason() {
return deleteReason;
}
@Override
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
@Override
public String getActivityId() {
return activityId;
}
@Override
public void setActivityId(String activityId) {
this.activityId = activityId;
}
@Override
public String getActivityName() {
return activityName;
}
@Override
public void setActivityName(String activityName) {
this.activityName = activityName;
}
@Override
public String getActivityType() {
return activityType;
}
@Override
public void setActivityType(String activityType) {
this.activityType = activityType;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@Override
public String getAssignee() {
return assignee;
}
@Override
public void setAssignee(String assignee) {
this.assignee = assignee;
}
@Override
public String getCompletedBy() {
return completedBy;
}
@Override
public void setCompletedBy(String completedBy) {
this.completedBy = completedBy;
}
@Override
public String getTaskId() {
return taskId;
}
@Override
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public String getCalledProcessInstanceId() { | return calledProcessInstanceId;
}
@Override
public void setCalledProcessInstanceId(String calledProcessInstanceId) {
this.calledProcessInstanceId = calledProcessInstanceId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public Date getTime() {
return getStartTime();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ActivityInstanceEntity[id=").append(id)
.append(", activityId=").append(activityId);
if (activityName != null) {
sb.append(", activityName=").append(activityName);
}
sb.append(", executionId=").append(executionId)
.append(", definitionId=").append(processDefinitionId);
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ActivityInstanceEntityImpl.java | 1 |
请完成以下Java代码 | public static void normalizeExp(double[] predictionScores)
{
double max = Double.NEGATIVE_INFINITY;
for (double value : predictionScores)
{
max = Math.max(max, value);
}
double sum = 0.0;
//通过减去最大值防止浮点数溢出
for (int i = 0; i < predictionScores.length; i++)
{
predictionScores[i] = Math.exp(predictionScores[i] - max);
sum += predictionScores[i];
}
if (sum != 0.0)
{
for (int i = 0; i < predictionScores.length; i++)
{
predictionScores[i] /= sum; | }
}
}
/**
* 从一个词到另一个词的词的花费
*
* @param from 前面的词
* @param to 后面的词
* @return 分数
*/
public static double calculateWeight(Vertex from, Vertex to)
{
int fFrom = from.getAttribute().totalFrequency;
int fBigram = CoreBiGramTableDictionary.getBiFrequency(from.wordID, to.wordID);
int fTo = to.getAttribute().totalFrequency;
// logger.info(String.format("%5s frequency:%6d, %s fBigram:%3d, weight:%.2f", from.word, frequency, from.word + "@" + to.word, fBigram, value));
return -Math.log(Predefine.lambda * (Predefine.myu * fBigram / (fFrom + 1) + 1 - Predefine.myu) + (1 - Predefine.lambda) * fTo / Predefine.TOTAL_FREQUENCY);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\MathUtility.java | 1 |
请完成以下Java代码 | public Result processWorkPackage(
final @NonNull I_C_Queue_WorkPackage workpackage,
final String localTrxName_NOTUSED)
{
try
{
final File outputFile = concatenateFiles(workpackage);
attachmentEntryService.createNewAttachment(workpackage.getC_Async_Batch(), outputFile);
}
catch (Exception ex)
{
logger.warn("Failed concatenating files", ex);
Loggables.withLogger(logger, Level.ERROR).addLog(ex.getLocalizedMessage());
}
return Result.SUCCESS;
}
private File concatenateFiles(final I_C_Queue_WorkPackage workpackage) throws IOException, DocumentException
{
final File file = createNewTemporaryPDFFile(workpackage);
final Document document = new Document();
final FileOutputStream fos = new FileOutputStream(file, false);
try
{
final PdfCopy copy = new PdfCopy(document, fos);
document.open();
final List<I_C_Printing_Queue> pqs = queueDAO.retrieveAllItems(workpackage, I_C_Printing_Queue.class);
for (final I_C_Printing_Queue pq : pqs)
{
try (final MDC.MDCCloseable ignored = TableRecordMDC.putTableRecordReference(pq))
{
if (pq.isProcessed())
{
Loggables.withLogger(logger, Level.DEBUG).addLog("*** Printing queue is already processed. Skipping it: {}", pq);
continue;
}
final PdfReader reader = getPdfReader(pq);
appendToPdf(copy, reader);
copy.freeReader(reader);
reader.close();
printingQueueBL.setProcessedAndSave(pq);
}
}
}
finally
{
document.close();
fos.close();
return file;
}
}
@NonNull
private File createNewTemporaryPDFFile(final I_C_Queue_WorkPackage workpackage)
{
final I_C_Async_Batch asyncBatch = workpackage.getC_Async_Batch();
Check.assumeNotNull(asyncBatch, "Async batch is not null");
final String fileName = "PDF_" + asyncBatch.getC_Async_Batch_ID();
try
{ | return File.createTempFile(fileName, ".pdf");
}
catch (Exception ex)
{
throw new AdempiereException("Failed to create temporary file with prefix: " + fileName, ex);
}
}
@NonNull
private PdfReader getPdfReader(final I_C_Printing_Queue pq)
{
final I_AD_Archive archive = pq.getAD_Archive();
Check.assumeNotNull(archive, "Archive references an AD_Archive record");
final byte[] data = archiveBL.getBinaryData(archive);
try
{
return new PdfReader(data);
}
catch (IOException e)
{
throw new AdempiereException("Failed to create PDF reader from archive=" + archive + ", printing queue=" + pq, e);
}
}
private void appendToPdf(final PdfCopy pdf, final PdfReader from)
{
try
{
for (int page = 0; page < from.getNumberOfPages(); )
{
pdf.addPage(pdf.getImportedPage(from, ++page));
}
}
catch (IOException | BadPdfFormatException e)
{
throw new AdempiereException("Failed appending to pdf=" + pdf + " from " + from, e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\async\spi\impl\PrintingQueuePDFConcatenateWorkpackageProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonPickingJobQtyAvailable
{
@Nullable QtyAvailableStatus status;
@NonNull Map<PickingJobLineId, Line> lines;
public static JsonPickingJobQtyAvailable of(PickingJobQtyAvailable from)
{
return builder()
.status(from.getStatus())
.lines(from.getLines().stream()
.map(Line::of)
.collect(ImmutableMap.toImmutableMap(Line::getLineId, line -> line)))
.build();
}
//
//
//
//
//
@Value
@Builder
@Jacksonized
public static class Line
{
@NonNull PickingJobLineId lineId; | @Nullable QtyAvailableStatus status;
@NonNull String uom;
@NonNull BigDecimal qtyRemainingToPick;
@Nullable BigDecimal qtyAvailableToPick;
public static Line of(PickingJobLineQtyAvailable from)
{
return builder()
.lineId(from.getLineId())
.status(from.getStatus())
.uom(from.getUomSymbol())
.qtyRemainingToPick(from.getQtyRemainingToPick().toBigDecimal())
.qtyAvailableToPick(from.getQtyAvailableToPick() != null ? from.getQtyAvailableToPick().toBigDecimal() : null)
.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\rest_api\json\JsonPickingJobQtyAvailable.java | 2 |
请完成以下Java代码 | public ITcpConnectionEndPoint getEndPoint()
{
return endPoint;
}
public void setEndPoint(final ITcpConnectionEndPoint endPoint)
{
this.endPoint = endPoint;
}
/**
* See {@link #setRoundToPrecision(int)}.
*
* @return
*/
public int getRoundToPrecision()
{
return roundToPrecision;
}
/**
* This value is used to configure the {@link ScalesGetWeightHandler}.
*
* @param roundToPrecision may be <code>null</code> in that case, not rounding will be done.
* @see ScalesGetWeightHandler#setroundWeightToPrecision(int)
*/
public void setRoundToPrecision(final Integer roundToPrecision)
{
this.roundToPrecision = roundToPrecision == null
? -1
: roundToPrecision;
}
@Override
public IDeviceResponseGetConfigParams getRequiredConfigParams()
{ | final List<IDeviceConfigParam> params = new ArrayList<IDeviceConfigParam>();
// params.add(new DeviceConfigParamPojo("DeviceClass", "DeviceClass", "")); // if we can query this device for its params, then we already know the device class.
params.add(new DeviceConfigParam(PARAM_ENDPOINT_CLASS, "Endpoint.Class", ""));
params.add(new DeviceConfigParam(PARAM_ENDPOINT_IP, "Endpoint.IP", ""));
params.add(new DeviceConfigParam(PARAM_ENDPOINT_PORT, "Endpoint.Port", ""));
params.add(new DeviceConfigParam(PARAM_ENDPOINT_RETURN_LAST_LINE, PARAM_ENDPOINT_RETURN_LAST_LINE, "N"));
params.add(new DeviceConfigParam(PARAM_ENDPOINT_READ_TIMEOUT_MILLIS, PARAM_ENDPOINT_READ_TIMEOUT_MILLIS, "500"));
params.add(new DeviceConfigParam(PARAM_ROUND_TO_PRECISION, "RoundToPrecision", "-1"));
return new IDeviceResponseGetConfigParams()
{
@Override
public List<IDeviceConfigParam> getParams()
{
return params;
}
};
}
@Override
public IDeviceRequestHandler<DeviceRequestConfigureDevice, IDeviceResponse> getConfigureDeviceHandler()
{
return new ConfigureDeviceHandler(this);
}
@Override
public String toString()
{
return getClass().getSimpleName() + " with Endpoint " + endPoint.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\AbstractTcpScales.java | 1 |
请完成以下Java代码 | public void start() {
if (isRunning()) {
return;
}
try {
InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(this.defaultPartitionSuffix);
config.addAdditionalBindCredentials("uid=admin,ou=system", "secret");
config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("LDAP", this.port));
config.setEnforceSingleStructuralObjectClass(false);
config.setEnforceAttributeSyntaxCompliance(true);
DN dn = new DN(this.defaultPartitionSuffix);
Entry entry = new Entry(dn);
entry.addAttribute("objectClass", "top", "domain", "extensibleObject");
entry.addAttribute("dc", dn.getRDN().getAttributeValues()[0]);
InMemoryDirectoryServer directoryServer = new InMemoryDirectoryServer(config);
directoryServer.add(entry);
importLdif(directoryServer);
directoryServer.startListening();
this.port = directoryServer.getListenPort();
this.directoryServer = directoryServer;
this.running = true;
}
catch (LDAPException ex) {
throw new RuntimeException("Server startup failed", ex);
}
}
private void importLdif(InMemoryDirectoryServer directoryServer) {
if (StringUtils.hasText(this.ldif)) {
try {
Resource[] resources = this.context.getResources(this.ldif);
if (resources.length > 0) {
if (!resources[0].exists()) {
throw new IllegalArgumentException("Unable to find LDIF resource " + this.ldif);
}
try (InputStream inputStream = resources[0].getInputStream()) {
directoryServer.importFromLDIF(false, new LDIFReader(inputStream));
}
}
}
catch (Exception ex) { | throw new IllegalStateException("Unable to load LDIF " + this.ldif, ex);
}
}
}
@Override
public void stop() {
if (this.isEphemeral && this.context != null && !this.context.isClosed()) {
return;
}
this.directoryServer.shutDown(true);
this.running = false;
}
@Override
public boolean isRunning() {
return this.running;
}
} | repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\server\UnboundIdContainer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class XmlTransport
{
@NonNull
String from;
@NonNull
String to;
@Singular
List<XmlVia> vias;
@Value
@Builder
public static class XmlVia
{
@NonNull
String via;
@NonNull
Integer sequenceId;
}
public XmlTransport withMod(@Nullable final TransportMod transportMod)
{
if (transportMod == null)
{
return this;
}
final XmlTransportBuilder builder = toBuilder();
if (transportMod.getFrom() != null)
{
builder.from(transportMod.getFrom());
}
final List<String> replacementViaEANs = transportMod.getReplacementViaEANs();
if (replacementViaEANs != null && !replacementViaEANs.isEmpty())
{
builder.clearVias();
int currentMaxSeqNo = 0;
for (final String replacementViaEAN : replacementViaEANs)
{
currentMaxSeqNo += 1;
final XmlVia xmlVia = XmlVia.builder()
.via(replacementViaEAN)
.sequenceId(currentMaxSeqNo)
.build();
builder.via(xmlVia);
}
}
final List<String> additionalViaEANs = transportMod.getAdditionalViaEANs();
if (additionalViaEANs != null)
{
int currentMaxSeqNo = getVias()
.stream()
.map(XmlVia::getSequenceId) // is never null
.max(Comparator.naturalOrder())
.orElse(0);
for (final String additionalViaEAN : additionalViaEANs) | {
currentMaxSeqNo += 1;
final XmlVia xmlVia = XmlVia.builder()
.via(additionalViaEAN)
.sequenceId(currentMaxSeqNo)
.build();
builder.via(xmlVia);
}
}
return builder
.build();
}
@Value
@Builder
public static class TransportMod
{
@Nullable
String from;
/** {@code null} or an empty list both mean "don't replace" */
@Singular
List<String> replacementViaEANs;
@Singular
List<String> additionalViaEANs;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\request\model\processing\XmlTransport.java | 2 |
请完成以下Java代码 | public final class Hex {
private static final char[] HEX = "0123456789abcdef".toCharArray();
private Hex() {
}
public static char[] encode(byte[] bytes) {
final int nBytes = bytes.length;
char[] result = new char[2 * nBytes];
int j = 0;
for (byte aByte : bytes) {
// Char for top 4 bits
result[j++] = HEX[(0xF0 & aByte) >>> 4];
// Bottom 4
result[j++] = HEX[(0x0F & aByte)];
}
return result;
} | public static byte[] decode(CharSequence s) {
int nChars = s.length();
if (nChars % 2 != 0) {
throw new IllegalArgumentException("Hex-encoded string must have an even number of characters");
}
byte[] result = new byte[nChars / 2];
for (int i = 0; i < nChars; i += 2) {
int msb = Character.digit(s.charAt(i), 16);
int lsb = Character.digit(s.charAt(i + 1), 16);
if (msb < 0 || lsb < 0) {
throw new IllegalArgumentException(
"Detected a Non-hex character at " + (i + 1) + " or " + (i + 2) + " position");
}
result[i / 2] = (byte) ((msb << 4) | lsb);
}
return result;
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\codec\Hex.java | 1 |
请完成以下Java代码 | public String getFirstLetter() {
return firstLetter;
}
public void setFirstLetter(String firstLetter) {
this.firstLetter = firstLetter;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Integer getFactoryStatus() {
return factoryStatus;
}
public void setFactoryStatus(Integer factoryStatus) {
this.factoryStatus = factoryStatus;
}
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public Integer getProductCount() {
return productCount;
}
public void setProductCount(Integer productCount) {
this.productCount = productCount;
}
public Integer getProductCommentCount() {
return productCommentCount;
}
public void setProductCommentCount(Integer productCommentCount) {
this.productCommentCount = productCommentCount;
}
public String getLogo() { | return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getBigPic() {
return bigPic;
}
public void setBigPic(String bigPic) {
this.bigPic = bigPic;
}
public String getBrandStory() {
return brandStory;
}
public void setBrandStory(String brandStory) {
this.brandStory = brandStory;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", firstLetter=").append(firstLetter);
sb.append(", sort=").append(sort);
sb.append(", factoryStatus=").append(factoryStatus);
sb.append(", showStatus=").append(showStatus);
sb.append(", productCount=").append(productCount);
sb.append(", productCommentCount=").append(productCommentCount);
sb.append(", logo=").append(logo);
sb.append(", bigPic=").append(bigPic);
sb.append(", brandStory=").append(brandStory);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsBrand.java | 1 |
请完成以下Java代码 | public void setThrowableAnalyzer(ThrowableAnalyzer throwableAnalyzer) {
Assert.notNull(throwableAnalyzer, "throwableAnalyzer must not be null");
this.throwableAnalyzer = throwableAnalyzer;
}
/**
* @since 5.5
*/
@Override
public void setMessageSource(MessageSource messageSource) {
Assert.notNull(messageSource, "messageSource cannot be null");
this.messages = new MessageSourceAccessor(messageSource);
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
/**
* Default implementation of <code>ThrowableAnalyzer</code> which is capable of also
* unwrapping <code>ServletException</code>s.
*/ | private static final class DefaultThrowableAnalyzer extends ThrowableAnalyzer {
/**
* @see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap()
*/
@Override
protected void initExtractorMap() {
super.initExtractorMap();
registerExtractor(ServletException.class, (throwable) -> {
ThrowableAnalyzer.verifyThrowableHierarchy(throwable, ServletException.class);
return ((ServletException) throwable).getRootCause();
});
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\ExceptionTranslationFilter.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public String[] getActivityIds() {
return activityIds;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getJobType() { | return jobType;
}
public String getJobConfiguration() {
return jobConfiguration;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public Boolean getWithOverridingJobPriority() {
return withOverridingJobPriority;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\JobDefinitionQueryImpl.java | 1 |
请完成以下Java代码 | public static CompositeRecordAccessHandler of(@NonNull final Collection<RecordAccessHandler> handlers)
{
if (handlers.isEmpty())
{
return CompositeRecordAccessHandler.EMPTY;
}
else
{
return new CompositeRecordAccessHandler(handlers);
}
}
public static final CompositeRecordAccessHandler EMPTY = new CompositeRecordAccessHandler();
private final ImmutableSet<RecordAccessHandler> handlers;
@Getter
private final ImmutableSet<RecordAccessFeature> handledFeatures;
@Getter
private final ImmutableSet<String> handledTableNames;
private CompositeRecordAccessHandler()
{
handlers = ImmutableSet.of();
handledFeatures = ImmutableSet.of();
handledTableNames = ImmutableSet.of();
}
private CompositeRecordAccessHandler(@NonNull final Collection<RecordAccessHandler> handlers)
{
this.handlers = ImmutableSet.copyOf(handlers);
handledFeatures = handlers.stream()
.flatMap(handler -> handler.getHandledFeatures().stream()) | .collect(ImmutableSet.toImmutableSet());
handledTableNames = handlers.stream()
.flatMap(handler -> handler.getHandledTableNames().stream())
.collect(ImmutableSet.toImmutableSet());
}
public boolean isEmpty()
{
return handlers.isEmpty();
}
public ImmutableSet<RecordAccessHandler> handlingFeatureSet(final Set<RecordAccessFeature> features)
{
if (features.isEmpty())
{
return ImmutableSet.of();
}
return handlers.stream()
.filter(handler -> isAnyFeatureHandled(handler, features))
.collect(ImmutableSet.toImmutableSet());
}
private static boolean isAnyFeatureHandled(final RecordAccessHandler handler, final Set<RecordAccessFeature> features)
{
return !Sets.intersection(handler.getHandledFeatures(), features).isEmpty();
}
public boolean isTableHandled(@NonNull final String tableName)
{
return getHandledTableNames().contains(tableName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\record_access\handlers\CompositeRecordAccessHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AttachmentEntryId implements RepoIdAware
{
@JsonCreator
public static AttachmentEntryId ofRepoId(final int repoId)
{
return new AttachmentEntryId(repoId);
}
public static AttachmentEntryId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int getRepoId(final AttachmentEntryId attachmentEntryId)
{
return attachmentEntryId != null ? attachmentEntryId.getRepoId() : -1;
}
int repoId;
private AttachmentEntryId(final int repoId)
{ | this.repoId = Check.assumeGreaterThanZero(repoId, "repoId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final AttachmentEntryId id1, @Nullable final AttachmentEntryId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntryId.java | 2 |
请完成以下Java代码 | protected VariableMap getOutputVariables(VariableScope calledElementScope) {
return getCallableElement().getOutputVariables(calledElementScope);
}
protected VariableMap getOutputVariablesLocal(VariableScope calledElementScope) {
return getCallableElement().getOutputVariablesLocal(calledElementScope);
}
protected Integer getVersion(ActivityExecution execution) {
return getCallableElement().getVersion(execution);
}
protected String getDeploymentId(ActivityExecution execution) {
return getCallableElement().getDeploymentId();
}
protected CallableElementBinding getBinding() {
return getCallableElement().getBinding(); | }
protected boolean isLatestBinding() {
return getCallableElement().isLatestBinding();
}
protected boolean isDeploymentBinding() {
return getCallableElement().isDeploymentBinding();
}
protected boolean isVersionBinding() {
return getCallableElement().isVersionBinding();
}
protected abstract void startInstance(ActivityExecution execution, VariableMap variables, String businessKey);
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\CallableElementActivityBehavior.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8761
app:
id: springboot-apollo
apollo:
meta: http://127.0.0.1:8080
bootstrap:
enabled: true
eagerLoad:
enabled: tr | ue
logging:
level:
com:
gf:
controller: debug | repos\SpringBootLearning-master (1)\springboot-apollo\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public Quantity of(
@NonNull final Quantity qty,
@NonNull final UOMConversionContext conversionCtx,
@NonNull final UomId targetUomId)
{
final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
return uomConversionBL.convertQuantityTo(qty, conversionCtx, targetUomId);
}
public Quantity of(final int qty, @NonNull final UomId repoId)
{
return of(BigDecimal.valueOf(qty), repoId);
}
@Nullable
public static BigDecimal toBigDecimalOrNull(@Nullable final Quantity quantity)
{
return toBigDecimalOr(quantity, null);
}
@NonNull
public static BigDecimal toBigDecimalOrZero(@Nullable final Quantity quantity)
{
return toBigDecimalOr(quantity, BigDecimal.ZERO);
}
@Contract(value = "null, null -> null; _, !null -> !null; !null, _ -> !null", pure = true)
@Nullable
private static BigDecimal toBigDecimalOr(@Nullable final Quantity quantity, @Nullable final BigDecimal defaultValue)
{
if (quantity == null)
{
return defaultValue;
}
return quantity.toBigDecimal();
}
public static class QuantityDeserializer extends StdDeserializer<Quantity>
{
private static final long serialVersionUID = -5406622853902102217L;
public QuantityDeserializer()
{
super(Quantity.class);
}
@Override
public Quantity deserialize(final JsonParser p, final DeserializationContext ctx) throws IOException
{
final JsonNode node = p.getCodec().readTree(p);
final String qtyStr = node.get("qty").asText();
final int uomRepoId = (Integer)node.get("uomId").numberValue();
final String sourceQtyStr;
final int sourceUomRepoId;
if (node.has("sourceQty"))
{
sourceQtyStr = node.get("sourceQty").asText();
sourceUomRepoId = (Integer)node.get("sourceUomId").numberValue();
}
else
{
sourceQtyStr = qtyStr;
sourceUomRepoId = uomRepoId;
}
return Quantitys.of(
new BigDecimal(qtyStr), UomId.ofRepoId(uomRepoId),
new BigDecimal(sourceQtyStr), UomId.ofRepoId(sourceUomRepoId));
} | }
public static class QuantitySerializer extends StdSerializer<Quantity>
{
private static final long serialVersionUID = -8292209848527230256L;
public QuantitySerializer()
{
super(Quantity.class);
}
@Override
public void serialize(final Quantity value, final JsonGenerator gen, final SerializerProvider provider) throws IOException
{
gen.writeStartObject();
final String qtyStr = value.toBigDecimal().toString();
final int uomId = value.getUomId().getRepoId();
gen.writeFieldName("qty");
gen.writeString(qtyStr);
gen.writeFieldName("uomId");
gen.writeNumber(uomId);
final String sourceQtyStr = value.getSourceQty().toString();
final int sourceUomId = value.getSourceUomId().getRepoId();
if (!qtyStr.equals(sourceQtyStr) || uomId != sourceUomId)
{
gen.writeFieldName("sourceQty");
gen.writeString(sourceQtyStr);
gen.writeFieldName("sourceUomId");
gen.writeNumber(sourceUomId);
}
gen.writeEndObject();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\Quantitys.java | 1 |
请完成以下Java代码 | public class Line implements Serializable {
private String name;
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate dob;
private Long age;
public Line(String name, LocalDate dob) {
this.name = name;
this.dob = dob;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
public Long getAge() {
return age;
} | public void setAge(Long age) {
this.age = age;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(this.name);
sb.append(",");
sb.append(this.dob.format(DateTimeFormatter.ofPattern("MM/dd/yyyy")));
if (this.age != null) {
sb.append(",");
sb.append(this.age);
}
sb.append("]");
return sb.toString();
}
} | repos\tutorials-master\spring-batch\src\main\java\com\baeldung\taskletsvschunks\model\Line.java | 1 |
请完成以下Java代码 | public void setConfigurationLevel (String ConfigurationLevel)
{
set_Value (COLUMNNAME_ConfigurationLevel, ConfigurationLevel);
}
/** Get Configuration Level.
@return Configuration Level for this parameter
*/
public String getConfigurationLevel ()
{
return (String)get_Value(COLUMNNAME_ConfigurationLevel);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** 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);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name. | @return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SysConfig.java | 1 |
请完成以下Java代码 | public void setRfq_BidStartDate (java.sql.Timestamp Rfq_BidStartDate)
{
set_Value (COLUMNNAME_Rfq_BidStartDate, Rfq_BidStartDate);
}
/** Get Bid start date.
@return Bid start date */
@Override
public java.sql.Timestamp getRfq_BidStartDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_Rfq_BidStartDate);
}
/**
* RfQType AD_Reference_ID=540661
* Reference name: RfQType
*/
public static final int RFQTYPE_AD_Reference_ID=540661;
/** Default = D */
public static final String RFQTYPE_Default = "D";
/** Procurement = P */
public static final String RFQTYPE_Procurement = "P";
/** Set Ausschreibung Art.
@param RfQType Ausschreibung Art */
@Override
public void setRfQType (java.lang.String RfQType)
{
set_Value (COLUMNNAME_RfQType, RfQType);
}
/** Get Ausschreibung Art.
@return Ausschreibung Art */
@Override
public java.lang.String getRfQType ()
{
return (java.lang.String)get_Value(COLUMNNAME_RfQType);
}
@Override
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException
{ | return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep)
{
set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep);
}
/** Set Aussendienst.
@param SalesRep_ID Aussendienst */
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Aussendienst.
@return Aussendienst */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ.java | 1 |
请完成以下Java代码 | public class Book {
/**
* TODO Auto-generated attribute documentation
*
*/
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
/**
* TODO Auto-generated attribute documentation
*
*/
@Version
private Integer version;
/**
* TODO Auto-generated attribute documentation
* | */
@NotNull
private String title;
/**
* TODO Auto-generated attribute documentation
*
*/
@NotNull
private String author;
/**
* TODO Auto-generated attribute documentation
*
*/
@NotNull
private String isbn;
} | repos\tutorials-master\spring-roo\src\main\java\com\baeldung\domain\Book.java | 1 |
请完成以下Java代码 | public class PreDefinedSection implements Section {
private final String title;
private final List<Section> subSections = new ArrayList<>();
public PreDefinedSection(String title) {
this.title = title;
}
public PreDefinedSection addSection(Section section) {
this.subSections.add(section);
return this;
}
@Override
public void write(PrintWriter writer) throws IOException {
if (!isEmpty()) {
writer.println("# " + this.title);
writer.println(""); | for (Section section : resolveSubSections(this.subSections)) {
section.write(writer);
}
}
}
public boolean isEmpty() {
return this.subSections.isEmpty();
}
/**
* Resolve the sections to render based on the current registered sections.
* @param sections the registered sections
* @return the sections to render
*/
protected List<Section> resolveSubSections(List<Section> sections) {
return sections;
}
} | repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\documentation\PreDefinedSection.java | 1 |
请完成以下Java代码 | public int getAD_User_InCharge_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_InCharge_ID);
}
@Override
public void setC_ILCandHandler_ID (final int C_ILCandHandler_ID)
{
if (C_ILCandHandler_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ILCandHandler_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ILCandHandler_ID, C_ILCandHandler_ID);
}
@Override
public int getC_ILCandHandler_ID()
{
return get_ValueAsInt(COLUMNNAME_C_ILCandHandler_ID);
}
@Override
public void setClassname (final java.lang.String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
@Override
public java.lang.String getClassname()
{
return get_ValueAsString(COLUMNNAME_Classname);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@Override | public void setIs_AD_User_InCharge_UI_Setting (final boolean Is_AD_User_InCharge_UI_Setting)
{
set_Value (COLUMNNAME_Is_AD_User_InCharge_UI_Setting, Is_AD_User_InCharge_UI_Setting);
}
@Override
public boolean is_AD_User_InCharge_UI_Setting()
{
return get_ValueAsBoolean(COLUMNNAME_Is_AD_User_InCharge_UI_Setting);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setTableName (final java.lang.String TableName)
{
set_Value (COLUMNNAME_TableName, TableName);
}
@Override
public java.lang.String getTableName()
{
return get_ValueAsString(COLUMNNAME_TableName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_ILCandHandler.java | 1 |
请完成以下Java代码 | public void setPromotionUsageLimit (int PromotionUsageLimit)
{
set_Value (COLUMNNAME_PromotionUsageLimit, Integer.valueOf(PromotionUsageLimit));
}
/** Get Usage Limit.
@return Maximum usage limit
*/
public int getPromotionUsageLimit ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PromotionUsageLimit);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/ | public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionPreCondition.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FactAcctChanges
{
@NonNull FactAcctChangesType type;
@Nullable FactLineMatchKey matchKey;
@NonNull AcctSchemaId acctSchemaId;
@NonNull PostingSign postingSign;
@Nullable ElementValueId accountId;
@NonNull Money amount_DC;
@NonNull Money amount_LC;
@Nullable TaxId taxId;
@Nullable String description;
@Nullable ProductId productId;
@Nullable String userElementString1;
@Nullable OrderId salesOrderId;
@Nullable ActivityId activityId;
@Builder
private FactAcctChanges(
@NonNull final FactAcctChangesType type,
@Nullable final FactLineMatchKey matchKey,
@NonNull final AcctSchemaId acctSchemaId,
@NonNull final PostingSign postingSign,
@Nullable final ElementValueId accountId,
@NonNull final Money amount_DC,
@NonNull final Money amount_LC,
@Nullable final TaxId taxId,
@Nullable final String description,
@Nullable final ProductId productId,
@Nullable final String userElementString1,
@Nullable final OrderId salesOrderId,
@Nullable final ActivityId activityId)
{
if (type.isChangeOrDelete() && matchKey == null)
{
throw new AdempiereException("MatchKey is mandatory when type is " + type);
}
this.type = type;
this.matchKey = matchKey;
this.acctSchemaId = acctSchemaId;
this.postingSign = postingSign;
this.accountId = accountId;
this.amount_DC = amount_DC;
this.amount_LC = amount_LC;
this.taxId = taxId;
this.description = description;
this.productId = productId;
this.userElementString1 = userElementString1; | this.salesOrderId = salesOrderId;
this.activityId = activityId;
}
public ElementValueId getAccountIdNotNull()
{
final ElementValueId accountId = getAccountId();
if (accountId == null)
{
throw new AdempiereException("accountId shall be set for " + this);
}
return accountId;
}
@Nullable
public Money getAmtSourceDr() {return postingSign.isDebit() ? amount_DC : null;}
@Nullable
public Money getAmtSourceCr() {return postingSign.isCredit() ? amount_DC : null;}
@Nullable
public Money getAmtAcctDr() {return postingSign.isDebit() ? amount_LC : null;}
@Nullable
public Money getAmtAcctCr() {return postingSign.isCredit() ? amount_LC : null;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\factacct_userchanges\FactAcctChanges.java | 2 |
请完成以下Java代码 | public class CaseTaskXmlConverter extends TaskXmlConverter {
@Override
public String getXMLElementName() {
return CmmnXmlConstants.ELEMENT_CASE_TASK;
}
@Override
protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) {
CaseTask caseTask = new CaseTask();
convertCommonTaskAttributes(xtr, caseTask);
caseTask.setCaseRef(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_CASE_REF));
String businessKey = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_BUSINESS_KEY);
if (businessKey != null) {
caseTask.setBusinessKey(businessKey);
}
String inheritBusinessKey = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_INHERIT_BUSINESS_KEY);
if (inheritBusinessKey != null) {
caseTask.setInheritBusinessKey(Boolean.parseBoolean(inheritBusinessKey));
}
String fallbackToDefaultTenantValue = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_FALLBACK_TO_DEFAULT_TENANT); | if (fallbackToDefaultTenantValue != null) {
caseTask.setFallbackToDefaultTenant(Boolean.valueOf(fallbackToDefaultTenantValue));
}
String sameDeployment = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_SAME_DEPLOYMENT);
if (sameDeployment != null) {
caseTask.setSameDeployment(Boolean.parseBoolean(sameDeployment));
}
String idVariableName = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_ID_VARIABLE_NAME);
if (StringUtils.isNotEmpty(idVariableName)) {
caseTask.setCaseInstanceIdVariableName(idVariableName);
}
return caseTask;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\CaseTaskXmlConverter.java | 1 |
请完成以下Java代码 | public static LU of(@NonNull final I_M_HU lu, @NonNull final TU... tus)
{
return builder().hu(lu).tus(TUsList.of(tus)).build();
}
public static LU of(@NonNull final I_M_HU lu, @NonNull final List<TU> tus)
{
return builder().hu(lu).tus(TUsList.of(tus)).build();
}
public static LU of(@NonNull final I_M_HU lu, @NonNull final TUsList tus)
{
return builder().hu(lu).tus(tus).build();
}
public LU markedAsPreExistingLU()
{
return this.isPreExistingLU ? this : toBuilder().isPreExistingLU(true).build();
}
public HuId getId() {return HuId.ofRepoId(hu.getM_HU_ID());}
public I_M_HU toHU() {return hu;}
public Stream<I_M_HU> streamAllLUAndTURecords()
{
return Stream.concat(Stream.of(hu), tus.streamHURecords());
}
public Stream<TU> streamTUs() {return tus.stream();}
public QtyTU getQtyTU() {return tus.getQtyTU();}
public LU mergeWith(@NonNull final LU other)
{
if (this.hu.getM_HU_ID() != other.hu.getM_HU_ID())
{
throw new AdempiereException("Cannot merge " + this + " with " + other + " because they don't have the same HU");
}
return builder()
.hu(this.hu)
.isPreExistingLU(this.isPreExistingLU && other.isPreExistingLU)
.tus(this.tus.mergeWith(other.tus))
.build();
} | private static List<LU> mergeLists(final List<LU> list1, final List<LU> list2)
{
if (list2.isEmpty())
{
return list1;
}
if (list1.isEmpty())
{
return list2;
}
else
{
final HashMap<HuId, LU> lusNew = new HashMap<>();
list1.forEach(lu -> lusNew.put(lu.getId(), lu));
list2.forEach(lu -> lusNew.compute(lu.getId(), (luId, existingLU) -> existingLU == null ? lu : existingLU.mergeWith(lu)));
return ImmutableList.copyOf(lusNew.values());
}
}
public boolean containsAnyOfHUIds(final Collection<HuId> huIds)
{
if (huIds.isEmpty()) {return false;}
return huIds.contains(getId()) // LU matches
|| tus.containsAnyOfHUIds(huIds); // any of the TU matches
}
public void forEachAffectedHU(@NonNull final LUTUCUConsumer consumer)
{
tus.forEachAffectedHU(this, consumer);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\LUTUResult.java | 1 |
请完成以下Java代码 | public boolean isFinished() {
return this.finished;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(final ReadListener readListener) {
throw new UnsupportedOperationException();
}
@Override
public int read() throws IOException {
int data = this.inputStream.read();
if (data == -1) {
this.finished = true;
}
return data;
}
@Override
public int available() throws IOException {
return inputStream.available();
}
@Override
public void close() throws IOException {
inputStream.close();
}
@Override
public synchronized void mark(int readlimit) {
inputStream.mark(readlimit); | }
@Override
public synchronized void reset() throws IOException {
inputStream.reset();
}
@Override
public boolean markSupported() {
return inputStream.markSupported();
}
};
}
@Override
public BufferedReader getReader() throws IOException {
return EmptyBodyFilter.this.getReader(this.getInputStream());
}
};
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest-jakarta\src\main\java\org\camunda\bpm\engine\rest\filter\EmptyBodyFilter.java | 1 |
请完成以下Java代码 | public void setEnableSelection(boolean showSelection)
{
m_select = showSelection;
} // setEnableSelection
/**
* Ask the editor if it can start editing using anEvent.
* This method is intended for the use of client to avoid the cost of
* setting up and installing the editor component if editing is not possible.
* If editing can be started this method returns true
*/
@Override
public boolean isCellEditable(EventObject anEvent)
{
return m_select;
} // isCellEditable
/**
* Sets an initial value for the editor. This will cause the editor to
* stopEditing and lose any partially edited value if the editor is editing
* when this method is called.
* Returns the component that should be added to the client's Component hierarchy.
* Once installed in the client's hierarchy this component
* will then be able to draw and receive user input.
*/
@Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int col)
{
log.debug("Value=" + value + ", row=" + row + ", col=" + col);
m_rid = (Object[])value;
if (m_rid == null || m_rid[1] == null)
m_cb.setSelected(false);
else
{
Boolean sel = (Boolean)m_rid[1]; | m_cb.setSelected(sel.booleanValue());
}
return m_cb;
} // getTableCellEditorComponent
/**
* The editing cell should be selected or not
*/
@Override
public boolean shouldSelectCell(EventObject anEvent)
{
return m_select;
} // shouldSelectCell
/**
* Returns the value contained in the editor
*/
@Override
public Object getCellEditorValue()
{
log.debug("" + m_cb.isSelected());
if (m_rid == null)
return null;
m_rid[1] = Boolean.valueOf(m_cb.isSelected());
return m_rid;
} // getCellEditorValue
} // VRowIDEditor | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VRowIDEditor.java | 1 |
请完成以下Java代码 | public Optional<String> getTableName() {return getLookupDataSourceFetcher().getLookupTableName();}
public boolean isNumericKey() {return getLookupDataSourceFetcher().isNumericKey();}
@Override
public boolean hasParameters()
{
return !lookupDataSourceFetcher.getSqlForFetchingLookups().getParameters().isEmpty()
|| (!filters.getDependsOnFieldNames().isEmpty());
}
public ImmutableSet<String> getDependsOnFieldNames()
{
return filters.getDependsOnFieldNames();
}
public ImmutableSet<String> getDependsOnTableNames()
{
return filters.getDependsOnTableNames();
}
@NonNull
public SqlForFetchingLookupById getSqlForFetchingLookupByIdExpression()
{
return lookupDataSourceFetcher.getSqlForFetchingLookupById(); | }
public SqlLookupDescriptor withScope(@Nullable LookupDescriptorProvider.LookupScope scope)
{
return withFilters(this.filters.withOnlyScope(scope));
}
public SqlLookupDescriptor withOnlyForAvailableParameterNames(@Nullable Set<String> onlyForAvailableParameterNames)
{
return withFilters(this.filters.withOnlyForAvailableParameterNames(onlyForAvailableParameterNames));
}
private SqlLookupDescriptor withFilters(@NonNull final CompositeSqlLookupFilter filters)
{
return !Objects.equals(this.filters, filters)
? toBuilder().filters(filters).build()
: this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlLookupDescriptor.java | 1 |
请完成以下Java代码 | public void debugFailedJobListenerSkipped(String jobId) {
logDebug("031", "Failed job listener skipped for job {} because it's been already re-acquired", jobId);
}
public ProcessEngineException jobExecutorPriorityRangeException(String reason) {
return new ProcessEngineException(exceptionMessage("031", "Invalid configuration for job executor priority range. Reason: {}", reason));
}
public void failedAcquisitionLocks(String processEngine, AcquiredJobs acquiredJobs) {
logDebug("033", "Jobs failed to Lock during Acquisition of jobs for the process engine '{}' : {}", processEngine,
acquiredJobs.getNumberOfJobsFailedToLock());
}
public void jobsToAcquire(String processEngine, int numJobsToAcquire) {
logDebug("034", "Attempting to acquire {} jobs for the process engine '{}'", numJobsToAcquire, processEngine);
}
public void rejectedJobExecutions(String processEngine, int numJobsRejected) {
logDebug("035", "Jobs execution rejections for the process engine '{}' : {}", processEngine, numJobsRejected);
}
public void availableJobExecutionThreads(String processEngine, int numAvailableThreads) {
logDebug("036", "Available job execution threads for the process engine '{}' : {}", processEngine,
numAvailableThreads); | }
public void currentJobExecutions(String processEngine, int numExecutions) {
logDebug("037", "Jobs currently in execution for the process engine '{}' : {}", processEngine, numExecutions);
}
public void numJobsInQueue(String processEngine, int numJobsInQueue, int maxQueueSize) {
logDebug("038",
"Jobs currently in queue to be executed for the process engine '{}' : {} (out of the max queue size : {})",
processEngine, numJobsInQueue, maxQueueSize);
}
public void availableThreadsCalculationError() {
logDebug("039", "Arithmetic exception occurred while computing remaining available thread count for logging.");
}
public void totalQueueCapacityCalculationError() {
logDebug("040", "Arithmetic exception occurred while computing total queue capacity for logging.");
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobExecutorLogger.java | 1 |
请完成以下Java代码 | public Thread startBatch (final Runnable process)
{
Thread worker = new Thread()
{
@Override
public void run()
{
setBusy(true);
process.run();
setBusy(false);
}
};
worker.start();
return worker;
} // startBatch
/**
* @return Returns the AD_Form_ID.
*/
public int getAD_Form_ID ()
{
return p_AD_Form_ID;
} // getAD_Window_ID
public int getWindowNo()
{ | return m_WindowNo;
}
/**
* @return Returns the manuBar
*/
public JMenuBar getMenu()
{
return menuBar;
}
public void showFormWindow()
{
if (m_panel instanceof FormPanel2)
{
((FormPanel2)m_panel).showFormWindow(m_WindowNo, this);
}
else
{
AEnv.showCenterScreenOrMaximized(this);
}
}
} // FormFrame | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\FormFrame.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getConsignmentReference() {
return consignmentReference;
}
/**
* Sets the value of the consignmentReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConsignmentReference(String value) {
this.consignmentReference = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence maxOccurs="unbounded">
* <element ref="{http://erpel.at/schemas/1p0/documents/extensions/edifact}InvoiceFooter" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"invoiceFooter" | })
public static class InvoiceFooters {
@XmlElement(name = "InvoiceFooter")
protected List<InvoiceFooterType> invoiceFooter;
/**
* Gets the value of the invoiceFooter 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 invoiceFooter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getInvoiceFooter().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link InvoiceFooterType }
*
*
*/
public List<InvoiceFooterType> getInvoiceFooter() {
if (invoiceFooter == null) {
invoiceFooter = new ArrayList<InvoiceFooterType>();
}
return this.invoiceFooter;
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\INVOICExtensionType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ItemController {
private ItemService service;
public ItemController(ItemService service) {
this.service = service;
}
@PostMapping
@ApiResponse(responseCode = "200", description = "Success", content = { @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = Item.class)) })
public ResponseEntity<Item> post(@Valid @RequestBody Item item) {
service.insert(item);
return ResponseEntity.ok(item);
}
@GetMapping
@ApiResponse(responseCode = "200", description = "Success", content = { @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, array = @ArraySchema(schema = @Schema(implementation = Item.class))) })
public ResponseEntity<List<Item>> get() {
return ResponseEntity.ok(service.findAll());
}
@GetMapping("/{id}")
@ApiResponse(responseCode = "200", description = "Success", content = { @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = Item.class)) }) | public ResponseEntity<Item> get(@PathVariable String id) {
try {
return ResponseEntity.ok(service.findById(id));
} catch (EntityNotFoundException e) {
return ResponseEntity.status(404)
.build();
}
}
@DeleteMapping("/{id}")
@ApiResponse(responseCode = "204", description = "Success")
public ResponseEntity<Void> delete(@PathVariable String id) {
try {
service.deleteById(id);
return ResponseEntity.status(204)
.build();
} catch (EntityNotFoundException e) {
return ResponseEntity.status(404)
.build();
}
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\cats\controller\ItemController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setActivityType(String activityType) {
this.activityType = activityType;
}
@ApiModelProperty(example = "oneTaskProcess%3A1%3A4")
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@ApiModelProperty(example = "http://localhost:8182/repository/process-definitions/oneTaskProcess%3A1%3A4")
public String getProcessDefinitionUrl() {
return processDefinitionUrl;
}
public void setProcessDefinitionUrl(String processDefinitionUrl) {
this.processDefinitionUrl = processDefinitionUrl;
}
@ApiModelProperty(example = "3")
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@ApiModelProperty(example = "http://localhost:8182/history/historic-process-instances/3")
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
@ApiModelProperty(example = "4")
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@ApiModelProperty(example = "4")
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@ApiModelProperty(example = "null")
public String getCalledProcessInstanceId() {
return calledProcessInstanceId;
} | public void setCalledProcessInstanceId(String calledProcessInstanceId) {
this.calledProcessInstanceId = calledProcessInstanceId;
}
@ApiModelProperty(example = "fozzie")
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
@ApiModelProperty(example = "2013-04-17T10:17:43.902+0000")
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
@ApiModelProperty(example = "2013-04-18T14:06:32.715+0000")
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
@ApiModelProperty(example = "86400056")
public Long getDurationInMillis() {
return durationInMillis;
}
public void setDurationInMillis(Long durationInMillis) {
this.durationInMillis = durationInMillis;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricActivityInstanceResponse.java | 2 |
请完成以下Java代码 | public class EventSubProcessErrorStartEventActivityBehavior extends AbstractBpmnActivityBehavior {
private static final long serialVersionUID = 1L;
public void execute(DelegateExecution execution) {
StartEvent startEvent = (StartEvent) execution.getCurrentFlowElement();
EventSubProcess eventSubProcess = (EventSubProcess) startEvent.getSubProcess();
execution.setCurrentFlowElement(eventSubProcess);
execution.setScope(true);
// initialize the template-defined data objects as variables
Map<String, Object> dataObjectVars = processDataObjects(eventSubProcess.getDataObjects());
if (dataObjectVars != null) {
execution.setVariablesLocal(dataObjectVars);
}
ExecutionEntity startSubProcessExecution = Context.getCommandContext()
.getExecutionEntityManager()
.createChildExecution((ExecutionEntity) execution); | startSubProcessExecution.setCurrentFlowElement(startEvent);
Context.getAgenda().planTakeOutgoingSequenceFlowsOperation(startSubProcessExecution, true);
}
protected Map<String, Object> processDataObjects(Collection<ValuedDataObject> dataObjects) {
Map<String, Object> variablesMap = new HashMap<String, Object>();
// convert data objects to process variables
if (dataObjects != null) {
for (ValuedDataObject dataObject : dataObjects) {
variablesMap.put(dataObject.getName(), dataObject.getValue());
}
}
return variablesMap;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\EventSubProcessErrorStartEventActivityBehavior.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
MGroup group = MGroup.get(getCtx(), p_R_Group_ID);
if (group == null)
{
throw new FillMandatoryException("R_Group_ID");
}
int AD_BoilerPlate_ID = group.get_ValueAsInt(MADBoilerPlate.COLUMNNAME_AD_BoilerPlate_ID);
if (AD_BoilerPlate_ID <= 0)
{
throw new FillMandatoryException(MADBoilerPlate.COLUMNNAME_AD_BoilerPlate_ID);
}
final MADBoilerPlate text = MADBoilerPlate.get(getCtx(), AD_BoilerPlate_ID);
int count_ok = 0;
int count_all = 0;
for (MRGroupProspect prospect : getProspects(p_R_Group_ID))
{
if (notify(text, prospect))
{
count_ok++;
}
count_all++;
}
return "@Sent@ #" + count_ok + "/" + count_all;
}
private boolean notify(final MADBoilerPlate text, final MRGroupProspect prospect)
{
boolean ok = true;
try
{
if (CCM_NotificationType_EMail.equals(p_CCM_NotificationType))
{
notifyEMail(text, prospect);
}
else if (CCM_NotificationType_Letter.equals(p_CCM_NotificationType))
{
notifyLetter(text, prospect);
}
else
{
throw new AdempiereException("@NotSupported@ @CCM_NotificationType@ - " + p_CCM_NotificationType);
}
}
catch (Exception e)
{
addLog(prospect.toString() + ": Error: " + e.getLocalizedMessage());
ok = false;
if (LogManager.isLevelFine())
{
e.printStackTrace();
}
}
return ok;
}
private void notifyEMail(final MADBoilerPlate text, final MRGroupProspect prospect)
{
MADBoilerPlate.sendEMail(new IEMailEditor()
{
@Override
public Object getBaseObject()
{
return prospect;
}
@Override
public int getAD_Table_ID()
{
return X_R_Group.Table_ID; | }
@Override
public int getRecord_ID()
{
return prospect.getR_Group_ID();
}
@Override
public EMail sendEMail(I_AD_User from, String toEmail, String subject, final BoilerPlateContext attributes)
{
final Mailbox mailbox = mailService.findMailbox(MailboxQuery.builder()
.clientId(getClientId())
.orgId(getOrgId())
.adProcessId(getProcessInfo().getAdProcessId())
.fromUserId(UserId.ofRepoId(from.getAD_User_ID()))
.build());
return mailService.sendEMail(EMailRequest.builder()
.mailbox(mailbox)
.toList(toEMailAddresses(toEmail))
.subject(text.getSubject())
.message(text.getTextSnippetParsed(attributes))
.html(true)
.build());
}
});
}
private void notifyLetter(MADBoilerPlate text, MRGroupProspect prospect)
{
throw new UnsupportedOperationException();
}
private List<MRGroupProspect> getProspects(int R_Group_ID)
{
final String whereClause = MRGroupProspect.COLUMNNAME_R_Group_ID + "=?";
return new Query(getCtx(), MRGroupProspect.Table_Name, whereClause, get_TrxName())
.setParameters(R_Group_ID)
.list(MRGroupProspect.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\report\AD_BoilderPlate_SendToGroup.java | 1 |
请完成以下Java代码 | public void setDataEntry_RecordData (java.lang.String DataEntry_RecordData)
{
set_Value (COLUMNNAME_DataEntry_RecordData, DataEntry_RecordData);
}
/** Get DataEntry_RecordData.
@return Holds the (JSON-)data of all fields for a data entry. The json is supposed to be rendered into the respective fields, the column is not intended for actual display
*/
@Override
public java.lang.String getDataEntry_RecordData ()
{
return (java.lang.String)get_Value(COLUMNNAME_DataEntry_RecordData);
}
@Override
public de.metas.dataentry.model.I_DataEntry_SubTab getDataEntry_SubTab() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class);
}
@Override
public void setDataEntry_SubTab(de.metas.dataentry.model.I_DataEntry_SubTab DataEntry_SubTab)
{
set_ValueFromPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class, DataEntry_SubTab);
}
/** Set Unterregister.
@param DataEntry_SubTab_ID Unterregister */
@Override
public void setDataEntry_SubTab_ID (int DataEntry_SubTab_ID)
{
if (DataEntry_SubTab_ID < 1)
set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, Integer.valueOf(DataEntry_SubTab_ID));
}
/** Get Unterregister.
@return Unterregister */
@Override
public int getDataEntry_SubTab_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_SubTab_ID);
if (ii == null)
return 0;
return ii.intValue(); | }
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Record.java | 1 |
请完成以下Java代码 | public static int getMinute_UOM_ID(Properties ctx)
{
if (Ini.isSwingClient())
{
final Iterator<MUOM> it = s_cache.values().iterator();
while (it.hasNext())
{
final MUOM uom = it.next();
if (UOMUtil.isMinute(uom))
{
return uom.getC_UOM_ID();
}
}
}
// Server
String sql = "SELECT C_UOM_ID FROM C_UOM WHERE IsActive='Y' AND X12DE355=?";
return DB.getSQLValueEx(ITrx.TRXNAME_None, sql, X12DE355.MINUTE.getCode());
} // getMinute_UOM_ID
/**
* Get Default C_UOM_ID
*
* @param ctx context for AD_Client
* @return C_UOM_ID
*/
public static int getDefault_UOM_ID(Properties ctx)
{
String sql = "SELECT C_UOM_ID "
+ "FROM C_UOM "
+ "WHERE AD_Client_ID IN (0,?) "
+ "ORDER BY IsDefault DESC, AD_Client_ID DESC, C_UOM_ID";
return DB.getSQLValue(null, sql, Env.getAD_Client_ID(ctx));
} // getDefault_UOM_ID
/*************************************************************************/
/** UOM Cache */
private static CCache<Integer, MUOM> s_cache = new CCache<>(Table_Name, 30);
/**
* Get UOM from Cache
*
* @param ctx context
* @param C_UOM_ID ID
* @return UOM
*/
@Deprecated
public static MUOM get(Properties ctx, int C_UOM_ID)
{
if (s_cache.size() == 0)
{
loadUOMs(ctx);
}
//
MUOM uom = s_cache.get(C_UOM_ID);
if (uom != null)
{
return uom;
}
//
uom = new MUOM(ctx, C_UOM_ID, null);
s_cache.put(C_UOM_ID, uom);
return uom;
} // get
/**
* Get Precision
*
* @param ctx context
* @param C_UOM_ID ID
* @return Precision
*/
@Deprecated
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 swapCities() {
int a = generateRandomIndex();
int b = generateRandomIndex();
previousTravel = new ArrayList<>(travel);
City x = travel.get(a);
City y = travel.get(b);
travel.set(a, y);
travel.set(b, x);
}
public void revertSwap() {
travel = previousTravel;
}
private int generateRandomIndex() {
return (int) (Math.random() * travel.size());
}
public City getCity(int index) {
return travel.get(index);
}
public int getDistance() { | int distance = 0;
for (int index = 0; index < travel.size(); index++) {
City starting = getCity(index);
City destination;
if (index + 1 < travel.size()) {
destination = getCity(index + 1);
} else {
destination = getCity(0);
}
distance += starting.distanceToCity(destination);
}
return distance;
}
} | repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\annealing\Travel.java | 1 |
请完成以下Java代码 | public boolean isAutoCommit()
{
return true;
}
// metas
@Override
public void addMouseListener(MouseListener l)
{
m_text.addMouseListener(l);
m_button.addMouseListener(l);
m_combo.getEditor().getEditorComponent().addMouseListener(l); // popup
}
private boolean isRowLoading()
{
if (m_mField == null)
{
return false;
}
final String rowLoadingStr = Env.getContext(Env.getCtx(), m_mField.getWindowNo(), m_mField.getVO().TabNo, GridTab.CTX_RowLoading);
return "Y".equals(rowLoadingStr);
}
/* package */IValidationContext getValidationContext()
{
final GridField gridField = m_mField;
// In case there is no GridField set (e.g. VLookup was created from a custom swing form)
if (gridField == null)
{
return IValidationContext.DISABLED;
}
final IValidationContext evalCtx = Services.get(IValidationRuleFactory.class).createValidationContext(gridField);
// In case grid field validation context could not be created, disable validation
// NOTE: in most of the cases when we reach this point is when we are in a custom form which used GridFields to create the lookups
// but those custom fields does not have a GridTab
// e.g. de.metas.paymentallocation.form.PaymentAllocationForm
if (evalCtx == null)
{
return IValidationContext.DISABLED;
}
return evalCtx;
}
@Override
public void addFocusListener(final FocusListener l) | {
getEditorComponent().addFocusListener(l);
}
@Override
public void removeFocusListener(FocusListener l)
{
getEditorComponent().removeFocusListener(l);
}
public void setInfoWindowEnabled(final boolean enabled)
{
this.infoWindowEnabled = enabled;
if (m_button != null)
{
m_button.setVisible(enabled);
}
}
@Override
public ICopyPasteSupportEditor getCopyPasteSupport()
{
return copyPasteSupport;
}
} // VLookup | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLookup.java | 1 |
请完成以下Java代码 | public static String formatRight(String str, int reservedLength){
String name = str.substring(0, reservedLength);
String stars = String.join("", Collections.nCopies(str.length()-reservedLength, "*"));
return name + stars;
}
/**
* 将左边的格式化成*
* @param str 字符串
* @param reservedLength 保留长度
* @return 格式化后的字符串
*/
public static String formatLeft(String str, int reservedLength){
int len = str.length();
String show = str.substring(len-reservedLength);
String stars = String.join("", Collections.nCopies(len-reservedLength, "*"));
return stars + show; | }
/**
* 将中间的格式化成*
* @param str 字符串
* @param beginLen 开始保留长度
* @param endLen 结尾保留长度
* @return 格式化后的字符串
*/
public static String formatBetween(String str, int beginLen, int endLen){
int len = str.length();
String begin = str.substring(0, beginLen);
String end = str.substring(len-endLen);
String stars = String.join("", Collections.nCopies(len-beginLen-endLen, "*"));
return begin + stars + end;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\desensitization\util\SensitiveInfoUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SinceQuery
{
public static SinceQuery anyEntity(@Nullable final Instant sinceInstant, final int pageSize, @Nullable final OrgId orgId, @Nullable final String externalSystem)
{
return new SinceQuery(SinceEntity.ALL, sinceInstant, pageSize, orgId, externalSystem);
}
public static SinceQuery onlyContacts(@Nullable final Instant sinceInstant, final int pageSize)
{
return new SinceQuery(SinceEntity.CONTACT_ONLY, sinceInstant, pageSize,null, null);
}
SinceEntity sinceEntity;
Instant sinceInstant;
int pageSize;
@Nullable
OrgId orgId;
@Nullable
String externalSystem; | private SinceQuery(
@NonNull final SinceEntity sinceEntity,
@NonNull final Instant sinceInstant,
final int pageSize,
@Nullable final OrgId orgId,
@Nullable final String externalSystem)
{
this.sinceEntity = sinceEntity;
this.sinceInstant = sinceInstant;
this.pageSize = assumeGreaterThanZero(pageSize, "pageSize");
this.orgId = orgId;
this.externalSystem = externalSystem;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\repository\SinceQuery.java | 2 |
请完成以下Java代码 | public Queue findQueueByTenantIdAndName(TenantId tenantId, String queueName) {
log.trace("Executing findQueueByTenantIdAndName, tenantId: [{}] queueName: [{}]", tenantId, queueName);
return queueDao.findQueueByTenantIdAndName(getSystemOrIsolatedTenantId(tenantId), queueName);
}
@Override
public Queue findQueueByTenantIdAndNameInternal(TenantId tenantId, String queueName) {
log.trace("Executing findQueueByTenantIdAndNameInternal, tenantId: [{}] queueName: [{}]", tenantId, queueName);
return queueDao.findQueueByTenantIdAndName(tenantId, queueName);
}
@Override
public void deleteQueuesByTenantId(TenantId tenantId) {
validateId(tenantId, __ -> "Incorrect tenant id for delete queues request.");
tenantQueuesRemover.removeEntities(tenantId, tenantId);
}
@Override
public void deleteByTenantId(TenantId tenantId) {
deleteQueuesByTenantId(tenantId);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findQueueById(tenantId, new QueueId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(queueDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.QUEUE;
}
private final PaginatedRemover<TenantId, Queue> tenantQueuesRemover = new PaginatedRemover<>() { | @Override
protected PageData<Queue> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return queueDao.findQueuesByTenantId(id, pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, Queue entity) {
deleteQueue(tenantId, entity.getId());
}
};
private TenantId getSystemOrIsolatedTenantId(TenantId tenantId) {
if (!tenantId.equals(TenantId.SYS_TENANT_ID)) {
TenantProfile tenantProfile = tenantProfileCache.get(tenantId);
if (tenantProfile.isIsolatedTbRuleEngine()) {
return tenantId;
}
}
return TenantId.SYS_TENANT_ID;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\queue\BaseQueueService.java | 1 |
请完成以下Java代码 | public List<String> getInvolvedGroups() {
return involvedGroups;
}
public String getOwner() {
return owner;
}
public String getOwnerLike() {
return ownerLike;
}
public String getTaskParentTaskId() {
return taskParentTaskId;
}
public String getCategory() {
return category;
}
public String getProcessDefinitionKeyLike() {
return processDefinitionKeyLike;
}
public List<String> getProcessDefinitionKeys() {
return processDefinitionKeys;
}
public String getProcessDefinitionNameLike() {
return processDefinitionNameLike;
}
public List<String> getProcessCategoryInList() {
return processCategoryInList;
}
public List<String> getProcessCategoryNotInList() {
return processCategoryNotInList;
}
public String getDeploymentId() {
return deploymentId;
}
public List<String> getDeploymentIds() {
return deploymentIds;
}
public String getProcessInstanceBusinessKeyLike() {
return processInstanceBusinessKeyLike;
}
public Date getDueDate() {
return dueDate;
}
public Date getDueBefore() {
return dueBefore;
}
public Date getDueAfter() {
return dueAfter;
}
public boolean isWithoutDueDate() {
return withoutDueDate;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public boolean isIncludeTaskLocalVariables() {
return includeTaskLocalVariables;
}
public boolean isIncludeProcessVariables() {
return includeProcessVariables;
} | public boolean isBothCandidateAndAssigned() {
return bothCandidateAndAssigned;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public String getDescriptionLikeIgnoreCase() {
return descriptionLikeIgnoreCase;
}
public String getAssigneeLikeIgnoreCase() {
return assigneeLikeIgnoreCase;
}
public String getOwnerLikeIgnoreCase() {
return ownerLikeIgnoreCase;
}
public String getProcessInstanceBusinessKeyLikeIgnoreCase() {
return processInstanceBusinessKeyLikeIgnoreCase;
}
public String getProcessDefinitionKeyLikeIgnoreCase() {
return processDefinitionKeyLikeIgnoreCase;
}
public String getLocale() {
return locale;
}
public boolean isOrActive() {
return orActive;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TaskQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getName() {
return name;
}
public int getVersion() {
return version;
}
public String getResource() {
return resource;
}
public String getDeploymentId() {
return deploymentId;
}
public String getTenantId() {
return tenantId;
} | public static DecisionRequirementsDefinitionDto fromDecisionRequirementsDefinition(DecisionRequirementsDefinition definition) {
DecisionRequirementsDefinitionDto dto = new DecisionRequirementsDefinitionDto();
dto.id = definition.getId();
dto.key = definition.getKey();
dto.category = definition.getCategory();
dto.name = definition.getName();
dto.version = definition.getVersion();
dto.resource = definition.getResourceName();
dto.deploymentId = definition.getDeploymentId();
dto.tenantId = definition.getTenantId();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\DecisionRequirementsDefinitionDto.java | 2 |
请完成以下Java代码 | public class DataElasticsearchReactiveHealthIndicator extends AbstractReactiveHealthIndicator {
private final ReactiveElasticsearchClient client;
public DataElasticsearchReactiveHealthIndicator(ReactiveElasticsearchClient client) {
super("Elasticsearch health check failed");
this.client = client;
}
@Override
protected Mono<Health> doHealthCheck(Health.Builder builder) {
return this.client.cluster().health((b) -> b).map((response) -> processResponse(builder, response));
}
private Health processResponse(Health.Builder builder, HealthResponse response) {
if (!response.timedOut()) {
HealthStatus status = response.status();
builder.status((HealthStatus.Red == status) ? Status.OUT_OF_SERVICE : Status.UP);
builder.withDetail("cluster_name", response.clusterName());
builder.withDetail("status", response.status().jsonValue());
builder.withDetail("timed_out", response.timedOut());
builder.withDetail("number_of_nodes", response.numberOfNodes());
builder.withDetail("number_of_data_nodes", response.numberOfDataNodes());
builder.withDetail("active_primary_shards", response.activePrimaryShards());
builder.withDetail("active_shards", response.activeShards()); | builder.withDetail("relocating_shards", response.relocatingShards());
builder.withDetail("initializing_shards", response.initializingShards());
builder.withDetail("unassigned_shards", response.unassignedShards());
builder.withDetail("delayed_unassigned_shards", response.delayedUnassignedShards());
builder.withDetail("number_of_pending_tasks", response.numberOfPendingTasks());
builder.withDetail("number_of_in_flight_fetch", response.numberOfInFlightFetch());
builder.withDetail("task_max_waiting_in_queue_millis", response.taskMaxWaitingInQueueMillis());
builder.withDetail("active_shards_percent_as_number", response.activeShardsPercentAsNumber());
builder.withDetail("unassigned_primary_shards", response.unassignedPrimaryShards());
return builder.build();
}
return builder.down().build();
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-elasticsearch\src\main\java\org\springframework\boot\data\elasticsearch\health\DataElasticsearchReactiveHealthIndicator.java | 1 |
请完成以下Java代码 | public class FindEvenAndOdd {
// Method to find Even numbers using loop
public static List<Integer> findEvenNumbersWithLoop(int[] numbers) {
List<Integer> evenNumbers = new ArrayList<>();
for (int number : numbers) {
if (number % 2 == 0) {
evenNumbers.add(number);
}
}
return evenNumbers;
}
// Method to find odd numbers using loop
public static List<Integer> findOddNumbersWithLoop(int[] numbers) {
List<Integer> oddNumbers = new ArrayList<>();
for (int number : numbers) {
if (number % 2 != 0) {
oddNumbers.add(number);
}
}
return oddNumbers; | }
// Method to find even numbers using Stream
public static List<Integer> findEvenNumbersWithStream(int[] numbers) {
return Arrays.stream(numbers)
.filter(number -> number % 2 == 0)
.boxed()
.collect(Collectors.toList());
}
// Method to find odd numbers using Stream
public static List<Integer> findOddNumbersWithStream(int[] numbers) {
return Arrays.stream(numbers)
.filter(number -> number % 2 != 0)
.boxed()
.collect(Collectors.toList());
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\evenandodd\FindEvenAndOdd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public TaskExecutor splitWordsChannelThreadPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(5);
executor.setThreadNamePrefix("split-words-channel-thread-pool");
executor.initialize();
return executor;
}
@Bean("toLowerCaseChannelThreadPool")
public TaskExecutor toLowerCaseChannelThreadPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(5);
executor.setThreadNamePrefix("tto-lower-case-channel-thread-pool");
executor.initialize();
return executor;
}
@Bean("countWordsChannelThreadPool")
public TaskExecutor countWordsChannelThreadPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1); | executor.setMaxPoolSize(5);
executor.setThreadNamePrefix("count-words-channel-thread-pool");
executor.initialize();
return executor;
}
@Bean("returnResponseChannelThreadPool")
public TaskExecutor returnResponseChannelThreadPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(5);
executor.setThreadNamePrefix("return-response-channel-thread-pool");
executor.initialize();
return executor;
}
} | repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\seda\springintegration\TaskExecutorConfiguration.java | 2 |
请完成以下Java代码 | public Integer getWarmUpPeriodSec() {
return warmUpPeriodSec;
}
public void setWarmUpPeriodSec(Integer warmUpPeriodSec) {
this.warmUpPeriodSec = warmUpPeriodSec;
}
public Integer getMaxQueueingTimeMs() {
return maxQueueingTimeMs;
}
public void setMaxQueueingTimeMs(Integer maxQueueingTimeMs) {
this.maxQueueingTimeMs = maxQueueingTimeMs;
}
public boolean isClusterMode() {
return clusterMode;
}
public FlowRuleEntity setClusterMode(boolean clusterMode) {
this.clusterMode = clusterMode;
return this;
}
public ClusterFlowConfig getClusterConfig() {
return clusterConfig;
}
public FlowRuleEntity setClusterConfig(ClusterFlowConfig clusterConfig) {
this.clusterConfig = clusterConfig;
return this;
}
@Override
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModified() {
return gmtModified;
} | public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
@Override
public FlowRule toRule() {
FlowRule flowRule = new FlowRule();
flowRule.setCount(this.count);
flowRule.setGrade(this.grade);
flowRule.setResource(this.resource);
flowRule.setLimitApp(this.limitApp);
flowRule.setRefResource(this.refResource);
flowRule.setStrategy(this.strategy);
if (this.controlBehavior != null) {
flowRule.setControlBehavior(controlBehavior);
}
if (this.warmUpPeriodSec != null) {
flowRule.setWarmUpPeriodSec(warmUpPeriodSec);
}
if (this.maxQueueingTimeMs != null) {
flowRule.setMaxQueueingTimeMs(maxQueueingTimeMs);
}
flowRule.setClusterMode(clusterMode);
flowRule.setClusterConfig(clusterConfig);
return flowRule;
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\FlowRuleEntity.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: demo-consumer # Spring 应用名
server:
port: 28080 # 服务器端口。默认为 8080
eureka:
client:
register-with-eureka: true
fetch-registry | : true
service-url:
defaultZone: http://127.0.0.1:8761/eureka/ | repos\SpringBoot-Labs-master\labx-22\labx-22-scn-eureka-demo01-consumer\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public byte[] getFullMessageBytes() {
return (fullMessage != null ? fullMessage.getBytes() : null);
}
public void setFullMessageBytes(byte[] fullMessageBytes) {
fullMessage = (fullMessageBytes != null ? new String(fullMessageBytes) : null);
}
public static String MESSAGE_PARTS_MARKER = "_|_";
public static Pattern MESSAGE_PARTS_MARKER_REGEX = Pattern.compile("_\\|_");
public void setMessage(String[] messageParts) {
StringBuilder stringBuilder = new StringBuilder();
for (String part : messageParts) {
if (part != null) {
stringBuilder.append(part.replace(MESSAGE_PARTS_MARKER, " | "));
stringBuilder.append(MESSAGE_PARTS_MARKER);
} else {
stringBuilder.append("null");
stringBuilder.append(MESSAGE_PARTS_MARKER);
}
}
for (int i = 0; i < MESSAGE_PARTS_MARKER.length(); i++) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
message = stringBuilder.toString();
}
public List<String> getMessageParts() {
if (message == null) {
return null;
}
List<String> messageParts = new ArrayList<String>();
String[] parts = MESSAGE_PARTS_MARKER_REGEX.split(message);
for (String part : parts) {
if ("null".equals(part)) {
messageParts.add(null);
} else {
messageParts.add(part);
}
}
return messageParts;
}
// getters and setters
// //////////////////////////////////////////////////////
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getMessage() { | return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFullMessage() {
return fullMessage;
}
public void setFullMessage(String fullMessage) {
this.fullMessage = fullMessage;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\CommentEntityImpl.java | 1 |
请完成以下Java代码 | public void onShipperBPartner(final I_M_ShipperTransportation shipperTransportation, final ICalloutField field)
{
// fix to avoid NPE when new entry
if (shipperTransportation == null)
{
// new entry
return;
}
final BPartnerId shipperPartnerId = BPartnerId.ofRepoIdOrNull(shipperTransportation.getShipper_BPartner_ID());
if (shipperPartnerId == null)
{
return;
}
shipperDAO.getShipperIdByShipperPartnerId(shipperPartnerId)
.ifPresent(shipperId -> shipperTransportationBL.setShipper(shipperTransportation, shipperId));
}
@CalloutMethod(columnNames = { I_M_ShipperTransportation.COLUMNNAME_M_Shipper_ID })
public void onShipper(final I_M_ShipperTransportation shipperTransportation, final ICalloutField field)
{
final ShipperId shipperId = ShipperId.ofRepoIdOrNull(shipperTransportation.getM_Shipper_ID());
if (shipperId != null)
{
shipperTransportationBL.setShipper(shipperTransportation, shipperId);
}
}
@CalloutMethod(columnNames = I_M_Inventory.COLUMNNAME_C_DocType_ID)
public void updateFromDocType(final I_M_ShipperTransportation shipperTransportationRecord, final ICalloutField field)
{
final IDocumentNoInfo documentNoInfo = Services.get(IDocumentNoBuilderFactory.class)
.createPreliminaryDocumentNoBuilder()
.setNewDocType(getDocTypeOrNull(shipperTransportationRecord))
.setOldDocumentNo(shipperTransportationRecord.getDocumentNo())
.setDocumentModel(shipperTransportationRecord)
.buildOrNull();
if (documentNoInfo == null) | {
return;
}
// DocumentNo
if (documentNoInfo.isDocNoControlled())
{
shipperTransportationRecord.setDocumentNo(documentNoInfo.getDocumentNo());
}
}
@Nullable
private I_C_DocType getDocTypeOrNull(final I_M_ShipperTransportation shipperTransportationRecord)
{
final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(shipperTransportationRecord.getC_DocType_ID());
return docTypeId != null
? docTypeDAO.getById(docTypeId)
: null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\callout\M_ShipperTransportation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
private BusCategoryEnum(String code,String desc,String minAmount,String maxAmount,String beginTime,String endTime) {
this.code = code;
this.desc = desc;
this.minAmount = minAmount;
this.maxAmount = maxAmount;
this.beginTime = beginTime;
this.endTime = endTime;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public static BusCategoryEnum getEnum(String enumName) {
BusCategoryEnum resultEnum = null;
BusCategoryEnum[] enumAry = BusCategoryEnum.values();
for (int i = 0; i < enumAry.length; i++) {
if (enumAry[i].name().equals(enumName)) {
resultEnum = enumAry[i];
break;
}
}
return resultEnum;
}
public static Map<String, Map<String, Object>> toMap() {
BusCategoryEnum[] ary = BusCategoryEnum.values();
Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>();
for (int num = 0; num < ary.length; num++) {
Map<String, Object> map = new HashMap<String, Object>();
String key = ary[num].name();
map.put("desc", ary[num].getDesc());
enumMap.put(key, map); | }
return enumMap;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List toList() {
BusCategoryEnum[] ary = BusCategoryEnum.values();
List list = new ArrayList();
for (int i = 0; i < ary.length; i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("name", ary[i].name());
map.put("desc", ary[i].getDesc());
map.put("minAmount", ary[i].getMinAmount());
map.put("maxAmount", ary[i].getMaxAmount());
map.put("beginTime", ary[i].getBeginTime());
map.put("endTime", ary[i].getEndTime());
list.add(map);
}
return list;
}
/**
* 取枚举的json字符串
*
* @return
*/
public static String getJsonStr() {
BusCategoryEnum[] enums = BusCategoryEnum.values();
StringBuffer jsonStr = new StringBuffer("[");
for (BusCategoryEnum senum : enums) {
if (!"[".equals(jsonStr.toString())) {
jsonStr.append(",");
}
jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}");
}
jsonStr.append("]");
return jsonStr.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\enums\BusCategoryEnum.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JmsPoolConnectionFactoryFactory {
private final JmsPoolConnectionFactoryProperties properties;
public JmsPoolConnectionFactoryFactory(JmsPoolConnectionFactoryProperties properties) {
this.properties = properties;
}
/**
* Create a {@link JmsPoolConnectionFactory} based on the specified
* {@link ConnectionFactory}.
* @param connectionFactory the connection factory to wrap
* @return a pooled connection factory
*/
public JmsPoolConnectionFactory createPooledConnectionFactory(ConnectionFactory connectionFactory) {
JmsPoolConnectionFactory pooledConnectionFactory = new JmsPoolConnectionFactory();
pooledConnectionFactory.setConnectionFactory(connectionFactory);
pooledConnectionFactory.setBlockIfSessionPoolIsFull(this.properties.isBlockIfFull());
if (this.properties.getBlockIfFullTimeout() != null) {
pooledConnectionFactory
.setBlockIfSessionPoolIsFullTimeout(this.properties.getBlockIfFullTimeout().toMillis()); | }
if (this.properties.getIdleTimeout() != null) {
pooledConnectionFactory.setConnectionIdleTimeout((int) this.properties.getIdleTimeout().toMillis());
}
pooledConnectionFactory.setMaxConnections(this.properties.getMaxConnections());
pooledConnectionFactory.setMaxSessionsPerConnection(this.properties.getMaxSessionsPerConnection());
if (this.properties.getTimeBetweenExpirationCheck() != null) {
pooledConnectionFactory
.setConnectionCheckInterval(this.properties.getTimeBetweenExpirationCheck().toMillis());
}
pooledConnectionFactory.setUseAnonymousProducers(this.properties.isUseAnonymousProducers());
return pooledConnectionFactory;
}
} | repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JmsPoolConnectionFactoryFactory.java | 2 |
请完成以下Java代码 | public class HUPackingInfoFormatter
{
public static HUPackingInfoFormatter newInstance()
{
return new HUPackingInfoFormatter();
}
private boolean _showLU = true;
/**
* Format given packing info.
*
* If you want to quickly create some {@link IHUPackingInfo} instances from other objects, please check the {@link HUPackingInfos} facade.
*
* @return formatted packing info string
*/
@Nullable
public String format(final IHUPackingInfo huPackingInfo)
{
final StringBuilder packingInfo = new StringBuilder();
//
// LU
if (isShowLU())
{
final I_M_HU_PI luPI = huPackingInfo.getM_LU_HU_PI();
if (luPI != null)
{
packingInfo.append(luPI.getName());
}
}
//
// TU
final I_M_HU_PI tuPI = huPackingInfo.getM_TU_HU_PI();
if (tuPI != null && !Services.get(IHandlingUnitsBL.class).isVirtual(tuPI))
{
if (packingInfo.length() > 0)
{
packingInfo.append(" x ");
}
final BigDecimal qtyTU = huPackingInfo.getQtyTUsPerLU();
if (!huPackingInfo.isInfiniteQtyTUsPerLU() && qtyTU != null && qtyTU.signum() > 0)
{ | packingInfo.append(qtyTU.intValue()).append(" ");
}
packingInfo.append(tuPI.getName());
}
//
// CU
final BigDecimal qtyCU = huPackingInfo.getQtyCUsPerTU();
if (!huPackingInfo.isInfiniteQtyCUsPerTU() && qtyCU != null && qtyCU.signum() > 0)
{
if (packingInfo.length() > 0)
{
packingInfo.append(" x ");
}
final DecimalFormat qtyFormat = DisplayType.getNumberFormat(DisplayType.Quantity);
packingInfo.append(qtyFormat.format(qtyCU));
final I_C_UOM uom = huPackingInfo.getQtyCUsPerTU_UOM();
final String uomSymbol = uom == null ? null : uom.getUOMSymbol();
if (uomSymbol != null)
{
packingInfo.append(" ").append(uomSymbol);
}
}
if (packingInfo.length() == 0)
{
return null; // no override
}
return packingInfo.toString();
}
public HUPackingInfoFormatter setShowLU(final boolean showLU)
{
_showLU = showLU;
return this;
}
private boolean isShowLU()
{
return _showLU;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\HUPackingInfoFormatter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Queue queueThree() {
return new Queue(RabbitConsts.QUEUE_THREE);
}
/**
* 分列模式队列
*/
@Bean
public FanoutExchange fanoutExchange() {
return new FanoutExchange(RabbitConsts.FANOUT_MODE_QUEUE);
}
/**
* 分列模式绑定队列1
*
* @param directOneQueue 绑定队列1
* @param fanoutExchange 分列模式交换器
*/
@Bean
public Binding fanoutBinding1(Queue directOneQueue, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(directOneQueue).to(fanoutExchange);
}
/**
* 分列模式绑定队列2
*
* @param queueTwo 绑定队列2
* @param fanoutExchange 分列模式交换器
*/
@Bean
public Binding fanoutBinding2(Queue queueTwo, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(queueTwo).to(fanoutExchange);
}
/**
* 主题模式队列
* <li>路由格式必须以 . 分隔,比如 user.email 或者 user.aaa.email</li>
* <li>通配符 * ,代表一个占位符,或者说一个单词,比如路由为 user.*,那么 user.email 可以匹配,但是 user.aaa.email 就匹配不了</li>
* <li>通配符 # ,代表一个或多个占位符,或者说一个或多个单词,比如路由为 user.#,那么 user.email 可以匹配,user.aaa.email 也可以匹配</li>
*/
@Bean
public TopicExchange topicExchange() {
return new TopicExchange(RabbitConsts.TOPIC_MODE_QUEUE);
}
/**
* 主题模式绑定分列模式
*
* @param fanoutExchange 分列模式交换器
* @param topicExchange 主题模式交换器
*/
@Bean
public Binding topicBinding1(FanoutExchange fanoutExchange, TopicExchange topicExchange) {
return BindingBuilder.bind(fanoutExchange).to(topicExchange).with(RabbitConsts.TOPIC_ROUTING_KEY_ONE);
}
/**
* 主题模式绑定队列2
*
* @param queueTwo 队列2
* @param topicExchange 主题模式交换器
*/
@Bean
public Binding topicBinding2(Queue queueTwo, TopicExchange topicExchange) {
return BindingBuilder.bind(queueTwo).to(topicExchange).with(RabbitConsts.TOPIC_ROUTING_KEY_TWO);
}
/** | * 主题模式绑定队列3
*
* @param queueThree 队列3
* @param topicExchange 主题模式交换器
*/
@Bean
public Binding topicBinding3(Queue queueThree, TopicExchange topicExchange) {
return BindingBuilder.bind(queueThree).to(topicExchange).with(RabbitConsts.TOPIC_ROUTING_KEY_THREE);
}
/**
* 延迟队列
*/
@Bean
public Queue delayQueue() {
return new Queue(RabbitConsts.DELAY_QUEUE, true);
}
/**
* 延迟队列交换器, x-delayed-type 和 x-delayed-message 固定
*/
@Bean
public CustomExchange delayExchange() {
Map<String, Object> args = Maps.newHashMap();
args.put("x-delayed-type", "direct");
return new CustomExchange(RabbitConsts.DELAY_MODE_QUEUE, "x-delayed-message", true, false, args);
}
/**
* 延迟队列绑定自定义交换器
*
* @param delayQueue 队列
* @param delayExchange 延迟交换器
*/
@Bean
public Binding delayBinding(Queue delayQueue, CustomExchange delayExchange) {
return BindingBuilder.bind(delayQueue).to(delayExchange).with(RabbitConsts.DELAY_QUEUE).noargs();
}
} | repos\spring-boot-demo-master\demo-mq-rabbitmq\src\main\java\com\xkcoding\mq\rabbitmq\config\RabbitMqConfig.java | 2 |
请完成以下Java代码 | private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, String value) {
StringTokenizer tokenizer = new StringTokenizer(value, this.stringSeparator, false);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (StringUtils.hasText(token)) {
result.add(new SimpleGrantedAuthority(token));
}
}
}
/**
*
* @see org.springframework.security.core.authority.mapping.MappableAttributesRetriever#getMappableAttributes()
*/
@Override
public Set<String> getMappableAttributes() {
return this.mappableAttributes;
}
/** | * @return Returns the stringSeparator.
*/
public String getStringSeparator() {
return this.stringSeparator;
}
/**
* @param stringSeparator The stringSeparator to set.
*/
public void setStringSeparator(String stringSeparator) {
Assert.notNull(stringSeparator, "stringSeparator cannot be null");
this.stringSeparator = stringSeparator;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\core\authority\mapping\MapBasedAttributes2GrantedAuthoritiesMapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable Duration getFixedDelay() {
return this.fixedDelay;
}
public void setFixedDelay(@Nullable Duration fixedDelay) {
this.fixedDelay = fixedDelay;
}
public @Nullable Duration getFixedRate() {
return this.fixedRate;
}
public void setFixedRate(@Nullable Duration fixedRate) {
this.fixedRate = fixedRate;
}
public @Nullable Duration getInitialDelay() {
return this.initialDelay;
}
public void setInitialDelay(@Nullable Duration initialDelay) {
this.initialDelay = initialDelay;
}
public @Nullable String getCron() {
return this.cron;
}
public void setCron(@Nullable String cron) {
this.cron = cron;
}
}
public static class Management {
/**
* Whether Spring Integration components should perform logging in the main
* message flow. When disabled, such logging will be skipped without checking the | * logging level. When enabled, such logging is controlled as normal by the
* logging system's log level configuration.
*/
private boolean defaultLoggingEnabled = true;
/**
* List of simple patterns to match against the names of Spring Integration
* components. When matched, observation instrumentation will be performed for the
* component. Please refer to the javadoc of the smartMatch method of Spring
* Integration's PatternMatchUtils for details of the pattern syntax.
*/
private List<String> observationPatterns = new ArrayList<>();
public boolean isDefaultLoggingEnabled() {
return this.defaultLoggingEnabled;
}
public void setDefaultLoggingEnabled(boolean defaultLoggingEnabled) {
this.defaultLoggingEnabled = defaultLoggingEnabled;
}
public List<String> getObservationPatterns() {
return this.observationPatterns;
}
public void setObservationPatterns(List<String> observationPatterns) {
this.observationPatterns = observationPatterns;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-integration\src\main\java\org\springframework\boot\integration\autoconfigure\IntegrationProperties.java | 2 |
请完成以下Java代码 | public HttpResponseMessage calculateSalary(
@HttpTrigger(
name="http",
methods = HttpMethod.POST,
authLevel = AuthorizationLevel.ANONYMOUS)HttpRequestMessage<Optional<Employee>> employeeHttpRequestMessage,
ExecutionContext executionContext
) {
Employee employeeRequest = employeeHttpRequestMessage.getBody().get();
executionContext.getLogger().info("Salary of " + employeeRequest.getName() + " is:" + employeeRequest.getSalary());
Employee employee = employeeSalaryFunction.apply(employeeRequest);
executionContext.getLogger().info("Final salary of " + employee.getName() + " is:" + employee.getSalary());
return employeeHttpRequestMessage.createResponseBuilder(HttpStatus.OK)
.body(employee)
.build();
}
@FunctionName("calculateSalaryWithSCF")
public HttpResponseMessage calculateSalaryWithSCF(
@HttpTrigger(
name="http",
methods = HttpMethod.POST, | authLevel = AuthorizationLevel.ANONYMOUS)HttpRequestMessage<Optional<Employee>> employeeHttpRequestMessage,
ExecutionContext executionContext
) {
Employee employeeRequest = employeeHttpRequestMessage.getBody().get();
executionContext.getLogger().info("Salary of " + employeeRequest.getName() + " is:" + employeeRequest.getSalary());
EmployeeSalaryFunctionWrapper employeeSalaryFunctionWrapper = new EmployeeSalaryFunctionWrapper(functionCatalog);
Function<Employee, Employee> cityBasedSalaryFunction = employeeSalaryFunctionWrapper.getCityBasedSalaryFunction(employeeRequest);
executionContext.getLogger().info("The class of the cityBasedSalaryFunction:" + cityBasedSalaryFunction.getClass());
Employee employee = cityBasedSalaryFunction.apply(employeeRequest);
executionContext.getLogger().info("Final salary of " + employee.getName() + " is:" + employee.getSalary());
return employeeHttpRequestMessage.createResponseBuilder(HttpStatus.OK)
.body(employee)
.build();
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-functions-azure\src\main\java\com\baeldung\azure\functions\EmployeeSalaryHandler.java | 1 |
请完成以下Java代码 | public Object execute(CommandContext commandContext) {
ensureNotNull(BadUserRequestException.class, "taskId", taskId);
TaskEntity task = commandContext.getTaskManager().findTaskById(taskId);
ensureNotNull("No task exists with taskId: " + taskId, "task", task);
checkTaskWork(task, commandContext);
if (commentId != null) {
CommentEntity comment = commandContext.getCommentManager().findCommentByTaskIdAndCommentId(taskId, commentId);
if (comment != null) {
commandContext.getDbEntityManager().delete(comment);
}
} else { // delete all comments
List<Comment> comments = commandContext.getCommentManager().findCommentsByTaskId(taskId);
if (!comments.isEmpty()) {
commandContext.getCommentManager().deleteCommentsByTaskId(taskId);
} | }
commandContext.getOperationLogManager()
.logCommentOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE_COMMENT, task,
new PropertyChange("comment", null, null));
task.triggerUpdateEvent();
return null;
}
protected void checkTaskWork(TaskEntity task, CommandContext commandContext) {
for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkTaskWork(task);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteTaskCommentCmd.java | 1 |
请完成以下Java代码 | public ExecutionInput getExecutionInput() {
return this.executionInput;
}
/**
* Return the {@link ExecutionContext context} for the request execution.
* @since 1.3.7
*/
public @Nullable ExecutionContext getExecutionContext() {
return this.executionContext;
}
/**
* Set the {@link ExecutionContext context} for the request execution.
* @param executionContext the execution context
* @since 1.3.7
*/
public void setExecutionContext(ExecutionContext executionContext) {
this.executionContext = executionContext;
}
/**
* Return the {@link ExecutionResult result} for the request execution. | * @since 1.1.4
*/
public @Nullable ExecutionResult getExecutionResult() {
return this.executionResult;
}
/**
* Set the {@link ExecutionResult result} for the request execution.
* @param executionResult the execution result
* @since 1.1.4
*/
public void setExecutionResult(ExecutionResult executionResult) {
this.executionResult = executionResult;
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\ExecutionRequestObservationContext.java | 1 |
请完成以下Java代码 | private static ImmutableMap<HuId, Boolean> getHUId2ProcessedFlag(@NonNull final ImmutableList<PickingCandidate> pickingCandidates)
{
final HashMap<HuId, Boolean> huId2ProcessedFlag = new HashMap<>();
pickingCandidates.stream()
.filter(pickingCandidate -> pickingCandidate.getPickingSlotId() != null)
.filter(pickingCandidate -> !pickingCandidate.isRejectedToPick())
.filter(pickingCandidate -> pickingCandidate.getPickFrom().getHuId() != null)
.forEach(pickingCandidate -> huId2ProcessedFlag.merge(pickingCandidate.getPickFrom().getHuId(),
PickingCandidateHURowsProvider.isPickingCandidateProcessed(pickingCandidate),
(oldValue, newValue) -> oldValue || newValue));
return ImmutableMap.copyOf(huId2ProcessedFlag);
}
private static boolean isPickingCandidateProcessed(@NonNull final PickingCandidate pc)
{
final PickingCandidateStatus status = pc.getProcessingStatus();
if (PickingCandidateStatus.Closed.equals(status)) | {
return true;
}
else if (PickingCandidateStatus.Processed.equals(status))
{
return true;
}
else if (PickingCandidateStatus.Draft.equals(status))
{
return false;
}
else
{
throw new AdempiereException("Unexpected M_Picking_Candidate.Status=" + status).setParameter("pc", pc);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingCandidateHURowsProvider.java | 1 |
请完成以下Java代码 | public boolean isQualityInspection(final int ppOrderId)
{
final I_PP_Order ppOrderRecord = loadOutOfTrx(ppOrderId, I_PP_Order.class);
return isQualityInspection(ppOrderRecord);
}
@Override
public boolean isQualityInspection(@NonNull final I_PP_Order ppOrder)
{
// NOTE: keep in sync with #qualityInspectionFilter
final String orderType = ppOrder.getOrderType();
return C_DocType_DOCSUBTYPE_QualityInspection.equals(orderType);
}
@Override
public void assertQualityInspectionOrder(@NonNull final I_PP_Order ppOrder)
{
Check.assume(isQualityInspection(ppOrder), "Order shall be Quality Inspection Order: {}", ppOrder);
}
@Override
public IQueryFilter<I_PP_Order> getQualityInspectionFilter()
{
return qualityInspectionFilter;
}
@Override
public Timestamp getDateOfProduction(final I_PP_Order ppOrder)
{
final Timestamp dateOfProduction;
if (ppOrder.getDateDelivered() != null)
{
dateOfProduction = ppOrder.getDateDelivered();
}
else
{
dateOfProduction = ppOrder.getDateFinishSchedule();
}
Check.assumeNotNull(dateOfProduction, "dateOfProduction not null for PP_Order {}", ppOrder);
return dateOfProduction;
} | @Override
public List<I_M_InOutLine> retrieveIssuedInOutLines(final I_PP_Order ppOrder)
{
// services
final IPPOrderMInOutLineRetrievalService ppOrderMInOutLineRetrievalService = Services.get(IPPOrderMInOutLineRetrievalService.class);
final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class);
final IPPCostCollectorDAO ppCostCollectorDAO = Services.get(IPPCostCollectorDAO.class);
final List<I_M_InOutLine> allIssuedInOutLines = new ArrayList<>();
final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID());
for (final I_PP_Cost_Collector cc : ppCostCollectorDAO.getByOrderId(ppOrderId))
{
if (!ppCostCollectorBL.isAnyComponentIssueOrCoProduct(cc))
{
continue;
}
final List<I_M_InOutLine> issuedInOutLinesForCC = ppOrderMInOutLineRetrievalService.provideIssuedInOutLines(cc);
allIssuedInOutLines.addAll(issuedInOutLinesForCC);
}
return allIssuedInOutLines;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingPPOrderBL.java | 1 |
请完成以下Java代码 | public class LoginDto {
@JsonProperty("user")
private String user;
@JsonProperty("pass")
private String pass;
public LoginDto user(String user) {
this.user = user;
return this;
}
/**
* Get user
* @return user
*/
@Schema(name = "user", requiredMode = RequiredMode.REQUIRED)
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public LoginDto pass(String pass) {
this.pass = pass;
return this;
}
/**
* Get pass
* @return pass
*/
@Schema(name = "pass", required = true)
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
@Override | public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LoginDto login = (LoginDto) o;
return Objects.equals(this.user, login.user) && Objects.equals(this.pass, login.pass);
}
@Override
public int hashCode() {
return Objects.hash(user, pass);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class LoginDto {\n");
sb.append(" user: ")
.append(toIndentedString(user))
.append("\n");
sb.append(" pass: ")
.append(toIndentedString(pass))
.append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString()
.replace("\n", "\n ");
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\defaultglobalsecurityscheme\dto\LoginDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void updateDiscountSchemaBreakRecords(@NonNull final PricingConditionsBreak fromBreak, @NonNull final PricingConditionsBreak toBreak)
{
final I_M_DiscountSchemaBreak to = getPricingConditionsBreakbyId(toBreak.getId());
to.setPricingSystemSurchargeAmt(fromBreak.getPricingSystemSurchargeAmt());
saveRecord(to);
}
private void inactivateDiscountSchemaBreakRecords(@NonNull final PricingConditionsBreak db)
{
final I_M_DiscountSchemaBreak record = getPricingConditionsBreakbyId(db.getId());
record.setIsActive(false);
saveRecord(record);
}
@Override
public boolean isSingleProductId(final IQueryFilter<I_M_DiscountSchemaBreak> selectionFilter)
{
final Set<ProductId> distinctProductIds = retrieveDistinctProductIdsForSelection(selectionFilter);
return distinctProductIds.size() == 1;
}
@Override
public ProductId retrieveUniqueProductIdForSelectionOrNull(final IQueryFilter<I_M_DiscountSchemaBreak> selectionFilter)
{
final Set<ProductId> distinctProductsForSelection = retrieveDistinctProductIdsForSelection(selectionFilter);
if (distinctProductsForSelection.isEmpty())
{ | return null;
}
if (distinctProductsForSelection.size() > 1)
{
throw new AdempiereException("Multiple products or none in the selected rows")
.appendParametersToMessage()
.setParameter("selectionFilter", selectionFilter);
}
final ProductId uniqueProductId = distinctProductsForSelection.iterator().next();
return uniqueProductId;
}
private Set<ProductId> retrieveDistinctProductIdsForSelection(final IQueryFilter<I_M_DiscountSchemaBreak> selectionFilter)
{
final IQuery<I_M_DiscountSchemaBreak> breaksQuery = queryBL.createQueryBuilder(I_M_DiscountSchemaBreak.class)
.filter(selectionFilter)
.create();
final List<Integer> distinctProductRecordIds = breaksQuery.listDistinct(I_M_DiscountSchemaBreak.COLUMNNAME_M_Product_ID, Integer.class);
return ProductId.ofRepoIds(distinctProductRecordIds);
}
public I_M_DiscountSchemaBreak getPricingConditionsBreakbyId(@NonNull PricingConditionsBreakId discountSchemaBreakId)
{
return load(discountSchemaBreakId.getDiscountSchemaBreakId(), I_M_DiscountSchemaBreak.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\service\impl\PricingConditionsRepository.java | 2 |
请完成以下Java代码 | private ConfigurableListableBeanFactory getConfigurableBeanFactory() {
if (this.configurableBeanFactory == null) {
this.configurableBeanFactory = ((ConfigurableApplicationContext) this.applicationContext).getBeanFactory();
}
return this.configurableBeanFactory;
}
/**
* Gets the bean name from the given annotation.
*
* @param grpcClientBean The annotation to extract it from.
* @return The extracted name.
*/
private String getBeanName(final GrpcClientBean grpcClientBean) {
if (!grpcClientBean.beanName().isEmpty()) {
return grpcClientBean.beanName(); | } else {
return grpcClientBean.client().value() + grpcClientBean.clazz().getSimpleName();
}
}
/**
* Checks whether the given class is annotated with {@link Configuration}.
*
* @param clazz The class to check.
* @return True, if the given class is annotated with {@link Configuration}. False otherwise.
*/
private boolean isAnnotatedWithConfiguration(final Class<?> clazz) {
final Configuration configurationAnnotation = AnnotationUtils.findAnnotation(clazz, Configuration.class);
return configurationAnnotation != null;
}
} | repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\inject\GrpcClientBeanPostProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ResultHolder implements Serializable {
@Id @NonNull
private Integer operand;
@Id
@NonNull
@Enumerated(EnumType.STRING)
private Operator operator;
@NonNull
private Integer result;
protected ResultHolder() { }
@Override
public String toString() {
return getOperator().toString(getOperand(), getResult());
} | @Getter
@EqualsAndHashCode
@RequiredArgsConstructor(staticName = "of")
public static class ResultKey implements Serializable {
@NonNull
private Integer operand;
@NonNull
private Operator operator;
protected ResultKey() { }
}
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline\src\main\java\example\app\caching\inline\model\ResultHolder.java | 2 |
请完成以下Java代码 | public static String prettyPrintByDom4j(String xmlString, int indent, boolean skipDeclaration) {
try {
final OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
format.setIndentSize(indent);
format.setSuppressDeclaration(skipDeclaration);
final org.dom4j.Document document = DocumentHelper.parseText(xmlString);
final StringWriter sw = new StringWriter();
final XMLWriter writer = new XMLWriter(sw, format);
writer.write(document);
return sw.toString();
} catch (Exception e) {
throw new RuntimeException("Error occurs when pretty-printing xml:\n" + xmlString, e);
}
}
public static void main(String[] args) throws IOException {
InputStream inputStream = XmlPrettyPrinter.class.getResourceAsStream("/xml/emails.xml");
String xmlString = readFromInputStream(inputStream);
System.out.println("Pretty printing by Transformer");
System.out.println("=============================================");
System.out.println(prettyPrintByTransformer(xmlString, 2, true)); | System.out.println("=============================================");
System.out.println("Pretty printing by Dom4j");
System.out.println("=============================================");
System.out.println(prettyPrintByDom4j(xmlString, 8, false));
System.out.println("=============================================");
}
private static String readPrettyPrintXslt() throws IOException {
InputStream inputStream = XmlPrettyPrinter.class.getResourceAsStream("/xml/prettyprint.xsl");
return readFromInputStream(inputStream);
}
private static String readFromInputStream(InputStream inputStream) throws IOException {
StringBuilder resultStringBuilder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = br.readLine()) != null) {
resultStringBuilder.append(line).append("\n");
}
}
return resultStringBuilder.toString();
}
} | repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\prettyprint\XmlPrettyPrinter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public void setExecutionDate(String executionDate) {
this.executionDate = executionDate;
}
public void setIncludeProcessInstances(boolean includeProcessInstances) {
this.includeProcessInstances = includeProcessInstances;
}
public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
}
public void updateSuspensionState(ProcessEngine engine) {
if (processDefinitionId != null && processDefinitionKey != null) {
String message = "Only one of processDefinitionId or processDefinitionKey should be set to update the suspension state.";
throw new InvalidRequestException(Status.BAD_REQUEST, message);
}
RepositoryService repositoryService = engine.getRepositoryService();
Date delayedExecutionDate = null;
if (executionDate != null && !executionDate.equals("")) {
delayedExecutionDate = DateTimeUtil.parseDate(executionDate);
}
if (processDefinitionId != null) {
// activate/suspend process definition by id
if (getSuspended()) { | repositoryService.suspendProcessDefinitionById(processDefinitionId, includeProcessInstances, delayedExecutionDate);
} else {
repositoryService.activateProcessDefinitionById(processDefinitionId, includeProcessInstances, delayedExecutionDate);
}
} else
if (processDefinitionKey != null) {
// activate/suspend process definition by key
if (getSuspended()) {
repositoryService.suspendProcessDefinitionByKey(processDefinitionKey, includeProcessInstances, delayedExecutionDate);
} else {
repositoryService.activateProcessDefinitionByKey(processDefinitionKey, includeProcessInstances, delayedExecutionDate);
}
} else {
String message = "Either processDefinitionId or processDefinitionKey should be set to update the suspension state.";
throw new InvalidRequestException(Status.BAD_REQUEST, message);
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\ProcessDefinitionSuspensionStateDto.java | 2 |
请完成以下Java代码 | public String getKey() {
return kv.getKey();
}
@Override
public DataType getDataType() {
return kv.getDataType();
}
@Override
public Optional<String> getStrValue() {
return kv.getStrValue();
}
@Override
public Optional<Long> getLongValue() {
return kv.getLongValue();
}
@Override
public Optional<Boolean> getBooleanValue() {
return kv.getBooleanValue();
} | @Override
public Optional<Double> getDoubleValue() {
return kv.getDoubleValue();
}
@Override
public Optional<String> getJsonValue() {
return kv.getJsonValue();
}
@Override
public String getValueAsString() {
return kv.getValueAsString();
}
@Override
public Object getValue() {
return kv.getValue();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\BaseAttributeKvEntry.java | 1 |
请完成以下Java代码 | public static int getDefaultContactId(final int cBPartnerId)
{
for (final I_AD_User user : Services.get(IBPartnerDAO.class).retrieveContacts(Env.getCtx(), cBPartnerId, ITrx.TRXNAME_None))
{
if (user.isDefaultContact())
{
return user.getAD_User_ID();
}
}
LogManager.getLogger(MBPartner.class).warn("Every BPartner with associated contacts is expected to have exactly one default contact, but C_BPartner_ID {} doesn't have one.", cBPartnerId);
return -1;
}
// end metas
/**
* Before Save
*
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave(final boolean newRecord)
{
if (newRecord || is_ValueChanged("C_BP_Group_ID"))
{
final I_C_BP_Group grp = getBPGroup();
if (grp == null)
{
throw new AdempiereException("@NotFound@: @C_BP_Group_ID@");
}
final BPGroupId parentGroupId = BPGroupId.ofRepoIdOrNull(grp.getParent_BP_Group_ID());
if (parentGroupId != null)
{
final I_C_BP_Group parentGroup = bpGroupsRepo.getById(parentGroupId);
setBPGroup(parentGroup); // attempt to set from parent group first
}
setBPGroup(grp); // setDefaults
}
return true;
} // beforeSave
/**************************************************************************
* After Save
*
* @param newRecord
* new
* @param success
* success
* @return success
*/
@Override
protected boolean afterSave(final boolean newRecord, final boolean success)
{
if (newRecord && success)
{
// Trees
insert_Tree(MTree_Base.TREETYPE_BPartner);
// Accounting
insert_Accounting("C_BP_Customer_Acct", "C_BP_Group_Acct",
"p.C_BP_Group_ID=" + getC_BP_Group_ID());
insert_Accounting("C_BP_Vendor_Acct", "C_BP_Group_Acct",
"p.C_BP_Group_ID=" + getC_BP_Group_ID());
insert_Accounting("C_BP_Employee_Acct", "C_AcctSchema_Default",
null);
}
// Value/Name change
if (success && !newRecord
&& (is_ValueChanged("Value") || is_ValueChanged("Name")))
{
MAccount.updateValueDescription(getCtx(), "C_BPartner_ID="
+ getC_BPartner_ID(), get_TrxName()); | }
return success;
} // afterSave
/**
* Before Delete
*
* @return true
*/
@Override
protected boolean beforeDelete()
{
return delete_Accounting("C_BP_Customer_Acct")
&& delete_Accounting("C_BP_Vendor_Acct")
&& delete_Accounting("C_BP_Employee_Acct");
} // beforeDelete
/**
* After Delete
*
* @param success
* @return deleted
*/
@Override
protected boolean afterDelete(final boolean success)
{
if (success)
{
delete_Tree(MTree_Base.TREETYPE_BPartner);
}
return success;
} // afterDelete
} // MBPartner | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MBPartner.java | 1 |
请完成以下Java代码 | public <T extends ServerResponse> RouterFunctions.Builder path(String pattern,
Supplier<RouterFunction<T>> routerFunctionSupplier) {
builder.path(pattern, routerFunctionSupplier);
return this;
}
@Override
public RouterFunctions.Builder path(String pattern, Consumer<RouterFunctions.Builder> builderConsumer) {
builder.path(pattern, builderConsumer);
return this;
}
@Override
public <T extends ServerResponse, R extends ServerResponse> RouterFunctions.Builder filter(
HandlerFilterFunction<T, R> filterFunction) {
builder.filter(filterFunction);
return this;
}
@Override
public RouterFunctions.Builder before(Function<ServerRequest, ServerRequest> requestProcessor) {
builder.before(requestProcessor);
return this;
}
@Override
public <T extends ServerResponse, R extends ServerResponse> RouterFunctions.Builder after(
BiFunction<ServerRequest, T, R> responseProcessor) {
builder.after(responseProcessor);
return this;
}
@Override
public <T extends ServerResponse> RouterFunctions.Builder onError(Predicate<Throwable> predicate,
BiFunction<Throwable, ServerRequest, T> responseProvider) {
builder.onError(predicate, responseProvider);
return this;
}
@Override | public <T extends ServerResponse> RouterFunctions.Builder onError(Class<? extends Throwable> exceptionType,
BiFunction<Throwable, ServerRequest, T> responseProvider) {
builder.onError(exceptionType, responseProvider);
return this;
}
@Override
public RouterFunctions.Builder withAttribute(String name, Object value) {
builder.withAttribute(name, value);
return this;
}
@Override
public RouterFunctions.Builder withAttributes(Consumer<Map<String, Object>> attributesConsumer) {
builder.withAttributes(attributesConsumer);
return this;
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayRouterFunctionsBuilder.java | 1 |
请完成以下Java代码 | default void onPdfUpdate(final I_AD_Archive archive, final UserId userId)
{
// nothing
}
default void onPdfUpdate(
final I_AD_Archive archive,
final UserId userId,
final String action)
{
// nothing
}
default void onEmailSent(
final I_AD_Archive archive,
final UserEMailConfig user,
final EMailAddress from,
final EMailAddress to,
final EMailAddress cc,
final EMailAddress bcc,
final ArchiveEmailSentStatus status)
{
// nothing
} | default void onPrintOut(
final I_AD_Archive archive,
final UserId userId,
final String printerName,
final int copies,
final ArchivePrintOutStatus status)
{
// nothing
}
default void onVoidDocument(final I_AD_Archive archive)
{
// nothing
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\spi\IArchiveEventListener.java | 1 |
请完成以下Java代码 | public long getMaxScriptExecutionTime() {
return maxScriptExecutionTime;
}
public SecureJavascriptConfigurator setMaxScriptExecutionTime(long maxScriptExecutionTime) {
this.maxScriptExecutionTime = maxScriptExecutionTime;
return this;
}
public int getNrOfInstructionsBeforeStateCheckCallback() {
return nrOfInstructionsBeforeStateCheckCallback;
}
public SecureJavascriptConfigurator setNrOfInstructionsBeforeStateCheckCallback(int nrOfInstructionsBeforeStateCheckCallback) {
this.nrOfInstructionsBeforeStateCheckCallback = nrOfInstructionsBeforeStateCheckCallback;
return this;
}
public int getMaxStackDepth() {
return maxStackDepth;
}
public SecureJavascriptConfigurator setMaxStackDepth(int maxStackDepth) {
this.maxStackDepth = maxStackDepth;
return this;
}
public long getMaxMemoryUsed() {
return maxMemoryUsed;
}
public SecureJavascriptConfigurator setMaxMemoryUsed(long maxMemoryUsed) {
this.maxMemoryUsed = maxMemoryUsed;
return this;
}
public int getScriptOptimizationLevel() {
return scriptOptimizationLevel;
}
public SecureJavascriptConfigurator setScriptOptimizationLevel(int scriptOptimizationLevel) {
this.scriptOptimizationLevel = scriptOptimizationLevel; | return this;
}
public SecureScriptContextFactory getSecureScriptContextFactory() {
return secureScriptContextFactory;
}
public static SecureScriptClassShutter getSecureScriptClassShutter() {
return secureScriptClassShutter;
}
public SecureJavascriptConfigurator setEnableAccessToBeans(boolean enableAccessToBeans) {
this.enableAccessToBeans = enableAccessToBeans;
return this;
}
public boolean isEnableAccessToBeans() {
return enableAccessToBeans;
}
} | repos\flowable-engine-main\modules\flowable-secure-javascript\src\main\java\org\flowable\scripting\secure\SecureJavascriptConfigurator.java | 1 |
请完成以下Java代码 | public JSONViewRowAttributes getData(
@PathVariable(PARAM_WindowId) final String windowIdStr //
, @PathVariable(PARAM_ViewId) final String viewIdStr //
, @PathVariable(PARAM_RowId) final String rowIdStr //
)
{
userSession.assertLoggedIn();
final ViewId viewId = ViewId.of(windowIdStr, viewIdStr);
final DocumentId rowId = DocumentId.of(rowIdStr);
return viewsRepo.getView(viewId)
.getById(rowId)
.getAttributes()
.toJson(newJSONOptions());
}
@PatchMapping
public List<JSONDocument> processChanges(
@PathVariable(PARAM_WindowId) final String windowIdStr //
, @PathVariable(PARAM_ViewId) final String viewIdStr //
, @PathVariable(PARAM_RowId) final String rowIdStr //
, @RequestBody final List<JSONDocumentChangedEvent> events //
)
{
userSession.assertLoggedIn();
final ViewId viewId = ViewId.of(windowIdStr, viewIdStr);
final DocumentId rowId = DocumentId.of(rowIdStr);
return Execution.callInNewExecution("processChanges", () -> {
viewsRepo.getView(viewId)
.getById(rowId)
.getAttributes()
.processChanges(events);
return JSONDocument.ofEvents(Execution.getCurrentDocumentChangesCollectorOrNull(), newJSONDocumentOptions());
});
}
@GetMapping("/attribute/{attributeName}/typeahead")
public JSONLookupValuesList getAttributeTypeahead(
@PathVariable(PARAM_WindowId) final String windowIdStr //
, @PathVariable(PARAM_ViewId) final String viewIdStr//
, @PathVariable(PARAM_RowId) final String rowIdStr //
, @PathVariable("attributeName") final String attributeName //
, @RequestParam(name = "query", required = true) final String query //
)
{
userSession.assertLoggedIn();
final ViewId viewId = ViewId.of(windowIdStr, viewIdStr);
final DocumentId rowId = DocumentId.of(rowIdStr);
return viewsRepo.getView(viewId)
.getById(rowId)
.getAttributes() | .getAttributeTypeahead(attributeName, query)
.transform(this::toJSONLookupValuesList);
}
private JSONLookupValuesList toJSONLookupValuesList(final LookupValuesList lookupValuesList)
{
return JSONLookupValuesList.ofLookupValuesList(lookupValuesList, userSession.getAD_Language());
}
@GetMapping("/attribute/{attributeName}/dropdown")
public JSONLookupValuesList getAttributeDropdown(
@PathVariable(PARAM_WindowId) final String windowIdStr //
, @PathVariable(PARAM_ViewId) final String viewIdStr //
, @PathVariable(PARAM_RowId) final String rowIdStr //
, @PathVariable("attributeName") final String attributeName //
)
{
userSession.assertLoggedIn();
final ViewId viewId = ViewId.of(windowIdStr, viewIdStr);
final DocumentId rowId = DocumentId.of(rowIdStr);
return viewsRepo.getView(viewId)
.getById(rowId)
.getAttributes()
.getAttributeDropdown(attributeName)
.transform(this::toJSONLookupValuesList);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowAttributesRestController.java | 1 |
请完成以下Java代码 | public static void setWindowLocation(final int AD_Window_ID, final Point windowLocation)
{
final String key = "WindowLoc" + AD_Window_ID;
if (windowLocation != null)
{
final String value = windowLocation.x + "|" + windowLocation.y;
s_prop.put(key, value);
}
else
s_prop.remove(key);
} // setWindowLocation
/**
* Get Divider Location
*
* @return location or 400
*/
public static int getDividerLocation()
{
final int defaultValue = 400;
final String key = "Divider";
final String value = (String)s_prop.get(key);
if (value == null || value.length() == 0)
return defaultValue;
int valueInt = defaultValue;
try
{
valueInt = Integer.parseInt(value);
}
catch (final Exception ignored)
{
}
return valueInt <= 0 ? defaultValue : valueInt;
} // getDividerLocation
/**
* Set Divider Location
*
* @param dividerLocation location
*/
public static void setDividerLocation(final int dividerLocation)
{
final String key = "Divider";
final String value = String.valueOf(dividerLocation);
s_prop.put(key, value);
} // setDividerLocation
/**
* Get Available Encoding Charsets
*
* @return array of available encoding charsets | * @since 3.1.4
*/
public static Charset[] getAvailableCharsets()
{
final Collection<Charset> col = Charset.availableCharsets().values();
final Charset[] arr = new Charset[col.size()];
col.toArray(arr);
return arr;
}
/**
* Get current charset
*
* @return current charset
* @since 3.1.4
*/
public static Charset getCharset()
{
final String charsetName = getProperty(P_CHARSET);
if (Check.isBlank(charsetName))
{
return Charset.defaultCharset();
}
try
{
return Charset.forName(charsetName);
}
catch (final Exception ignored)
{
}
return Charset.defaultCharset();
}
public static String getPropertyFileName()
{
return s_propertyFileName;
}
// public static class IsNotSwingClient implements Condition
// {
// @Override
// public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata)
// {
// return Ini.getRunMode() != RunMode.SWING_CLIENT;
// }
// }
} // Ini | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Ini.java | 1 |
请完成以下Java代码 | public void addConfigurationProperties(Properties properties) {
super.addConfigurationProperties(properties);
this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
}
/**
* 给字段添加注释
*/
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
String remarks = introspectedColumn.getRemarks();
//根据参数和备注信息判断是否添加swagger注解信息
if(addRemarkComments&&StringUtility.stringHasValue(remarks)){
// addFieldJavaDoc(field, remarks);
//数据库中特殊字符需要转义
if(remarks.contains("\"")){
remarks = remarks.replace("\"","'");
}
//给model的字段添加swagger注解
field.addJavaDocLine("@ApiModelProperty(value = \""+remarks+"\")");
}
}
/**
* 给model的字段添加注释
*/
private void addFieldJavaDoc(Field field, String remarks) {
//文档注释开始
field.addJavaDocLine("/**");
//获取数据库字段的备注信息
String[] remarkLines = remarks.split(System.getProperty("line.separator"));
for(String remarkLine:remarkLines){ | field.addJavaDocLine(" * "+remarkLine);
}
addJavadocTag(field, false);
field.addJavaDocLine(" */");
}
@Override
public void addJavaFileComment(CompilationUnit compilationUnit) {
super.addJavaFileComment(compilationUnit);
//只在model中添加swagger注解类的导入
if(!compilationUnit.getType().getFullyQualifiedName().contains(MAPPER_SUFFIX)&&!compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)){
compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
}
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\CommentGenerator.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_M_BOMAlternative[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Alternative Group.
@param M_BOMAlternative_ID
Product BOM Alternative Group
*/
public void setM_BOMAlternative_ID (int M_BOMAlternative_ID)
{
if (M_BOMAlternative_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_BOMAlternative_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_BOMAlternative_ID, Integer.valueOf(M_BOMAlternative_ID));
}
/** Get Alternative Group.
@return Product BOM Alternative Group
*/
public int getM_BOMAlternative_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_BOMAlternative_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product. | @param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_BOMAlternative.java | 1 |
请完成以下Java代码 | public final <T> T coerceToType(Object obj, Class<T> targetType) {
return converter.convert(obj, targetType);
}
@Override
public final ObjectValueExpression createValueExpression(Object instance, Class<?> expectedType) {
return new ObjectValueExpression(converter, instance, expectedType);
}
@Override
public final TreeValueExpression createValueExpression(
ELContext context,
String expression,
Class<?> expectedType
) {
return new TreeValueExpression(
store,
context.getFunctionMapper(),
context.getVariableMapper(),
converter,
expression,
expectedType | );
}
@Override
public final TreeMethodExpression createMethodExpression(
ELContext context,
String expression,
Class<?> expectedReturnType,
Class<?>[] expectedParamTypes
) {
return new TreeMethodExpression(
store,
context.getFunctionMapper(),
context.getVariableMapper(),
converter,
expression,
expectedReturnType,
expectedParamTypes
);
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\ExpressionFactoryImpl.java | 1 |
请完成以下Java代码 | public void startMonitoring() {
entityService.checkEntities();
monitoringServices.forEach(BaseMonitoringService::init);
for (int i = 0; i < monitoringServices.size(); i++) {
int initialDelay = (monitoringRateMs / monitoringServices.size()) * i;
BaseMonitoringService<?, ?> service = monitoringServices.get(i);
log.info("Scheduling initialDelay {}, fixedDelay {} for monitoring '{}' ", initialDelay, monitoringRateMs, service.getClass().getSimpleName());
scheduler.scheduleWithFixedDelay(service::runChecks, initialDelay, monitoringRateMs, TimeUnit.MILLISECONDS);
}
String publicDashboardUrl = entityService.getDashboardPublicLink();
notificationService.sendNotification(new InfoNotification(":rocket: <"+publicDashboardUrl+"|Monitoring> started"));
}
@EventListener(ContextClosedEvent.class)
public void onShutdown(ContextClosedEvent event) {
log.info("Shutting down monitoring service");
try { | var futures = notificationService.sendNotification(new InfoNotification(":warning: Monitoring is shutting down"));
for (Future<?> future : futures) {
future.get(5, TimeUnit.SECONDS);
}
} catch (Exception e) {
log.warn("Failed to send shutdown notification", e);
}
}
@PreDestroy
public void shutdownScheduler() {
scheduler.shutdown();
}
} | repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\ThingsboardMonitoringApplication.java | 1 |
请完成以下Java代码 | private static <T> T createEventObject(InvocationContext invocation, Class<T> eventType) {
return eventType.getConstructor(invocation.getMethod()
.getParameterTypes())
.newInstance(invocation.getParameters());
}
@AroundInvoke
public Object fireEvent(InvocationContext invocation) throws Exception {
final Optional<FireEvent> annotation = AnnotationUtils.findAnnotation(invocation.getMethod(), FireEvent.class);
@SuppressWarnings("unchecked") final Optional<Class<Object>> eventType = AnnotationUtils.findAnnotation(invocation.getMethod(), FireEvent.class)
.map((FireEvent publishEvent) -> (Class<Object>) publishEvent.value());
final FireEvent.FireMode mode = annotation.map(FireEvent::mode)
.orElse(FireEvent.FireMode.SYNC_AND_ASYNC);
final Optional<Object> event = eventType.map(clazz -> createEventObject(invocation, clazz));
// if something is wrong until here, we do not invoke the service's create-method
// now, we invoke the service
final Object result = invocation.proceed();
// if an exception occured, the event is not fired
// now, we fire the event | event.ifPresent(e -> eventType.map(eventPublisher::select)
.ifPresent(publisher -> {
// fire synchronous events
if (mode.isFireSync()) {
publisher.fire(e);
}
// if no error occured, fire asynchronous events
if (mode.isFireAsync()) {
publisher.fireAsync(e);
}
}));
// and we need to return the service's result to the invoker (the controller)
return result;
}
} | repos\tutorials-master\quarkus-modules\quarkus-citrus\src\main\java\com\baeldung\quarkus\shared\interceptors\FireEventInterceptor.java | 1 |
请完成以下Java代码 | public static Map<String, String[]> loadCorpus(String path)
{
Map<String, String[]> dataSet = new TreeMap<String, String[]>();
File root = new File(path);
File[] folders = root.listFiles();
if (folders == null) return null;
for (File folder : folders)
{
if (folder.isFile()) continue;
File[] files = folder.listFiles();
if (files == null) continue;
String[] documents = new String[files.length];
for (int i = 0; i < files.length; i++)
{
documents[i] = IOUtil.readTxt(files[i].getAbsolutePath());
}
dataSet.put(folder.getName(), documents);
}
return dataSet;
}
/**
* 加载一个文件夹下的所有语料
*
* @param folderPath
* @return
*/
public static Map<String, String[]> loadCorpusWithException(String folderPath, String charsetName) throws IOException
{
if (folderPath == null) throw new IllegalArgumentException("参数 folderPath == null");
File root = new File(folderPath);
if (!root.exists()) throw new IllegalArgumentException(String.format("目录 %s 不存在", root.getAbsolutePath()));
if (!root.isDirectory())
throw new IllegalArgumentException(String.format("目录 %s 不是一个目录", root.getAbsolutePath()));
Map<String, String[]> dataSet = new TreeMap<String, String[]>();
File[] folders = root.listFiles();
if (folders == null) return null;
for (File folder : folders)
{
if (folder.isFile()) continue;
File[] files = folder.listFiles();
if (files == null) continue;
String[] documents = new String[files.length];
for (int i = 0; i < files.length; i++)
{
documents[i] = readTxt(files[i], charsetName);
}
dataSet.put(folder.getName(), documents); | }
return dataSet;
}
public static String readTxt(File file, String charsetName) throws IOException
{
FileInputStream is = new FileInputStream(file);
byte[] targetArray = new byte[is.available()];
int len;
int off = 0;
while ((len = is.read(targetArray, off, targetArray.length - off)) != -1 && off < targetArray.length)
{
off += len;
}
is.close();
return new String(targetArray, charsetName);
}
public static Map<String, String[]> loadCorpusWithException(String corpusPath) throws IOException
{
return loadCorpusWithException(corpusPath, "UTF-8");
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\utilities\TextProcessUtility.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_CM_Template_Ad_Cat[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_CM_Ad_Cat getCM_Ad_Cat() throws RuntimeException
{
return (I_CM_Ad_Cat)MTable.get(getCtx(), I_CM_Ad_Cat.Table_Name)
.getPO(getCM_Ad_Cat_ID(), get_TrxName()); }
/** Set Advertisement Category.
@param CM_Ad_Cat_ID
Advertisement Category like Banner Homepage
*/
public void setCM_Ad_Cat_ID (int CM_Ad_Cat_ID)
{
if (CM_Ad_Cat_ID < 1)
set_Value (COLUMNNAME_CM_Ad_Cat_ID, null);
else
set_Value (COLUMNNAME_CM_Ad_Cat_ID, Integer.valueOf(CM_Ad_Cat_ID));
}
/** Get Advertisement Category.
@return Advertisement Category like Banner Homepage
*/
public int getCM_Ad_Cat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Ad_Cat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_CM_Template getCM_Template() throws RuntimeException
{
return (I_CM_Template)MTable.get(getCtx(), I_CM_Template.Table_Name)
.getPO(getCM_Template_ID(), get_TrxName()); }
/** Set Template.
@param CM_Template_ID
Template defines how content is displayed
*/
public void setCM_Template_ID (int CM_Template_ID)
{
if (CM_Template_ID < 1)
set_Value (COLUMNNAME_CM_Template_ID, null);
else
set_Value (COLUMNNAME_CM_Template_ID, Integer.valueOf(CM_Template_ID));
}
/** Get Template.
@return Template defines how content is displayed
*/
public int getCM_Template_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Template_ID);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Template_Ad_Cat.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LoggingFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class);
@Override
public void doFilter(jakarta.servlet.ServletRequest request, jakarta.servlet.ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
logRequest(httpRequest);
ResponseWrapper responseWrapper = new ResponseWrapper(httpResponse);
chain.doFilter(request, responseWrapper);
logResponse(httpRequest, responseWrapper);
} else {
chain.doFilter(request, response); | }
}
private void logRequest(HttpServletRequest request) {
logger.info("Incoming Request: [{}] {}", request.getMethod(), request.getRequestURI());
request.getHeaderNames().asIterator().forEachRemaining(header ->
logger.info("Header: {} = {}", header, request.getHeader(header))
);
}
private void logResponse(HttpServletRequest request, ResponseWrapper responseWrapper) throws IOException {
logger.info("Outgoing Response for [{}] {}: Status = {}",
request.getMethod(), request.getRequestURI(), responseWrapper.getStatus());
logger.info("Response Body: {}", responseWrapper.getBodyAsString());
}
} | repos\tutorials-master\logging-modules\log-all-requests\src\main\java\com\baeldung\logallrequests\LoggingFilter.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.