instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | private static void throwError(String errorCode, String parameterName) {
OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
private static final class OAuth2DeviceCodeGenerator implements OAuth2TokenGenerator<OAuth2DeviceCode> {
private final StringKeyGenerator deviceCodeGenerator = new Base64StringKeyGenerator(
Base64.getUrlEncoder().withoutPadding(), 96);
@Nullable
@Override
public OAuth2DeviceCode generate(OAuth2TokenContext context) {
if (context.getTokenType() == null
|| !OAuth2ParameterNames.DEVICE_CODE.equals(context.getTokenType().getValue())) {
return null;
}
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt
.plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive());
return new OAuth2DeviceCode(this.deviceCodeGenerator.generateKey(), issuedAt, expiresAt);
}
}
private static final class UserCodeStringKeyGenerator implements StringKeyGenerator {
// @formatter:off
private static final char[] VALID_CHARS = {
'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Z'
};
// @formatter:on
private final BytesKeyGenerator keyGenerator = KeyGenerators.secureRandom(8);
@Override
public String generateKey() {
byte[] bytes = this.keyGenerator.generateKey();
StringBuilder sb = new StringBuilder();
for (byte b : bytes) { | int offset = Math.abs(b % 20);
sb.append(VALID_CHARS[offset]);
}
sb.insert(4, '-');
return sb.toString();
}
}
private static final class OAuth2UserCodeGenerator implements OAuth2TokenGenerator<OAuth2UserCode> {
private final StringKeyGenerator userCodeGenerator = new UserCodeStringKeyGenerator();
@Nullable
@Override
public OAuth2UserCode generate(OAuth2TokenContext context) {
if (context.getTokenType() == null
|| !OAuth2ParameterNames.USER_CODE.equals(context.getTokenType().getValue())) {
return null;
}
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt
.plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive());
return new OAuth2UserCode(this.userCodeGenerator.generateKey(), issuedAt, expiresAt);
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2DeviceAuthorizationRequestAuthenticationProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RequisitionService
{
public BigDecimal computePrice(final I_M_Requisition requisition, final I_M_RequisitionLine line)
{
if (line.getC_Charge_ID() > 0)
{
final MCharge charge = MCharge.get(Env.getCtx(), line.getC_Charge_ID());
return charge.getChargeAmt();
}
else if (line.getM_Product_ID() > 0)
{
final int priceListId = requisition.getM_PriceList_ID();
if (priceListId <= 0)
{
// TODO: metas: we already changed the whole pricing engine, so for now we accept to not have a price here
// throw new AdempiereException("PriceList unknown!");
return BigDecimal.ZERO;
}
else
{
final MProductPricing pp = new MProductPricing(
OrgId.ofRepoId(requisition.getAD_Org_ID()),
line.getM_Product_ID(),
line.getC_BPartner_ID(),
null,
line.getQty(),
SOTrx.PURCHASE.toBoolean()); | pp.setM_PriceList_ID(priceListId);
// pp.setPriceDate(getDateOrdered());
//
return pp.getPriceStd();
}
}
else
{
return null;
}
}
public void updateLineNetAmt(final I_M_RequisitionLine line)
{
BigDecimal lineNetAmt = line.getQty().multiply(line.getPriceActual());
line.setLineNetAmt(lineNetAmt);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\requisition\RequisitionService.java | 2 |
请完成以下Java代码 | public class SalaryType implements UserType<Salary>, DynamicParameterizedType {
private String localCurrency;
@Override
public int getSqlType() {
return Types.VARCHAR;
}
@Override
public Class<Salary> returnedClass() {
return Salary.class;
}
@Override
public boolean equals(Salary x, Salary y) {
if (x == y)
return true;
if (Objects.isNull(x) || Objects.isNull(y))
return false;
return x.equals(y);
}
@Override
public int hashCode(Salary x) {
return x.hashCode();
}
@Override
public Salary nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
Salary salary = new Salary();
String salaryValue = rs.getString(position);
salary.setAmount(Long.parseLong(salaryValue.split(" ")[1]));
salary.setCurrency(salaryValue.split(" ")[0]);
return salary;
}
@Override
public void nullSafeSet(PreparedStatement st, Salary value, int index, SharedSessionContractImplementor session) throws SQLException {
if (Objects.isNull(value))
st.setNull(index, Types.VARCHAR);
else {
Long salaryValue = SalaryCurrencyConvertor.convert(value.getAmount(),
value.getCurrency(), localCurrency); | st.setString(index, value.getCurrency() + " " + salaryValue);
}
}
@Override
public Salary deepCopy(Salary value) {
if (Objects.isNull(value))
return null;
Salary newSal = new Salary();
newSal.setAmount(value.getAmount());
newSal.setCurrency(value.getCurrency());
return newSal;
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Serializable disassemble(Salary value) {
return deepCopy(value);
}
@Override
public Salary assemble(Serializable cached, Object owner) {
return deepCopy((Salary) cached);
}
@Override
public Salary replace(Salary detached, Salary managed, Object owner) {
return detached;
}
@Override
public void setParameterValues(Properties parameters) {
this.localCurrency = parameters.getProperty("currency");
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\SalaryType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DruidWallConfigRegister implements SpringApplicationRunListener {
public SpringApplication application;
private String[] args;
/**
* 必备,否则启动报错
* @param application
* @param args
*/
public DruidWallConfigRegister(SpringApplication application, String[] args) {
this.application = application;
this.args = args; | }
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
ConfigurableEnvironment env = context.getEnvironment();
Map<String, Object> props = new HashMap<>();
props.put("spring.datasource.dynamic.druid.wall.selectWhereAlwayTrueCheck", false);
MutablePropertySources propertySources = env.getPropertySources();
PropertySource<Map<String, Object>> propertySource = new MapPropertySource("jeecg-datasource-config", props);
propertySources.addLast(propertySource);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\DruidWallConfigRegister.java | 2 |
请完成以下Java代码 | public void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
this.requestMatcher = requestMatcher;
}
/**
* <p>
* Sets the value (in seconds) for the max-age directive of the
* Strict-Transport-Security header. The default is one year.
* </p>
*
* <p>
* This instructs browsers how long to remember to keep this domain as a known HSTS
* Host. See <a href="https://tools.ietf.org/html/rfc6797#section-6.1.1">Section
* 6.1.1</a> for additional details.
* </p>
* @param maxAgeInSeconds the maximum amount of time (in seconds) to consider this
* domain as a known HSTS Host.
* @throws IllegalArgumentException if maxAgeInSeconds is negative
*/
public void setMaxAgeInSeconds(long maxAgeInSeconds) {
Assert.isTrue(maxAgeInSeconds >= 0, () -> "maxAgeInSeconds must be non-negative. Got " + maxAgeInSeconds);
this.maxAgeInSeconds = maxAgeInSeconds;
updateHstsHeaderValue();
}
/**
* <p>
* If true, subdomains should be considered HSTS Hosts too. The default is true.
* </p>
*
* <p>
* See <a href="https://tools.ietf.org/html/rfc6797#section-6.1.2">Section 6.1.2</a>
* for additional details.
* </p>
* @param includeSubDomains true to include subdomains, else false
*/
public void setIncludeSubDomains(boolean includeSubDomains) {
this.includeSubDomains = includeSubDomains;
updateHstsHeaderValue();
}
/**
* <p> | * If true, preload will be included in HSTS Header. The default is false.
* </p>
*
* <p>
* See <a href="https://tools.ietf.org/html/rfc6797#section-6.1.2">Section 6.1.2</a>
* for additional details.
* </p>
* @param preload true to include preload, else false
* @since 5.2.0
*/
public void setPreload(boolean preload) {
this.preload = preload;
updateHstsHeaderValue();
}
private void updateHstsHeaderValue() {
String headerValue = "max-age=" + this.maxAgeInSeconds;
if (this.includeSubDomains) {
headerValue += " ; includeSubDomains";
}
if (this.preload) {
headerValue += " ; preload";
}
this.hstsHeaderValue = headerValue;
}
private static final class SecureRequestMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest request) {
return request.isSecure();
}
@Override
public String toString() {
return "Is Secure";
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\HstsHeaderWriter.java | 1 |
请完成以下Java代码 | public Boolean getVariableNamesIgnoreCase() {
return variableNamesIgnoreCase;
}
public Boolean getVariableValuesIgnoreCase() {
return variableValuesIgnoreCase;
}
@Override
public HistoricVariableInstanceQuery includeDeleted() {
includeDeleted = true;
return this;
}
public String getProcessDefinitionId() { | return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public List<String> getVariableNameIn() {
return variableNameIn;
}
public Date getCreatedAfter() {
return createdAfter;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricVariableInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void changeCurrencyRate(@NonNull final BankStatementLineId bankStatementLineId, @NonNull final BigDecimal currencyRate)
{
if (currencyRate.signum() == 0)
{
throw new AdempiereException("Invalid currency rate: " + currencyRate);
}
final I_C_BankStatementLine line = getLineById(bankStatementLineId);
final BankStatementId bankStatementId = BankStatementId.ofRepoId(line.getC_BankStatement_ID());
final I_C_BankStatement bankStatement = getById(bankStatementId);
assertBankStatementIsDraftOrInProcessOrCompleted(bankStatement);
final CurrencyId currencyId = CurrencyId.ofRepoId(line.getC_Currency_ID());
final CurrencyId baseCurrencyId = getBaseCurrencyId(line);
if (CurrencyId.equals(currencyId, baseCurrencyId))
{
throw new AdempiereException("line is not in foreign currency"); | }
line.setCurrencyRate(currencyRate);
InterfaceWrapperHelper.save(line);
unpost(bankStatement);
}
@Override
public CurrencyId getBaseCurrencyId(final I_C_BankStatementLine line)
{
final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(line.getAD_Client_ID(), line.getAD_Org_ID());
return moneyService.getBaseCurrencyId(clientAndOrgId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\service\impl\BankStatementBL.java | 2 |
请完成以下Java代码 | public class HashMapToArrayListConverterUtils {
static ArrayList<String> convertUsingConstructor(HashMap<Integer, String> hashMap) {
if (hashMap == null) {
return null;
}
return new ArrayList<String>(hashMap.values());
}
static ArrayList<String> convertUsingAddAllMethod(HashMap<Integer, String> hashMap) {
if (hashMap == null) {
return null;
}
ArrayList<String> arrayList = new ArrayList<String>(hashMap.size());
arrayList.addAll(hashMap.values());
return arrayList;
}
static ArrayList<String> convertUsingStreamApi(HashMap<Integer, String> hashMap) {
if (hashMap == null) {
return null;
}
return hashMap.values()
.stream()
.collect(Collectors.toCollection(ArrayList::new));
}
static ArrayList<String> convertUsingForLoop(HashMap<Integer, String> hashMap) {
if (hashMap == null) {
return null;
}
ArrayList<String> arrayList = new ArrayList<String>(hashMap.size());
for (Map.Entry<Integer, String> entry : hashMap.entrySet()) { | arrayList.add(entry.getValue());
}
return arrayList;
}
static public ArrayList<String> convertUsingGuava(HashMap<Integer, String> hashMap) {
if (hashMap == null) {
return null;
}
EntryTransformer<Integer, String, String> entryMapTransformer = (key, value) -> value;
return Lists.newArrayList(Maps.transformEntries(hashMap, entryMapTransformer)
.values());
}
} | repos\tutorials-master\core-java-modules\core-java-collections-conversions-2\src\main\java\com\baeldung\hashmaptoarraylist\HashMapToArrayListConverterUtils.java | 1 |
请完成以下Java代码 | public class SimplifiedChineseDictionary extends BaseChineseDictionary
{
/**
* 简体=繁体
*/
static AhoCorasickDoubleArrayTrie<String> trie = new AhoCorasickDoubleArrayTrie<String>();
static
{
long start = System.currentTimeMillis();
if (!load(HanLP.Config.tcDictionaryRoot + "s2t.txt", trie, false))
{
throw new IllegalArgumentException("简繁词典" + HanLP.Config.tcDictionaryRoot + "s2t.txt" + Predefine.BIN_EXT + "加载失败");
}
logger.info("简繁词典" + HanLP.Config.tcDictionaryRoot + "s2t.txt" + Predefine.BIN_EXT + "加载成功,耗时" + (System.currentTimeMillis() - start) + "ms"); | }
public static String convertToTraditionalChinese(String simplifiedChineseString)
{
return segLongest(simplifiedChineseString.toCharArray(), trie);
}
public static String convertToTraditionalChinese(char[] simplifiedChinese)
{
return segLongest(simplifiedChinese, trie);
}
public static String getTraditionalChinese(String simplifiedChinese)
{
return trie.get(simplifiedChinese);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\ts\SimplifiedChineseDictionary.java | 1 |
请完成以下Java代码 | public class HelloWorkflowV2Impl implements HelloWorkflowV2 {
private static final Logger log = LoggerFactory.getLogger(HelloWorkflowV2Impl.class);
private final HelloV2Activities activity = Workflow.newActivityStub(
HelloV2Activities.class,
ActivityOptions.newBuilder()
.setStartToCloseTimeout(Duration.ofSeconds(10))
.setRetryOptions(RetryOptions.newBuilder()
.setMaximumAttempts(3)
.setInitialInterval(Duration.ofSeconds(1))
.build())
.build()
);
@Override | public String hello(String person) {
var info = Workflow.getInfo();
log.info("Running workflow for person {}: id={}, attempt={}",
person,
info.getWorkflowId(),
info.getAttempt());
var step1result = activity.sayHello(person);
var step2result = activity.sayGoodbye(person);
return "Workflow OK";
}
} | repos\tutorials-master\saas-modules\temporal\src\main\java\com\baeldung\temporal\workflows\hellov2\HelloWorkflowV2Impl.java | 1 |
请完成以下Java代码 | public class WEBUI_M_HU_MoveToQualityWarehouse extends HUEditorProcessTemplate implements IProcessPrecondition
{
private final transient IHUMovementBL huMovementBL = Services.get(IHUMovementBL.class);
@Param(parameterName = I_M_Warehouse.COLUMNNAME_M_Warehouse_ID, mandatory = true)
private I_M_Warehouse warehouse;
private HUMovementGeneratorResult movementResult = null;
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if(!isHUEditorView())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view");
}
if (!streamSelectedHUIds(Select.ONLY_TOPLEVEL).findAny().isPresent())
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(WEBUI_HU_Constants.MSG_WEBUI_ONLY_TOP_LEVEL_HU));
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception | {
Check.assume(warehouse.isQualityReturnWarehouse(), "not a quality returns warehouse");
final List<I_M_HU> selectedTopLevelHUs = streamSelectedHUs(Select.ONLY_TOPLEVEL).collect(ImmutableList.toImmutableList());
if (selectedTopLevelHUs.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
movementResult = huMovementBL.moveHUsToWarehouse(selectedTopLevelHUs, WarehouseId.ofRepoId(warehouse.getM_Warehouse_ID()));
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
if (movementResult != null)
{
getView().invalidateAll();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_MoveToQualityWarehouse.java | 1 |
请完成以下Java代码 | public List<Object> getValues(@NonNull final I_M_ShipmentSchedule sched)
{
final IShipmentScheduleEffectiveBL shipmentScheduleEffectiveBL = Services.get(IShipmentScheduleEffectiveBL.class);
final IShipmentScheduleBL shipmentScheduleBL = Services.get(IShipmentScheduleBL.class);
final List<Object> values = new ArrayList<>();
values.add(VERSION);
values.add(sched.getC_DocType_ID());
values.add(shipmentScheduleEffectiveBL.getBPartnerId(sched).getRepoId());
values.add(shipmentScheduleEffectiveBL.getC_BP_Location_ID(sched));
if (!shipmentScheduleBL.isSchedAllowsConsolidate(sched))
{
values.add(sched.getC_Order_ID());
}
values.add(shipmentScheduleEffectiveBL.getWarehouseId(sched));
final BPartnerContactId adUserID = shipmentScheduleEffectiveBL.getBPartnerContactId(sched);
if (adUserID != null)
{
values.add(BPartnerContactId.toRepoId(adUserID));
}
values.add(sched.getAD_Org_ID());
if (ShipperId.ofRepoIdOrNull(sched.getM_Shipper_ID()) != null)
{
values.add(sched.getM_Shipper_ID());
final CarrierGoodsTypeId carrierGoodsTypeId = CarrierGoodsTypeId.ofRepoIdOrNull(sched.getCarrier_Goods_Type_ID());
if (carrierGoodsTypeId != null)
{
values.add("cgt:" + carrierGoodsTypeId.getRepoId());
}
final CarrierProductId carrierProductId = CarrierProductId.ofRepoIdOrNull(sched.getCarrier_Product_ID());
if (carrierProductId != null)
{
values.add("cpr:" + carrierProductId.getRepoId());
}
}
if (sched.getC_Async_Batch_ID() > 0)
{ | values.add(sched.getC_Async_Batch_ID());
}
values.add(sched.getExternalHeaderId());
if (sched.getExternalSystem_ID() > 0)
{
values.add(sched.getExternalSystem_ID());
}
return values;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\agg\key\impl\ShipmentScheduleKeyValueHandler.java | 1 |
请完成以下Java代码 | protected ExposableWebEndpoint createEndpoint(Object endpointBean, EndpointId id, Access defaultAccess,
Collection<WebOperation> operations) {
String rootPath = PathMapper.getRootPath(this.endpointPathMappers, id);
return new DiscoveredWebEndpoint(this, endpointBean, id, rootPath, defaultAccess, operations,
this.additionalPathsMappers);
}
@Override
protected WebOperation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod,
OperationInvoker invoker) {
String rootPath = PathMapper.getRootPath(this.endpointPathMappers, endpointId);
WebOperationRequestPredicate requestPredicate = this.requestPredicateFactory.getRequestPredicate(rootPath,
operationMethod);
return new DiscoveredWebOperation(endpointId, operationMethod, invoker, requestPredicate);
} | @Override
protected OperationKey createOperationKey(WebOperation operation) {
return new OperationKey(operation.getRequestPredicate(),
() -> "web request predicate " + operation.getRequestPredicate());
}
static class WebEndpointDiscovererRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.reflection().registerType(WebEndpointFilter.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\annotation\WebEndpointDiscoverer.java | 1 |
请完成以下Java代码 | protected String doIt()
{
final HURow row = getSingleHURow();
pickHU(row);
// invalidate view in order to be refreshed
getView().invalidateAll();
return MSG_OK;
}
private void pickHU(@NonNull final HURow row)
{
final HuId huId = row.getHuId();
final PickRequest pickRequest = PickRequest.builder()
.shipmentScheduleId(shipmentScheduleId)
.pickFrom(PickFrom.ofHuId(huId))
.pickingSlotId(pickingSlotId)
.build();
final ProcessPickingRequest.ProcessPickingRequestBuilder pickingRequestBuilder = ProcessPickingRequest.builder()
.huIds(ImmutableSet.of(huId))
.shipmentScheduleId(shipmentScheduleId)
.isTakeWholeHU(isTakeWholeHU);
final IView view = getView();
if (view instanceof PPOrderLinesView)
{ | final PPOrderLinesView ppOrderView = PPOrderLinesView.cast(view);
pickingRequestBuilder.ppOrderId(ppOrderView.getPpOrderId());
}
WEBUI_PP_Order_ProcessHelper.pickAndProcessSingleHU(pickRequest, pickingRequestBuilder.build());
}
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
invalidateView();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_Pick.java | 1 |
请完成以下Java代码 | public DmnDecisionQuery orderByDecisionType() {
return orderBy(DecisionQueryProperty.DECISION_TYPE);
}
// results ////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getDecisionEntityManager(commandContext).findDecisionCountByQueryCriteria(this);
}
@Override
public List<DmnDecision> executeList(CommandContext commandContext) {
return CommandContextUtil.getDecisionEntityManager(commandContext).findDecisionsByQueryCriteria(this);
}
// getters ////////////////////////////////////////////
public String getDeploymentId() {
return deploymentId;
}
public Set<String> getDeploymentIds() {
return deploymentIds;
}
public String getParentDeploymentId() {
return parentDeploymentId;
}
public String getId() {
return id;
}
public Set<String> getIds() {
return ids;
}
public String getDecisionId() {
return decisionId;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public Integer getVersion() {
return version;
}
public Integer getVersionGt() {
return versionGt;
} | public Integer getVersionGte() {
return versionGte;
}
public Integer getVersionLt() {
return versionLt;
}
public Integer getVersionLte() {
return versionLte;
}
public boolean isLatest() {
return latest;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getDecisionType() {
return decisionType;
}
public String getDecisionTypeLike() {
return decisionTypeLike;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\DecisionQueryImpl.java | 1 |
请完成以下Java代码 | private boolean deploymentsDifferDefault(DeploymentEntity deployment, DeploymentEntity saved) {
if (deployment.getResources() == null || saved.getResources() == null) {
return true;
}
Map<String, ResourceEntity> resources = deployment.getResources();
Map<String, ResourceEntity> savedResources = saved.getResources();
for (String resourceName : resources.keySet()) {
ResourceEntity savedResource = savedResources.get(resourceName);
if (savedResource == null) {
return true;
}
if (!savedResource.isGenerated()) {
ResourceEntity resource = resources.get(resourceName);
byte[] bytes = resource.getBytes();
byte[] savedBytes = savedResource.getBytes();
if (!Arrays.equals(bytes, savedBytes)) {
return true;
}
}
}
return false;
}
protected void scheduleProcessDefinitionActivation(CommandContext commandContext, DeploymentEntity deployment) {
for (ProcessDefinitionEntity processDefinitionEntity : deployment.getDeployedArtifacts( | ProcessDefinitionEntity.class
)) {
// If activation date is set, we first suspend all the process
// definition
SuspendProcessDefinitionCmd suspendProcessDefinitionCmd = new SuspendProcessDefinitionCmd(
processDefinitionEntity,
false,
null,
deployment.getTenantId()
);
suspendProcessDefinitionCmd.execute(commandContext);
// And we schedule an activation at the provided date
ActivateProcessDefinitionCmd activateProcessDefinitionCmd = new ActivateProcessDefinitionCmd(
processDefinitionEntity,
false,
deploymentBuilder.getProcessDefinitionsActivationDate(),
deployment.getTenantId()
);
activateProcessDefinitionCmd.execute(commandContext);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeployCmd.java | 1 |
请完成以下Java代码 | public FetchAndLockRequest setAsyncResponse(AsyncResponse asyncResponse) {
this.asyncResponse = asyncResponse;
return this;
}
public String getProcessEngineName() {
return processEngineName;
}
public FetchAndLockRequest setProcessEngineName(String processEngineName) {
this.processEngineName = processEngineName;
return this;
}
public Authentication getAuthentication() {
return authentication;
}
public FetchAndLockRequest setAuthentication(Authentication authentication) {
this.authentication = authentication;
return this; | }
public long getTimeoutTimestamp() {
FetchExternalTasksExtendedDto dto = getDto();
long requestTime = getRequestTime().getTime();
long asyncResponseTimeout = dto.getAsyncResponseTimeout();
return requestTime + asyncResponseTimeout;
}
@Override
public String toString() {
return "FetchAndLockRequest [requestTime=" + requestTime + ", dto=" + dto + ", asyncResponse=" + asyncResponse + ", processEngineName=" + processEngineName
+ ", authentication=" + authentication + "]";
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\FetchAndLockRequest.java | 1 |
请完成以下Java代码 | public class AppInfo {
private String app = "";
private Integer appType = 0;
private Set<MachineInfo> machines = ConcurrentHashMap.newKeySet();
public AppInfo() {}
public AppInfo(String app) {
this.app = app;
}
public AppInfo(String app, Integer appType) {
this.app = app;
this.appType = appType;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public Integer getAppType() {
return appType;
}
public void setAppType(Integer appType) {
this.appType = appType;
}
/**
* Get the current machines.
*
* @return a new copy of the current machines.
*/
public Set<MachineInfo> getMachines() {
return new HashSet<>(machines);
}
@Override
public String toString() {
return "AppInfo{" + "app='" + app + ", machines=" + machines + '}';
}
public boolean addMachine(MachineInfo machineInfo) {
machines.remove(machineInfo);
return machines.add(machineInfo);
}
public synchronized boolean removeMachine(String ip, int port) {
Iterator<MachineInfo> it = machines.iterator();
while (it.hasNext()) {
MachineInfo machine = it.next();
if (machine.getIp().equals(ip) && machine.getPort() == port) {
it.remove();
return true; | }
}
return false;
}
public Optional<MachineInfo> getMachine(String ip, int port) {
return machines.stream()
.filter(e -> e.getIp().equals(ip) && e.getPort().equals(port))
.findFirst();
}
private boolean heartbeatJudge(final int threshold) {
if (machines.size() == 0) {
return false;
}
if (threshold > 0) {
long healthyCount = machines.stream()
.filter(MachineInfo::isHealthy)
.count();
if (healthyCount == 0) {
// No healthy machines.
return machines.stream()
.max(Comparator.comparingLong(MachineInfo::getLastHeartbeat))
.map(e -> System.currentTimeMillis() - e.getLastHeartbeat() < threshold)
.orElse(false);
}
}
return true;
}
/**
* Check whether current application has no healthy machines and should not be displayed.
*
* @return true if the application should be displayed in the sidebar, otherwise false
*/
public boolean isShown() {
return heartbeatJudge(DashboardConfig.getHideAppNoMachineMillis());
}
/**
* Check whether current application has no healthy machines and should be removed.
*
* @return true if the application is dead and should be removed, otherwise false
*/
public boolean isDead() {
return !heartbeatJudge(DashboardConfig.getRemoveAppNoMachineMillis());
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\discovery\AppInfo.java | 1 |
请完成以下Java代码 | private static final class ManageSchedulerRequestHandlerAsEventListener implements IEventListener
{
private final EventLogUserService eventLogUserService;
private final ManageSchedulerRequestHandler handler;
@lombok.Builder
private ManageSchedulerRequestHandlerAsEventListener(
@NonNull final ManageSchedulerRequestHandler handler,
@NonNull final EventLogUserService eventLogUserService)
{
this.handler = handler;
this.eventLogUserService = eventLogUserService;
}
@Override
public void onEvent(@NonNull final IEventBus eventBus, @NonNull final Event event)
{
final ManageSchedulerRequest request = extractManageSchedulerRequest(event);
try (final IAutoCloseable ignored = switchCtx(request);
final MDC.MDCCloseable ignored1 = MDC.putCloseable("eventHandler.className", handler.getClass().getName()))
{
eventLogUserService.invokeHandlerAndLog(EventLogUserService.InvokeHandlerAndLogRequest.builder()
.handlerClass(handler.getClass())
.invokaction(() -> handleRequest(request))
.build()); | }
}
private void handleRequest(@NonNull final ManageSchedulerRequest request)
{
handler.handleRequest(request);
}
private IAutoCloseable switchCtx(@NonNull final ManageSchedulerRequest request)
{
final Properties ctx = createCtx(request);
return Env.switchContext(ctx);
}
private Properties createCtx(@NonNull final ManageSchedulerRequest request)
{
final Properties ctx = Env.newTemporaryCtx();
Env.setClientId(ctx, request.getClientId());
return ctx;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scheduler\eventbus\SchedulerEventBusService.java | 1 |
请完成以下Java代码 | public Builder id(String jti) {
return claim(JwtClaimNames.JTI, jti);
}
/**
* Sets the claim.
* @param name the claim name
* @param value the claim value
* @return the {@link Builder}
*/
public Builder claim(String name, Object value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
this.claims.put(name, value);
return this;
}
/**
* A {@code Consumer} to be provided access to the claims allowing the ability to
* add, replace, or remove.
* @param claimsConsumer a {@code Consumer} of the claims
*/
public Builder claims(Consumer<Map<String, Object>> claimsConsumer) {
claimsConsumer.accept(this.claims);
return this;
}
/**
* Builds a new {@link JwtClaimsSet}.
* @return a {@link JwtClaimsSet}
*/
public JwtClaimsSet build() {
Assert.notEmpty(this.claims, "claims cannot be empty"); | // The value of the 'iss' claim is a String or URL (StringOrURI).
// Attempt to convert to URL.
Object issuer = this.claims.get(JwtClaimNames.ISS);
if (issuer != null) {
URL convertedValue = ClaimConversionService.getSharedInstance().convert(issuer, URL.class);
if (convertedValue != null) {
this.claims.put(JwtClaimNames.ISS, convertedValue);
}
}
return new JwtClaimsSet(this.claims);
}
}
} | repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtClaimsSet.java | 1 |
请完成以下Java代码 | public int priority() {
return 30;
}
protected Val spinJsonToVal(SpinJsonNode node, Function<Object, Val> innerValueMapper) {
if (node.isObject()) {
Map pairs = node.fieldNames()
.stream()
.collect(toMap(field -> field,
field -> spinJsonToVal(node.prop(field), innerValueMapper)));
return innerValueMapper.apply(pairs);
} else if (node.isArray()) {
List<Val> values = node.elements()
.stream()
.map(e -> spinJsonToVal(e, innerValueMapper)).collect(toList());
return innerValueMapper.apply(values);
} else if (node.isNull()) {
return innerValueMapper.apply(null);
} else {
return innerValueMapper.apply(node.value());
}
}
protected Val spinXmlToVal(SpinXmlElement element, Function<Object, Val> innerValueMapper) {
String name = nodeName(element);
Val value = spinXmlElementToVal(element, innerValueMapper);
Map<String, Object> map = Collections.singletonMap(name, value);
return innerValueMapper.apply(map);
}
protected Val spinXmlElementToVal(final SpinXmlElement e,
Function<Object, Val> innerValueMapper) {
Map<String, Object> membersMap = new HashMap<>();
String content = e.textContent().trim();
if (!content.isEmpty()) {
membersMap.put("$content", new ValString(content));
}
Map<String, ValString> attributes = e.attrs()
.stream()
.collect(toMap(this::spinXmlAttributeToKey, attr -> new ValString(attr.value())));
if (!attributes.isEmpty()) {
membersMap.putAll(attributes);
}
Map<String, Val> childrenMap = e.childElements().stream()
.collect(
groupingBy(
this::nodeName,
mapping(el -> spinXmlElementToVal(el, innerValueMapper), toList())
)) | .entrySet().stream()
.collect(toMap(Map.Entry::getKey, entry -> {
List<Val> valList = entry.getValue();
if (!valList.isEmpty() && valList.size() > 1) {
return innerValueMapper.apply(valList);
} else {
return valList.get(0);
}
}));
membersMap.putAll(childrenMap);
if (membersMap.isEmpty()) {
return innerValueMapper.apply(null);
} else {
return innerValueMapper.apply(membersMap);
}
}
protected String spinXmlAttributeToKey(SpinXmlAttribute attribute) {
return "@" + nodeName(attribute);
}
protected String nodeName(SpinXmlNode n) {
String prefix = n.prefix();
String name = n.name();
return (prefix != null && !prefix.isEmpty())? prefix + "$" + name : name;
}
} | repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\impl\feel\integration\SpinValueMapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public Integer getUserState() {
return userState;
}
public void setUserState(Integer userState) {
this.userState = userState;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getRegisterTimeStart() {
return registerTimeStart;
}
public void setRegisterTimeStart(String registerTimeStart) {
this.registerTimeStart = registerTimeStart;
}
public String getRegisterTimeEnd() {
return registerTimeEnd;
}
public void setRegisterTimeEnd(String registerTimeEnd) {
this.registerTimeEnd = registerTimeEnd;
}
public Integer getOrderByRegisterTime() {
return orderByRegisterTime;
}
public void setOrderByRegisterTime(Integer orderByRegisterTime) {
this.orderByRegisterTime = orderByRegisterTime;
}
public String getPassword() {
return password;
} | public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserQueryReq{" +
"id='" + id + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", mail='" + mail + '\'' +
", registerTimeStart='" + registerTimeStart + '\'' +
", registerTimeEnd='" + registerTimeEnd + '\'' +
", userType=" + userType +
", userState=" + userState +
", roleId='" + roleId + '\'' +
", orderByRegisterTime=" + orderByRegisterTime +
", page=" + page +
", numPerPage=" + numPerPage +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\UserQueryReq.java | 2 |
请完成以下Java代码 | public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler) {
Assert.notNull(successHandler, "successHandler cannot be null");
this.successHandler = successHandler;
}
public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) {
Assert.notNull(failureHandler, "failureHandler cannot be null");
this.failureHandler = failureHandler;
}
/**
* Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on
* authentication success. The default action is not to save the
* {@link SecurityContext}.
* @param securityContextRepository the {@link SecurityContextRepository} to use.
* Cannot be null.
*/
public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
}
/**
* 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;
}
protected AuthenticationSuccessHandler getSuccessHandler() {
return this.successHandler;
}
protected AuthenticationFailureHandler getFailureHandler() {
return this.failureHandler;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\AbstractAuthenticationProcessingFilter.java | 1 |
请完成以下Java代码 | public void setIsTableBased (boolean IsTableBased)
{
set_ValueNoCheck (COLUMNNAME_IsTableBased, Boolean.valueOf(IsTableBased));
}
/** Get Table Based.
@return Table based List Reporting
*/
@Override
public boolean isTableBased ()
{
Object oo = get_Value(COLUMNNAME_IsTableBased);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public org.compiere.model.I_AD_Process getJasperProcess() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_JasperProcess_ID, org.compiere.model.I_AD_Process.class);
}
@Override
public void setJasperProcess(org.compiere.model.I_AD_Process JasperProcess)
{
set_ValueFromPO(COLUMNNAME_JasperProcess_ID, org.compiere.model.I_AD_Process.class, JasperProcess);
}
/** Set Jasper Process.
@param JasperProcess_ID
The Jasper Process used by the printengine if any process defined
*/
@Override
public void setJasperProcess_ID (int JasperProcess_ID)
{
if (JasperProcess_ID < 1)
set_Value (COLUMNNAME_JasperProcess_ID, null);
else
set_Value (COLUMNNAME_JasperProcess_ID, Integer.valueOf(JasperProcess_ID));
}
/** Get Jasper Process.
@return The Jasper Process used by the printengine if any process defined
*/
@Override
public int getJasperProcess_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_JasperProcess_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name); | }
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Drucker.
@param PrinterName
Name of the Printer
*/
@Override
public void setPrinterName (java.lang.String PrinterName)
{
set_Value (COLUMNNAME_PrinterName, PrinterName);
}
/** Get Drucker.
@return Name of the Printer
*/
@Override
public java.lang.String getPrinterName ()
{
return (java.lang.String)get_Value(COLUMNNAME_PrinterName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintFormat.java | 1 |
请完成以下Java代码 | private int createDocType (String Name, String PrintName,
String DocBaseType, String DocSubType,
int C_DocTypeShipment_ID, int C_DocTypeInvoice_ID,
int StartNo, int GL_Category_ID)
{
log.debug("In createDocType");
log.debug("docBaseType: " + DocBaseType);
log.debug("GL_Category_ID: " + GL_Category_ID);
MSequence sequence = null;
if (StartNo != 0)
{
sequence = new MSequence(Env.getCtx(), getAD_Client_ID(), Name, StartNo, trxname);
if (!sequence.save())
{
log.error("Sequence NOT created - " + Name);
return 0;
}
}
//MDocType dt = new MDocType (Env.getCtx(), DocBaseType, Name, trxname);
MDocType dt = new MDocType (Env.getCtx(),0 , trxname);
dt.setAD_Org_ID(0);
dt.set_CustomColumn("DocBaseType", (Object) DocBaseType);
dt.setName (Name);
dt.setPrintName (Name);
if (DocSubType != null)
dt.setDocSubType(DocSubType);
if (C_DocTypeShipment_ID != 0) | dt.setC_DocTypeShipment_ID(C_DocTypeShipment_ID);
if (C_DocTypeInvoice_ID != 0)
dt.setC_DocTypeInvoice_ID(C_DocTypeInvoice_ID);
if (GL_Category_ID != 0)
dt.setGL_Category_ID(GL_Category_ID);
if (sequence == null)
dt.setIsDocNoControlled(false);
else
{
dt.setIsDocNoControlled(true);
dt.setDocNoSequence_ID(sequence.getAD_Sequence_ID());
}
dt.setIsSOTrx(false);
if (!dt.save())
{
log.error("DocType NOT created - " + Name);
return 0;
}
//
return dt.getC_DocType_ID();
} // createDocType
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\CreateDocType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CommentDTO {
/** The task id. */
private String taskId;
/** The last name. */
private String comment;
/** The completed. */
private Date posted;
/**
* Instantiates a new task dto.
*/
public CommentDTO() {
super();
}
/**
* Instantiates a new task dto.
*
* @param taskId
* the task id
* @param description
* the description
*/
public CommentDTO(String taskId, String comment, Date posted) {
super();
this.taskId = taskId;
this.comment = comment;
this.posted = posted;
}
/**
* @return the taskId
*/
public String getTaskId() {
return taskId;
}
/**
* @param taskId
* the taskId to set
*/
public void setTaskId(String taskId) {
this.taskId = taskId;
}
/**
* @return the comment
*/
public String getComment() {
return comment;
}
/**
* @param comment
* the comment to set
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
* @return the posted
*/
@JsonSerialize(using = CustomDateToLongSerializer.class)
public Date getPosted() {
return posted;
}
/**
* @param posted
* the posted to set
*/
public void setPosted(Date posted) {
this.posted = posted;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((comment == null) ? 0 : comment.hashCode());
result = prime * result + ((posted == null) ? 0 : posted.hashCode());
result = prime * result + ((taskId == null) ? 0 : taskId.hashCode());
return result;
}
/*
* (non-Javadoc) | *
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CommentDTO other = (CommentDTO) obj;
if (comment == null) {
if (other.comment != null)
return false;
} else if (!comment.equals(other.comment))
return false;
if (posted == null) {
if (other.posted != null)
return false;
} else if (!posted.equals(other.posted))
return false;
if (taskId == null) {
if (other.taskId != null)
return false;
} else if (!taskId.equals(other.taskId))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "CommentDTO [taskId=" + taskId + ", comment=" + comment + ", posted=" + posted + "]";
}
}
/**
* Custom date serializer that converts the date to long before sending it out
*
* @author anilallewar
*
*/
class CustomDateToLongSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeNumber(value.getTime());
}
} | repos\spring-boot-microservices-master\comments-webservice\src\main\java\com\rohitghatol\microservices\comments\dtos\CommentDTO.java | 2 |
请完成以下Java代码 | public class DedupeResponseHeaderGatewayFilterFactory
extends AbstractGatewayFilterFactory<DedupeResponseHeaderGatewayFilterFactory.Config> {
/**
* The name of the strategy key.
*/
public static final String STRATEGY_KEY = "strategy";
public DedupeResponseHeaderGatewayFilterFactory() {
super(Config.class);
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList(NAME_KEY, STRATEGY_KEY);
}
@Override
public GatewayFilter apply(Config config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return chain.filter(exchange)
.then(Mono.fromRunnable(() -> dedupe(exchange.getResponse().getHeaders(), config)));
}
@Override
public String toString() {
String name = config.getName();
return filterToStringCreator(DedupeResponseHeaderGatewayFilterFactory.this)
.append(name != null ? name : "", config.getStrategy())
.toString();
}
};
}
public enum Strategy {
/**
* Default: Retain the first value only.
*/
RETAIN_FIRST,
/**
* Retain the last value only.
*/
RETAIN_LAST,
/**
* Retain all unique values in the order of their first encounter.
*/
RETAIN_UNIQUE | }
void dedupe(HttpHeaders headers, Config config) {
String names = config.getName();
Strategy strategy = config.getStrategy();
if (headers == null || names == null || strategy == null) {
return;
}
for (String name : names.split(" ")) {
dedupe(headers, name.trim(), strategy);
}
}
private void dedupe(HttpHeaders headers, String name, Strategy strategy) {
List<String> values = headers.get(name);
if (values == null || values.size() <= 1) {
return;
}
switch (strategy) {
case RETAIN_FIRST:
headers.set(name, values.get(0));
break;
case RETAIN_LAST:
headers.set(name, values.get(values.size() - 1));
break;
case RETAIN_UNIQUE:
headers.put(name, new ArrayList<>(new LinkedHashSet<>(values)));
break;
default:
break;
}
}
public static class Config extends AbstractGatewayFilterFactory.NameConfig {
private Strategy strategy = Strategy.RETAIN_FIRST;
public Strategy getStrategy() {
return strategy;
}
public Config setStrategy(Strategy strategy) {
this.strategy = strategy;
return this;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\DedupeResponseHeaderGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public GitIgnoreSection getVscode() {
return this.vscode;
}
/**
* Representation of a section of a {@code .gitignore} file.
*/
public static class GitIgnoreSection implements Section {
private final String name;
private final LinkedList<String> items;
public GitIgnoreSection(String name) {
this.name = name;
this.items = new LinkedList<>();
}
public void add(String... items) {
this.items.addAll(Arrays.asList(items));
} | public LinkedList<String> getItems() {
return this.items;
}
@Override
public void write(PrintWriter writer) {
if (!this.items.isEmpty()) {
if (this.name != null) {
writer.println();
writer.println(String.format("### %s ###", this.name));
}
this.items.forEach(writer::println);
}
}
}
} | repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\scm\git\GitIgnore.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getStreet() {
return street;
}
/** 银行卡开户具体地址 **/
public void setStreet(String street) {
this.street = street;
}
/** 银行卡开户名eg:张三 **/
public String getBankAccountName() {
return bankAccountName;
}
/** 银行卡开户名eg:张三 **/
public void setBankAccountName(String bankAccountName) {
this.bankAccountName = bankAccountName;
}
/** 银行卡卡号 **/
public String getBankAccountNo() {
return bankAccountNo;
}
/** 银行卡卡号 **/
public void setBankAccountNo(String bankAccountNo) {
this.bankAccountNo = bankAccountNo;
}
/** 银行编号eg:ICBC **/
public String getBankCode() {
return bankCode;
}
/** 银行编号eg:ICBC **/
public void setBankCode(String bankCode) {
this.bankCode = bankCode;
}
/** 银行卡类型 **/
public String getBankAccountType() {
return bankAccountType;
}
/** 银行卡类型 **/
public void setBankAccountType(String bankAccountType) {
this.bankAccountType = bankAccountType;
}
/** 证件类型 **/
public String getCardType() {
return cardType;
}
/** 证件类型 **/
public void setCardType(String cardType) {
this.cardType = cardType;
}
/** 证件号码 **/
public String getCardNo() { | return cardNo;
}
/** 证件号码 **/
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
/** 手机号码 **/
public String getMobileNo() {
return mobileNo;
}
/** 手机号码 **/
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
/** 银行名称 **/
public String getBankName() {
return bankName;
}
/** 银行名称 **/
public void setBankName(String bankName) {
this.bankName = bankName;
}
/** 用户编号 **/
public String getUserNo() {
return userNo;
}
/** 用户编号 **/
public void setUserNo(String userNo) {
this.userNo = userNo;
}
/** 是否默认 **/
public String getIsDefault() {
return isDefault;
}
/** 是否默认 **/
public void setIsDefault(String isDefault) {
this.isDefault = isDefault;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserBankAccount.java | 2 |
请完成以下Java代码 | public class GitHubServiceGenerator {
private static final String BASE_URL = "https://api.github.com/";
private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static HttpLoggingInterceptor logging = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC);
public static <S> S createService(Class<S> serviceClass) {
if (!httpClient.interceptors().contains(logging)) {
httpClient.addInterceptor(logging);
builder.client(httpClient.build());
retrofit = builder.build();
}
return retrofit.create(serviceClass);
} | public static <S> S createService(Class<S> serviceClass, final String token) {
if (token != null) {
httpClient.interceptors().clear();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder().header("Authorization", token);
Request request = builder.build();
return chain.proceed(request);
}
});
builder.client(httpClient.build());
retrofit = builder.build();
}
return retrofit.create(serviceClass);
}
} | repos\tutorials-master\libraries-http\src\main\java\com\baeldung\retrofitguide\GitHubServiceGenerator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class NotifyQueue implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Log LOG = LogFactory.getLog(NotifyQueue.class);
@Autowired
private NotifyParam notifyParam;
@Autowired
private NotifyPersist notifyPersist;
/**
* 将传过来的对象进行通知次数判断,之后决定是否放在任务队列中
*
* @param notifyRecord
* @throws Exception
*/
public void addElementToList(RpNotifyRecord notifyRecord) {
if (notifyRecord == null) {
return;
}
Integer notifyTimes = notifyRecord.getNotifyTimes(); // 通知次数
Integer maxNotifyTime = 0;
try {
maxNotifyTime = notifyParam.getMaxNotifyTime();
} catch (Exception e) {
LOG.error(e); | }
if (notifyRecord.getVersion().intValue() == 0) {// 刚刚接收到的数据
notifyRecord.setLastNotifyTime(new Date());
}
long time = notifyRecord.getLastNotifyTime().getTime();
Map<Integer, Integer> timeMap = notifyParam.getNotifyParams();
if (notifyTimes < maxNotifyTime) {
Integer nextKey = notifyTimes + 1;
Integer next = timeMap.get(nextKey);
if (next != null) {
time += 1000 * 60 * next + 1;
notifyRecord.setLastNotifyTime(new Date(time));
AppNotifyApplication.tasks.put(new NotifyTask(notifyRecord, this, notifyParam));
}
} else {
try {
// 持久化到数据库中
notifyPersist.updateNotifyRord(notifyRecord.getId(),
notifyRecord.getNotifyTimes(), NotifyStatusEnum.FAILED.name());
LOG.info("Update NotifyRecord failed,merchantNo:" + notifyRecord.getMerchantNo() + ",merchantOrderNo:"
+ notifyRecord.getMerchantOrderNo());
} catch (Exception e) {
LOG.error(e);
}
}
}
} | repos\roncoo-pay-master\roncoo-pay-app-notify\src\main\java\com\roncoo\pay\app\notify\core\NotifyQueue.java | 2 |
请完成以下Java代码 | public String getBusinessKey() {
return businessKey;
}
public String getBusinessKeyLike() {
return businessKeyLike;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getCaseDefinitionIdLike() {
return caseDefinitionKey + ":%:%";
}
public String getCaseDefinitionName() {
return caseDefinitionName;
}
public String getCaseDefinitionNameLike() {
return caseDefinitionNameLike;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public Set<String> getCaseInstanceIds() {
return caseInstanceIds;
}
public String getStartedBy() {
return createdBy;
}
public String getSuperCaseInstanceId() {
return superCaseInstanceId;
} | public void setSuperCaseInstanceId(String superCaseInstanceId) {
this.superCaseInstanceId = superCaseInstanceId;
}
public List<String> getCaseKeyNotIn() {
return caseKeyNotIn;
}
public Date getCreatedAfter() {
return createdAfter;
}
public Date getCreatedBefore() {
return createdBefore;
}
public Date getClosedAfter() {
return closedAfter;
}
public Date getClosedBefore() {
return closedBefore;
}
public String getSubCaseInstanceId() {
return subCaseInstanceId;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public String getSubProcessInstanceId() {
return subProcessInstanceId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricCaseInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public void setQtyEnteredInBPartnerUOM (final @Nullable BigDecimal QtyEnteredInBPartnerUOM)
{
set_Value (COLUMNNAME_QtyEnteredInBPartnerUOM, QtyEnteredInBPartnerUOM);
}
@Override
public BigDecimal getQtyEnteredInBPartnerUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredInBPartnerUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyItemCapacity (final @Nullable BigDecimal QtyItemCapacity)
{
set_Value (COLUMNNAME_QtyItemCapacity, QtyItemCapacity);
}
@Override
public BigDecimal getQtyItemCapacity()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyItemCapacity);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOrdered (final BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOrdered_Override (final @Nullable BigDecimal QtyOrdered_Override)
{
set_Value (COLUMNNAME_QtyOrdered_Override, QtyOrdered_Override);
}
@Override
public BigDecimal getQtyOrdered_Override()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered_Override);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override | public void setUPC_CU (final @Nullable java.lang.String UPC_CU)
{
set_Value (COLUMNNAME_UPC_CU, UPC_CU);
}
@Override
public java.lang.String getUPC_CU()
{
return get_ValueAsString(COLUMNNAME_UPC_CU);
}
@Override
public void setUPC_TU (final @Nullable java.lang.String UPC_TU)
{
set_Value (COLUMNNAME_UPC_TU, UPC_TU);
}
@Override
public java.lang.String getUPC_TU()
{
return get_ValueAsString(COLUMNNAME_UPC_TU);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_DesadvLine.java | 1 |
请完成以下Java代码 | protected TbResultSetFuture executeAsyncRead(TenantId tenantId, Statement statement) {
return executeAsync(tenantId, statement, defaultReadLevel, rateReadLimiter);
}
protected TbResultSetFuture executeAsyncWrite(TenantId tenantId, Statement statement) {
return executeAsync(tenantId, statement, defaultWriteLevel, rateWriteLimiter);
}
private AsyncResultSet execute(TenantId tenantId, Statement statement, ConsistencyLevel level,
BufferedRateExecutor<CassandraStatementTask, TbResultSetFuture> rateExecutor) {
if (log.isDebugEnabled()) {
log.debug("Execute cassandra statement {}", statementToString(statement));
}
return executeAsync(tenantId, statement, level, rateExecutor).getUninterruptibly();
}
private TbResultSetFuture executeAsync(TenantId tenantId, Statement statement, ConsistencyLevel level,
BufferedRateExecutor<CassandraStatementTask, TbResultSetFuture> rateExecutor) {
if (log.isDebugEnabled()) { | log.debug("Execute cassandra async statement {}", statementToString(statement));
}
if (statement.getConsistencyLevel() == null) {
statement = statement.setConsistencyLevel(level);
}
return rateExecutor.submit(new CassandraStatementTask(tenantId, getSession(), statement));
}
private static String statementToString(Statement statement) {
if (statement instanceof BoundStatement) {
return ((BoundStatement) statement).getPreparedStatement().getQuery();
} else {
return statement.toString();
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\nosql\CassandraAbstractDao.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Publisher implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String company;
@OneToMany(cascade = CascadeType.ALL,
mappedBy = "publisher", orphanRemoval = true)
private List<Book> books = new ArrayList<>();
public void addBook(Book book) {
this.books.add(book);
book.setPublisher(this);
}
public void removeBook(Book book) {
book.setPublisher(null);
this.books.remove(book);
}
public void removeBooks() {
Iterator<Book> iterator = this.books.iterator();
while (iterator.hasNext()) {
Book book = iterator.next();
book.setPublisher(null);
iterator.remove();
}
} | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
@Override
public String toString() {
return "Publisher{" + "id=" + id + ", company=" + company + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootNamedSubgraph\src\main\java\com\bookstore\entity\Publisher.java | 2 |
请完成以下Java代码 | public Integer getCamundaHistoryTimeToLive() {
String ttl = getCamundaHistoryTimeToLiveString();
if (ttl != null) {
return Integer.parseInt(ttl);
}
return null;
}
public void setCamundaHistoryTimeToLive(Integer historyTimeToLive) {
setCamundaHistoryTimeToLiveString(String.valueOf(historyTimeToLive));
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Case.class, CMMN_ELEMENT_CASE)
.extendsType(CmmnElement.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<Case>() {
public Case newInstance(ModelTypeInstanceContext instanceContext) {
return new CaseImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
camundaHistoryTimeToLive = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_HISTORY_TIME_TO_LIVE)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
caseFileModelChild = sequenceBuilder.element(CaseFileModel.class)
.build();
casePlanModelChild = sequenceBuilder.element(CasePlanModel.class)
.build();
caseRolesCollection = sequenceBuilder.elementCollection(CaseRole.class)
.build();
caseRolesChild = sequenceBuilder.element(CaseRoles.class)
.build(); | inputCollection = sequenceBuilder.elementCollection(InputCaseParameter.class)
.build();
outputCollection = sequenceBuilder.elementCollection(OutputCaseParameter.class)
.build();
typeBuilder.build();
}
@Override
public String getCamundaHistoryTimeToLiveString() {
return camundaHistoryTimeToLive.getValue(this);
}
@Override
public void setCamundaHistoryTimeToLiveString(String historyTimeToLive) {
camundaHistoryTimeToLive.setValue(this, historyTimeToLive);
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseImpl.java | 1 |
请完成以下Java代码 | public final void addConnection(Connection connection) {
Assert.notNull(connection, "Connection must not be null");
if (!this.connections.contains(connection)) {
this.connections.add(connection);
}
}
public final void addChannel(Channel channel) {
addChannel(channel, null);
}
public final void addChannel(Channel channel, @Nullable Connection connection) {
Assert.notNull(channel, "Channel must not be null");
if (!this.channels.contains(channel)) {
this.channels.add(channel);
if (connection != null) {
List<Channel> channelsForConnection =
this.channelsPerConnection.computeIfAbsent(connection, k -> new LinkedList<>());
channelsForConnection.add(channel);
}
}
}
public boolean containsChannel(Channel channel) {
return this.channels.contains(channel);
}
public @Nullable Connection getConnection() {
return (!this.connections.isEmpty() ? this.connections.get(0) : null);
}
public @Nullable Channel getChannel() {
return (!this.channels.isEmpty() ? this.channels.get(0) : null);
}
public void commitAll() throws AmqpException {
try {
for (Channel channel : this.channels) {
if (this.deliveryTags.containsKey(channel)) {
for (Long deliveryTag : this.deliveryTags.get(channel)) {
channel.basicAck(deliveryTag, false);
}
}
channel.txCommit();
}
}
catch (IOException e) {
throw new AmqpException("failed to commit RabbitMQ transaction", e);
}
}
public void closeAll() {
for (Channel channel : this.channels) {
try {
if (channel != ConsumerChannelRegistry.getConsumerChannel()) { // NOSONAR
channel.close();
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Skipping close of consumer channel: " + channel.toString());
}
}
}
catch (Exception ex) {
logger.debug("Could not close synchronized Rabbit Channel after transaction", ex);
}
} | for (Connection con : this.connections) { //NOSONAR
RabbitUtils.closeConnection(con);
}
this.connections.clear();
this.channels.clear();
this.channelsPerConnection.clear();
}
public void addDeliveryTag(Channel channel, long deliveryTag) {
this.deliveryTags.add(channel, deliveryTag);
}
public void rollbackAll() {
for (Channel channel : this.channels) {
if (logger.isDebugEnabled()) {
logger.debug("Rolling back messages to channel: " + channel);
}
RabbitUtils.rollbackIfNecessary(channel);
if (this.deliveryTags.containsKey(channel)) {
for (Long deliveryTag : this.deliveryTags.get(channel)) {
try {
channel.basicReject(deliveryTag, this.requeueOnRollback);
}
catch (IOException ex) {
throw new AmqpIOException(ex);
}
}
// Need to commit the reject (=nack)
RabbitUtils.commitIfNecessary(channel);
}
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\RabbitResourceHolder.java | 1 |
请完成以下Java代码 | public int divideAndConquer(int number) {
if (number < 100000){
// 5 digits or less
if (number < 100){
// 1 or 2
if (number < 10)
return 1;
else
return 2;
}else{
// 3 to 5 digits
if (number < 1000)
return 3;
else{
// 4 or 5 digits
if (number < 10000)
return 4;
else
return 5;
}
}
} else {
// 6 digits or more
if (number < 10000000) { | // 6 or 7 digits
if (number < 1000000)
return 6;
else
return 7;
} else {
// 8 to 10 digits
if (number < 100000000)
return 8;
else {
// 9 or 10 digits
if (number < 1000000000)
return 9;
else
return 10;
}
}
}
}
} | repos\tutorials-master\core-java-modules\core-java-numbers\src\main\java\com\baeldung\numberofdigits\NumberOfDigits.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private RelationalPersistentEntity<?> getPersistentEntity(Class<?> entityType) {
return r2dbcEntityTemplate.getConverter().getMappingContext().getPersistentEntity(entityType);
}
private static Collection<? extends OrderByField> createOrderByFields(Table table, Sort sortToUse) {
List<OrderByField> fields = new ArrayList<>();
for (Sort.Order order : sortToUse) {
String propertyName = order.getProperty();
OrderByField orderByField = !propertyName.contains(".")
? OrderByField.from(table.column(propertyName).as(EntityManager.ALIAS_PREFIX + propertyName))
: createOrderByField(propertyName);
fields.add(order.isAscending() ? orderByField.asc() : orderByField.desc());
}
return fields;
}
/**
* Creates an OrderByField instance for sorting a query by the specified property.
*
* @param propertyName The full property name in the format "tableName.columnName".
* @return An OrderByField instance for sorting by the specified property.
*/
private static OrderByField createOrderByField(String propertyName) {
// Split the propertyName into table name and column name
String[] parts = propertyName.split("\\.");
String tableName = parts[0];
String columnName = parts[1];
// Create and return an OrderByField instance
return OrderByField.from(
// Create a column with the given name and alias it with the table name and column name
Column.aliased(
columnName,
// Create a table alias with the same name as the table
Table.aliased(camelCaseToSnakeCase(tableName), tableName), | // Use a composite alias of "tableName_columnName"
String.format("%s_%s", tableName, columnName)
)
);
}
/**
* Converts a camel case string to snake case.
*
* @param input The camel case string to be converted to snake case.
* @return The input string converted to snake case.
*/
public static String camelCaseToSnakeCase(String input) {
// Regular Expression
String regex = "([a-z])([A-Z]+)";
// Replacement string
String replacement = "$1_$2";
// Replace the given regex
// with replacement string
// and convert it to lower case.
return input.replaceAll(regex, replacement).toLowerCase();
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\repository\EntityManager.java | 2 |
请完成以下Java代码 | protected ProcessDefinitionEntityManager getProcessDefinitionManager() {
return getSession(ProcessDefinitionEntityManager.class);
}
protected ProcessDefinitionInfoEntityManager getProcessDefinitionInfoManager() {
return getSession(ProcessDefinitionInfoEntityManager.class);
}
protected ModelEntityManager getModelManager() {
return getSession(ModelEntityManager.class);
}
protected ExecutionEntityManager getProcessInstanceManager() {
return getSession(ExecutionEntityManager.class);
}
protected TaskEntityManager getTaskManager() {
return getSession(TaskEntityManager.class);
}
protected IdentityLinkEntityManager getIdentityLinkManager() {
return getSession(IdentityLinkEntityManager.class);
}
protected EventSubscriptionEntityManager getEventSubscriptionManager() {
return (getSession(EventSubscriptionEntityManager.class));
}
protected VariableInstanceEntityManager getVariableInstanceManager() {
return getSession(VariableInstanceEntityManager.class);
}
protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceManager() {
return getSession(HistoricProcessInstanceEntityManager.class);
}
protected HistoricDetailEntityManager getHistoricDetailManager() {
return getSession(HistoricDetailEntityManager.class);
}
protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceManager() {
return getSession(HistoricActivityInstanceEntityManager.class);
}
protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceManager() {
return getSession(HistoricVariableInstanceEntityManager.class);
} | protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceManager() {
return getSession(HistoricTaskInstanceEntityManager.class);
}
protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return getSession(HistoricIdentityLinkEntityManager.class);
}
protected AttachmentEntityManager getAttachmentManager() {
return getSession(AttachmentEntityManager.class);
}
protected HistoryManager getHistoryManager() {
return getSession(HistoryManager.class);
}
protected ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return Context.getProcessEngineConfiguration();
}
@Override
public void close() {
}
@Override
public void flush() {
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\AbstractManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class)
public List<RestVariable> getVariables() {
return variables;
}
public void setTransientVariables(List<RestVariable> transientVariables) {
this.transientVariables = transientVariables;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class)
public List<RestVariable> getTransientVariables() {
return transientVariables;
}
@ApiModelProperty(value = "Name of the signal", example = "My Signal")
public String getSignalName() {
return signalName;
}
public void setSignalName(String signalName) { | this.signalName = signalName;
}
@ApiModelProperty(value = "Message of the signal", example = "My Signal")
public String getMessageName() {
return messageName;
}
public void setMessageName(String messageName) {
this.messageName = messageName;
}
@Override
@ApiModelProperty(value = "Action to perform: Either signal, trigger, signalEventReceived or messageEventReceived", example = "signalEventReceived", required = true)
public String getAction() {
return super.getAction();
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ExecutionActionRequest.java | 2 |
请完成以下Java代码 | public int getM_CostRevaluation_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostRevaluation_ID);
}
@Override
public void setM_CostRevaluationLine_ID (final int M_CostRevaluationLine_ID)
{
if (M_CostRevaluationLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostRevaluationLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostRevaluationLine_ID, M_CostRevaluationLine_ID);
}
@Override
public int getM_CostRevaluationLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostRevaluationLine_ID);
}
@Override
public org.compiere.model.I_M_CostType getM_CostType()
{
return get_ValueAsPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class);
}
@Override
public void setM_CostType(final org.compiere.model.I_M_CostType M_CostType)
{
set_ValueFromPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class, M_CostType);
}
@Override
public void setM_CostType_ID (final int M_CostType_ID)
{
if (M_CostType_ID < 1)
set_Value (COLUMNNAME_M_CostType_ID, null);
else
set_Value (COLUMNNAME_M_CostType_ID, M_CostType_ID);
} | @Override
public int getM_CostType_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostType_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setNewCostPrice (final BigDecimal NewCostPrice)
{
set_Value (COLUMNNAME_NewCostPrice, NewCostPrice);
}
@Override
public BigDecimal getNewCostPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_NewCostPrice);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostRevaluationLine.java | 1 |
请完成以下Java代码 | public class ParsedDeployment {
protected DeploymentEntity deploymentEntity;
protected List<ProcessDefinitionEntity> processDefinitions;
protected Map<ProcessDefinitionEntity, BpmnParse> mapProcessDefinitionsToParses;
protected Map<ProcessDefinitionEntity, ResourceEntity> mapProcessDefinitionsToResources;
public ParsedDeployment(
DeploymentEntity entity,
List<ProcessDefinitionEntity> processDefinitions,
Map<ProcessDefinitionEntity, BpmnParse> mapProcessDefinitionsToParses,
Map<ProcessDefinitionEntity, ResourceEntity> mapProcessDefinitionsToResources
) {
this.deploymentEntity = entity;
this.processDefinitions = processDefinitions;
this.mapProcessDefinitionsToParses = mapProcessDefinitionsToParses;
this.mapProcessDefinitionsToResources = mapProcessDefinitionsToResources;
}
public DeploymentEntity getDeployment() {
return deploymentEntity;
}
public List<ProcessDefinitionEntity> getAllProcessDefinitions() {
return processDefinitions;
} | public ResourceEntity getResourceForProcessDefinition(ProcessDefinitionEntity processDefinition) {
return mapProcessDefinitionsToResources.get(processDefinition);
}
public BpmnParse getBpmnParseForProcessDefinition(ProcessDefinitionEntity processDefinition) {
return mapProcessDefinitionsToParses.get(processDefinition);
}
public BpmnModel getBpmnModelForProcessDefinition(ProcessDefinitionEntity processDefinition) {
BpmnParse parse = getBpmnParseForProcessDefinition(processDefinition);
return (parse == null ? null : parse.getBpmnModel());
}
public Process getProcessModelForProcessDefinition(ProcessDefinitionEntity processDefinition) {
BpmnModel model = getBpmnModelForProcessDefinition(processDefinition);
return (model == null ? null : model.getProcessById(processDefinition.getKey()));
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\ParsedDeployment.java | 1 |
请完成以下Java代码 | public void resolveIncident(final String incidentId) {
IncidentEntity incident = (IncidentEntity) Context
.getCommandContext()
.getIncidentManager()
.findIncidentById(incidentId);
IncidentContext incidentContext = new IncidentContext(incident);
IncidentHandling.removeIncidents(incident.getIncidentType(), incidentContext, true);
}
public IncidentHandler findIncidentHandler(String incidentType) {
Map<String, IncidentHandler> incidentHandlers = Context.getProcessEngineConfiguration().getIncidentHandlers();
return incidentHandlers.get(incidentType);
}
public boolean isExecutingScopeLeafActivity() {
return isActive && getActivity() != null && getActivity().isScope() && activityInstanceId != null
&& !(getActivity().getActivityBehavior() instanceof CompositeActivityBehavior);
}
/**
* This case is special, because the execution tree is different if an async after | * activity is left via transition (case 1) or not (case 2). In case 1, when the
* execution becomes async, the scope execution is already removed. In case 2 it is not.
*
* @return true if
* <ul>
* <li>the execution is in asyncAfter state and completes
* <li>leaves a scope activity
* <li>completes the parent scope (i.e. does not leave via a transition
* but propagates control to the parent)
* </ul>
*/
public boolean isAsyncAfterScopeWithoutTransition() {
return activityInstanceId == null && activity.isScope() && !isActive;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\PvmExecutionImpl.java | 1 |
请完成以下Java代码 | public class ExpiresSoonMedicineReader extends AbstractItemCountingItemStreamItemReader<Medicine> implements ContainsJobParameters {
private static final String FIND_EXPIRING_SOON_MEDICINE = "Select * from MEDICINE where EXPIRATION_DATE >= CURRENT_DATE AND EXPIRATION_DATE <= DATEADD('DAY', ?, CURRENT_DATE)";
//common job parameters populated in bean initialization
private ZonedDateTime triggeredDateTime;
private String traceId;
//job parameter injected by Spring
@Value("#{jobParameters['DEFAULT_EXPIRATION']}")
private long defaultExpiration;
private final JdbcTemplate jdbcTemplate;
private List<Medicine> expiringMedicineList;
@Override
protected Medicine doRead() {
if (expiringMedicineList != null && !expiringMedicineList.isEmpty()) {
return expiringMedicineList.get(getCurrentItemCount() - 1);
}
return null;
}
@Override
protected void doOpen() {
expiringMedicineList = jdbcTemplate.query(FIND_EXPIRING_SOON_MEDICINE, ps -> ps.setLong(1, defaultExpiration), (rs, row) -> getMedicine(rs));
log.info("Trace = {}. Found {} meds that expires soon", traceId, expiringMedicineList.size());
if (!expiringMedicineList.isEmpty()) {
setMaxItemCount(expiringMedicineList.size());
} | }
private static Medicine getMedicine(ResultSet rs) throws SQLException {
return new Medicine(UUID.fromString(rs.getString(1)), rs.getString(2), MedicineCategory.valueOf(rs.getString(3)), rs.getTimestamp(4), rs.getDouble(5), rs.getObject(6, Double.class));
}
@Override
protected void doClose() {
}
@PostConstruct
public void init() {
setName(ClassUtils.getShortName(getClass()));
}
@BeforeStep
public void beforeStep(StepExecution stepExecution) {
JobParameters parameters = stepExecution.getJobExecution()
.getJobParameters();
log.info("Before step params: {}", parameters);
}
} | repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batchreaderproperties\job\ExpiresSoonMedicineReader.java | 1 |
请完成以下Java代码 | private Stream<HttpExchange> sort(String[] params, Stream<HttpExchange> stream) {
if (params.length < 2) {
return stream;
}
String sortBy = params[1];
String order;
if (params.length > 2) {
order = params[2];
} else {
order = "desc";
}
return stream.sorted((o1, o2) -> {
int i = 0;
if("timeTaken".equalsIgnoreCase(sortBy)) {
i = o1.getTimeTaken().compareTo(o2.getTimeTaken());
}else if("timestamp".equalsIgnoreCase(sortBy)){
i = o1.getTimestamp().compareTo(o2.getTimestamp());
}
if("desc".equalsIgnoreCase(order)){
i *=-1;
}
return i;
});
}
private static Stream<HttpExchange> filter(String[] params, Stream<HttpExchange> stream) {
if (params.length == 0) {
return stream;
}
String statusQuery = params[0];
if (null != statusQuery && !statusQuery.isEmpty()) {
statusQuery = statusQuery.toLowerCase().trim();
switch (statusQuery) {
case "error":
stream = stream.filter(httpTrace -> {
int status = httpTrace.getResponse().getStatus(); | return status >= 404 && status < 501;
});
break;
case "warn":
stream = stream.filter(httpTrace -> {
int status = httpTrace.getResponse().getStatus();
return status >= 201 && status < 404;
});
break;
case "success":
stream = stream.filter(httpTrace -> {
int status = httpTrace.getResponse().getStatus();
return status == 200;
});
break;
case "all":
default:
break;
}
return stream;
}
return stream;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\monitor\actuator\httptrace\CustomInMemoryHttpTraceRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class Config {
private String baseMessage;
private boolean preLogger;
private boolean postLogger;
public Config() {
};
public Config(String baseMessage, boolean preLogger, boolean postLogger) {
super();
this.baseMessage = baseMessage;
this.preLogger = preLogger;
this.postLogger = postLogger;
}
public String getBaseMessage() {
return this.baseMessage;
}
public boolean isPreLogger() { | return preLogger;
}
public boolean isPostLogger() {
return postLogger;
}
public void setBaseMessage(String baseMessage) {
this.baseMessage = baseMessage;
}
public void setPreLogger(boolean preLogger) {
this.preLogger = preLogger;
}
public void setPostLogger(boolean postLogger) {
this.postLogger = postLogger;
}
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\LoggingGatewayFilterFactory.java | 2 |
请完成以下Java代码 | public int hashCode() {
return Objects.hash(id);
}
public Long getId() {
return id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
} | public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\entities\Customer.java | 1 |
请完成以下Java代码 | public class OAuth2ClientInfo extends BaseData<OAuth2ClientId> implements HasName {
@Schema(description = "Oauth2 client registration title (e.g. My google)")
private String title;
@Schema(description = "Oauth2 client provider name (e.g. Google)")
private String providerName;
@Schema(description = "List of platforms for which usage of the OAuth2 client is allowed (empty for all allowed)")
private List<PlatformType> platforms;
public OAuth2ClientInfo() {
super();
}
public OAuth2ClientInfo(OAuth2ClientId id) { | super(id);
}
public OAuth2ClientInfo(OAuth2Client oAuth2Client) {
super(oAuth2Client);
this.title = oAuth2Client.getTitle();
this.providerName = oAuth2Client.getAdditionalInfoField("providerName", JsonNode::asText,"");
this.platforms = oAuth2Client.getPlatforms();
}
@Override
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getName() {
return title;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\oauth2\OAuth2ClientInfo.java | 1 |
请完成以下Java代码 | public void clearBOMOwnCostPrice(@NonNull final CostElementId costElementId)
{
getCostPrice().clearOwnCostPrice(costElementId);
}
private Optional<CostAmount> computeComponentsCostPrice(@NonNull final CostElementId costElementId)
{
final Optional<CostAmount> componentsTotalAmt = getLines()
.stream()
.filter(BOMLine::isInboundBOMCosts)
.map(bomLine -> bomLine.getCostAmountOrNull(costElementId))
.filter(Objects::nonNull)
.reduce(CostAmount::add);
return componentsTotalAmt.map(amt -> amt.divide(qty, precision));
}
@Nullable
private CostAmount distributeToCoProductBOMLines(
@Nullable final CostAmount bomCostPrice,
@NonNull final CostElementId costElementId)
{
CostAmount bomCostPriceWithoutCoProducts = bomCostPrice;
for (final BOMLine bomLine : getLines())
{
if (!bomLine.isCoProduct())
{
continue;
}
if (bomCostPrice != null && !bomCostPrice.isZero())
{
final Percent costAllocationPerc = bomLine.getCoProductCostDistributionPercent();
final CostAmount coProductCostPrice = bomCostPrice.multiply(costAllocationPerc, precision);
bomLine.setComponentsCostPrice(coProductCostPrice, costElementId);
bomCostPriceWithoutCoProducts = bomCostPriceWithoutCoProducts.subtract(coProductCostPrice);
}
else
{
bomLine.clearComponentsCostPrice(costElementId);
}
}
return bomCostPriceWithoutCoProducts;
}
Stream<BOMCostPrice> streamCostPrices()
{ | final Stream<BOMCostPrice> linesCostPrices = getLines().stream().map(BOMLine::getCostPrice);
return Stream.concat(Stream.of(getCostPrice()), linesCostPrices);
}
private ImmutableSet<CostElementId> getCostElementIds()
{
return streamCostPrices()
.flatMap(BOMCostPrice::streamCostElementIds)
.distinct()
.collect(ImmutableSet.toImmutableSet());
}
<T extends RepoIdAware> Set<T> getCostIds(@NonNull final Class<T> idType)
{
return streamCostPrices()
.flatMap(bomCostPrice -> bomCostPrice.streamIds(idType))
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
public Set<ProductId> getProductIds()
{
final ImmutableSet.Builder<ProductId> productIds = ImmutableSet.builder();
productIds.add(getProductId());
getLines().forEach(bomLine -> productIds.add(bomLine.getComponentId()));
return productIds.build();
}
public ImmutableList<BOMCostElementPrice> getElementPrices()
{
return getCostPrice().getElementPrices();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\costing\BOM.java | 1 |
请完成以下Java代码 | private void removeWeightConfig(String routeId) {
log.trace(LogMessage.format("Removing weight config for route %s", routeId));
groupWeights.forEach((group, weightConfig) -> {
if (weightConfig.normalizedWeights.containsKey(routeId)) {
weightConfig.normalizedWeights.remove(routeId);
weightConfig.weights.remove(routeId);
}
});
}
/* for testing */ Map<String, GroupWeightConfig> getGroupWeights() {
return groupWeights;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
Map<String, String> weights = getWeights(exchange);
for (String group : groupWeights.keySet()) {
GroupWeightConfig config = groupWeights.get(group);
if (config == null) {
if (log.isDebugEnabled()) {
log.debug("No GroupWeightConfig found for group: " + group);
}
continue; // nothing we can do, but this is odd
}
// Usually, multiple threads accessing the same random object will have some
// performance problems, so we can use ThreadLocalRandom by default
double r = randomFunction.apply(exchange);
List<Double> ranges = config.ranges;
if (log.isTraceEnabled()) {
log.trace("Weight for group: " + group + ", ranges: " + ranges + ", r: " + r);
}
for (int i = 0; i < ranges.size() - 1; i++) {
if (r >= ranges.get(i) && r < ranges.get(i + 1)) {
String routeId = config.rangeIndexes.get(i);
weights.put(group, routeId);
break;
}
}
}
if (log.isTraceEnabled()) {
log.trace("Weights attr: " + weights);
}
return chain.filter(exchange);
}
/* for testing */ static class GroupWeightConfig {
String group;
LinkedHashMap<String, Integer> weights = new LinkedHashMap<>();
LinkedHashMap<String, Double> normalizedWeights = new LinkedHashMap<>(); | LinkedHashMap<Integer, String> rangeIndexes = new LinkedHashMap<>();
List<Double> ranges = new ArrayList<>();
GroupWeightConfig(String group) {
this.group = group;
}
GroupWeightConfig(GroupWeightConfig other) {
this.group = other.group;
this.weights = new LinkedHashMap<>(other.weights);
this.normalizedWeights = new LinkedHashMap<>(other.normalizedWeights);
this.rangeIndexes = new LinkedHashMap<>(other.rangeIndexes);
}
@Override
public String toString() {
return new ToStringCreator(this).append("group", group)
.append("weights", weights)
.append("normalizedWeights", normalizedWeights)
.append("rangeIndexes", rangeIndexes)
.toString();
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\WeightCalculatorWebFilter.java | 1 |
请完成以下Spring Boot application配置 | spring.main.banner-mode=off
logging.pattern.console= %d{MM-dd HH:mm:ss} - %logger{36} - %msg%n
#spring.security.user.name=in28minutes
#spring.securi | ty.user.password=dummy
spring.datasource.url=jdbc:h2:mem:testdb | repos\master-spring-and-spring-boot-main\71-spring-security\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BatchElementConfiguration {
protected static final Comparator<String> NULLS_LAST_STRING_COMPARATOR = Comparator.nullsLast(String::compareToIgnoreCase);
protected SortedMap<String, Set<String>> collectedMappings = new TreeMap<>(NULLS_LAST_STRING_COMPARATOR);
protected List<String> ids;
protected DeploymentMappings mappings;
/**
* Add mappings of deployment ids to resource ids to the overall element
* mapping list.
*
* @param mappings
* the mappings to add
*/
public void addDeploymentMappings(List<ImmutablePair<String, String>> mappings) {
addDeploymentMappings(mappings, null);
}
/**
* Add mappings of deployment ids to resource ids to the overall element
* mapping list. All elements from <code>idList</code> that are not part of
* the mappings will be added to the list of <code>null</code> deployment id
* mappings.
*
* @param mappingsList
* the mappings to add
* @param idList
* the list of ids to check for missing elements concerning the
* mappings to add
*/
public void addDeploymentMappings(List<ImmutablePair<String, String>> mappingsList, Collection<String> idList) {
if (ids != null) {
ids = null;
mappings = null;
}
Set<String> missingIds = idList == null ? null : new HashSet<>(idList);
mappingsList.forEach(pair -> {
String deploymentId = pair.getLeft();
Set<String> idSet = collectedMappings.get(deploymentId);
if (idSet == null) {
idSet = new HashSet<>();
collectedMappings.put(deploymentId, idSet);
}
idSet.add(pair.getRight());
if (missingIds != null) {
missingIds.remove(pair.getRight());
}
});
// add missing ids to "null" deployment id
if (missingIds != null && !missingIds.isEmpty()) { | Set<String> nullIds = collectedMappings.get(null);
if (nullIds == null) {
nullIds = new HashSet<>();
collectedMappings.put(null, nullIds);
}
nullIds.addAll(missingIds);
}
}
/**
* @return the list of ids that are mapped to deployment ids, ordered by
* deployment id
*/
public List<String> getIds() {
if (ids == null) {
createDeploymentMappings();
}
return ids;
}
/**
* @return the list of {@link DeploymentMapping}s
*/
public DeploymentMappings getMappings() {
if (mappings == null) {
createDeploymentMappings();
}
return mappings;
}
public boolean isEmpty() {
return collectedMappings.isEmpty();
}
protected void createDeploymentMappings() {
ids = new ArrayList<>();
mappings = new DeploymentMappings();
for (Entry<String, Set<String>> mapping : collectedMappings.entrySet()) {
ids.addAll(mapping.getValue());
mappings.add(new DeploymentMapping(mapping.getKey(), mapping.getValue().size()));
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchElementConfiguration.java | 2 |
请完成以下Java代码 | public static final JSONNotificationEvent eventReadAll()
{
final String notificationId = null;
final JSONNotification notification = null;
final int unreadCount = 0;
return new JSONNotificationEvent(EventType.ReadAll, notificationId, notification, unreadCount);
}
public static final JSONNotificationEvent eventDeleted(final String notificationId, final int unreadCount)
{
final JSONNotification notification = null;
return new JSONNotificationEvent(EventType.Delete, notificationId, notification, unreadCount);
}
public static final JSONNotificationEvent eventDeletedAll()
{
final String notificationId = null;
final JSONNotification notification = null;
final int unreadCount = 0;
return new JSONNotificationEvent(EventType.DeleteAll, notificationId, notification, unreadCount);
}
public static enum EventType
{
New, Read, ReadAll, Delete, DeleteAll
};
@JsonProperty("eventType")
private final EventType eventType;
@JsonProperty("notificationId")
private final String notificationId;
@JsonProperty("notification") | @JsonInclude(JsonInclude.Include.NON_ABSENT)
private final JSONNotification notification;
@JsonProperty("unreadCount")
@JsonInclude(JsonInclude.Include.NON_ABSENT)
private final Integer unreadCount;
private JSONNotificationEvent(final EventType eventType, final String notificationId, final JSONNotification notification, final Integer unreadCount)
{
this.eventType = eventType;
this.notificationId = notificationId;
this.notification = notification;
this.unreadCount = unreadCount;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\json\JSONNotificationEvent.java | 1 |
请完成以下Java代码 | public class ConditionXmlConverter extends CaseElementXmlConverter {
@Override
public String getXMLElementName() {
return CmmnXmlConstants.ELEMENT_CONDITION;
}
@Override
public boolean hasChildElements() {
return false;
}
@Override
protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) {
try {
String condition = xtr.getElementText(); | if (StringUtils.isNotEmpty(condition)) {
CmmnElement currentCmmnElement = conversionHelper.getCurrentCmmnElement();
if (currentCmmnElement instanceof SentryIfPart) {
((SentryIfPart) currentCmmnElement).setCondition(condition);
} else if (currentCmmnElement instanceof PlanItemRule) {
((PlanItemRule) currentCmmnElement).setCondition(condition);
}
}
} catch (XMLStreamException e) {
throw new FlowableException("Error converting condition", e);
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\ConditionXmlConverter.java | 1 |
请完成以下Java代码 | public final AppsAction getIgnoreAction()
{
return aIgnore;
}
public final boolean isAlignVerticalTabsWithHorizontalTabs()
{
return alignVerticalTabsWithHorizontalTabs;
}
/**
* For a given component, it removes component's key bindings (defined in ancestor's map) that this panel also have defined.
*
* The main purpose of doing this is to make sure menu/toolbar key bindings will not be intercepted by given component, so panel's key bindings will work when given component is embedded in our
* panel.
*
* @param comp component or <code>null</code>
*/
public final void removeAncestorKeyBindingsOf(final JComponent comp, final Predicate<KeyStroke> isRemoveKeyStrokePredicate)
{
// Skip null components (but tolerate that)
if (comp == null)
{
return;
}
// Get component's ancestors input map (the map which defines which key bindings will work when pressed in a component which is included inside this component).
final InputMap compInputMap = comp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
// NOTE: don't check and exit if "compInputMap.size() <= 0" because it might be that this map is empty but the key bindings are defined in it's parent map.
// Iterate all key bindings for our panel and remove those which are also present in component's ancestor map.
final InputMap thisInputMap = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
for (final KeyStroke key : thisInputMap.allKeys()) | {
// Check if the component has a key binding defined for our panel key binding.
final Object compAction = compInputMap.get(key);
if (compAction == null)
{
continue;
}
if (isRemoveKeyStrokePredicate != null && !isRemoveKeyStrokePredicate.apply(key))
{
continue;
}
// NOTE: Instead of removing it, it is much more safe to bind it to "none",
// to explicitly say to not consume that key event even if is defined in some parent map of this input map.
compInputMap.put(key, "none");
if (log.isDebugEnabled())
{
log.debug("Removed " + key + "->" + compAction + " which in this component is binded to " + thisInputMap.get(key)
+ "\n\tThis panel: " + this
+ "\n\tComponent: " + comp);
}
}
}
} // APanel | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\APanel.java | 1 |
请完成以下Java代码 | public int getSEPA_Export_Line_ID()
{
return get_ValueAsInt(COLUMNNAME_SEPA_Export_Line_ID);
}
@Override
public void setSEPA_Export_Line_Ref_ID (final int SEPA_Export_Line_Ref_ID)
{
if (SEPA_Export_Line_Ref_ID < 1)
set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_Ref_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_Ref_ID, SEPA_Export_Line_Ref_ID);
}
@Override
public int getSEPA_Export_Line_Ref_ID()
{ | return get_ValueAsInt(COLUMNNAME_SEPA_Export_Line_Ref_ID);
}
@Override
public void setStructuredRemittanceInfo (final @Nullable String StructuredRemittanceInfo)
{
set_Value (COLUMNNAME_StructuredRemittanceInfo, StructuredRemittanceInfo);
}
@Override
public String getStructuredRemittanceInfo()
{
return get_ValueAsString(COLUMNNAME_StructuredRemittanceInfo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java-gen\de\metas\payment\sepa\model\X_SEPA_Export_Line_Ref.java | 1 |
请完成以下Java代码 | public void dispose()
{
m_mField = null;
} // dispose
private GridField m_mField = null;
private String m_columnName;
private String m_oldText;
private String m_VFormat;
private int m_fieldLength;
private volatile boolean m_setting = false;
/**
* Set Editor to value
* @param value value
*/
public void setValue (Object value)
{
if (value == null)
m_oldText = "";
else
m_oldText = value.toString();
if (!m_setting)
setText (m_oldText);
} // setValue
/**
* Property Change Listener
* @param evt event
*/
public void propertyChange (PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
setValue(evt.getNewValue());
} // propertyChange
/**
* Return Editor value
* @return value
*/
public Object getValue()
{
return String.valueOf(getPassword());
} // getValue
/**
* Return Display Value
* @return value
*/
public String getDisplay()
{
return String.valueOf(getPassword());
} // getDisplay
/**************************************************************************
* Key Listener Interface
* @param e event
*/
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {}
/**
* Key Listener.
* @param e event
*/
public void keyReleased(KeyEvent e)
{ | String newText = String.valueOf(getPassword());
m_setting = true;
try
{
fireVetoableChange(m_columnName, m_oldText, newText);
}
catch (PropertyVetoException pve) {}
m_setting = false;
} // keyReleased
/**
* Data Binding to MTable (via GridController) - Enter pressed
* @param e event
*/
public void actionPerformed(ActionEvent e)
{
String newText = String.valueOf(getPassword());
// Data Binding
try
{
fireVetoableChange(m_columnName, m_oldText, newText);
}
catch (PropertyVetoException pve) {}
} // actionPerformed
/**
* Set Field/WindowNo for ValuePreference
* @param mField field
*/
public void setField (GridField mField)
{
m_mField = mField;
} // setField
@Override
public GridField getField() {
return m_mField;
}
// metas: Ticket#2011062310000013
public boolean isAutoCommit()
{
return false;
}
} // VPassword | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VPassword.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DocumentAcctLogsRelatedDocumentsProvider implements IRelatedDocumentsProvider
{
@NonNull private final IQueryBL queryBL = Services.get(IQueryBL.class);
@NonNull private final IADWindowDAO adWindowDAO = Services.get(IADWindowDAO.class);
@NonNull private final AcctDocRegistry acctDocRegistry;
private final Priority relatedDocumentsPriority = Priority.HIGHEST;
@Override
public List<RelatedDocumentsCandidateGroup> retrieveRelatedDocumentsCandidates(
@NonNull final IZoomSource fromDocument,
@Nullable final AdWindowId targetWindowId)
{
if (!fromDocument.isSingleKeyRecord())
{
return ImmutableList.of();
}
final AdWindowId logsWindowId = RecordWindowFinder.findAdWindowId(I_Document_Acct_Log.Table_Name).orElse(null);
if (logsWindowId == null)
{
return ImmutableList.of();
}
if (targetWindowId != null && !AdWindowId.equals(targetWindowId, logsWindowId))
{
return ImmutableList.of();
}
if (!isAccountableDocument(fromDocument))
{
return ImmutableList.of();
}
final DocumentAcctLogsQuerySupplier querySupplier = createQuerySupplier(fromDocument);
return ImmutableList.of( | RelatedDocumentsCandidateGroup.of(
RelatedDocumentsCandidate.builder()
.id(RelatedDocumentsId.ofString(I_Document_Acct_Log.Table_Name))
.internalName(I_Document_Acct_Log.Table_Name)
.targetWindow(RelatedDocumentsTargetWindow.ofAdWindowId(logsWindowId))
.windowCaption(adWindowDAO.retrieveWindowName(logsWindowId))
.priority(relatedDocumentsPriority)
.querySupplier(querySupplier)
.documentsCountSupplier(querySupplier)
.build()));
}
private boolean isAccountableDocument(final @NonNull IZoomSource fromDocument)
{
return acctDocRegistry.isAccountingTable(fromDocument.getTableName());
}
private DocumentAcctLogsQuerySupplier createQuerySupplier(final @NonNull IZoomSource fromDocument)
{
return DocumentAcctLogsQuerySupplier.builder()
.queryBL(queryBL)
.adTableId(fromDocument.getAD_Table_ID())
.recordId(fromDocument.getRecord_ID())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\related_documents\DocumentAcctLogsRelatedDocumentsProvider.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private static final Logger log = Logger.getLogger(BookstoreService.class.getName());
private final TransactionTemplate template;
private final ChapterRepository chapterRepository;
private final ModificationRepository modificationRepository;
public BookstoreService(ChapterRepository chapterRepository,
ModificationRepository modificationRepository,
TransactionTemplate template) {
this.chapterRepository = chapterRepository;
this.modificationRepository = modificationRepository;
this.template = template;
}
// running this application will
// throw org.springframework.orm.ObjectOptimisticLockingFailureException
public void editChapter() {
template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
template.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
log.info("Starting first transaction ...");
Chapter chapter = chapterRepository.findById(1L).orElseThrow();
Modification modification = new Modification();
modification.setDescription("Rewording first paragraph");
modification.setModification("Reword: ... Added: ...");
modification.setChapter(chapter);
template.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
log.info("Starting second transaction ...");
Chapter chapter = chapterRepository.findById(1L).orElseThrow();
Modification modification = new Modification();
modification.setDescription("Formatting second paragraph"); | modification.setModification("Format ...");
modification.setChapter(chapter);
modificationRepository.save(modification);
log.info("Commit second transaction ...");
}
});
log.info("Resuming first transaction ...");
modificationRepository.save(modification);
log.info("Commit first transaction ...");
}
});
log.info("Done!");
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootOptimisticForceIncrement\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public String toString()
{
return value ? "TRUE" : "FALSE";
}
}
private static final class NamedConstant extends LogicExpressionResult
{
private transient String _toString = null; // lazy
private NamedConstant(final String name, final boolean value)
{
super(name, value, value ? ConstantLogicExpression.TRUE : ConstantLogicExpression.FALSE, null);
} | @Override
public String toString()
{
if (_toString == null)
{
_toString = MoreObjects.toStringHelper(value ? "TRUE" : "FALSE")
.omitNullValues()
.addValue(name)
.toString();
}
return _toString;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\LogicExpressionResult.java | 1 |
请完成以下Java代码 | public void setName(String name) {
this.name = name;
}
public Integer getRoleLevel() {
return roleLevel;
}
public void setRoleLevel(Integer roleLevel) {
this.roleLevel = roleLevel;
}
public String getDescription() {
return description;
} | public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", name=" + name +
", roleLevel=" + roleLevel +
", description=" + description +
'}';
}
} | repos\springBoot-master\springboot-dubbo\abel-user-api\src\main\java\cn\abel\user\models\Role.java | 1 |
请完成以下Java代码 | public java.lang.String getInvoicableQtyBasedOn()
{
return get_ValueAsString(COLUMNNAME_InvoicableQtyBasedOn);
}
@Override
public void setM_InOut_ID (final int M_InOut_ID)
{
if (M_InOut_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_InOut_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_InOut_ID, M_InOut_ID);
}
@Override
public int getM_InOut_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOut_ID);
}
@Override
public void setMovementDate (final @Nullable java.sql.Timestamp MovementDate)
{
set_ValueNoCheck (COLUMNNAME_MovementDate, MovementDate);
}
@Override
public java.sql.Timestamp getMovementDate()
{
return get_ValueAsTimestamp(COLUMNNAME_MovementDate);
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_ValueNoCheck (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setProcessed (final boolean Processed)
{
set_ValueNoCheck (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_ValueNoCheck (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
} | @Override
public void setSumDeliveredInStockingUOM (final @Nullable BigDecimal SumDeliveredInStockingUOM)
{
set_ValueNoCheck (COLUMNNAME_SumDeliveredInStockingUOM, SumDeliveredInStockingUOM);
}
@Override
public BigDecimal getSumDeliveredInStockingUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumDeliveredInStockingUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSumOrderedInStockingUOM (final @Nullable BigDecimal SumOrderedInStockingUOM)
{
set_ValueNoCheck (COLUMNNAME_SumOrderedInStockingUOM, SumOrderedInStockingUOM);
}
@Override
public BigDecimal getSumOrderedInStockingUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumOrderedInStockingUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUserFlag (final @Nullable java.lang.String UserFlag)
{
set_ValueNoCheck (COLUMNNAME_UserFlag, UserFlag);
}
@Override
public java.lang.String getUserFlag()
{
return get_ValueAsString(COLUMNNAME_UserFlag);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_M_InOut_Desadv_V.java | 1 |
请完成以下Java代码 | public final class TablePermissions extends AbstractPermissions<TablePermission>
{
public static final Builder builder()
{
return new Builder();
}
private TablePermissions(final PermissionsBuilder<TablePermission, TablePermissions> builder)
{
super(builder);
}
public Builder toBuilder()
{
final Builder builder = builder();
builder.addPermissions(this, CollisionPolicy.Override);
return builder;
}
@Override
protected TablePermission noPermission()
{
return TablePermission.NONE;
}
public final boolean hasAccess(final int adTableId, final Access access)
{
final TableResource resource = TableResource.ofAD_Table_ID(adTableId);
return hasAccess(resource, access);
} | public boolean isCanReport(final int AD_Table_ID)
{
return hasAccess(AD_Table_ID, Access.REPORT);
}
public boolean isCanExport(final int AD_Table_ID)
{
return hasAccess(AD_Table_ID, Access.EXPORT);
}
public static class Builder extends PermissionsBuilder<TablePermission, TablePermissions>
{
@Override
protected TablePermissions createPermissionsInstance()
{
return new TablePermissions(this);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TablePermissions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CreatedUpdatedInfo
{
public static CreatedUpdatedInfo createNew(
@NonNull final UserId createdBy,
@NonNull final ZonedDateTime created)
{
return new CreatedUpdatedInfo(createdBy, created, createdBy, created);
}
public static CreatedUpdatedInfo of(
@NonNull final ZonedDateTime created,
@NonNull final UserId createdBy,
@NonNull final ZonedDateTime updated,
@NonNull final UserId updatedBy)
{
return new CreatedUpdatedInfo(createdBy, created, updatedBy, updated);
}
UserId createdBy;
ZonedDateTime created;
UserId updatedBy;
ZonedDateTime updated;
@Builder
@JsonCreator
private CreatedUpdatedInfo(
@NonNull @JsonProperty("createdBy") final UserId createdBy,
@NonNull @JsonProperty("created") final ZonedDateTime created,
@NonNull @JsonProperty("updatedBy") final UserId updatedBy,
@NonNull @JsonProperty("updated") final ZonedDateTime updated) | {
this.createdBy = createdBy;
this.created = created;
this.updatedBy = updatedBy;
this.updated = updated;
}
public CreatedUpdatedInfo updated(
@NonNull final UserId updatedBy,
@NonNull final ZonedDateTime updated)
{
return new CreatedUpdatedInfo(createdBy, created, updatedBy, updated);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\CreatedUpdatedInfo.java | 2 |
请完成以下Java代码 | public void setBinaryData (byte[] BinaryData)
{
set_Value (COLUMNNAME_BinaryData, BinaryData);
}
/** Get BinaryData.
@return Binary Data
*/
public byte[] getBinaryData ()
{
return (byte[])get_Value(COLUMNNAME_BinaryData);
}
/** 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 Image URL.
@param ImageURL
URL of image
*/
public void setImageURL (String ImageURL)
{
set_Value (COLUMNNAME_ImageURL, ImageURL);
}
/** Get Image URL.
@return URL of image
*/
public String getImageURL ()
{ | return (String)get_Value(COLUMNNAME_ImageURL);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Image.java | 1 |
请完成以下Java代码 | public IScriptFactory getScriptFactory()
{
return getDelegate().getScriptFactory();
}
@Override
public void setScriptFactory(final IScriptFactory scriptFactory)
{
getDelegate().setScriptFactory(scriptFactory);
}
@Override
public IScriptFactory getScriptFactoryToUse()
{
return getDelegate().getScriptFactoryToUse(); | }
@Override
public boolean hasNext()
{
return getDelegate().hasNext();
}
@Override
public IScript next()
{
return getDelegate().next();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\ForwardingScriptScanner.java | 1 |
请完成以下Java代码 | public java.lang.String getInternalName ()
{
return (java.lang.String)get_Value(COLUMNNAME_InternalName);
}
/** Set inkl. "leer"-Eintrag.
@param IsIncludeEmpty
Legt fest, ob die Dimension einen dezidierten "Leer" Eintrag enthalten soll
*/
@Override
public void setIsIncludeEmpty (boolean IsIncludeEmpty)
{
set_Value (COLUMNNAME_IsIncludeEmpty, Boolean.valueOf(IsIncludeEmpty));
}
/** Get inkl. "leer"-Eintrag.
@return Legt fest, ob die Dimension einen dezidierten "Leer" Eintrag enthalten soll
*/
@Override
public boolean isIncludeEmpty ()
{
Object oo = get_Value(COLUMNNAME_IsIncludeEmpty);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set inkl. "sonstige"-Eintrag.
@param IsIncludeOtherGroup
Legt fest, ob die Dimension einen dezidierten "Sonstige" Eintrag enthalten soll
*/
@Override
public void setIsIncludeOtherGroup (boolean IsIncludeOtherGroup)
{
set_Value (COLUMNNAME_IsIncludeOtherGroup, Boolean.valueOf(IsIncludeOtherGroup));
} | /** Get inkl. "sonstige"-Eintrag.
@return Legt fest, ob die Dimension einen dezidierten "Sonstige" Eintrag enthalten soll
*/
@Override
public boolean isIncludeOtherGroup ()
{
Object oo = get_Value(COLUMNNAME_IsIncludeOtherGroup);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Spec.java | 1 |
请完成以下Java代码 | public JsonSerde<T> forKeys() {
this.jsonSerializer.forKeys();
this.jsonDeserializer.forKeys();
return this;
}
/**
* Configure the serializer to not add type information.
* @return the serde.
* @since 2.3
*/
public JsonSerde<T> noTypeInfo() {
this.jsonSerializer.noTypeInfo();
return this;
}
/**
* Don't remove type information headers after deserialization.
* @return the serde.
* @since 2.3
*/
public JsonSerde<T> dontRemoveTypeHeaders() {
this.jsonDeserializer.dontRemoveTypeHeaders();
return this;
} | /**
* Ignore type information headers and use the configured target class.
* @return the serde.
* @since 2.3
*/
public JsonSerde<T> ignoreTypeHeaders() {
this.jsonDeserializer.ignoreTypeHeaders();
return this;
}
/**
* Use the supplied {@link org.springframework.kafka.support.mapping.Jackson2JavaTypeMapper}.
* @param mapper the mapper.
* @return the serde.
* @since 2.3
*/
public JsonSerde<T> typeMapper(org.springframework.kafka.support.mapping.Jackson2JavaTypeMapper mapper) {
this.jsonSerializer.setTypeMapper(mapper);
this.jsonDeserializer.setTypeMapper(mapper);
return this;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\JsonSerde.java | 1 |
请完成以下Java代码 | public Map<String, Map<String, Object>> getChildInstanceTaskVariables() {
return childInstanceTaskVariables;
}
public CaseInstanceChangeState setChildInstanceTaskVariables(Map<String, Map<String, Object>> childInstanceTaskVariables) {
this.childInstanceTaskVariables = childInstanceTaskVariables;
return this;
}
public Map<String, PlanItemInstanceEntity> getCreatedStageInstances() {
return createdStageInstances;
}
public CaseInstanceChangeState setCreatedStageInstances(HashMap<String, PlanItemInstanceEntity> createdStageInstances) {
this.createdStageInstances = createdStageInstances;
return this;
}
public void addCreatedStageInstance(String key, PlanItemInstanceEntity planItemInstance) { | this.createdStageInstances.put(key, planItemInstance);
}
public Map<String, PlanItemInstanceEntity> getTerminatedPlanItemInstances() {
return terminatedPlanItemInstances;
}
public CaseInstanceChangeState setTerminatedPlanItemInstances(HashMap<String, PlanItemInstanceEntity> terminatedPlanItemInstances) {
this.terminatedPlanItemInstances = terminatedPlanItemInstances;
return this;
}
public void addTerminatedPlanItemInstance(String key, PlanItemInstanceEntity planItemInstance) {
this.terminatedPlanItemInstances.put(key, planItemInstance);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceChangeState.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.sysCommentService.removeByIds(Arrays.asList(ids.split(",")));
return Result.OK("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
//@AutoLog(value = "系统评论回复表-通过id查询")
@Operation(summary = "系统评论回复表-通过id查询")
@GetMapping(value = "/queryById")
public Result<SysComment> queryById(@RequestParam(name = "id", required = true) String id) {
SysComment sysComment = sysCommentService.getById(id);
if (sysComment == null) {
return Result.error("未找到对应数据");
}
return Result.OK(sysComment);
}
/**
* 导出excel
*
* @param request
* @param sysComment
*/
//@RequiresPermissions("org.jeecg.modules.demo:sys_comment:exportXls")
@RequestMapping(value = "/exportXls") | public ModelAndView exportXls(HttpServletRequest request, SysComment sysComment) {
return super.exportXls(request, sysComment, SysComment.class, "系统评论回复表");
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
//@RequiresPermissions("sys_comment:importExcel")
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, SysComment.class);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysCommentController.java | 2 |
请完成以下Java代码 | private static PPOrderLineRowId fromStringPartsList(final List<String> parts)
{
final int partsCount = parts.size();
if (partsCount < 1)
{
throw new IllegalArgumentException("Invalid id: " + parts);
}
final PPOrderLineRowType type = PPOrderLineRowType.forCode(parts.get(0));
final DocumentId parentRowId = !Check.isEmpty(parts.get(1), true) ? DocumentId.of(parts.get(1)) : null;
final int recordId = Integer.parseInt(parts.get(2));
return new PPOrderLineRowId(type, parentRowId, recordId);
}
public static PPOrderLineRowId ofPPOrderBomLineId(int ppOrderBomLineId)
{
Preconditions.checkArgument(ppOrderBomLineId > 0, "ppOrderBomLineId > 0");
return new PPOrderLineRowId(PPOrderLineRowType.PP_OrderBomLine, null, ppOrderBomLineId);
}
public static PPOrderLineRowId ofPPOrderId(int ppOrderId)
{ | Preconditions.checkArgument(ppOrderId > 0, "ppOrderId > 0");
return new PPOrderLineRowId(PPOrderLineRowType.PP_Order, null, ppOrderId);
}
public static PPOrderLineRowId ofIssuedOrReceivedHU(@Nullable DocumentId parentRowId, @NonNull final HuId huId)
{
return new PPOrderLineRowId(PPOrderLineRowType.IssuedOrReceivedHU, parentRowId, huId.getRepoId());
}
public static PPOrderLineRowId ofSourceHU(@NonNull DocumentId parentRowId, @NonNull final HuId sourceHuId)
{
return new PPOrderLineRowId(PPOrderLineRowType.Source_HU, parentRowId, sourceHuId.getRepoId());
}
public Optional<PPOrderBOMLineId> getPPOrderBOMLineIdIfApplies()
{
return type.isPP_OrderBomLine() ? PPOrderBOMLineId.optionalOfRepoId(recordId) : Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLineRowId.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public MscExecutorService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
@Override
public void start(StartContext context) throws StartException {
provider.accept(this);
}
@Override
public void stop(StopContext context) {
provider.accept(null);
}
@Override
public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) {
return new ExecuteJobsRunnable(jobIds, processEngine);
}
@Override
public boolean schedule(Runnable runnable, boolean isLongRunning) {
if(isLongRunning) {
return scheduleLongRunningWork(runnable);
} else {
return scheduleShortRunningWork(runnable);
}
}
protected boolean scheduleShortRunningWork(Runnable runnable) {
EnhancedQueueExecutor EnhancedQueueExecutor = managedQueueSupplier.get();
try {
EnhancedQueueExecutor.execute(runnable);
return true;
} catch (Exception e) {
// we must be able to schedule this
log.log(Level.WARNING, "Cannot schedule long running work.", e);
}
return false;
}
protected boolean scheduleLongRunningWork(Runnable runnable) { | final EnhancedQueueExecutor EnhancedQueueExecutor = managedQueueSupplier.get();
boolean rejected = false;
try {
EnhancedQueueExecutor.execute(runnable);
} catch (RejectedExecutionException e) {
rejected = true;
} catch (Exception e) {
// if it fails for some other reason, log a warning message
long now = System.currentTimeMillis();
// only log every 60 seconds to prevent log flooding
if((now-lastWarningLogged) >= (60*1000)) {
log.log(Level.WARNING, "Unexpected Exception while submitting job to executor pool.", e);
} else {
log.log(Level.FINE, "Unexpected Exception while submitting job to executor pool.", e);
}
}
return !rejected;
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscExecutorService.java | 2 |
请完成以下Java代码 | public String getProductSkuCode() {
return productSkuCode;
}
public void setProductSkuCode(String productSkuCode) {
this.productSkuCode = productSkuCode;
}
public String getMemberNickname() {
return memberNickname;
}
public void setMemberNickname(String memberNickname) {
this.memberNickname = memberNickname;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
public Integer getDeleteStatus() {
return deleteStatus;
}
public void setDeleteStatus(Integer deleteStatus) {
this.deleteStatus = deleteStatus;
}
public Long getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(Long productCategoryId) {
this.productCategoryId = productCategoryId;
}
public String getProductBrand() {
return productBrand;
}
public void setProductBrand(String productBrand) {
this.productBrand = productBrand;
}
public String getProductSn() {
return productSn;
}
public void setProductSn(String productSn) {
this.productSn = productSn;
}
public String getProductAttr() {
return productAttr;
}
public void setProductAttr(String productAttr) {
this.productAttr = productAttr; | }
@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(", productId=").append(productId);
sb.append(", productSkuId=").append(productSkuId);
sb.append(", memberId=").append(memberId);
sb.append(", quantity=").append(quantity);
sb.append(", price=").append(price);
sb.append(", productPic=").append(productPic);
sb.append(", productName=").append(productName);
sb.append(", productSubTitle=").append(productSubTitle);
sb.append(", productSkuCode=").append(productSkuCode);
sb.append(", memberNickname=").append(memberNickname);
sb.append(", createDate=").append(createDate);
sb.append(", modifyDate=").append(modifyDate);
sb.append(", deleteStatus=").append(deleteStatus);
sb.append(", productCategoryId=").append(productCategoryId);
sb.append(", productBrand=").append(productBrand);
sb.append(", productSn=").append(productSn);
sb.append(", productAttr=").append(productAttr);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsCartItem.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
final I_C_Invoice invoice = context.getSelectedModel(I_C_Invoice.class);
if (invoice == null)
{
return ProcessPreconditionsResolution.reject(Services.get(IMsgBL.class).getTranslatableMsgText(MSG_NO_INVOICE_SELECTED));
}
// only completed invoiced
if (!invoiceBL.isComplete(invoice))
{
return ProcessPreconditionsResolution.reject(Services.get(IMsgBL.class).getTranslatableMsgText(MSG_INVOICE_IS_NOT_COMPLETED));
}
return ProcessPreconditionsResolution.acceptIf(!invoice.isSOTrx());
}
public void createPaymentRequestFromTemplate(@NonNull final org.compiere.model.I_C_Invoice invoice, @Nullable final I_C_Payment_Request template)
{
if (template == null)
{
throw new AdempiereException(MSG_COULD_NOT_CREATE_PAYMENT_REQUEST).markAsUserValidationError();
}
//
// Get the selected invoice
if (paymentRequestDAO.hasPaymentRequests(invoice))
{
throw new AdempiereException(MSG_PAYMENT_REQUEST_FOR_INVOICE_ALREADY_EXISTS_EXCEPTION).markAsUserValidationError();
} | paymentRequestBL.createPaymentRequest(invoice, template);
}
public I_C_Payment_Request createPaymentRequestTemplate(final I_C_BP_BankAccount bankAccount, final BigDecimal amount, final PaymentString paymentString)
{
final IContextAware contextProvider = PlainContextAware.newOutOfTrx(Env.getCtx());
//
// Create it, but do not save it!
final I_C_Payment_Request paymentRequestTemplate = InterfaceWrapperHelper.newInstance(I_C_Payment_Request.class, contextProvider);
InterfaceWrapperHelper.setSaveDeleteDisabled(paymentRequestTemplate, true);
paymentRequestTemplate.setC_BP_BankAccount(bankAccount);
paymentRequestTemplate.setAmount(amount);
if (paymentString != null)
{
paymentRequestTemplate.setReference(paymentString.getReferenceNoComplete());
paymentRequestTemplate.setFullPaymentString(paymentString.getRawPaymentString());
}
return paymentRequestTemplate;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\process\paymentdocumentform\PaymentStringProcessService.java | 1 |
请完成以下Java代码 | public boolean isDisabled()
{
return getPreconditionsResolution().isRejected();
}
public boolean isEnabled()
{
final ProcessPreconditionsResolution preconditionsResolution = getPreconditionsResolution();
return preconditionsResolution.isAccepted();
}
public boolean isEnabledOrNotSilent()
{
try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(I_AD_Process.Table_Name, processId == null ? null : processId.toAdProcessIdOrNull()))
{
final ProcessPreconditionsResolution preconditionsResolution = getPreconditionsResolution();
return preconditionsResolution.isAccepted() || !preconditionsResolution.isInternal();
}
}
public boolean isInternal()
{
final ProcessPreconditionsResolution preconditionsResolution = getPreconditionsResolution();
return preconditionsResolution.isInternal();
}
public String getDisabledReason(final String adLanguage)
{
return getPreconditionsResolution().getRejectReason().translate(adLanguage);
}
public Map<String, Object> getDebugProperties()
{
final ImmutableMap.Builder<String, Object> debugProperties = ImmutableMap.builder(); | if (debugProcessClassname != null)
{
debugProperties.put("debug-classname", debugProcessClassname);
}
return debugProperties.build();
}
public boolean isDisplayedOn(@NonNull final DisplayPlace displayPlace)
{
return getDisplayPlaces().contains(displayPlace);
}
@Value
private static class ValueAndDuration<T>
{
public static <T> ValueAndDuration<T> fromSupplier(final Supplier<T> supplier)
{
final Stopwatch stopwatch = Stopwatch.createStarted();
final T value = supplier.get();
final Duration duration = Duration.ofNanos(stopwatch.stop().elapsed(TimeUnit.NANOSECONDS));
return new ValueAndDuration<>(value, duration);
}
T value;
Duration duration;
private ValueAndDuration(final T value, final Duration duration)
{
this.value = value;
this.duration = duration;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\descriptor\WebuiRelatedProcessDescriptor.java | 1 |
请完成以下Java代码 | public class RefundProfitPriceActualComponent implements ProfitPriceActualComponent
{
private final CalculateProfitPriceActualRequest request;
private final RefundContractRepository refundContractRepository; // TODO: take out the repo/service from here !
private final MoneyService moneyService;
public RefundProfitPriceActualComponent(
@NonNull final CalculateProfitPriceActualRequest request,
@NonNull final RefundContractRepository refundContractRepository,
@NonNull final MoneyService moneyService)
{
this.request = request;
this.refundContractRepository = refundContractRepository;
this.moneyService = moneyService;
}
@Override
public Money applyToInput(@NonNull final Money input)
{
final RefundContractQuery query = RefundContractQuery.of(request);
final RefundConfig refundConfig = refundContractRepository | .getByQuery(query)
.flatMap(RefundContract::getRefundConfigToUseProfitCalculation)
.orElse(null);
if (refundConfig == null)
{
return input;
}
if (RefundBase.AMOUNT_PER_UNIT.equals(refundConfig.getRefundBase()))
{
final Money amountPerUnit = refundConfig.getAmount();
return input.subtract(amountPerUnit);
}
final Percent percent = refundConfig.getPercent();
return moneyService.subtractPercent(percent, input);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\grossprofit\RefundProfitPriceActualComponent.java | 1 |
请完成以下Java代码 | public ResponseEntity handleMethodArgumentNotValidException(
HttpServletRequest request,
HttpServletResponse response,
MethodArgumentNotValidException ex) {
String errMsg = null;
if (ex.getBindingResult() != null && ex.getBindingResult().hasErrors()) {
errMsg = ex.getBindingResult().getFieldErrors().get(0).getDefaultMessage();
}
return ResponseEntity.error(ARG_ERROR_CODE, errMsg);
}
/**
* 参数验证异常。
*
* @param ex
* @return
*/
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity handleConstraintViolationException(
HttpServletRequest request,
HttpServletResponse response,
ConstraintViolationException ex) {
String errMsg = ((ConstraintViolationException) ex).getConstraintViolations()
.iterator().next().getMessage();
return ResponseEntity.error(ARG_ERROR_CODE, errMsg);
}
/**
* ServiceException异常
*
* @param exception
* @return
*/
@ExceptionHandler({ServiceException.class})
@ResponseStatus(HttpStatus.OK)
public String processServiceException(Exception exception, Model model) {
model.addAttribute("exception", exception.getMessage());
logger.error("rpc接口调用异常。{}", exception.getMessage());
return ERROR_500;
}
/**
* 没有权限 异常
* <p/>
* 后续根据不同的需求定制即可
* 应用到所有@RequestMapping注解的方法,在其抛出UnauthorizedException异常时执行
* | * @param request
* @param e
* @return
*/
@ExceptionHandler({UnauthorizedException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String processUnauthorizedException(NativeWebRequest request, Model model, UnauthorizedException e) {
model.addAttribute("exception", e.getMessage());
logger.error("权限异常。{}", e.getMessage());
return ERROR_403;
}
/**
* 运行时异常
*
* @param exception
* @return
*/
@ExceptionHandler({RuntimeException.class})
@ResponseStatus(HttpStatus.OK)
public String processException(RuntimeException exception, Model model) {
model.addAttribute("exception", exception.getMessage());
logger.error("程序异常", exception);
return ERROR_500;
}
/**
* Exception异常
*
* @param exception
* @return
*/
@ExceptionHandler({Exception.class})
@ResponseStatus(HttpStatus.OK)
public String processException(Exception exception, Model model) {
model.addAttribute("exception", exception.getMessage());
logger.error("程序异常", exception);
return ERROR_500;
//logger.info("自定义异常处理-Exception");
//ModelAndView m = new ModelAndView();
//m.addObject("exception", exception.getMessage());
//m.setViewName("error/500");
//return m;
}
} | repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\exception\DefaultExceptionHandler.java | 1 |
请完成以下Java代码 | public boolean accept(I_C_ReferenceNo_Doc pojo)
{
return pojo.getRecord_ID() == InterfaceWrapperHelper.getId(model)
&& pojo.getAD_Table_ID() == MTable.getTable_ID(InterfaceWrapperHelper.getModelTableName(model));
}
});
// add the C_ReferenceNos into a set to avoid duplicates
final Set<I_C_ReferenceNo> refNos = new HashSet<>();
for (final I_C_ReferenceNo_Doc doc : docs)
{
final I_C_ReferenceNo referenceNo = doc.getC_ReferenceNo();
if (referenceNo.getC_ReferenceNo_Type_ID() == type.getC_ReferenceNo_Type_ID())
{
refNos.add(referenceNo);
}
} | return new ArrayList<>(refNos);
}
@Override
protected List<I_C_ReferenceNo_Doc> retrieveRefNoDocByRefNoAndTableName(final I_C_ReferenceNo referenceNo, final String tableName)
{
return lookupMap.getRecords(I_C_ReferenceNo_Doc.class, new IPOJOFilter<I_C_ReferenceNo_Doc>()
{
@Override
public boolean accept(I_C_ReferenceNo_Doc pojo)
{
return pojo.getC_ReferenceNo_ID() == referenceNo.getC_ReferenceNo_ID()
&& pojo.getAD_Table_ID() == MTable.getTable_ID(tableName);
}
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\api\impl\PlainReferenceNoDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public User getUser(@PathVariable Long id) {
Map<String, Object> params = new HashMap<>();
params.put("id", id);
URI uri = UriComponentsBuilder.fromUriString("http://Server-Provider/user/{id}")
.build().expand(params).encode().toUri();
return this.restTemplate.getForEntity(uri, User.class).getBody();
}
@GetMapping("user")
public List<User> getUsers() {
return this.restTemplate.getForObject("http://Server-Provider/user", List.class);
}
@GetMapping("user/add")
public String addUser() {
User user = new User(1L, "mrbird", "123456");
HttpStatus status = this.restTemplate.postForEntity("http://Server-Provider/user", user, null).getStatusCode(); | if (status.is2xxSuccessful()) {
return "新增用户成功";
} else {
return "新增用户失败";
}
}
@GetMapping("user/update")
public void updateUser() {
User user = new User(1L, "mrbird", "123456");
this.restTemplate.put("http://Server-Provider/user", user);
}
@GetMapping("user/delete/{id:\\d+}")
public void deleteUser(@PathVariable Long id) {
this.restTemplate.delete("http://Server-Provider/user/{1}", id);
}
} | repos\SpringAll-master\29.Spring-Cloud-Ribbon-LoadBalance\Ribbon-Consumer\src\main\java\com\example\demo\controller\TestController.java | 2 |
请完成以下Java代码 | protected void prepare()
{
ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("AD_PrintFormat_ID"))
m_AD_PrintFormat_ID = ((BigDecimal)para[i].getParameter());
else if (name.equals("AD_Table_ID"))
m_AD_Table_ID = ((BigDecimal)para[i].getParameter());
else
log.error("prepare - Unknown Parameter="
+ para[i].getParameterName());
}
} // prepare
/**
* Perform process.
* <pre>
* If AD_Table_ID is not null, create from table,
* otherwise copy from AD_PrintFormat_ID
* </pre>
* @return Message
* @throws Exception
*/
protected String doIt() throws Exception
{
if (m_AD_Table_ID != null && m_AD_Table_ID.intValue() > 0) | {
log.info("Create from AD_Table_ID=" + m_AD_Table_ID);
MPrintFormat pf = MPrintFormat.createFromTable(getCtx(), m_AD_Table_ID.intValue(), getRecord_ID());
addLog(m_AD_Table_ID.intValue(), null, new BigDecimal(pf.getItemCount()), pf.getName());
return pf.getName() + " #" + pf.getItemCount();
}
else if (m_AD_PrintFormat_ID != null && m_AD_PrintFormat_ID.intValue() > 0)
{
log.info("Copy from AD_PrintFormat_ID=" + m_AD_PrintFormat_ID);
MPrintFormat pf = MPrintFormat.copy (getCtx(), m_AD_PrintFormat_ID.intValue(), getRecord_ID());
addLog(m_AD_PrintFormat_ID.intValue(), null, new BigDecimal(pf.getItemCount()), pf.getName());
return pf.getName() + " #" + pf.getItemCount();
}
else
throw new Exception (MSG_InvalidArguments);
} // doIt
} // MPrintFormatProcess | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintFormatProcess.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CountryRepository {
private static final Map<String, Country> countries = new HashMap<>();
{
initData();
}
private final static void initData() {
Country usa = new Country();
usa.setName("USA");
usa.setCapital("Washington D.C.");
usa.setCurrency(Currency.USD);
usa.setPopulation(323947000);
countries.put(usa.getName(), usa);
Country india = new Country();
india.setName("India"); | india.setCapital("New Delhi");
india.setCurrency(Currency.INR);
india.setPopulation(1295210000);
countries.put(india.getName(), india);
Country france = new Country();
france.setName("France");
france.setCapital("Paris");
france.setCurrency(Currency.EUR);
france.setPopulation(66710000);
countries.put(france.getName(), france);
}
public Country findCountry(String name) {
return countries.get(name);
}
} | repos\tutorials-master\core-java-modules\core-java-11-2\src\main\java\com\baeldung\soap\ws\server\CountryRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getAccountNo() {
return accountNo;
}
/**
* 账户编号
*
* @param accountNo
*/
public void setAccountNo(String accountNo) {
this.accountNo = accountNo == null ? null : accountNo.trim();
}
/** 用户名称 **/
public String getUserName() {
return userName;
}
/** 用户名称 **/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* 汇总日期
*
* @return
*/
public Date getCollectDate() {
return collectDate;
}
/**
* 汇总日期
*
* @param collectDate
*/
public void setCollectDate(Date collectDate) {
this.collectDate = collectDate;
}
/**
* 汇总类型(参考枚举:SettDailyCollectTypeEnum)
*
* @return
*/
public String getCollectType() {
return collectType;
}
/**
* 汇总类型(参考枚举:SettDailyCollectTypeEnum)
*
* @param collectType
*/
public void setCollectType(String collectType) {
this.collectType = collectType;
}
/**
* 结算批次号(结算之后再回写过来)
*
* @return
*/
public String getBatchNo() {
return batchNo;
}
/**
* 结算批次号(结算之后再回写过来)
*
* @param batchNo
*/
public void setBatchNo(String batchNo) {
this.batchNo = batchNo == null ? null : batchNo.trim();
} | /**
* 交易总金额
*
* @return
*/
public BigDecimal getTotalAmount() {
return totalAmount;
}
/**
* 交易总金额
*
* @param totalAmount
*/
public void setTotalAmount(BigDecimal totalAmount) {
this.totalAmount = totalAmount;
}
/**
* 交易总笔数
*
* @return
*/
public Integer getTotalCount() {
return totalCount;
}
/**
* 交易总笔数
*
* @param totalCount
*/
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
/**
* 结算状态(参考枚举:SettDailyCollectStatusEnum)
*
* @return
*/
public String getSettStatus() {
return settStatus;
}
/**
* 结算状态(参考枚举:SettDailyCollectStatusEnum)
*
* @param settStatus
*/
public void setSettStatus(String settStatus) {
this.settStatus = settStatus;
}
/**
* 风险预存期
*/
public Integer getRiskDay() {
return riskDay;
}
/**
* 风险预存期
*/
public void setRiskDay(Integer riskDay) {
this.riskDay = riskDay;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpSettDailyCollect.java | 2 |
请完成以下Java代码 | 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);
}
/** 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_C_Campaign.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public static AccountTypeEnum getEnum(String enumName) {
AccountTypeEnum resultEnum = null;
AccountTypeEnum[] enumAry = AccountTypeEnum.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() {
AccountTypeEnum[] ary = AccountTypeEnum.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() {
AccountTypeEnum[] ary = AccountTypeEnum.values();
List list = new ArrayList();
for (int i = 0; i < ary.length; i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("desc", ary[i].getDesc());
list.add(map);
}
return list;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\enums\AccountTypeEnum.java | 2 |
请完成以下Java代码 | public int getM_QualityInsp_LagerKonf_Version_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set % ab.
@param PercentFrom % ab */
@Override
public void setPercentFrom (java.math.BigDecimal PercentFrom)
{
set_Value (COLUMNNAME_PercentFrom, PercentFrom);
}
/** Get % ab.
@return % ab */
@Override
public java.math.BigDecimal getPercentFrom ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PercentFrom);
if (bd == null)
return Env.ZERO;
return bd; | }
/** Set Betrag pro Einheit.
@param Processing_Fee_Amt_Per_UOM Betrag pro Einheit */
@Override
public void setProcessing_Fee_Amt_Per_UOM (java.math.BigDecimal Processing_Fee_Amt_Per_UOM)
{
set_Value (COLUMNNAME_Processing_Fee_Amt_Per_UOM, Processing_Fee_Amt_Per_UOM);
}
/** Get Betrag pro Einheit.
@return Betrag pro Einheit */
@Override
public java.math.BigDecimal getProcessing_Fee_Amt_Per_UOM ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Processing_Fee_Amt_Per_UOM);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_QualityInsp_LagerKonf_ProcessingFee.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonHUUpdate
{
@NonNull
@JsonProperty("FLAG")
Integer flag;
@NonNull
@JsonProperty("ID")
String id;
@NonNull
@JsonProperty("ATTRIBUTES")
Map<String, Object> attributes;
@Builder
public JsonHUUpdate( | @JsonProperty("FLAG") @NonNull final Integer flag,
@JsonProperty("ID") @NonNull final String id,
@JsonProperty("ATTRIBUTES") @NonNull final Map<String, Object> attributes)
{
this.flag = flag;
this.id = id;
this.attributes = attributes;
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPOJOBuilder(withPrefix = "")
public static class JsonHUUpdateBuilder
{
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\api\model\JsonHUUpdate.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private Saml2AuthenticationToken tokenByRegistration(HttpServletRequest request,
RelyingPartyRegistration registration, AbstractSaml2AuthenticationRequest authenticationRequest) {
if (registration == null) {
return null;
}
String decoded = decode(request);
UriResolver resolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration);
registration = registration.mutate()
.entityId(resolver.resolve(registration.getEntityId()))
.assertionConsumerServiceLocation(resolver.resolve(registration.getAssertionConsumerServiceLocation()))
.build();
return new Saml2AuthenticationToken(registration, decoded, authenticationRequest);
}
/**
* Use the given {@link Saml2AuthenticationRequestRepository} to load authentication
* request.
* @param authenticationRequestRepository the
* {@link Saml2AuthenticationRequestRepository} to use
*/
void setAuthenticationRequestRepository(
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) {
Assert.notNull(authenticationRequestRepository, "authenticationRequestRepository cannot be null");
this.authenticationRequests = authenticationRequestRepository;
}
/**
* Use the given {@link RequestMatcher} to match the request.
* @param requestMatcher the {@link RequestMatcher} to use
*/
void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
this.requestMatcher = requestMatcher;
}
void setShouldConvertGetRequests(boolean shouldConvertGetRequests) {
this.shouldConvertGetRequests = shouldConvertGetRequests;
} | private String decode(HttpServletRequest request) {
String encoded = request.getParameter(Saml2ParameterNames.SAML_RESPONSE);
boolean isGet = HttpMethod.GET.matches(request.getMethod());
if (!this.shouldConvertGetRequests && isGet) {
return null;
}
Saml2Utils.DecodingConfigurer decoding = Saml2Utils.withEncoded(encoded).requireBase64(true).inflate(isGet);
try {
return decoding.decode();
}
catch (Exception ex) {
throw new Saml2AuthenticationException(Saml2Error.invalidResponse(ex.getMessage()), ex);
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\BaseOpenSamlAuthenticationTokenConverter.java | 2 |
请完成以下Java代码 | public int getAlberta_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_Alberta_Order_ID);
}
@Override
public void setAlberta_OrderedArticleLine_ID (final int Alberta_OrderedArticleLine_ID)
{
if (Alberta_OrderedArticleLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_Alberta_OrderedArticleLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Alberta_OrderedArticleLine_ID, Alberta_OrderedArticleLine_ID);
}
@Override
public int getAlberta_OrderedArticleLine_ID()
{
return get_ValueAsInt(COLUMNNAME_Alberta_OrderedArticleLine_ID);
}
@Override
public void setC_OLCand_ID (final int C_OLCand_ID)
{
if (C_OLCand_ID < 1)
set_Value (COLUMNNAME_C_OLCand_ID, null);
else
set_Value (COLUMNNAME_C_OLCand_ID, C_OLCand_ID);
}
@Override
public int getC_OLCand_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_ID);
}
@Override
public void setDurationAmount (final @Nullable BigDecimal DurationAmount)
{
set_Value (COLUMNNAME_DurationAmount, DurationAmount);
}
@Override
public BigDecimal getDurationAmount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DurationAmount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setExternalId (final String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setExternallyUpdatedAt (final @Nullable java.sql.Timestamp ExternallyUpdatedAt)
{
set_Value (COLUMNNAME_ExternallyUpdatedAt, ExternallyUpdatedAt);
}
@Override | public java.sql.Timestamp getExternallyUpdatedAt()
{
return get_ValueAsTimestamp(COLUMNNAME_ExternallyUpdatedAt);
}
@Override
public void setIsPrivateSale (final boolean IsPrivateSale)
{
set_Value (COLUMNNAME_IsPrivateSale, IsPrivateSale);
}
@Override
public boolean isPrivateSale()
{
return get_ValueAsBoolean(COLUMNNAME_IsPrivateSale);
}
@Override
public void setIsRentalEquipment (final boolean IsRentalEquipment)
{
set_Value (COLUMNNAME_IsRentalEquipment, IsRentalEquipment);
}
@Override
public boolean isRentalEquipment()
{
return get_ValueAsBoolean(COLUMNNAME_IsRentalEquipment);
}
@Override
public void setSalesLineId (final @Nullable String SalesLineId)
{
set_Value (COLUMNNAME_SalesLineId, SalesLineId);
}
@Override
public String getSalesLineId()
{
return get_ValueAsString(COLUMNNAME_SalesLineId);
}
@Override
public void setTimePeriod (final @Nullable BigDecimal TimePeriod)
{
set_Value (COLUMNNAME_TimePeriod, TimePeriod);
}
@Override
public BigDecimal getTimePeriod()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TimePeriod);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUnit (final @Nullable String Unit)
{
set_Value (COLUMNNAME_Unit, Unit);
}
@Override
public String getUnit()
{
return get_ValueAsString(COLUMNNAME_Unit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_OrderedArticleLine.java | 1 |
请完成以下Java代码 | public static ValueNamePair of(
@JsonProperty("v") final String value,
@JsonProperty("n") final String name)
{
return of(value, name, null/* help */);
}
public static ValueNamePair of(
@JsonProperty("v") final String value,
@JsonProperty("n") final String name,
@JsonProperty("description") final String description)
{
if (Objects.equals(value, EMPTY.getValue()) && Objects.equals(name, EMPTY.getName()))
{
return EMPTY;
}
return new ValueNamePair(value, name, description);
}
@JsonCreator
public static ValueNamePair of(
@JsonProperty("v") final String value,
@JsonProperty("n") final String name,
@JsonProperty("description") final String description,
@JsonProperty("validationInformation") @Nullable final ValueNamePairValidationInformation validationInformation)
{
if (Objects.equals(value, EMPTY.getValue())
&& Objects.equals(name, EMPTY.getName())
&& validationInformation == null)
{
return EMPTY;
}
return new ValueNamePair(value, name, description, validationInformation);
}
/**
* Construct KeyValue Pair
*
* @param value value
* @param name string representation
*/
public ValueNamePair(final String value, final String name, final String help)
{
super(name, help);
m_value = value == null ? "" : value;
m_validationInformation = null;
} // ValueNamePair
public ValueNamePair(
final String value,
final String name,
final String help,
@Nullable final ValueNamePairValidationInformation validationInformation)
{
super(name, help);
m_value = value == null ? "" : value;
m_validationInformation = validationInformation;
} // ValueNamePair
/**
* The Value
*/
private final String m_value;
/**
* Get Value
*
* @return Value
*/
@JsonProperty("v") | public String getValue()
{
return m_value;
} // getValue
/**
* Get Validation Message
*
* @return Validation Message
*/
@JsonProperty("validationInformation")
@JsonInclude(JsonInclude.Include.NON_NULL)
public ValueNamePairValidationInformation getValidationInformation()
{
return m_validationInformation;
}
/**
* Get ID
*
* @return Value
*/
@Override
@JsonIgnore
public String getID()
{
return m_value;
} // getID
@Override
public boolean equals(final Object obj)
{
if (obj == this)
{
return true;
}
if (obj instanceof ValueNamePair)
{
final ValueNamePair other = (ValueNamePair)obj;
return Objects.equals(this.m_value, other.m_value)
&& Objects.equals(this.getName(), other.getName())
&& Objects.equals(this.m_validationInformation, other.m_validationInformation);
}
return false;
} // equals
@Override
public int hashCode()
{
return m_value.hashCode();
} // hashCode
} // KeyValuePair | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\ValueNamePair.java | 1 |
请完成以下Java代码 | private static AttributesKeyPattern parseSinglePartPattern(final String string)
{
if ("<ALL_STORAGE_ATTRIBUTES_KEYS>".equals(string))
{
return AttributesKeyPattern.ALL;
}
else if ("<OTHER_STORAGE_ATTRIBUTES_KEYS>".equals(string))
{
return AttributesKeyPattern.OTHER;
}
else
{
final AttributesKeyPartPattern partPattern = AttributesKeyPartPattern.parseString(string);
return AttributesKeyPattern.ofPart(partPattern);
}
}
public static AttributesKeyPattern ofAttributeKey(@NonNull final AttributesKey attributesKey)
{
if (attributesKey.isAll())
{
return AttributesKeyPattern.ALL;
}
else if (attributesKey.isOther())
{
return AttributesKeyPattern.OTHER;
}
else if (attributesKey.isNone())
{
return AttributesKeyPattern.NONE;
}
else
{
final ImmutableList<AttributesKeyPartPattern> partPatterns = attributesKey.getParts()
.stream()
.map(AttributesKeyPartPattern::ofAttributesKeyPart)
.collect(ImmutableList.toImmutableList());
return AttributesKeyPattern.ofParts(partPatterns);
}
}
public static List<AttributesKeyMatcher> extractAttributesKeyMatchers(@NonNull final List<AttributesKeyPattern> patterns)
{
if (patterns.isEmpty())
{
return ImmutableList.of(matchingAll());
} | else if (!patterns.contains(AttributesKeyPattern.OTHER))
{
return patterns.stream()
.map(AttributesKeyPatternsUtil::matching)
.collect(ImmutableList.toImmutableList());
}
else
{
final ImmutableSet<AttributesKeyMatcher> otherMatchers = patterns.stream()
.filter(AttributesKeyPattern::isSpecific)
.map(AttributesKeyPatternsUtil::matching)
.collect(ImmutableSet.toImmutableSet());
final AttributesKeyMatcher othersMatcher = ExcludeAttributesKeyMatcher.of(otherMatchers);
return patterns.stream()
.map(pattern -> pattern.isOther() ? othersMatcher : matching(pattern))
.collect(ImmutableList.toImmutableList());
}
}
public static AttributesKeyMatcher matchingAll()
{
return AcceptAllAttributesKeyMatcher.instance;
}
public static AttributesKeyMatcher matching(@NonNull final AttributesKeyPattern pattern)
{
if (pattern.isAll())
{
return AcceptAllAttributesKeyMatcher.instance;
}
return StandardAttributesKeyPatternMatcher.of(pattern);
}
public static AttributesKeyMatcher matching(@NonNull final AttributesKey attributesKey)
{
return matching(ofAttributeKey(attributesKey));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\keys\AttributesKeyPatternsUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OLCandWithUOMForTUsCapacityProvider implements IOLCandWithUOMForTUsCapacityProvider
{
private static final AdMessageKey MSG_TU_UOM_CAPACITY_REQUIRED = AdMessageKey.of("de.metas.handlingunits.ordercandidate.UOMForTUsCapacityRequired");
private final IUOMDAO uomDAO = Services.get(IUOMDAO.class);
private final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
private final IHUPackingAwareBL huPackingAwareBL = Services.get(IHUPackingAwareBL.class);
private final IOLCandEffectiveValuesBL olCandEffectiveValuesBL = Services.get(IOLCandEffectiveValuesBL.class);
@Override
public boolean isProviderNeededForOLCand(@NonNull final I_C_OLCand olCand)
{
final ProductId productId = ProductId.ofRepoIdOrNull(olCand.getM_Product_ID());
if (productId == null)
{
return false; // nothing to do
}
if (!isNull(olCand, I_C_OLCand.COLUMNNAME_QtyItemCapacityInternal))
{
return false; // already set; nothing to do
}
final UomId uomId = olCandEffectiveValuesBL.getEffectiveUomId(olCand);
return uomDAO.isUOMForTUs(uomId);
}
@NonNull
@Override
public Optional<Quantity> computeQtyItemCapacity(@NonNull final I_C_OLCand olCand) | {
final OLCandHUPackingAware huPackingAware = new OLCandHUPackingAware(olCand);
final Capacity capacity = huPackingAwareBL.calculateCapacity(huPackingAware);
if (capacity == null)
{
return Optional.empty();
}
final ProductId productId = ProductId.ofRepoId(olCand.getM_Product_ID());
// note that the product's stocking UOM is never a TU-UOM
if (capacity.isInfiniteCapacity())
{
return Optional.of(Quantity.infinite(capacity.getC_UOM()));
}
return Optional.of(uomConversionBL.convertToProductUOM(capacity.toQuantity(), productId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\ordercandidate\spi\impl\OLCandWithUOMForTUsCapacityProvider.java | 2 |
请完成以下Java代码 | public comment removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return (this);
}
protected String createStartTag()
{
setEndTagChar(' ');
StringBuffer out = new StringBuffer();
out.append(getStartTagChar());
if (getBeginStartModifierDefined())
{
out.append(getBeginStartModifier());
}
out.append(getElementType());
if (getBeginEndModifierDefined())
{
out.append(getBeginEndModifier());
}
out.append(getEndTagChar());
setEndTagChar('>'); // put back the end tag character.
return (out.toString());
}
protected String createEndTag()
{
StringBuffer out = new StringBuffer();
setStartTagChar(' '); | setEndStartModifier(' ');
out.append(getStartTagChar());
if (getEndStartModifierDefined())
{
out.append(getEndStartModifier());
}
out.append(getElementType());
if (getEndEndModifierDefined())
{
out.append(getEndEndModifier());
}
out.append(getEndTagChar());
setStartTagChar('<'); // put back the tag start character
return (out.toString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\comment.java | 1 |
请完成以下Java代码 | public String encodeNonNullPassword(String rawPassword) {
String salt = PREFIX + this.saltGenerator.generateKey() + SUFFIX;
return digest(salt, rawPassword);
}
private String digest(String salt, CharSequence rawPassword) {
if (rawPassword == null) {
rawPassword = "";
}
String saltedPassword = rawPassword + salt;
byte[] saltedPasswordBytes = Utf8.encode(saltedPassword);
Md4 md4 = new Md4();
md4.update(saltedPasswordBytes, 0, saltedPasswordBytes.length);
byte[] digest = md4.digest();
String encoded = encodedNonNullPassword(digest);
return salt + encoded;
}
private String encodedNonNullPassword(byte[] digest) {
if (this.encodeHashAsBase64) {
return Utf8.decode(Base64.getEncoder().encode(digest));
}
return new String(Hex.encode(digest));
}
/** | * Takes a previously encoded password and compares it with a rawpassword after mixing
* in the salt and encoding that value
* @param rawPassword plain text password
* @param encodedPassword previously encoded password
* @return true or false
*/
@Override
protected boolean matchesNonNull(String rawPassword, String encodedPassword) {
String salt = extractSalt(encodedPassword);
String rawPasswordEncoded = digest(salt, rawPassword);
return PasswordEncoderUtils.equals(encodedPassword.toString(), rawPasswordEncoded);
}
private String extractSalt(String prefixEncodedPassword) {
int start = prefixEncodedPassword.indexOf(PREFIX);
if (start != 0) {
return "";
}
int end = prefixEncodedPassword.indexOf(SUFFIX, start);
if (end < 0) {
return "";
}
return prefixEncodedPassword.substring(start, end + 1);
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password\Md4PasswordEncoder.java | 1 |
请完成以下Java代码 | public RecordAccessConfig getByRoleId(@NonNull final RoleId roleId)
{
return configs.getOrLoad(roleId, this::retrieveByRoleId);
}
private RecordAccessConfig retrieveByRoleId(@NonNull final RoleId roleId)
{
final List<I_AD_Role_Record_Access_Config> records = queryActiveConfigs()
.addEqualsFilter(I_AD_Role_Record_Access_Config.COLUMN_AD_Role_ID, roleId)
.create()
.list();
if (records.isEmpty())
{
return RecordAccessConfig.EMPTY;
}
final IADTableDAO adTablesRepo = Services.get(IADTableDAO.class);
//
//
final Set<String> manualHandledTableNames = new HashSet<>();
final Set<RecordAccessFeature> features = new HashSet<>();
for (final I_AD_Role_Record_Access_Config record : records)
{
final String type = record.getType();
if (X_AD_Role_Record_Access_Config.TYPE_Table.contentEquals(type))
{
final int adTableId = record.getAD_Table_ID();
if (adTableId <= 0)
{
logger.warn("Invalid config record because type=Table but AD_Table_ID is not set: {}", record);
continue;
}
final String tableName = adTablesRepo.retrieveTableName(adTableId);
if (tableName == null)
{
logger.warn("No table name found for AD_Table_ID={}", adTableId);
continue;
}
manualHandledTableNames.add(tableName);
}
else
{
features.add(RecordAccessFeature.of(type));
}
}
//
//
final Set<RecordAccessHandler> handlers = new HashSet<>();
handlers.addAll(allHandlers.handlingFeatureSet(features));
if (!manualHandledTableNames.isEmpty())
{
handlers.add(ManualRecordAccessHandler.ofTableNames(manualHandledTableNames));
}
//
//
if (handlers.isEmpty())
{ | return RecordAccessConfig.EMPTY;
}
return RecordAccessConfig.builder()
.handlers(CompositeRecordAccessHandler.of(handlers))
.build();
}
private IQueryBuilder<I_AD_Role_Record_Access_Config> queryActiveConfigs()
{
return Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_AD_Role_Record_Access_Config.class)
.addOnlyActiveRecordsFilter();
}
public boolean isFeatureEnabled(@NonNull final RecordAccessFeature feature)
{
return getAllEnabledFeatures()
.contains(feature);
}
private ImmutableSet<RecordAccessFeature> getAllEnabledFeatures()
{
return allEnabledFeaturesCache.getOrLoad(0, this::retrieveAllEnabledFeatures);
}
private ImmutableSet<RecordAccessFeature> retrieveAllEnabledFeatures()
{
final ImmutableSet<RecordAccessFeature> allEnabledFeatures = queryActiveConfigs()
.create()
.listDistinct(I_AD_Role_Record_Access_Config.COLUMNNAME_Type, String.class)
.stream()
.map(RecordAccessFeature::of)
.collect(ImmutableSet.toImmutableSet());
logger.info("Loaded all enabled features: {}", allEnabledFeatures);
return allEnabledFeatures;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\record_access\RecordAccessConfigService.java | 1 |
请完成以下Java代码 | public void setPrice (java.math.BigDecimal Price)
{
throw new IllegalArgumentException ("Price is virtual column"); }
/** Get Preis.
@return Price
*/
@Override
public java.math.BigDecimal getPrice ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); | if (bd == null)
return BigDecimal.ZERO;
return bd;
}
@Override
public void setSourceAmt (final @Nullable BigDecimal SourceAmt)
{
set_Value (COLUMNNAME_SourceAmt, SourceAmt);
}
@Override
public BigDecimal getSourceAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SourceAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSource_Currency_ID (final int Source_Currency_ID)
{
if (Source_Currency_ID < 1)
set_Value (COLUMNNAME_Source_Currency_ID, null);
else
set_Value (COLUMNNAME_Source_Currency_ID, Source_Currency_ID);
}
@Override
public int getSource_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Currency_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostDetail.java | 1 |
请完成以下Java代码 | public class M_InOut_AddToTransportationOrderProcess_GridView extends ViewBasedProcessTemplate implements IProcessPrecondition
{
@Param(parameterName = "M_ShipperTransportation_ID", mandatory = true)
private I_M_ShipperTransportation transportationOrder;
public static final AdMessageKey ALL_SELECTED_SHIPMENTS_SHOULD_BE_COMPLETED_MSG = AdMessageKey.of("de.metas.ui.web.inout.process.M_InOut_AddToTransportationOrderProcess.AllSelectedShipmentsShouldBeCompleted");
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (getSelectedRowIds().isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
final List<I_M_InOut> inOuts = getSelectedInOuts();
for (final I_M_InOut inOut : inOuts)
{
final DocStatus docStatus = DocStatus.ofCode(inOut.getDocStatus());
if (!docStatus.isCompleted())
{
return ProcessPreconditionsResolution.reject(Services.get(IMsgBL.class).getTranslatableMsgText(ALL_SELECTED_SHIPMENTS_SHOULD_BE_COMPLETED_MSG));
}
}
return ProcessPreconditionsResolution.accept();
}
private ImmutableList<I_M_InOut> getSelectedInOuts()
{
final IInOutDAO inOutDAO = Services.get(IInOutDAO.class);
return getSelectedRowIds()
.stream()
.map(rowId -> inOutDAO.getById(InOutId.ofRepoId(rowId.toInt()), I_M_InOut.class))
.collect(GuavaCollectors.toImmutableList());
} | @Override
protected String doIt() throws Exception
{
final DocStatus docStatus = DocStatus.ofCode(transportationOrder.getDocStatus());
if (docStatus.isCompleted())
{
// this error should not be thrown since we have AD_Val_Rule for the parameter
throw new AdempiereException("Transportation Order should not be closed");
}
final ImmutableList<InOutId> inOutIds = getSelectedInOuts()
.stream()
.map(it -> InOutId.ofRepoId(it.getM_InOut_ID()))
.collect(GuavaCollectors.toImmutableList());
final InOutToTransportationOrderService service = SpringContextHolder.instance.getBean(InOutToTransportationOrderService.class);
service.addShipmentsToTransportationOrder(ShipperTransportationId.ofRepoId(transportationOrder.getM_ShipperTransportation_ID()), inOutIds);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\inout\process\M_InOut_AddToTransportationOrderProcess_GridView.java | 1 |
请完成以下Java代码 | public void setApp(String app) {
this.app = app;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
public Double getCount() {
return count;
}
public void setCount(Double count) {
this.count = count;
}
public Long getInterval() {
return interval;
}
public void setInterval(Long interval) {
this.interval = interval;
}
public Integer getIntervalUnit() {
return intervalUnit;
}
public void setIntervalUnit(Integer intervalUnit) {
this.intervalUnit = intervalUnit;
}
public Integer getControlBehavior() {
return controlBehavior; | }
public void setControlBehavior(Integer controlBehavior) {
this.controlBehavior = controlBehavior;
}
public Integer getBurst() {
return burst;
}
public void setBurst(Integer burst) {
this.burst = burst;
}
public Integer getMaxQueueingTimeoutMs() {
return maxQueueingTimeoutMs;
}
public void setMaxQueueingTimeoutMs(Integer maxQueueingTimeoutMs) {
this.maxQueueingTimeoutMs = maxQueueingTimeoutMs;
}
public GatewayParamFlowItemVo getParamItem() {
return paramItem;
}
public void setParamItem(GatewayParamFlowItemVo paramItem) {
this.paramItem = paramItem;
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\gateway\rule\UpdateFlowRuleReqVo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
if (PARAM_Qty.equals(parameter.getColumnName()))
{
return getTask().getQtyToReserve().toZeroIfNegative().toBigDecimal();
}
if (PARAM_C_UOM_ID.equals(parameter.getColumnName()))
{
return getTask().getQtyToReserve().getUomId();
}
else
{
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
}
@Override
protected String doIt()
{
final Quantity qtyToReserve = getQtyToReserveParam();
final ImmutableSet<HuId> huIds = getSelectedTopLevelHUIds();
final ServiceRepairProjectTaskId taskId = getTaskId();
projectService.reserveSparePartsFromHUs(taskId, qtyToReserve, huIds);
tasksCache.clear();
return MSG_OK;
}
private Quantity getQtyToReserveParam()
{
final Quantity qtyToReserve = Quantitys.of(qty, uomId);
if (qtyToReserve.signum() <= 0)
{
throw new FillMandatoryException(PARAM_Qty);
}
return qtyToReserve;
}
private ServiceRepairProjectTask getTask()
{ | return tasksCache.computeIfAbsent(getTaskId(), projectService::getTaskById);
}
private ServiceRepairProjectTaskId getTaskId()
{
final HUsToIssueViewContext husToIssueViewContext = getHusToIssueViewContext();
return husToIssueViewContext.getTaskId();
}
private ImmutableSet<HuId> getSelectedTopLevelHUIds()
{
return streamSelectedHUIds(HUEditorRowFilter.Select.ONLY_TOPLEVEL).collect(ImmutableSet.toImmutableSet());
}
private HUsToIssueViewContext getHusToIssueViewContext()
{
return getView()
.getParameter(HUsToIssueViewFactory.PARAM_HUsToIssueViewContext, HUsToIssueViewContext.class)
.orElseThrow(() -> new AdempiereException("No view context"));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\project\process\HUsToIssueView_IssueHUs.java | 2 |
请完成以下Java代码 | public String toString()
{
return ObjectUtils.toString(this);
}
@Override
public int release()
{
return lockDatabase.unlock(this);
}
@Override
public Future<Integer> releaseAfterTrxCommit(final String trxName)
{
final FutureValue<Integer> countUnlockedFuture = new FutureValue<>();
final ITrxManager trxManager = Services.get(ITrxManager.class);
trxManager.getTrxListenerManagerOrAutoCommit(trxName)
.newEventListener(TrxEventTiming.AFTER_COMMIT)
.invokeMethodJustOnce(false) // invoke the handling method on *every* commit, because that's how it was and I can't check now if it's really needed
.registerHandlingMethod(innerTrx -> {
try
{
final int countUnlocked = release();
countUnlockedFuture.set(countUnlocked);
}
catch (Exception e)
{
countUnlockedFuture.setError(e);
}
});
return countUnlockedFuture;
}
@Override
public IUnlockCommand setOwner(final LockOwner owner)
{
this.owner = owner;
return this;
}
@Override
public final LockOwner getOwner()
{
Check.assumeNotNull(owner, UnlockFailedException.class, "owner not null");
return this.owner;
}
@Override
public IUnlockCommand setRecordByModel(final Object model)
{
_recordsToUnlock.setRecordByModel(model);
return this; | }
@Override
public IUnlockCommand setRecordsByModels(final Collection<?> models)
{
_recordsToUnlock.setRecordsByModels(models);
return this;
}
@Override
public IUnlockCommand setRecordByTableRecordId(final int tableId, final int recordId)
{
_recordsToUnlock.setRecordByTableRecordId(tableId, recordId);
return this;
}
@Override
public IUnlockCommand setRecordByTableRecordId(final String tableName, final int recordId)
{
_recordsToUnlock.setRecordByTableRecordId(tableName, recordId);
return this;
}
@Override
public IUnlockCommand setRecordsBySelection(final Class<?> modelClass, final PInstanceId adPIstanceId)
{
_recordsToUnlock.setRecordsBySelection(modelClass, adPIstanceId);
return this;
}
@Override
public final AdTableId getSelectionToUnlock_AD_Table_ID()
{
return _recordsToUnlock.getSelection_AD_Table_ID();
}
@Override
public final PInstanceId getSelectionToUnlock_AD_PInstance_ID()
{
return _recordsToUnlock.getSelection_PInstanceId();
}
@Override
public final Iterator<TableRecordReference> getRecordsToUnlockIterator()
{
return _recordsToUnlock.getRecordsIterator();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\UnlockCommand.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.