instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public void setImpEx_Connector_ID (int ImpEx_Connector_ID)
{
if (ImpEx_Connector_ID < 1)
set_ValueNoCheck (COLUMNNAME_ImpEx_Connector_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ImpEx_Connector_ID, Integer.valueOf(ImpEx_Connector_ID));
}
/** Get Konnektor.
@return Konnektor */
public int getImpEx_Connector_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_Connector_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Konnektor-Parameter.
@param Impex_ConnectorParam_ID Konnektor-Parameter */
public void setImpex_ConnectorParam_ID (int Impex_ConnectorParam_ID)
{
if (Impex_ConnectorParam_ID < 1)
set_ValueNoCheck (COLUMNNAME_Impex_ConnectorParam_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Impex_ConnectorParam_ID, Integer.valueOf(Impex_ConnectorParam_ID));
}
/** Get Konnektor-Parameter.
@return Konnektor-Parameter */
public int getImpex_ConnectorParam_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Impex_ConnectorParam_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
|
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Parameter-Name.
@param ParamName Parameter-Name */
public void setParamName (String ParamName)
{
set_Value (COLUMNNAME_ParamName, ParamName);
}
/** Get Parameter-Name.
@return Parameter-Name */
public String getParamName ()
{
return (String)get_Value(COLUMNNAME_ParamName);
}
/** Set Parameterwert.
@param ParamValue Parameterwert */
public void setParamValue (String ParamValue)
{
set_Value (COLUMNNAME_ParamValue, ParamValue);
}
/** Get Parameterwert.
@return Parameterwert */
public String getParamValue ()
{
return (String)get_Value(COLUMNNAME_ParamValue);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_Impex_ConnectorParam.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int updateStatus(Long id, OmsUpdateStatusParam statusParam) {
Integer status = statusParam.getStatus();
OmsOrderReturnApply returnApply = new OmsOrderReturnApply();
if(status.equals(1)){
//确认退货
returnApply.setId(id);
returnApply.setStatus(1);
returnApply.setReturnAmount(statusParam.getReturnAmount());
returnApply.setCompanyAddressId(statusParam.getCompanyAddressId());
returnApply.setHandleTime(new Date());
returnApply.setHandleMan(statusParam.getHandleMan());
returnApply.setHandleNote(statusParam.getHandleNote());
}else if(status.equals(2)){
//完成退货
returnApply.setId(id);
returnApply.setStatus(2);
returnApply.setReceiveTime(new Date());
returnApply.setReceiveMan(statusParam.getReceiveMan());
returnApply.setReceiveNote(statusParam.getReceiveNote());
}else if(status.equals(3)){
//拒绝退货
|
returnApply.setId(id);
returnApply.setStatus(3);
returnApply.setHandleTime(new Date());
returnApply.setHandleMan(statusParam.getHandleMan());
returnApply.setHandleNote(statusParam.getHandleNote());
}else{
return 0;
}
return returnApplyMapper.updateByPrimaryKeySelective(returnApply);
}
@Override
public OmsOrderReturnApplyResult getItem(Long id) {
return returnApplyDao.getDetail(id);
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\OmsOrderReturnApplyServiceImpl.java
| 2
|
请完成以下Java代码
|
void add_feature(int key, double value)
{
feature_.put(key, value);
}
/**
* Set features.
*
* @param feature a feature vector
*/
void set_features(SparseVector feature)
{
feature_ = feature;
}
/**
* Clear features.
*/
void clear()
{
feature_.clear();
}
/**
* Apply IDF(inverse document frequency) weighting.
*
* @param df document frequencies
* @param ndocs the number of documents
*/
void idf(HashMap<Integer, Integer> df, int ndocs)
{
for (Map.Entry<Integer, Double> entry : feature_.entrySet())
{
|
Integer denom = df.get(entry.getKey());
if (denom == null) denom = 1;
entry.setValue((double) (entry.getValue() * Math.log(ndocs / denom)));
}
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Document<?> document = (Document<?>) o;
return id_ != null ? id_.equals(document.id_) : document.id_ == null;
}
@Override
public int hashCode()
{
return id_ != null ? id_.hashCode() : 0;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\cluster\Document.java
| 1
|
请完成以下Java代码
|
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof CustomerShortNames)) {
return false;
}
CustomerShortNames other = (CustomerShortNames) obj;
return Objects.equals(city, other.city) && Objects.equals(email, other.email) && Objects.equals(firstName, other.firstName) && id == other.id && Objects.equals(lastName, other.lastName) && Objects.equals(phoneNumber, other.phoneNumber)
&& Objects.equals(postalCode, other.postalCode) && Objects.equals(state, other.state) && Objects.equals(street, other.street);
}
@Override
public String toString() {
return "CustomerWithShorterAttributes [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", street=" + street + ", postalCode=" + postalCode + ", city=" + city + ", state=" + state + ", phoneNumber=" + phoneNumber + ", email=" + email
+ "]";
}
public static CustomerShortNames[] fromCustomers(Customer[] customers) {
CustomerShortNames[] feedback = new CustomerShortNames[customers.length];
|
for (int i = 0; i < customers.length; i++) {
Customer aCustomer = customers[i];
CustomerShortNames newOne = new CustomerShortNames();
newOne.setId(aCustomer.getId());
newOne.setFirstName(aCustomer.getFirstName());
newOne.setLastName(aCustomer.getLastName());
newOne.setStreet(aCustomer.getStreet());
newOne.setCity(aCustomer.getCity());
newOne.setPostalCode(aCustomer.getPostalCode());
newOne.setState(aCustomer.getState());
newOne.setPhoneNumber(aCustomer.getPhoneNumber());
newOne.setEmail(aCustomer.getEmail());
feedback[i] = newOne;
}
return feedback;
}
}
|
repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonoptimization\CustomerShortNames.java
| 1
|
请完成以下Java代码
|
public class SetDeploymentCategoryCmd implements Command<Void> {
protected String deploymentId;
protected String category;
public SetDeploymentCategoryCmd(String deploymentId, String category) {
this.deploymentId = deploymentId;
this.category = category;
}
public Void execute(CommandContext commandContext) {
if (deploymentId == null) {
throw new ActivitiIllegalArgumentException("Deployment id is null");
}
DeploymentEntity deployment = commandContext.getDeploymentEntityManager().findById(deploymentId);
if (deployment == null) {
throw new ActivitiObjectNotFoundException(
"No deployment found for id = '" + deploymentId + "'",
Deployment.class
);
}
executeInternal(commandContext, deployment);
return null;
}
|
protected void executeInternal(CommandContext commandContext, DeploymentEntity deployment) {
// Update category
deployment.setCategory(category);
if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
commandContext
.getProcessEngineConfiguration()
.getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_UPDATED, deployment));
}
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SetDeploymentCategoryCmd.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BigDecimal getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setValue(BigDecimal value) {
this.value = value;
}
/**
* The VAT code for the used tax rate.
*
* @return
* possible object is
* {@link String }
*
|
*/
public String getTaxCode() {
return taxCode;
}
/**
* Sets the value of the taxCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTaxCode(String value) {
this.taxCode = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\TaxRateType.java
| 2
|
请完成以下Java代码
|
public String getErrorMessage() {
return errorMessage;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTypeName() {
if(value != null) {
return value.getType().getName();
}
else {
return null;
}
}
public String getName() {
return name;
}
public Object getValue() {
if(value != null) {
return value.getValue();
}
else {
return null;
}
}
public TypedValue getTypedValue() {
|
return value;
}
public ProcessEngineServices getProcessEngineServices() {
return Context.getProcessEngineConfiguration().getProcessEngine();
}
public ProcessEngine getProcessEngine() {
return Context.getProcessEngineConfiguration().getProcessEngine();
}
public static DelegateCaseVariableInstanceImpl fromVariableInstance(VariableInstance variableInstance) {
DelegateCaseVariableInstanceImpl delegateInstance = new DelegateCaseVariableInstanceImpl();
delegateInstance.variableId = variableInstance.getId();
delegateInstance.processDefinitionId = variableInstance.getProcessDefinitionId();
delegateInstance.processInstanceId = variableInstance.getProcessInstanceId();
delegateInstance.executionId = variableInstance.getExecutionId();
delegateInstance.caseExecutionId = variableInstance.getCaseExecutionId();
delegateInstance.caseInstanceId = variableInstance.getCaseInstanceId();
delegateInstance.taskId = variableInstance.getTaskId();
delegateInstance.activityInstanceId = variableInstance.getActivityInstanceId();
delegateInstance.tenantId = variableInstance.getTenantId();
delegateInstance.errorMessage = variableInstance.getErrorMessage();
delegateInstance.name = variableInstance.getName();
delegateInstance.value = variableInstance.getTypedValue();
return delegateInstance;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\listener\DelegateCaseVariableInstanceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class ProcessEngineConfigurationImplDependingConfiguration {
@Autowired
protected ProcessEngineConfigurationImpl processEngineConfigurationImpl;
@Bean
public ProcessEngineFactoryBean processEngineFactoryBean() {
final ProcessEngineFactoryBean factoryBean = new ProcessEngineFactoryBean();
factoryBean.setProcessEngineConfiguration(processEngineConfigurationImpl);
return factoryBean;
}
@Bean
@Primary
public CommandExecutor commandExecutorTxRequired() {
return processEngineConfigurationImpl.getCommandExecutorTxRequired();
}
@Bean
public CommandExecutor commandExecutorTxRequiresNew() {
return processEngineConfigurationImpl.getCommandExecutorTxRequiresNew();
}
|
@Bean
public CommandExecutor commandExecutorSchemaOperations() {
return processEngineConfigurationImpl.getCommandExecutorSchemaOperations();
}
}
@Bean
public CamundaBpmVersion camundaBpmVersion() {
return new CamundaBpmVersion();
}
@Bean
public ProcessApplicationEventPublisher processApplicationEventPublisher(ApplicationEventPublisher publisher) {
return new ProcessApplicationEventPublisher(publisher);
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\CamundaBpmAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private static class CurrencyAndRate
{
@NonNull CurrencyId currencyId;
@NonNull BigDecimal currencyRate;
private CurrencyAndRate(@NonNull final CurrencyId currencyId, @NonNull final BigDecimal currencyRate)
{
this.currencyId = currencyId;
this.currencyRate = NumberUtils.stripTrailingDecimalZeros(currencyRate);
}
}
@Value
@Builder(toBuilder = true)
private static class AmountSourceAndAcct
{
@NonNull CurrencyAndRate currencyAndRate;
@NonNull BigDecimal amtSource;
@NonNull BigDecimal amtAcct;
public static AmountSourceAndAcct zero(@NonNull final CurrencyAndRate currencyAndRate)
{
return builder().currencyAndRate(currencyAndRate).amtSource(BigDecimal.ZERO).amtAcct(BigDecimal.ZERO).build();
}
public boolean isZero()
{
return amtSource.signum() == 0 && amtAcct.signum() == 0;
}
public boolean isZeroAmtSource()
{
return amtSource.signum() == 0;
}
public AmountSourceAndAcct negate()
{
return isZero()
? this
: toBuilder().amtSource(this.amtSource.negate()).amtAcct(this.amtAcct.negate()).build();
}
public AmountSourceAndAcct add(@NonNull final AmountSourceAndAcct other)
{
|
assertCurrencyAndRateMatching(other);
if (other.isZero())
{
return this;
}
else if (this.isZero())
{
return other;
}
else
{
return toBuilder()
.amtSource(this.amtSource.add(other.amtSource))
.amtAcct(this.amtAcct.add(other.amtAcct))
.build();
}
}
public AmountSourceAndAcct subtract(@NonNull final AmountSourceAndAcct other)
{
return add(other.negate());
}
private void assertCurrencyAndRateMatching(@NonNull final AmountSourceAndAcct other)
{
if (!Objects.equals(this.currencyAndRate, other.currencyAndRate))
{
throw new AdempiereException("Currency rate not matching: " + this.currencyAndRate + ", " + other.currencyAndRate);
}
}
}
} // Doc_Bank
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\acct\Doc_BankStatement.java
| 2
|
请完成以下Java代码
|
public java.lang.String getUOMSymbol()
{
return get_ValueAsString(COLUMNNAME_UOMSymbol);
}
/**
* UOMType AD_Reference_ID=53323
* Reference name: UOM Type
*/
public static final int UOMTYPE_AD_Reference_ID=53323;
/** Angle = AN */
public static final String UOMTYPE_Angle = "AN";
/** Area = AR */
public static final String UOMTYPE_Area = "AR";
/** Data Storage = DS */
public static final String UOMTYPE_DataStorage = "DS";
/** Density = DE */
public static final String UOMTYPE_Density = "DE";
/** Energy = EN */
public static final String UOMTYPE_Energy = "EN";
/** Force = FO */
public static final String UOMTYPE_Force = "FO";
/** Kitchen Measures = KI */
public static final String UOMTYPE_KitchenMeasures = "KI";
/** Length = LE */
public static final String UOMTYPE_Length = "LE";
/** Power = PO */
public static final String UOMTYPE_Power = "PO";
/** Pressure = PR */
public static final String UOMTYPE_Pressure = "PR";
/** Temperature = TE */
public static final String UOMTYPE_Temperature = "TE";
/** Time = TM */
public static final String UOMTYPE_Time = "TM";
/** Torque = TO */
public static final String UOMTYPE_Torque = "TO";
/** Velocity = VE */
public static final String UOMTYPE_Velocity = "VE";
/** Volume Liquid = VL */
public static final String UOMTYPE_VolumeLiquid = "VL";
/** Volume Dry = VD */
public static final String UOMTYPE_VolumeDry = "VD";
/** Weigth = WE */
public static final String UOMTYPE_Weigth = "WE";
/** Currency = CU */
public static final String UOMTYPE_Currency = "CU";
/** Data Speed = DV */
public static final String UOMTYPE_DataSpeed = "DV";
/** Frequency = FR */
public static final String UOMTYPE_Frequency = "FR";
/** Other = OT */
public static final String UOMTYPE_Other = "OT";
|
/** Gesundheitswesen = HC */
public static final String UOMTYPE_Gesundheitswesen = "HC";
/** Zeit (Erfassungsgenauigkeit) = TD */
public static final String UOMTYPE_ZeitErfassungsgenauigkeit = "TD";
@Override
public void setUOMType (final java.lang.String UOMType)
{
set_Value (COLUMNNAME_UOMType, UOMType);
}
@Override
public java.lang.String getUOMType()
{
return get_ValueAsString(COLUMNNAME_UOMType);
}
@Override
public void setX12DE355 (final java.lang.String X12DE355)
{
set_Value (COLUMNNAME_X12DE355, X12DE355);
}
@Override
public java.lang.String getX12DE355()
{
return get_ValueAsString(COLUMNNAME_X12DE355);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_UOM.java
| 1
|
请完成以下Java代码
|
public void setPP_Order_Candidate(final org.eevolution.model.I_PP_Order_Candidate PP_Order_Candidate)
{
set_ValueFromPO(COLUMNNAME_PP_Order_Candidate_ID, org.eevolution.model.I_PP_Order_Candidate.class, PP_Order_Candidate);
}
@Override
public void setPP_Order_Candidate_ID (final int PP_Order_Candidate_ID)
{
if (PP_Order_Candidate_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Candidate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Candidate_ID, PP_Order_Candidate_ID);
}
@Override
public int getPP_Order_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Candidate_ID);
}
@Override
public void setPP_OrderLine_Candidate_ID (final int PP_OrderLine_Candidate_ID)
{
if (PP_OrderLine_Candidate_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_OrderLine_Candidate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_OrderLine_Candidate_ID, PP_OrderLine_Candidate_ID);
}
@Override
public int getPP_OrderLine_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_OrderLine_Candidate_ID);
}
@Override
public org.eevolution.model.I_PP_Product_BOMLine getPP_Product_BOMLine()
{
return get_ValueAsPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class);
}
@Override
public void setPP_Product_BOMLine(final org.eevolution.model.I_PP_Product_BOMLine PP_Product_BOMLine)
{
set_ValueFromPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class, PP_Product_BOMLine);
}
@Override
|
public void setPP_Product_BOMLine_ID (final int PP_Product_BOMLine_ID)
{
if (PP_Product_BOMLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Product_BOMLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Product_BOMLine_ID, PP_Product_BOMLine_ID);
}
@Override
public int getPP_Product_BOMLine_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Product_BOMLine_ID);
}
@Override
public void setQtyEntered (final @Nullable BigDecimal QtyEntered)
{
set_Value (COLUMNNAME_QtyEntered, QtyEntered);
}
@Override
public BigDecimal getQtyEntered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_OrderLine_Candidate.java
| 1
|
请完成以下Java代码
|
public class ShiftSchedule {
@ValueRangeProvider
private List<Employee> employees;
@PlanningEntityCollectionProperty
private List<Shift> shifts;
@PlanningScore
private HardSoftScore score;
// A no-arg constructor is required for @PlanningSolution annotated classes
public ShiftSchedule() {
}
public ShiftSchedule(List<Employee> employees, List<Shift> shifts) {
this.employees = employees;
|
this.shifts = shifts;
}
public List<Employee> getEmployees() {
return employees;
}
public List<Shift> getShifts() {
return shifts;
}
public HardSoftScore getScore() {
return score;
}
}
|
repos\tutorials-master\timefold-solver\src\main\java\com\baeldung\timefoldsolver\ShiftSchedule.java
| 1
|
请完成以下Java代码
|
static boolean checkUsingPatternClass(String input) {
if (input == null || input.isEmpty()) {
return false;
}
return Pattern.compile(".*\\d.*")
.matcher(input)
.matches();
}
static boolean checkUsingReplaceAllMethod(String input) {
if (input == null || input.isEmpty()) {
return false;
}
String result = input.replaceAll("\\d", "");
return result.length() != input.length();
}
static boolean checkUsingIsDigitMethod(String input) {
if (input == null || input.isEmpty()) {
return false;
}
for (char c : input.toCharArray()) {
if (Character.isDigit(c)) {
return true;
}
}
return false;
}
static boolean checkUsingStreamApi(String input) {
if (input == null || input.isEmpty()) {
|
return false;
}
return input.chars()
.anyMatch(Character::isDigit);
}
static boolean checkUsingApacheCommonsLang(String input) {
String result = StringUtils.getDigits(input);
return result != null && !result.isEmpty();
}
static boolean checkUsingGuava(String input) {
if (input == null || input.isEmpty()) {
return false;
}
String result = CharMatcher.forPredicate(Character::isDigit)
.retainFrom(input);
return !result.isEmpty();
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-operations-11\src\main\java\com\baeldung\strcontainsnumber\StrContainsNumberUtils.java
| 1
|
请完成以下Java代码
|
protected void setCalendarHour(Calendar cal, int hour) {
cal.set(Calendar.HOUR_OF_DAY, hour);
if (cal.get(Calendar.HOUR_OF_DAY) != hour && hour != 24) {
cal.set(Calendar.HOUR_OF_DAY, hour + 1);
}
}
/**
* NOT YET IMPLEMENTED: Returns the time before the given time
* that the <code>CronExpression</code> matches.
*/
public Date getTimeBefore(Date endTime) {
// FUTURE_TODO: implement QUARTZ-423
return null;
}
/**
* NOT YET IMPLEMENTED: Returns the final time that the
* <code>CronExpression</code> will match.
*/
public Date getFinalFireTime() {
// FUTURE_TODO: implement QUARTZ-423
return null;
}
protected boolean isLeapYear(int year) {
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
}
protected int getLastDayOfMonth(int monthNum, int year) {
switch (monthNum) {
case 1:
return 31;
case 2:
return (isLeapYear(year)) ? 29 : 28;
case 3:
return 31;
case 4:
return 30;
case 5:
return 31;
case 6:
return 30;
case 7:
return 31;
case 8:
return 31;
case 9:
return 30;
case 10:
return 31;
case 11:
return 30;
case 12:
|
return 31;
default:
throw new IllegalArgumentException("Illegal month number: "
+ monthNum);
}
}
private void readObject(java.io.ObjectInputStream stream)
throws java.io.IOException, ClassNotFoundException {
stream.defaultReadObject();
try {
buildExpression(cronExpression);
} catch (Exception ignore) {
} // never happens
}
@Override
@Deprecated
public Object clone() {
return new CronExpression(this);
}
}
class ValueSet {
public int value;
public int pos;
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\cron\CronExpression.java
| 1
|
请完成以下Java代码
|
public class UniqueRng implements Iterator<Integer> {
private int size;
private List<Integer> numbers = new ArrayList<>();
public UniqueRng(int size, boolean zeroBased) {
this.size = size;
int start = (zeroBased ? 0 : 1);
int limit = (zeroBased ? size - 1 : size);
for (int i = start; i <= limit; i++) {
numbers.add(i);
}
Collections.shuffle(numbers);
}
@Override
public Integer next() {
|
if (!hasNext())
throw new NoSuchElementException();
return numbers.remove(0);
}
@Override
public boolean hasNext() {
return !numbers.isEmpty();
}
public int getSize() {
return size;
}
}
|
repos\tutorials-master\core-java-modules\core-java-numbers-5\src\main\java\com\baeldung\uniquerng\UniqueRng.java
| 1
|
请完成以下Java代码
|
public class ListToMapConverter {
public Map<Integer, List<String>> groupingByStringLength(List<String> source,
Supplier<Map<Integer, List<String>>> mapSupplier,
Supplier<List<String>> listSupplier) {
return source.stream()
.collect(Collectors.groupingBy(String::length, mapSupplier, Collectors.toCollection(listSupplier)));
}
public Map<Integer, List<String>> streamCollectByStringLength(List<String> source,
Supplier<Map<Integer, List<String>>> mapSupplier,
Supplier<List<String>> listSupplier) {
BiConsumer<Map<Integer, List<String>>, String> accumulator = (response, element) -> {
Integer key = element.length();
List<String> values = response.getOrDefault(key, listSupplier.get());
values.add(element);
response.put(key, values);
};
BiConsumer<Map<Integer, List<String>>, Map<Integer, List<String>>> combiner = (res1, res2) -> {
res1.putAll(res2);
};
return source.stream()
.collect(mapSupplier, accumulator, combiner);
}
public Map<Integer, List<String>> collectorToMapByStringLength(List<String> source,
Supplier<Map<Integer, List<String>>> mapSupplier,
Supplier<List<String>> listSupplier) {
Function<String, Integer> keyMapper = String::length;
|
Function<String, List<String>> valueMapper = (element) -> {
List<String> collection = listSupplier.get();
collection.add(element);
return collection;
};
BinaryOperator<List<String>> mergeFunction = (existing, replacement) -> {
existing.addAll(replacement);
return existing;
};
return source.stream()
.collect(Collectors.toMap(keyMapper, valueMapper, mergeFunction, mapSupplier));
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-conversions-4\src\main\java\com\baeldung\convertlisttomap\ListToMapConverter.java
| 1
|
请完成以下Java代码
|
public void setValueDateInitial (final @Nullable java.sql.Timestamp ValueDateInitial)
{
set_Value (COLUMNNAME_ValueDateInitial, ValueDateInitial);
}
@Override
public java.sql.Timestamp getValueDateInitial()
{
return get_ValueAsTimestamp(COLUMNNAME_ValueDateInitial);
}
@Override
public void setValueInitial (final @Nullable java.lang.String ValueInitial)
{
set_ValueNoCheck (COLUMNNAME_ValueInitial, ValueInitial);
}
@Override
public java.lang.String getValueInitial()
{
return get_ValueAsString(COLUMNNAME_ValueInitial);
}
@Override
public void setValueNumber (final @Nullable BigDecimal ValueNumber)
{
set_Value (COLUMNNAME_ValueNumber, ValueNumber);
}
@Override
public BigDecimal getValueNumber()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber);
return bd != null ? bd : BigDecimal.ZERO;
|
}
@Override
public void setValueNumberInitial (final @Nullable BigDecimal ValueNumberInitial)
{
set_ValueNoCheck (COLUMNNAME_ValueNumberInitial, ValueNumberInitial);
}
@Override
public BigDecimal getValueNumberInitial()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumberInitial);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Attribute.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected int getMgmtThreadPoolSize() {
return Math.max(Runtime.getRuntime().availableProcessors(), 4);
}
@Override
protected TbQueueConsumer<TbProtoQueueMsg<ToCalculatedFieldNotificationMsg>> createNotificationsConsumer() {
return queueFactory.createToCalculatedFieldNotificationMsgConsumer();
}
@Override
protected void handleNotification(UUID id, TbProtoQueueMsg<ToCalculatedFieldNotificationMsg> msg, TbCallback callback) {
ToCalculatedFieldNotificationMsg toCfNotification = msg.getValue();
if (toCfNotification.hasLinkedTelemetryMsg()) {
forwardToActorSystem(toCfNotification.getLinkedTelemetryMsg(), callback);
}
}
@EventListener
public void handleComponentLifecycleEvent(ComponentLifecycleMsg event) {
if (event.getEntityId().getEntityType() == EntityType.TENANT) {
if (event.getEvent() == ComponentLifecycleEvent.DELETED) {
Set<TopicPartitionInfo> partitions = stateService.getPartitions();
if (CollectionUtils.isEmpty(partitions)) {
return;
}
stateService.delete(partitions.stream()
.filter(tpi -> tpi.getTenantId().isPresent() && tpi.getTenantId().get().equals(event.getTenantId()))
.collect(Collectors.toSet()));
}
}
}
private void forwardToActorSystem(CalculatedFieldTelemetryMsgProto msg, TbCallback callback) {
var tenantId = toTenantId(msg.getTenantIdMSB(), msg.getTenantIdLSB());
var entityId = EntityIdFactory.getByTypeAndUuid(msg.getEntityType(), new UUID(msg.getEntityIdMSB(), msg.getEntityIdLSB()));
actorContext.tell(new CalculatedFieldTelemetryMsg(tenantId, entityId, msg, callback));
|
}
private void forwardToActorSystem(CalculatedFieldLinkedTelemetryMsgProto linkedMsg, TbCallback callback) {
var msg = linkedMsg.getMsg();
var tenantId = toTenantId(msg.getTenantIdMSB(), msg.getTenantIdLSB());
var entityId = EntityIdFactory.getByTypeAndUuid(msg.getEntityType(), new UUID(msg.getEntityIdMSB(), msg.getEntityIdLSB()));
actorContext.tell(new CalculatedFieldLinkedTelemetryMsg(tenantId, entityId, linkedMsg, callback));
}
private TenantId toTenantId(long tenantIdMSB, long tenantIdLSB) {
return TenantId.fromUUID(new UUID(tenantIdMSB, tenantIdLSB));
}
@Override
protected void stopConsumers() {
super.stopConsumers();
stateService.stop(); // eventConsumer will be stopped by stateService
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\DefaultTbCalculatedFieldConsumerService.java
| 2
|
请完成以下Java代码
|
public String getBIC() {
return bic;
}
/**
* Sets the value of the bic property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBIC(String value) {
this.bic = value;
}
/**
* Gets the value of the clrSysMmbId property.
*
* @return
* possible object is
* {@link ClearingSystemMemberIdentification2 }
*
*/
public ClearingSystemMemberIdentification2 getClrSysMmbId() {
return clrSysMmbId;
}
/**
* Sets the value of the clrSysMmbId property.
*
* @param value
* allowed object is
* {@link ClearingSystemMemberIdentification2 }
*
*/
public void setClrSysMmbId(ClearingSystemMemberIdentification2 value) {
this.clrSysMmbId = value;
}
/**
* Gets the value of the nm property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNm() {
return nm;
}
/**
* Sets the value of the nm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNm(String value) {
this.nm = value;
}
/**
* Gets the value of the pstlAdr property.
*
* @return
|
* possible object is
* {@link PostalAddress6 }
*
*/
public PostalAddress6 getPstlAdr() {
return pstlAdr;
}
/**
* Sets the value of the pstlAdr property.
*
* @param value
* allowed object is
* {@link PostalAddress6 }
*
*/
public void setPstlAdr(PostalAddress6 value) {
this.pstlAdr = value;
}
/**
* Gets the value of the othr property.
*
* @return
* possible object is
* {@link GenericFinancialIdentification1 }
*
*/
public GenericFinancialIdentification1 getOthr() {
return othr;
}
/**
* Sets the value of the othr property.
*
* @param value
* allowed object is
* {@link GenericFinancialIdentification1 }
*
*/
public void setOthr(GenericFinancialIdentification1 value) {
this.othr = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\FinancialInstitutionIdentification7.java
| 1
|
请完成以下Java代码
|
protected static class HeapDumperUnavailableException extends RuntimeException {
public HeapDumperUnavailableException(String message, Throwable cause) {
super(message, cause);
}
}
private static final class TemporaryFileSystemResource extends FileSystemResource {
private final Log logger = LogFactory.getLog(getClass());
private TemporaryFileSystemResource(File file) {
super(file);
}
@Override
public ReadableByteChannel readableChannel() throws IOException {
ReadableByteChannel readableChannel = super.readableChannel();
return new ReadableByteChannel() {
@Override
public boolean isOpen() {
return readableChannel.isOpen();
}
@Override
public void close() throws IOException {
closeThenDeleteFile(readableChannel);
}
@Override
public int read(ByteBuffer dst) throws IOException {
return readableChannel.read(dst);
}
};
}
@Override
public InputStream getInputStream() throws IOException {
return new FilterInputStream(super.getInputStream()) {
|
@Override
public void close() throws IOException {
closeThenDeleteFile(this.in);
}
};
}
private void closeThenDeleteFile(Closeable closeable) throws IOException {
try {
closeable.close();
}
finally {
deleteFile();
}
}
private void deleteFile() {
try {
Files.delete(getFile().toPath());
}
catch (IOException ex) {
TemporaryFileSystemResource.this.logger
.warn("Failed to delete temporary heap dump file '" + getFile() + "'", ex);
}
}
@Override
public boolean isFile() {
// Prevent zero-copy so we can delete the file on close
return false;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\management\HeapDumpWebEndpoint.java
| 1
|
请完成以下Java代码
|
public class SpringRestClient {
private static final String GET_EMPLOYEES_ENDPOINT_URL = "http://localhost:8080/api/v1/employees";
private static final String GET_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees/{id}";
private static final String CREATE_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees";
private static final String UPDATE_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees/{id}";
private static final String DELETE_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees/{id}";
private static RestTemplate restTemplate = new RestTemplate();
public static void main(String[] args) {
SpringRestClient springRestClient = new SpringRestClient();
// Step1: first create a new employee
springRestClient.createEmployee();
// Step 2: get new created employee from step1
springRestClient.getEmployeeById();
// Step3: get all employees
springRestClient.getEmployees();
// Step4: Update employee with id = 1
springRestClient.updateEmployee();
// Step5: Delete employee with id = 1
springRestClient.deleteEmployee();
}
private void getEmployees() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> result = restTemplate.exchange(GET_EMPLOYEES_ENDPOINT_URL, HttpMethod.GET, entity,
String.class);
System.out.println(result);
}
private void getEmployeeById() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");
RestTemplate restTemplate = new RestTemplate();
Employee result = restTemplate.getForObject(GET_EMPLOYEE_ENDPOINT_URL, Employee.class, params);
System.out.println(result);
}
private void createEmployee() {
|
Employee newEmployee = new Employee("admin", "admin", "admin@gmail.com");
RestTemplate restTemplate = new RestTemplate();
Employee result = restTemplate.postForObject(CREATE_EMPLOYEE_ENDPOINT_URL, newEmployee, Employee.class);
System.out.println(result);
}
private void updateEmployee() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");
Employee updatedEmployee = new Employee("admin123", "admin123", "admin123@gmail.com");
RestTemplate restTemplate = new RestTemplate();
restTemplate.put(UPDATE_EMPLOYEE_ENDPOINT_URL, updatedEmployee, params);
}
private void deleteEmployee() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");
RestTemplate restTemplate = new RestTemplate();
restTemplate.delete(DELETE_EMPLOYEE_ENDPOINT_URL, params);
}
}
|
repos\Spring-Boot-Advanced-Projects-main\spring-aop-advice-examples\src\main\java\net\alanbinu\springboot2\springboot2jpacrudexample\SpringRestClient.java
| 1
|
请完成以下Java代码
|
public static ByteArrayOtherStream createByteArrayOtherStream(InputStream is) throws IOException
{
if (is == null) return null;
int size = is.available();
size = Math.max(102400, size); // 有些网络InputStream实现会返回0,直到read的时候才知道到底是不是0
int bufferSize = Math.min(1048576, size); // 最终缓冲区在100KB到1MB之间
byte[] bytes = new byte[bufferSize];
if (IOUtil.readBytesFromOtherInputStream(is, bytes) == 0)
{
throw new IOException("读取了空文件,或参数InputStream已经到了文件尾部");
}
return new ByteArrayOtherStream(bytes, bufferSize, is);
}
@Override
protected void ensureAvailableBytes(int size)
{
if (offset + size > bufferSize)
{
try
{
int wantedBytes = offset + size - bufferSize; // 实际只需要这么多
wantedBytes = Math.max(wantedBytes, is.available()); // 如果非阻塞IO能读到更多,那越多越好
wantedBytes = Math.min(wantedBytes, offset); // 但不能超过脏区的大小
byte[] bytes = new byte[wantedBytes];
int readBytes = IOUtil.readBytesFromOtherInputStream(is, bytes);
assert readBytes > 0 : "已到达文件尾部!";
System.arraycopy(this.bytes, offset, this.bytes, offset - wantedBytes, bufferSize - offset);
System.arraycopy(bytes, 0, this.bytes, bufferSize - wantedBytes, wantedBytes);
offset -= wantedBytes;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
|
}
@Override
public void close()
{
super.close();
if (is == null)
{
return;
}
try
{
is.close();
}
catch (IOException e)
{
Predefine.logger.warning(TextUtility.exceptionToString(e));
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\io\ByteArrayOtherStream.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static Map<String, Map<String, Object>> toMap() {
SettRecordStatusEnum[] ary = SettRecordStatusEnum.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() {
SettRecordStatusEnum[] ary = SettRecordStatusEnum.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;
}
/**
* 判断填入审核状态
*
* @param enumName
* @return
*/
public static boolean checkConfirm(String enumName) {
SettRecordStatusEnum[] enumAry = { SettRecordStatusEnum.CANCEL, SettRecordStatusEnum.CONFIRMED };
for (int i = 0; i < enumAry.length; i++) {
if (enumAry[i].name().equals(enumName)) {
return true;
|
}
}
return false;
}
/**
* 判断填入打款状态
*
* @param enumName
* @return
*/
public static boolean checkRemit(String enumName) {
SettRecordStatusEnum[] enumAry = { SettRecordStatusEnum.REMIT_FAIL, SettRecordStatusEnum.REMIT_SUCCESS };
for (int i = 0; i < enumAry.length; i++) {
if (enumAry[i].name().equals(enumName)) {
return true;
}
}
return false;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\enums\SettRecordStatusEnum.java
| 2
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("AD_Window_ID", windowId)
.add("caption", caption)
.add("elements", elements.isEmpty() ? null : elements)
.add("filters", filters.isEmpty() ? null : filters)
.toString();
}
@Value
@Builder
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public static class JSONIncludedViewSupport
{
public static JSONIncludedViewSupport fromNullable(final IncludedViewLayout includedViewLayout)
{
if (includedViewLayout == null)
{
|
return null;
}
return builder()
.openOnSelect(includedViewLayout.isOpenOnSelect())
.blurWhenOpen(includedViewLayout.isBlurWhenOpen())
.closeOnDeselect(includedViewLayout.isCloseOnDeselect())
.build();
}
boolean openOnSelect;
boolean blurWhenOpen;
boolean closeOnDeselect;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\json\JSONViewLayout.java
| 1
|
请完成以下Java代码
|
public IncidentQuery orderByActivityId() {
orderBy(IncidentQueryProperty.ACTIVITY_ID);
return this;
}
public IncidentQuery orderByProcessInstanceId() {
orderBy(IncidentQueryProperty.PROCESS_INSTANCE_ID);
return this;
}
public IncidentQuery orderByProcessDefinitionId() {
orderBy(IncidentQueryProperty.PROCESS_DEFINITION_ID);
return this;
}
public IncidentQuery orderByCauseIncidentId() {
orderBy(IncidentQueryProperty.CAUSE_INCIDENT_ID);
return this;
}
public IncidentQuery orderByRootCauseIncidentId() {
orderBy(IncidentQueryProperty.ROOT_CAUSE_INCIDENT_ID);
return this;
}
public IncidentQuery orderByConfiguration() {
orderBy(IncidentQueryProperty.CONFIGURATION);
return this;
}
public IncidentQuery orderByTenantId() {
|
return orderBy(IncidentQueryProperty.TENANT_ID);
}
@Override
public IncidentQuery orderByIncidentMessage() {
return orderBy(IncidentQueryProperty.INCIDENT_MESSAGE);
}
//results ////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getIncidentManager()
.findIncidentCountByQueryCriteria(this);
}
@Override
public List<Incident> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getIncidentManager()
.findIncidentByQueryCriteria(this, page);
}
public String[] getProcessDefinitionKeys() {
return processDefinitionKeys;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\IncidentQueryImpl.java
| 1
|
请完成以下Java代码
|
public String getOrgAD_Language(final Properties ctx) throws OrgHasNoBPartnerLinkException
{
final int orgId = Env.getAD_Org_ID(ctx);
return getOrgAD_Language(ctx, orgId);
}
@Override
public String getOrgAD_Language(final Properties ctx, final int orgRepoId) throws OrgHasNoBPartnerLinkException
{
final OrgId orgId = OrgId.ofRepoIdOrAny(orgRepoId);
//
// Check organization Language (if found);
if (orgId.isRegular())
{
final I_C_BPartner bpOrg = Services.get(IBPartnerDAO.class).retrieveOrgBPartner(ctx, orgId.getRepoId(), I_C_BPartner.class, ITrx.TRXNAME_None);
final String orgAD_Language = bpOrg.getAD_Language();
if (orgAD_Language != null)
{
return orgAD_Language;
}
}
//
// Check client language (if found)
final ClientId clientId;
if (orgId.isRegular())
{
clientId = Services.get(IOrgDAO.class).getClientIdByOrgId(orgId);
}
else // AD_Org_ID <= 0
{
clientId = Env.getClientId(ctx);
}
final String clientAD_Language = getClientAD_Language(ctx, clientId.getRepoId());
return clientAD_Language;
}
@Override
|
public Language getOrgLanguage(final Properties ctx, final int AD_Org_ID) throws OrgHasNoBPartnerLinkException
{
final String adLanguage = getOrgAD_Language(ctx, AD_Org_ID);
if (!Check.isEmpty(adLanguage, true))
{
return Language.getLanguage(adLanguage);
}
return null;
}
public String getClientAD_Language(final Properties ctx, final int clientId)
{
//
// Check AD_Client Language
if (clientId >= 0)
{
final I_AD_Client client = Services.get(IClientDAO.class).retriveClient(ctx, clientId);
final String clientAD_Language = client.getAD_Language();
if (clientAD_Language != null)
{
return clientAD_Language;
}
}
// If none of the above was found, return the base language
final String baseAD_Language = Language.getBaseAD_Language();
return baseAD_Language;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\impl\LanguageBL.java
| 1
|
请完成以下Spring Boot application配置
|
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/users_database?useSSL=false
spring.datasource.username = root
spring.datasource.password = root
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate
|
.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
|
repos\Spring-Boot-Advanced-Projects-main\spring-boot-crud-rest\src\main\resources\application.properties
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class UserCreateRequest {
/**
* 昵称
*/
private String name;
/**
* 性别别
*/
private Integer gender;
public String getName() {
return name;
}
|
public UserCreateRequest setName(String name) {
this.name = name;
return this;
}
public Integer getGender() {
return gender;
}
public UserCreateRequest setGender(Integer gender) {
this.gender = gender;
return this;
}
}
|
repos\SpringBoot-Labs-master\lab-65\lab-65-cxf-ws-demo\lab-65-cxf-ws-demo-user-service\src\main\java\cn\iocoder\springboot\lab65\userservice\request\UserCreateRequest.java
| 2
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
|
}
public YearMonth getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(YearMonth releaseDate) {
this.releaseDate = releaseDate;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title
+ ", isbn=" + isbn + ", releaseDate=" + releaseDate + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootYearMonth\src\main\java\com\bookstore\entity\Book.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void process(Exchange exchange) throws Exception
{
log.info("Filter order by state");
final EbayImportOrdersRouteContext importOrdersRouteContext = getPropertyOrThrowError(exchange, ROUTE_PROPERTY_IMPORT_ORDERS_CONTEXT, EbayImportOrdersRouteContext.class);
final Order order = exchange.getIn().getBody(Order.class);
if (order == null)
{
throw new RuntimeException("Empty body!");
}
log.debug("Checking order {} for further steps", order.getOrderId());
//only import new orders.
if( OrderFulfillmentStatus.NOT_STARTED.name().equalsIgnoreCase(order.getOrderFulfillmentStatus()) ) {
importOrdersRouteContext.setOrder(order);
exchange.getIn().setBody(order);
//remember order TS for future calls.
LocalDate created = order.getCreationDate() != null ? EbayUtils.toLocalDate(order.getCreationDate()) : null;
if(created != null) {
importOrdersRouteContext.setNextImportStartingTimestamp(DateAndImportStatus.of(true, created.atStartOfDay(ZoneId.systemDefault()).toInstant()));
|
}
}
else
{
// order was filtered
exchange.getIn().setBody(null);
//remember order TS for future calls.
LocalDate created = order.getCreationDate() != null ? EbayUtils.toLocalDate(order.getCreationDate()) : null;
if(created != null) {
importOrdersRouteContext.setNextImportStartingTimestamp(DateAndImportStatus.of(true, created.atStartOfDay(ZoneId.systemDefault()).toInstant()));
}
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\de-metas-camel-ebay-camelroutes\src\main\java\de\metas\camel\externalsystems\ebay\processor\order\OrderFilterProcessor.java
| 2
|
请完成以下Java代码
|
public String getName() {
return name;
}
@Schema(description = "JSON object with the Rule Chain Id. " +
"Specify this field to update the Rule Chain. " +
"Referencing non-existing Rule Chain Id will cause error. " +
"Omit this field to create new rule chain.")
@Override
public RuleChainId getId() {
return super.getId();
}
@Schema(description = "Timestamp of the rule chain creation, in milliseconds", example = "1609459200000", accessMode = Schema.AccessMode.READ_ONLY)
@Override
public long getCreatedTime() {
return super.getCreatedTime();
|
}
public JsonNode getConfiguration() {
return BaseDataWithAdditionalInfo.getJson(() -> configuration, () -> configurationBytes);
}
public void setConfiguration(JsonNode data) {
setJson(data, json -> this.configuration = json, bytes -> this.configurationBytes = bytes);
}
@JsonIgnore
@Override
public boolean isDefault() {
return root && type == RuleChainType.CORE;
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\rule\RuleChain.java
| 1
|
请完成以下Java代码
|
public col setCharOff(String char_off)
{
addAttribute("charoff",char_off);
return(this);
}
/**
Sets the lang="" and xml:lang="" attributes
@param lang the lang="" and xml:lang="" attributes
*/
public Element setLang(String lang)
{
addAttribute("lang",lang);
addAttribute("xml:lang",lang);
return this;
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public col addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public col addElement(String hashcode,String element)
{
|
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public col addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public col addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public col removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\col.java
| 1
|
请完成以下Java代码
|
public boolean isClassReloadable(Class<?> classType) {
return (classType.getClassLoader() instanceof RestartClassLoader);
}
/**
* Compound {@link Enumeration} that adds an item to the front.
*/
private static class CompoundEnumeration<E> implements Enumeration<E> {
private @Nullable E firstElement;
private final Enumeration<E> enumeration;
CompoundEnumeration(@Nullable E firstElement, Enumeration<E> enumeration) {
this.firstElement = firstElement;
this.enumeration = enumeration;
}
@Override
public boolean hasMoreElements() {
return (this.firstElement != null || this.enumeration.hasMoreElements());
|
}
@Override
public E nextElement() {
if (this.firstElement == null) {
return this.enumeration.nextElement();
}
E element = this.firstElement;
this.firstElement = null;
return element;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\classloader\RestartClassLoader.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
protected final BeanFactory getBeanFactory() {
return this.beanFactory;
}
protected final ClassLoader getBeanClassLoader() {
return this.beanClassLoader;
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.beanClassLoader = classLoader;
}
protected final List<String> filter(@Nullable Collection<String> classNames, ClassNameFilter classNameFilter,
@Nullable ClassLoader classLoader) {
if (CollectionUtils.isEmpty(classNames)) {
return Collections.emptyList();
}
List<String> matches = new ArrayList<>(classNames.size());
for (String candidate : classNames) {
if (classNameFilter.matches(candidate, classLoader)) {
matches.add(candidate);
}
}
return matches;
}
/**
* Slightly faster variant of {@link ClassUtils#forName(String, ClassLoader)} that
* doesn't deal with primitives, arrays or inner types.
* @param className the class name to resolve
* @param classLoader the class loader to use
* @return a resolved class
* @throws ClassNotFoundException if the class cannot be found
*/
protected static Class<?> resolve(String className, @Nullable ClassLoader classLoader)
throws ClassNotFoundException {
if (classLoader != null) {
return Class.forName(className, false, classLoader);
}
return Class.forName(className);
}
|
protected enum ClassNameFilter {
PRESENT {
@Override
public boolean matches(String className, @Nullable ClassLoader classLoader) {
return isPresent(className, classLoader);
}
},
MISSING {
@Override
public boolean matches(String className, @Nullable ClassLoader classLoader) {
return !isPresent(className, classLoader);
}
};
abstract boolean matches(String className, @Nullable ClassLoader classLoader);
private static boolean isPresent(String className, @Nullable ClassLoader classLoader) {
if (classLoader == null) {
classLoader = ClassUtils.getDefaultClassLoader();
}
try {
resolve(className, classLoader);
return true;
}
catch (Throwable ex) {
return false;
}
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\FilteringSpringBootCondition.java
| 2
|
请完成以下Java代码
|
public void setM_FreightCostShipper_ID (final int M_FreightCostShipper_ID)
{
if (M_FreightCostShipper_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_FreightCostShipper_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_FreightCostShipper_ID, M_FreightCostShipper_ID);
}
@Override
public int getM_FreightCostShipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_FreightCostShipper_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
|
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setShipmentValueAmt (final BigDecimal ShipmentValueAmt)
{
set_Value (COLUMNNAME_ShipmentValueAmt, ShipmentValueAmt);
}
@Override
public BigDecimal getShipmentValueAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ShipmentValueAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCostDetail.java
| 1
|
请完成以下Java代码
|
public void setPaymentRule (java.lang.String PaymentRule)
{
set_Value (COLUMNNAME_PaymentRule, PaymentRule);
}
/** Get Zahlungsweise.
@return Wie die Rechnung bezahlt wird
*/
@Override
public java.lang.String getPaymentRule ()
{
return (java.lang.String)get_Value(COLUMNNAME_PaymentRule);
}
/** Set Kaufstyp.
@param PurchaseType Kaufstyp */
@Override
public void setPurchaseType (java.math.BigDecimal PurchaseType)
{
set_Value (COLUMNNAME_PurchaseType, PurchaseType);
}
/** Get Kaufstyp.
@return Kaufstyp */
@Override
public java.math.BigDecimal getPurchaseType ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PurchaseType);
if (bd == null)
{
|
return BigDecimal.ZERO;
}
return bd;
}
/** Get Preis per Überprüfung.
@return Preis per Überprüfung */
@Override
public java.math.BigDecimal getRequestPrice ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RequestPrice);
if (bd == null)
{
return BigDecimal.ZERO;
}
return bd;
}
/** Set Preis per Überprüfung.
@param RequestPrice Preis per Überprüfung */
@Override
public void setRequestPrice (java.math.BigDecimal RequestPrice)
{
set_Value (COLUMNNAME_RequestPrice, RequestPrice);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_Config_PaymentRule.java
| 1
|
请完成以下Java代码
|
public R peek(final T input)
{
final ReadLock readLock = lock.readLock();
readLock.lock();
try
{
return lastValue;
}
finally
{
readLock.unlock();
}
}
@Override
public void forget()
{
final WriteLock writeLock = lock.writeLock();
writeLock.lock();
try
{
lastKey = null;
lastValue = null;
}
|
finally
{
writeLock.unlock();
}
}
}
private static final class SimpleMemoizingFunction<T, R> extends MemoizingFunctionWithKeyExtractor<T, R, T>
{
private SimpleMemoizingFunction(final Function<T, R> delegate)
{
super(delegate, input -> input);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Functions.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonAuthenticateRequest
{
@NonNull
String grantedAuthority;
@NonNull
String authKey;
@NonNull
JsonMetasfreshId pInstance;
@NonNull
String orgCode;
@Nullable
String externalSystemValue;
@Nullable
String auditTrailEndpoint;
@Builder
@JsonCreator
JsonAuthenticateRequest(
|
@JsonProperty("grantedAuthority") @NonNull final String grantedAuthority,
@JsonProperty("authKey") @NonNull final String authKey,
@JsonProperty("pinstance") @NonNull final JsonMetasfreshId pInstance,
@JsonProperty("externalSystemValue") @Nullable final String externalSystemValue,
@JsonProperty("auditTrailEndpoint") @Nullable final String auditTrailEndpoint,
@JsonProperty("orgCode") @NonNull final String orgCode)
{
this.grantedAuthority = grantedAuthority;
this.authKey = authKey;
this.pInstance = pInstance;
this.externalSystemValue = externalSystemValue;
this.auditTrailEndpoint = auditTrailEndpoint;
this.orgCode = orgCode;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\common\src\main\java\de\metas\camel\externalsystems\common\auth\JsonAuthenticateRequest.java
| 2
|
请完成以下Java代码
|
public void checkExecutionContext(String variableId) {
if (StringUtils.isEmpty(variableId)) {
throw new IllegalArgumentException("Variable id cannot be empty");
}
}
public void addRuleResult(int ruleNumber, String outputName, Object outputValue) {
Map<String, Object> ruleResult;
if (ruleResults.containsKey(ruleNumber)) {
ruleResult = ruleResults.get(ruleNumber);
} else {
ruleResult = new HashMap<>();
ruleResults.put(ruleNumber, ruleResult);
}
ruleResult.put(outputName, outputValue);
}
public void setStackVariables(Map<String, Object> variables) {
this.stackVariables = variables;
}
public Map<String, Object> getStackVariables() {
return stackVariables;
}
public Map<String, Object> getRuleResult(int ruleNumber) {
return ruleResults.get(ruleNumber);
}
public Map<Integer, Map<String, Object>> getRuleResults() {
return ruleResults;
}
public DecisionExecutionAuditContainer getAuditContainer() {
return auditContainer;
}
public void setAuditContainer(DecisionExecutionAuditContainer auditContainer) {
this.auditContainer = auditContainer;
}
public Map<String, List<Object>> getOutputValues() {
return outputValues;
}
public void addOutputValues(String outputName, List<Object> outputValues) {
this.outputValues.put(outputName, outputValues);
}
|
public BuiltinAggregator getAggregator() {
return aggregator;
}
public void setAggregator(BuiltinAggregator aggregator) {
this.aggregator = aggregator;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public boolean isForceDMN11() {
return forceDMN11;
}
public void setForceDMN11(boolean forceDMN11) {
this.forceDMN11 = forceDMN11;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\el\ELExecutionContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ApiService {
@Autowired
private AuthController controller;
public ResponseEntity<String> getCall(String url) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+controller.getManagementApiToken());
HttpEntity<String> entity = new HttpEntity<String>(headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
return result;
|
}
public ResponseEntity<String> postCall(String url, String requestBody) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+controller.getManagementApiToken());
HttpEntity<String> request = new HttpEntity<String>(requestBody, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> result = restTemplate.postForEntity(url, request, String.class);
return result;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-auth0\src\main\java\com\baeldung\auth0\service\ApiService.java
| 2
|
请完成以下Java代码
|
public String getMsgNmId() {
return msgNmId;
}
/**
* Sets the value of the msgNmId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMsgNmId(String value) {
this.msgNmId = value;
}
/**
* Gets the value of the msgId property.
*
* @return
* possible object is
|
* {@link String }
*
*/
public String getMsgId() {
return msgId;
}
/**
* Sets the value of the msgId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMsgId(String value) {
this.msgId = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\MessageIdentification2.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "processMigration")
public String getBatchType() {
return batchType;
}
public void setBatchType(String batchType) {
this.batchType = batchType;
}
@ApiModelProperty(example = "1:22:MP")
public String getSearchKey() {
return searchKey;
}
public void setSearchKey(String searchKey) {
this.searchKey = searchKey;
}
@ApiModelProperty(example = "1:24:MP")
public String getSearchKey2() {
return searchKey2;
}
public void setSearchKey2(String searchKey2) {
this.searchKey2 = searchKey2;
}
@ApiModelProperty(example = "2020-06-03T22:05:05.474+0000")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
|
}
@ApiModelProperty(example = "2020-06-03T22:05:05.474+0000")
public Date getCompleteTime() {
return completeTime;
}
public void setCompleteTime(Date completeTime) {
this.completeTime = completeTime;
}
@ApiModelProperty(example = "completed")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\BatchResponse.java
| 2
|
请完成以下Java代码
|
public List<String> getArguments() {
return this.arguments;
}
}
/**
* Profiles properties.
*/
public static class Profiles {
/**
* Docker compose profiles that should be active.
*/
private Set<String> active = new LinkedHashSet<>();
public Set<String> getActive() {
return this.active;
}
public void setActive(Set<String> active) {
this.active = active;
}
}
/**
* Skip options.
*/
public static class Skip {
/**
* Whether to skip in tests.
*/
private boolean inTests = true;
public boolean isInTests() {
return this.inTests;
}
public void setInTests(boolean inTests) {
this.inTests = inTests;
}
}
/**
* Readiness properties.
*/
public static class Readiness {
/**
* Wait strategy to use.
*/
private Wait wait = Wait.ALWAYS;
/**
* Timeout of the readiness checks.
*/
private Duration timeout = Duration.ofMinutes(2);
/**
* TCP properties.
*/
private final Tcp tcp = new Tcp();
public Wait getWait() {
return this.wait;
}
public void setWait(Wait wait) {
this.wait = wait;
}
public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public Tcp getTcp() {
return this.tcp;
}
/**
* Readiness wait strategies.
*/
|
public enum Wait {
/**
* Always perform readiness checks.
*/
ALWAYS,
/**
* Never perform readiness checks.
*/
NEVER,
/**
* Only perform readiness checks if docker was started with lifecycle
* management.
*/
ONLY_IF_STARTED
}
/**
* TCP properties.
*/
public static class Tcp {
/**
* Timeout for connections.
*/
private Duration connectTimeout = Duration.ofMillis(200);
/**
* Timeout for reads.
*/
private Duration readTimeout = Duration.ofMillis(200);
public Duration getConnectTimeout() {
return this.connectTimeout;
}
public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Duration getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
}
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\lifecycle\DockerComposeProperties.java
| 1
|
请完成以下Java代码
|
public String getStreet() {
return street;
}
public int getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(int houseNumber) {
this.houseNumber = houseNumber;
}
public String getCity() {
return city;
}
public void setCity(String city) {
|
this.city = city;
}
public int getZipCode() {
return zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
public void setStreet(String street) {
this.street = street;
}
}
|
repos\tutorials-master\persistence-modules\jpa-hibernate-cascade-type\src\main\java\com\baeldung\cascading\domain\Address.java
| 1
|
请完成以下Java代码
|
public JsonNode getJsonValue() {
return jsonValue;
}
public void setJsonValue(JsonNode jsonValue) {
this.jsonValue = jsonValue;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((jsonValue == null) ? 0 : jsonValue.hashCode());
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
AdminSettings other = (AdminSettings) obj;
if (jsonValue == null) {
if (other.jsonValue != null)
|
return false;
} else if (!jsonValue.equals(other.jsonValue))
return false;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AdminSettings [key=");
builder.append(key);
builder.append(", jsonValue=");
builder.append(jsonValue);
builder.append(", createdTime=");
builder.append(createdTime);
builder.append(", id=");
builder.append(id);
builder.append("]");
return builder.toString();
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\AdminSettings.java
| 1
|
请完成以下Java代码
|
public List<String> getProcessInstanceIds() {
return processInstanceIds;
}
public void setProcessInstanceIds(List<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
}
public ProcessInstanceQueryDto getProcessInstanceQuery() {
return processInstanceQuery;
}
public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) {
this.processInstanceQuery = processInstanceQuery;
}
public boolean isSkipIoMappings() {
return skipIoMappings;
|
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMappings = skipIoMappings;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public void setSkipCustomListeners(boolean skipCustomListeners) {
this.skipCustomListeners = skipCustomListeners;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\migration\MigrationExecutionDto.java
| 1
|
请完成以下Java代码
|
public Line readLine() {
try {
if (CSVReader == null) initReader();
String[] line = CSVReader.readNext();
if (line == null) return null;
return new Line(line[0], LocalDate.parse(line[1], DateTimeFormatter.ofPattern("MM/dd/yyyy")));
} catch (Exception e) {
logger.error("Error while reading line in file: " + this.fileName);
return null;
}
}
public void writeLine(Line line) {
try {
if (CSVWriter == null) initWriter();
String[] lineStr = new String[2];
lineStr[0] = line.getName();
lineStr[1] = line
.getAge()
.toString();
CSVWriter.writeNext(lineStr);
} catch (Exception e) {
logger.error("Error while writing line in file: " + this.fileName);
}
}
private void initReader() throws Exception {
ClassLoader classLoader = this
.getClass()
.getClassLoader();
if (file == null) file = new File(classLoader
.getResource(fileName)
.getFile());
if (fileReader == null) fileReader = new FileReader(file);
if (CSVReader == null) CSVReader = new CSVReader(fileReader);
|
}
private void initWriter() throws Exception {
if (file == null) {
file = new File(fileName);
file.createNewFile();
}
if (fileWriter == null) fileWriter = new FileWriter(file, true);
if (CSVWriter == null) CSVWriter = new CSVWriter(fileWriter);
}
public void closeWriter() {
try {
CSVWriter.close();
fileWriter.close();
} catch (IOException e) {
logger.error("Error while closing writer.");
}
}
public void closeReader() {
try {
CSVReader.close();
fileReader.close();
} catch (IOException e) {
logger.error("Error while closing reader.");
}
}
}
|
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\taskletsvschunks\utils\FileUtils.java
| 1
|
请完成以下Java代码
|
public synchronized void start() {
if (isRunning.compareAndSet(false, true)) {
thread = new Thread(this, TopicSubscriptionManager.class.getSimpleName());
thread.start();
}
}
protected void subscribe(TopicSubscription subscription) {
if (!subscriptions.addIfAbsent(subscription)) {
String topicName = subscription.getTopicName();
throw LOG.topicNameAlreadySubscribedException(topicName);
}
resume();
}
protected void unsubscribe(TopicSubscriptionImpl subscription) {
subscriptions.remove(subscription);
}
public EngineClient getEngineClient() {
return engineClient;
}
public List<TopicSubscription> getSubscriptions() {
return subscriptions;
}
public boolean isRunning() {
return isRunning.get();
}
public void setBackoffStrategy(BackoffStrategy backOffStrategy) {
this.backoffStrategy = backOffStrategy;
}
protected void runBackoffStrategy(FetchAndLockResponseDto fetchAndLockResponse) {
try {
List<ExternalTask> externalTasks = fetchAndLockResponse.getExternalTasks();
if (backoffStrategy instanceof ErrorAwareBackoffStrategy) {
ErrorAwareBackoffStrategy errorAwareBackoffStrategy = ((ErrorAwareBackoffStrategy) backoffStrategy);
ExternalTaskClientException exception = fetchAndLockResponse.getError();
errorAwareBackoffStrategy.reconfigure(externalTasks, exception);
} else {
backoffStrategy.reconfigure(externalTasks);
}
long waitTime = backoffStrategy.calculateBackoffTime();
suspend(waitTime);
} catch (Throwable e) {
LOG.exceptionWhileExecutingBackoffStrategyMethod(e);
}
}
|
protected void suspend(long waitTime) {
if (waitTime > 0 && isRunning.get()) {
ACQUISITION_MONITOR.lock();
try {
if (isRunning.get()) {
IS_WAITING.await(waitTime, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException e) {
LOG.exceptionWhileExecutingBackoffStrategyMethod(e);
}
finally {
ACQUISITION_MONITOR.unlock();
}
}
}
protected void resume() {
ACQUISITION_MONITOR.lock();
try {
IS_WAITING.signal();
}
finally {
ACQUISITION_MONITOR.unlock();
}
}
public void disableBackoffStrategy() {
this.isBackoffStrategyDisabled.set(true);
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\TopicSubscriptionManager.java
| 1
|
请完成以下Java代码
|
public DeviceCredentialsId getId() {
return super.getId();
}
@Schema(description = "Timestamp of the device credentials creation, in milliseconds", example = "1609459200000")
@Override
public long getCreatedTime() {
return super.getCreatedTime();
}
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "JSON object with the device Id.")
public DeviceId getDeviceId() {
return deviceId;
}
public void setDeviceId(DeviceId deviceId) {
this.deviceId = deviceId;
}
@Schema(description = "Type of the credentials", allowableValues = {"ACCESS_TOKEN", "X509_CERTIFICATE", "MQTT_BASIC", "LWM2M_CREDENTIALS"})
@Override
public DeviceCredentialsType getCredentialsType() {
return credentialsType;
}
public void setCredentialsType(DeviceCredentialsType credentialsType) {
this.credentialsType = credentialsType;
}
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Unique Credentials Id per platform instance. " +
"Used to lookup credentials from the database. " +
"By default, new access token for your device. " +
|
"Depends on the type of the credentials."
, example = "Access token or other value that depends on the credentials type")
@Override
public String getCredentialsId() {
return credentialsId;
}
public void setCredentialsId(String credentialsId) {
this.credentialsId = credentialsId;
}
@Schema(description = "Value of the credentials. " +
"Null in case of ACCESS_TOKEN credentials type. Base64 value in case of X509_CERTIFICATE. " +
"Complex object in case of MQTT_BASIC and LWM2M_CREDENTIALS", example = "Null in case of ACCESS_TOKEN. See model definition.")
public String getCredentialsValue() {
return credentialsValue;
}
public void setCredentialsValue(String credentialsValue) {
this.credentialsValue = credentialsValue;
}
@Override
public String toString() {
return "DeviceCredentials [deviceId=" + deviceId + ", credentialsType=" + credentialsType + ", credentialsId="
+ credentialsId + ", credentialsValue=" + credentialsValue + ", createdTime=" + createdTime + ", id="
+ id + "]";
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\security\DeviceCredentials.java
| 1
|
请完成以下Java代码
|
public static Authorization authorize(String requestMethod, String requestUri, List<SecurityFilterRule> filterRules) {
return FilterRules.authorize(requestMethod, requestUri, filterRules);
}
protected void loadFilterRules(FilterConfig filterConfig,
String applicationPath) throws ServletException {
String configFileName = filterConfig.getInitParameter("configFile");
InputStream configFileResource = filterConfig.getServletContext().getResourceAsStream(configFileName);
if (configFileResource == null) {
throw new ServletException("Could not read security filter config file '"+configFileName+"': no such resource in servlet context.");
} else {
try {
filterRules = FilterRules.load(configFileResource, applicationPath);
} catch (Exception e) {
throw new RuntimeException("Exception while parsing '" + configFileName + "'", e);
} finally {
IoUtil.closeSilently(configFileResource);
}
}
}
protected void sendForbidden(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.sendError(403);
}
|
protected void sendUnauthorized(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.sendError(401);
}
protected void sendForbiddenApplicationAccess(String application, HttpServletRequest request, HttpServletResponse response) throws IOException {
response.sendError(403, "No access rights for " + application);
}
protected boolean isAuthenticated(HttpServletRequest request) {
return Authentications.getCurrent() != null;
}
protected String getRequestUri(HttpServletRequest request) {
String contextPath = request.getContextPath();
return request.getRequestURI().substring(contextPath.length());
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\SecurityFilter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
public void setPropagatedStageInstanceId(String propagatedStageInstanceId) {
|
this.propagatedStageInstanceId = propagatedStageInstanceId;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricTaskInstanceResponse.java
| 2
|
请完成以下Java代码
|
public int getCommittedPercent()
{
long base = getMax();
long no = getCommitted() * 100;
if (no == 0)
return 0;
long percent = no/base;
return (int)percent;
} // getCommittedPercent
/**
* Format k/M
* @param info
* @return string info
*/
private String format (long info)
{
long infoK = info / 1024;
if (infoK == 0)
return String.valueOf(info);
long infoM = infoK / 1024;
if (infoM == 0)
|
return s_format.format(info);
return s_format.format(infoK) + "k";
} // format
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ();
sb.append ("Init=").append(format(getInit()))
.append (", Used=").append(format(getUsed()))
.append (", Free=").append(format(getFree()))
.append(" ").append(getFreePercent())
.append ("%, Committed=").append(format(getCommitted()))
.append(" ").append(getCommittedPercent())
.append ("%, Max=").append (format(getMax()));
return sb.toString ();
} // toString
} // CMemoryUsage
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\CMemoryUsage.java
| 1
|
请完成以下Java代码
|
public boolean hasAccess(@NonNull final UserId userId)
{
return UserId.equals(getResponsibleId(), userId);
}
public <T> T getDocumentAs(@NonNull final Class<T> type)
{
return type.cast(document);
}
public WFActivity getActivityById(@NonNull final WFActivityId id)
{
return getActivityByIdOptional(id)
.orElseThrow(() -> new AdempiereException(NO_ACTIVITY_ERROR_MSG)
.appendParametersToMessage()
.setParameter("ID", id)
.setParameter("WFProcess", this));
}
@NonNull
public Optional<WFActivity> getActivityByIdOptional(@NonNull final WFActivityId id)
{
return Optional.ofNullable(activitiesById.get(id));
}
public WFProcess withChangedActivityStatus(
@NonNull final WFActivityId wfActivityId,
@NonNull final WFActivityStatus newActivityStatus)
{
return withChangedActivityById(wfActivityId, wfActivity -> wfActivity.withStatus(newActivityStatus));
}
|
private WFProcess withChangedActivityById(@NonNull final WFActivityId wfActivityId, @NonNull final UnaryOperator<WFActivity> remappingFunction)
{
return withChangedActivities(wfActivity -> wfActivity.getId().equals(wfActivityId)
? remappingFunction.apply(wfActivity)
: wfActivity);
}
private WFProcess withChangedActivities(@NonNull final UnaryOperator<WFActivity> remappingFunction)
{
final ImmutableList<WFActivity> activitiesNew = CollectionUtils.map(this.activities, remappingFunction);
return !Objects.equals(this.activities, activitiesNew)
? toBuilder().activities(activitiesNew).build()
: this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WFProcess.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("type", documentType)
.add("typeId", documentTypeId)
.add("documentId", documentId)
.toString();
}
@Override
public int hashCode()
{
if (_hashcode == null)
{
_hashcode = Objects.hash(documentType, documentTypeId, documentId);
}
return _hashcode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (!(obj instanceof DocumentKey))
{
return false;
}
final DocumentKey other = (DocumentKey)obj;
return Objects.equals(documentType, other.documentType)
&& Objects.equals(documentTypeId, other.documentTypeId)
&& Objects.equals(documentId, other.documentId);
}
|
public WindowId getWindowId()
{
Check.assume(documentType == DocumentType.Window, "documentType shall be {} but it was {}", DocumentType.Window, documentType);
return WindowId.of(documentTypeId);
}
public DocumentId getDocumentId()
{
return documentId;
}
public DocumentPath getDocumentPath()
{
return DocumentPath.rootDocumentPath(documentType, documentTypeId, documentId);
}
} // DocumentKey
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentCollection.java
| 1
|
请完成以下Java代码
|
private static String toSqlWhereClause(@NonNull final GenericTargetColumnInfo targetColumn, @NonNull final IZoomSource fromDocument)
{
if (targetColumn.isDynamic())
{
return "AD_Table_ID=" + fromDocument.getAD_Table_ID() + " AND Record_ID=" + fromDocument.getRecord_ID();
}
else
{
final String columnSql = targetColumn.isVirtualTargetColumnName()
? "(" + targetColumn.getVirtualColumnSql() + ")"
: targetColumn.getColumnName();
return columnSql + "=" + fromDocument.getRecord_ID();
}
}
private static String joinSqlWhereClauses(final String join, final List<String> sqlWhereClauses)
{
if (sqlWhereClauses.isEmpty())
{
return "";
}
else if (sqlWhereClauses.size() == 1)
{
return sqlWhereClauses.get(0);
}
else
|
{
final StringBuilder result = new StringBuilder();
for (final String sqlWhereClause : sqlWhereClauses)
{
if (result.length() > 0)
{
result.append(" ").append(join).append(" ");
}
result.append("(").append(sqlWhereClause).append(")");
}
return result.insert(0, "(").append(")").toString();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\generic\GenericRelatedDocumentsProvider.java
| 1
|
请完成以下Java代码
|
public Set<java.util.Map.Entry<String, Object>> entrySet() {
return calculateBindingMap().entrySet();
}
public Set<String> keySet() {
return calculateBindingMap().keySet();
}
public int size() {
return calculateBindingMap().size();
}
public Collection<Object> values() {
return calculateBindingMap().values();
}
public void putAll(Map< ? extends String, ? extends Object> toMerge) {
for (java.util.Map.Entry<? extends String, ? extends Object> entry : toMerge.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
public Object remove(Object key) {
if (UNSTORED_KEYS.contains(key)) {
return null;
}
return wrappedBindings.remove(key);
}
public void clear() {
wrappedBindings.clear();
}
public boolean containsValue(Object value) {
return calculateBindingMap().containsValue(value);
}
public boolean isEmpty() {
|
return calculateBindingMap().isEmpty();
}
protected Map<String, Object> calculateBindingMap() {
Map<String, Object> bindingMap = new HashMap<String, Object>();
for (Resolver resolver : scriptResolvers) {
for (String key : resolver.keySet()) {
bindingMap.put(key, resolver.get(key));
}
}
Set<java.util.Map.Entry<String, Object>> wrappedBindingsEntries = wrappedBindings.entrySet();
for (Entry<String, Object> entry : wrappedBindingsEntries) {
bindingMap.put(entry.getKey(), entry.getValue());
}
return bindingMap;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\engine\ScriptBindings.java
| 1
|
请完成以下Java代码
|
public String getUsername() {
return determineTargetConnectionFactory().getUsername();
}
@Override
public @Nullable ConnectionFactory getTargetConnectionFactory(Object key) {
return this.targetConnectionFactories.get(key);
}
/**
* Specify whether to apply a validation enforcing all {@link ConnectionFactory#isPublisherConfirms()} and
* {@link ConnectionFactory#isPublisherReturns()} have a consistent value.
* <p>
* A consistent value means that all ConnectionFactories must have the same value between all
* {@link ConnectionFactory#isPublisherConfirms()} and the same value between all
* {@link ConnectionFactory#isPublisherReturns()}.
* </p>
* <p>
* Note that in any case the values between {@link ConnectionFactory#isPublisherConfirms()} and
* {@link ConnectionFactory#isPublisherReturns()} don't need to be equals between each other.
* </p>
* @param consistentConfirmsReturns true to validate, false to not validate.
* @since 2.4.4
*/
public void setConsistentConfirmsReturns(boolean consistentConfirmsReturns) {
this.consistentConfirmsReturns = consistentConfirmsReturns;
}
/**
* Adds the given {@link ConnectionFactory} and associates it with the given lookup key.
* @param key the lookup key.
* @param connectionFactory the {@link ConnectionFactory}.
*/
protected void addTargetConnectionFactory(Object key, ConnectionFactory connectionFactory) {
this.targetConnectionFactories.put(key, connectionFactory);
for (ConnectionListener listener : this.connectionListeners) {
connectionFactory.addConnectionListener(listener);
}
checkConfirmsAndReturns(connectionFactory);
}
/**
* Removes the {@link ConnectionFactory} associated with the given lookup key and returns it.
* @param key the lookup key
* @return the {@link ConnectionFactory} that was removed
*/
protected ConnectionFactory removeTargetConnectionFactory(Object key) {
return this.targetConnectionFactories.remove(key);
|
}
/**
* Determine the current lookup key. This will typically be implemented to check a thread-bound context.
*
* @return The lookup key.
*/
protected abstract @Nullable Object determineCurrentLookupKey();
@Override
public void destroy() {
resetConnection();
}
@Override
public void resetConnection() {
this.targetConnectionFactories.values().forEach(ConnectionFactory::resetConnection);
if (this.defaultTargetConnectionFactory != null) {
this.defaultTargetConnectionFactory.resetConnection();
}
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\AbstractRoutingConnectionFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserApi {
private final UserDetailsService userDetailsService;
public UserApi(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
/**
* API to get the current user. Returns the user details for the provided JWT token
* @param authentication The authentication object that contains the JWT token
* @return Returns the user details for the provided JWT token
*/
@Operation(summary = "Get user details", description = "Get the user details. The operation returns the details of the user that is associated " + "with the provided JWT token.")
@GetMapping
|
public UserDetails getUser(Authentication authentication) {
return userDetailsService.loadUserByUsername(authentication.getName());
}
/**
* API to delete the current user.
* @param authentication The authentication object that contains the JWT token
* @return Returns a success message on deletion of the user
*/
@Operation(summary = "Delete user details", description = "Delete user details. The operation deletes the details of the user that is " + "associated with the provided JWT token.")
@DeleteMapping
public String deleteUser(Authentication authentication) {
return MessageFormat.format("User {0} deleted successfully", authentication.getName());
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc\src\main\java\com\baeldung\jwt\UserApi.java
| 2
|
请完成以下Java代码
|
public void setS_Resource_ID (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
/** Get Resource.
@return Resource
*/
public int getS_Resource_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
|
{
return new KeyNamePair(get_ID(), String.valueOf(getS_Resource_ID()));
}
/** Set Resource Unavailability.
@param S_ResourceUnAvailable_ID Resource Unavailability */
public void setS_ResourceUnAvailable_ID (int S_ResourceUnAvailable_ID)
{
if (S_ResourceUnAvailable_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_ResourceUnAvailable_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_ResourceUnAvailable_ID, Integer.valueOf(S_ResourceUnAvailable_ID));
}
/** Get Resource Unavailability.
@return Resource Unavailability */
public int getS_ResourceUnAvailable_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceUnAvailable_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_ResourceUnAvailable.java
| 1
|
请完成以下Java代码
|
public int getInitSize()
{
return N;
}
@Override
public int getCharsetSize()
{
return N;
}
@Override
public int zeroId()
{
return 0;
}
@Override
public int[] toIdList(String key)
{
byte[] bytes = key.getBytes(UTF_8);
int[] res = new int[bytes.length];
for (int i = 0; i < res.length; i++)
{
res[i] = bytes[i] & 0xFF; // unsigned byte
}
if ((res.length == 1) && (res[0] == 0))
{
return EMPTYLIST;
}
return res;
}
/**
* codes ported from iconv lib in utf8.h utf8_codepointtomb
*/
@Override
public int[] toIdList(int codePoint)
{
int count;
if (codePoint < 0x80)
count = 1;
else if (codePoint < 0x800)
count = 2;
else if (codePoint < 0x10000)
count = 3;
else if (codePoint < 0x200000)
count = 4;
else if (codePoint < 0x4000000)
count = 5;
else if (codePoint <= 0x7fffffff)
count = 6;
else
return EMPTYLIST;
|
int[] r = new int[count];
switch (count)
{ /* note: code falls through cases! */
case 6:
r[5] = (char) (0x80 | (codePoint & 0x3f));
codePoint = codePoint >> 6;
codePoint |= 0x4000000;
case 5:
r[4] = (char) (0x80 | (codePoint & 0x3f));
codePoint = codePoint >> 6;
codePoint |= 0x200000;
case 4:
r[3] = (char) (0x80 | (codePoint & 0x3f));
codePoint = codePoint >> 6;
codePoint |= 0x10000;
case 3:
r[2] = (char) (0x80 | (codePoint & 0x3f));
codePoint = codePoint >> 6;
codePoint |= 0x800;
case 2:
r[1] = (char) (0x80 | (codePoint & 0x3f));
codePoint = codePoint >> 6;
codePoint |= 0xc0;
case 1:
r[0] = (char) codePoint;
}
return r;
}
@Override
public String toString(int[] ids)
{
byte[] bytes = new byte[ids.length];
for (int i = 0; i < ids.length; i++)
{
bytes[i] = (byte) ids[i];
}
try
{
return new String(bytes, "UTF-8");
}
catch (UnsupportedEncodingException e)
{
return null;
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\Utf8CharacterMapping.java
| 1
|
请完成以下Java代码
|
public class MImpexConnectorParam extends X_Impex_ConnectorParam
{
/**
*
*/
private static final long serialVersionUID = 6887898374268570467L;
public MImpexConnectorParam(Properties ctx, int C_ImpexConnectorParam_ID, String trxName)
{
super(ctx, C_ImpexConnectorParam_ID, trxName);
}
public MImpexConnectorParam(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
|
}
public static List<MImpexConnectorParam> retrieve(final MImpExConnector connector)
{
final String whereClause = COLUMNNAME_ImpEx_Connector_ID + "=?";
final Object[] parameters = { connector.get_ID() };
final String orderBy = COLUMNNAME_SeqNo;
return new Query(connector.getCtx(), Table_Name, whereClause, connector
.get_TrxName()).setParameters(parameters).setOrderBy(orderBy)
.list(MImpexConnectorParam.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\impex\model\MImpexConnectorParam.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setRemoveWaitingForRepetitionPlanItemDefinitionIds(List<String> removeWaitingForRepetitionPlanItemDefinitionIds) {
this.removeWaitingForRepetitionPlanItemDefinitionIds = removeWaitingForRepetitionPlanItemDefinitionIds;
}
public Map<String, String> getChangePlanItemIds() {
return changePlanItemIds;
}
@ApiModelProperty(value = "map an existing plan item id to new plan item id, this should not be necessary in general, but could be needed when plan item ids change between case definition versions.")
public void setChangePlanItemIds(Map<String, String> changePlanItemIds) {
this.changePlanItemIds = changePlanItemIds;
}
public Map<String, String> getChangePlanItemIdsWithDefinitionId() {
return changePlanItemIdsWithDefinitionId;
|
}
@ApiModelProperty(value = "map an existing plan item id to new plan item id with the plan item definition id, this should not be necessary in general, but could be needed when plan item ids change between case definition versions.")
public void setChangePlanItemIdsWithDefinitionId(Map<String, String> changePlanItemIdsWithDefinitionId) {
this.changePlanItemIdsWithDefinitionId = changePlanItemIdsWithDefinitionId;
}
public List<PlanItemDefinitionWithTargetIdsRequest> getChangePlanItemDefinitionsWithNewTargetIds() {
return changePlanItemDefinitionsWithNewTargetIds;
}
@ApiModelProperty(value = "map an existing plan item id to a new plan item id and plan item definition id, this should not be necessary in general, but could be needed when plan item ids change between case definition versions.")
public void setChangePlanItemDefinitionsWithNewTargetIds(List<PlanItemDefinitionWithTargetIdsRequest> changePlanItemDefinitionsWithNewTargetIds) {
this.changePlanItemDefinitionsWithNewTargetIds = changePlanItemDefinitionsWithNewTargetIds;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\ChangePlanItemStateRequest.java
| 2
|
请完成以下Java代码
|
static class PostgresJdbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails
implements JdbcConnectionDetails {
private static final JdbcUrlBuilder jdbcUrlBuilder = new JdbcUrlBuilder("postgresql", 5432);
private final PostgresEnvironment environment;
private final String jdbcUrl;
PostgresJdbcDockerComposeConnectionDetails(RunningService service, Environment environment) {
super(service);
this.environment = new PostgresEnvironment(service.env());
this.jdbcUrl = addApplicationNameIfNecessary(jdbcUrlBuilder.build(service, this.environment.getDatabase()),
environment);
}
@Override
public String getUsername() {
return this.environment.getUsername();
}
@Override
public @Nullable String getPassword() {
return this.environment.getPassword();
}
@Override
public String getJdbcUrl() {
return this.jdbcUrl;
}
private static String addApplicationNameIfNecessary(String jdbcUrl, Environment environment) {
if (jdbcUrl.contains("&ApplicationName=") || jdbcUrl.contains("?ApplicationName=")) {
return jdbcUrl;
}
String applicationName = environment.getProperty("spring.application.name");
|
if (!StringUtils.hasText(applicationName)) {
return jdbcUrl;
}
StringBuilder jdbcUrlBuilder = new StringBuilder(jdbcUrl);
if (!jdbcUrl.contains("?")) {
jdbcUrlBuilder.append("?");
}
else if (!jdbcUrl.endsWith("&")) {
jdbcUrlBuilder.append("&");
}
return jdbcUrlBuilder.append("ApplicationName")
.append('=')
.append(URLEncoder.encode(applicationName, StandardCharsets.UTF_8))
.toString();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\docker\compose\PostgresJdbcDockerComposeConnectionDetailsFactory.java
| 1
|
请完成以下Java代码
|
public <T> T parse(final ISoehenleCmd cmd, final String stringToParse, final String elementName, final Class<T> clazz)
{
try
{
if (Check.isBlank(stringToParse))
{
Loggables.withLogger(logger, Level.INFO).addLog("The scale returned no value for cmd={};", cmd);
return (T)ZERO.toString();
}
final SoehenleResultStringElement elementInfo = cmd.getResultElements().get(elementName);
final String[] tokens = stringToParse.split(" +"); // split string around spaces
final String status = getStatus(cmd, tokens);
//underweight
if (status.startsWith("1"))
{
Loggables.withLogger(logger, Level.INFO).addLog("The scale returned an underweight measurement {} for cmd={};Returning 0;", stringToParse, cmd);
return (T)ZERO.toString();
}
//overweight
if (status.startsWith("01"))
{
Loggables.withLogger(logger, Level.INFO).addLog("The scale returned an overweight measurement {} for cmd={};Returning 0;", stringToParse, cmd);
return (T)ZERO.toString();
}
final String resultToken = tokens[elementInfo.getPosition() - 1];
return (T)resultToken;
}
catch (final Exception e)
{
throw new ParserException(cmd, stringToParse, elementName, clazz, e);
}
}
|
private static String getStatus(final ISoehenleCmd cmd, final String[] tokens)
{
final SoehenleResultStringElement statusInfo = cmd.getResultElements().get(RESULT_ELEMENT_STATUS);
final String status = tokens[statusInfo.getPosition() - 1];
if (status.length() == STATUS_IN_ALIBISPEICHER_EXPECTED_LENGTH) //Message is in Alibispeicher format, drop the first 8 characters
{
return status.substring(8);
}
if (status.length() != STATUS_EXPECTED_LENGTH)
{
Loggables.withLogger(logger, Level.WARN).addLog("Found an incorrectly formatted status: {} ", status);
}
return status;
}
@Override
public String toString()
{
return "SicsResponseStringParser []";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\impl\soehenle\SoehenleResponseStringParser.java
| 1
|
请完成以下Java代码
|
public Account getTaxDueAcct(@NonNull final AcctSchema as)
{
return accountProvider.getTaxAccount(as.getId(), taxId, TaxAcctType.TaxDue);
}
public int getC_Tax_ID() {return taxId.getRepoId();}
public String getDescription() {return taxName + " " + taxBaseAmt;}
public void addIncludedTax(final BigDecimal amt)
{
includedTaxAmt = includedTaxAmt.add(amt);
}
/**
|
* @return tax amount - included tax amount
*/
public BigDecimal getIncludedTaxDifference()
{
return taxAmt.subtract(includedTaxAmt);
}
/**
* Included Tax differs from tax amount
*
* @return true if difference
*/
public boolean isIncludedTaxDifference() {return getIncludedTaxDifference().signum() != 0;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocTax.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DmnDeploymentBuilder name(String name) {
deployment.setName(name);
return this;
}
@Override
public DmnDeploymentBuilder category(String category) {
deployment.setCategory(category);
return this;
}
@Override
public DmnDeploymentBuilder disableSchemaValidation() {
this.isDmn20XsdValidationEnabled = false;
return this;
}
@Override
public DmnDeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
@Override
public DmnDeploymentBuilder parentDeploymentId(String parentDeploymentId) {
deployment.setParentDeploymentId(parentDeploymentId);
return this;
}
@Override
public DmnDeploymentBuilder enableDuplicateFiltering() {
isDuplicateFilterEnabled = true;
return this;
}
@Override
public DmnDeployment deploy() {
|
return repositoryService.deploy(this);
}
// getters and setters
// //////////////////////////////////////////////////////
public DmnDeploymentEntity getDeployment() {
return deployment;
}
public boolean isDmnXsdValidationEnabled() {
return isDmn20XsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\repository\DmnDeploymentBuilderImpl.java
| 2
|
请完成以下Java代码
|
public CaseInstanceQuery active() {
state = CaseExecutionState.ACTIVE;
return this;
}
public CaseInstanceQuery completed() {
state = CaseExecutionState.COMPLETED;
return this;
}
public CaseInstanceQuery terminated() {
state = CaseExecutionState.TERMINATED;
return this;
}
//ordering /////////////////////////////////////////////////////////////////
public CaseInstanceQuery orderByCaseInstanceId() {
orderBy(CaseInstanceQueryProperty.CASE_INSTANCE_ID);
return this;
}
public CaseInstanceQuery orderByCaseDefinitionKey() {
orderBy(new QueryOrderingProperty(QueryOrderingProperty.RELATION_CASE_DEFINITION,
CaseInstanceQueryProperty.CASE_DEFINITION_KEY));
return this;
}
public CaseInstanceQuery orderByCaseDefinitionId() {
orderBy(CaseInstanceQueryProperty.CASE_DEFINITION_ID);
return this;
}
public CaseInstanceQuery orderByTenantId() {
orderBy(CaseInstanceQueryProperty.TENANT_ID);
return this;
}
//results /////////////////////////////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
checkQueryOk();
ensureVariablesInitialized();
return commandContext
.getCaseExecutionManager()
.findCaseInstanceCountByQueryCriteria(this);
}
public List<CaseInstance> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
ensureVariablesInitialized();
return commandContext
.getCaseExecutionManager()
.findCaseInstanceByQueryCriteria(this, page);
}
//getters /////////////////////////////////////////////////////////////////
public String getCaseInstanceId() {
return caseExecutionId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getActivityId() {
return null;
}
public String getBusinessKey() {
return businessKey;
}
|
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getDeploymentId() {
return deploymentId;
}
public CaseExecutionState getState() {
return state;
}
public boolean isCaseInstancesOnly() {
return true;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public String getSubProcessInstanceId() {
return subProcessInstanceId;
}
public String getSuperCaseInstanceId() {
return superCaseInstanceId;
}
public String getSubCaseInstanceId() {
return subCaseInstanceId;
}
public Boolean isRequired() {
return required;
}
public Boolean isRepeatable() {
return repeatable;
}
public Boolean isRepetition() {
return repetition;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public void main() {
String data = new SimpleData().setData("Baeldung")
.getData();
logger.log(Level.INFO, new SimpleData().setData("Baeldung")
.getData());
logger.log(Level.INFO, data);
logger.log(Level.INFO, "Baeldung");
}
public class SimpleData {
private Logger logger = Logger.getGlobal();
private String data;
|
public String getData() {
logger.log(Level.INFO, "Get data called for SimpleData");
return data;
}
public SimpleData setData(String data) {
logger.log(Level.INFO, "Set data called for SimpleData");
this.data = data;
return this;
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-functional\src\main\java\com\baeldung\functional\ReferentialTransparency.java
| 1
|
请完成以下Java代码
|
public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut)
{
set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut);
}
@Override
public void setM_InOut_ID (final int M_InOut_ID)
{
if (M_InOut_ID < 1)
set_Value (COLUMNNAME_M_InOut_ID, null);
else
set_Value (COLUMNNAME_M_InOut_ID, M_InOut_ID);
}
@Override
public int getM_InOut_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOut_ID);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setName2 (final @Nullable java.lang.String Name2)
{
set_Value (COLUMNNAME_Name2, Name2);
}
@Override
public java.lang.String getName2()
{
return get_ValueAsString(COLUMNNAME_Name2);
}
@Override
public void setPhone (final @Nullable java.lang.String Phone)
{
set_Value (COLUMNNAME_Phone, Phone);
}
@Override
public java.lang.String getPhone()
{
return get_ValueAsString(COLUMNNAME_Phone);
}
@Override
public void setPostal (final @Nullable java.lang.String Postal)
{
set_Value (COLUMNNAME_Postal, Postal);
}
@Override
public java.lang.String getPostal()
{
return get_ValueAsString(COLUMNNAME_Postal);
}
@Override
|
public void setReferenceNo (final @Nullable java.lang.String ReferenceNo)
{
set_Value (COLUMNNAME_ReferenceNo, ReferenceNo);
}
@Override
public java.lang.String getReferenceNo()
{
return get_ValueAsString(COLUMNNAME_ReferenceNo);
}
@Override
public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No)
{
set_ValueNoCheck (COLUMNNAME_Setup_Place_No, Setup_Place_No);
}
@Override
public java.lang.String getSetup_Place_No()
{
return get_ValueAsString(COLUMNNAME_Setup_Place_No);
}
@Override
public void setSiteName (final @Nullable java.lang.String SiteName)
{
set_ValueNoCheck (COLUMNNAME_SiteName, SiteName);
}
@Override
public java.lang.String getSiteName()
{
return get_ValueAsString(COLUMNNAME_SiteName);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_119_v.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getEmail() {
return email;
}
/**
* Sets the value of the email property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEmail(String value) {
this.email = value;
}
/**
* Global Location Number of the party.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGLN() {
return gln;
}
/**
* Sets the value of the gln property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGLN(String value) {
this.gln = value;
}
/**
* Further contact details.
*
* @return
* possible object is
* {@link ContactType }
*
*/
public ContactType getContact() {
return contact;
}
/**
* Sets the value of the contact property.
*
* @param value
* allowed object is
|
* {@link ContactType }
*
*/
public void setContact(ContactType value) {
this.contact = value;
}
/**
* Address details of the party.
*
* @return
* possible object is
* {@link AddressType }
*
*/
public AddressType getAddress() {
return address;
}
/**
* Sets the value of the address property.
*
* @param value
* allowed object is
* {@link AddressType }
*
*/
public void setAddress(AddressType value) {
this.address = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\BusinessEntityType.java
| 2
|
请完成以下Java代码
|
public static void main(String[] args) throws Exception {
// 创建执行环境
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// 指定并行度,默认电脑线程数
env.setParallelism(3);
// 读取数据socket文本流 指定监听 IP 端口 只有在接收到数据才会执行任务
DataStreamSource<String> socketDS = env.socketTextStream("172.24.4.193", 8888);
// 处理数据: 切换、转换、分组、聚合 得到统计结果
SingleOutputStreamOperator<Tuple2<String, Integer>> sum = socketDS
.flatMap(
(String value, Collector<Tuple2<String, Integer>> out) -> {
String[] words = value.split(" ");
for (String word : words) {
out.collect(Tuple2.of(word, 1));
}
}
)
.setParallelism(2)
// // 显式地提供类型信息:对于flatMap传入Lambda表达式,系统只能推断出返回的是Tuple2类型,而无法得到Tuple2<String, Long>。只有显式设置系统当前返回类型,才能正确解析出完整数据
|
.returns(new TypeHint<Tuple2<String, Integer>>() {
})
// .returns(Types.TUPLE(Types.STRING,Types.INT))
.keyBy(value -> value.f0)
.sum(1);
// 输出
sum.print();
// 执行
env.execute();
}
}
|
repos\springboot-demo-master\flink\src\main\java\com\et\flink\job\SocketJob.java
| 1
|
请完成以下Java代码
|
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
|
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_HouseKeeping.java
| 1
|
请完成以下Java代码
|
public CostAmount roundToPrecisionIfNeeded(final CurrencyPrecision precision)
{
final Money valueRounded = value.roundIfNeeded(precision);
if (Money.equals(value, valueRounded))
{
return this;
}
else
{
return new CostAmount(valueRounded, sourceValue);
}
}
public CostAmount roundToCostingPrecisionIfNeeded(final AcctSchema acctSchema)
{
final AcctSchemaCosting acctSchemaCosting = acctSchema.getCosting();
final CurrencyPrecision precision = acctSchemaCosting.getCostingPrecision();
return roundToPrecisionIfNeeded(precision);
}
@NonNull
public CostAmount subtract(@NonNull final CostAmount amtToSubtract)
{
assertCurrencyMatching(amtToSubtract);
if (amtToSubtract.isZero())
{
return this;
}
return add(amtToSubtract.negate());
}
public CostAmount toZero()
|
{
if (isZero())
{
return this;
}
else
{
return new CostAmount(value.toZero(), sourceValue != null ? sourceValue.toZero() : null);
}
}
public Money toMoney()
{
return value;
}
@Nullable
public Money toSourceMoney()
{
return sourceValue;
}
public BigDecimal toBigDecimal() {return value.toBigDecimal();}
public boolean compareToEquals(@NonNull final CostAmount other)
{
return this.value.compareTo(other.value) == 0;
}
public static CurrencyId getCommonCurrencyIdOfAll(@Nullable final CostAmount... costAmounts)
{
return CurrencyId.getCommonCurrencyIdOfAll(CostAmount::getCurrencyId, "Amount", costAmounts);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostAmount.java
| 1
|
请完成以下Java代码
|
public String getSummary()
{
final StringBuilder sb = new StringBuilder();
sb.append(getDocumentNo());
// : Grand Total = 123.00 (#1)
sb.append(": ").append(Msg.translate(getCtx(), "GrandTotal")).append("=").append(getGrandTotal())
.append(" (#").append(getLines(false).length).append(")");
// - Description
if (getDescription() != null && getDescription().length() > 0)
{
sb.append(" - ").append(getDescription());
}
return sb.toString();
} // getSummary
@Override
public LocalDate getDocumentDate()
{
return TimeUtil.asLocalDate(getDateInvoiced());
}
@Override
public String getProcessMsg()
{
return null;
}
@Override
public int getDoc_User_ID()
{
return getSalesRep_ID();
}
@Override
public BigDecimal getApprovalAmt()
{
return getGrandTotal();
}
public void setRMA(final MRMA rma)
{
final MInvoice originalInvoice = rma.getOriginalInvoice();
if (originalInvoice == null)
{
throw new AdempiereException("Not invoiced - RMA: " + rma.getDocumentNo());
}
setM_RMA_ID(rma.getM_RMA_ID());
setAD_Org_ID(rma.getAD_Org_ID());
|
setDescription(rma.getDescription());
InvoiceDocumentLocationAdapterFactory
.locationAdapter(this)
.setFrom(originalInvoice);
setSalesRep_ID(rma.getSalesRep_ID());
setGrandTotal(rma.getAmt());
setOpenAmt(rma.getAmt());
setIsSOTrx(rma.isSOTrx());
setTotalLines(rma.getAmt());
setC_Currency_ID(originalInvoice.getC_Currency_ID());
setIsTaxIncluded(originalInvoice.isTaxIncluded());
setM_PriceList_ID(originalInvoice.getM_PriceList_ID());
setC_Project_ID(originalInvoice.getC_Project_ID());
setC_Activity_ID(originalInvoice.getC_Activity_ID());
setC_Campaign_ID(originalInvoice.getC_Campaign_ID());
setUser1_ID(originalInvoice.getUser1_ID());
setUser2_ID(originalInvoice.getUser2_ID());
}
/**
* Document Status is Complete or Closed
*
* @return true if CO, CL or RE
* @deprecated Please use {@link IInvoiceBL#isComplete(I_C_Invoice)}
*/
@Deprecated
public boolean isComplete()
{
return Services.get(IInvoiceBL.class).isComplete(this);
} // isComplete
} // MInvoice
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MInvoice.java
| 1
|
请完成以下Java代码
|
public int getM_CostElement_Acct_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostElement_Acct_ID);
}
@Override
public org.compiere.model.I_M_CostElement getM_CostElement()
{
return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class);
}
@Override
public void setM_CostElement(final org.compiere.model.I_M_CostElement M_CostElement)
{
set_ValueFromPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class, M_CostElement);
}
@Override
public void setM_CostElement_ID (final int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, M_CostElement_ID);
}
@Override
public int getM_CostElement_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostElement_ID);
}
@Override
public org.compiere.model.I_C_ValidCombination getP_CostClearing_A()
{
return get_ValueAsPO(COLUMNNAME_P_CostClearing_Acct, org.compiere.model.I_C_ValidCombination.class);
}
|
@Override
public void setP_CostClearing_A(final org.compiere.model.I_C_ValidCombination P_CostClearing_A)
{
set_ValueFromPO(COLUMNNAME_P_CostClearing_Acct, org.compiere.model.I_C_ValidCombination.class, P_CostClearing_A);
}
@Override
public void setP_CostClearing_Acct (final int P_CostClearing_Acct)
{
set_Value (COLUMNNAME_P_CostClearing_Acct, P_CostClearing_Acct);
}
@Override
public int getP_CostClearing_Acct()
{
return get_ValueAsInt(COLUMNNAME_P_CostClearing_Acct);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostElement_Acct.java
| 1
|
请完成以下Java代码
|
public class X_C_OLCand_AlbertaTherapy extends PO implements I_C_OLCand_AlbertaTherapy, I_Persistent
{
private static final long serialVersionUID = -249973234L;
/**
* Standard Constructor
*/
public X_C_OLCand_AlbertaTherapy(final Properties ctx, final int C_OLCand_AlbertaTherapy_ID, @Nullable final String trxName)
{
super(ctx, C_OLCand_AlbertaTherapy_ID, trxName);
}
/**
* Load Constructor
*/
public X_C_OLCand_AlbertaTherapy(final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super(ctx, rs, trxName);
}
/**
* Load Meta Data
*/
@Override
protected POInfo initPO(final Properties ctx)
{
return POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_OLCand_AlbertaTherapy_ID(final int C_OLCand_AlbertaTherapy_ID)
{
if (C_OLCand_AlbertaTherapy_ID < 1)
set_ValueNoCheck(COLUMNNAME_C_OLCand_AlbertaTherapy_ID, null);
else
set_ValueNoCheck(COLUMNNAME_C_OLCand_AlbertaTherapy_ID, C_OLCand_AlbertaTherapy_ID);
}
@Override
public int getC_OLCand_AlbertaTherapy_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_AlbertaTherapy_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 setTherapy(final String Therapy)
{
set_Value(COLUMNNAME_Therapy, Therapy);
}
@Override
public String getTherapy()
{
return get_ValueAsString(COLUMNNAME_Therapy);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_OLCand_AlbertaTherapy.java
| 1
|
请完成以下Java代码
|
protected boolean isDecisionTableWithCollectOrRuleOrderHitPolicy(DmnDecision evaluatedDecision) {
boolean isDecisionTableWithCollectHitPolicy = false;
if (evaluatedDecision.isDecisionTable()) {
DmnDecisionTableImpl decisionTable = (DmnDecisionTableImpl) evaluatedDecision.getDecisionLogic();
isDecisionTableWithCollectHitPolicy = COLLECT_HIT_POLICY.equals(decisionTable.getHitPolicyHandler().getHitPolicyEntry())
|| RULE_ORDER_HIT_POLICY.equals(decisionTable.getHitPolicyHandler().getHitPolicyEntry());
}
return isDecisionTableWithCollectHitPolicy;
}
protected void generateDecisionEvaluationEvent(List<DmnDecisionLogicEvaluationEvent> evaluatedEvents) {
DmnDecisionLogicEvaluationEvent rootEvaluatedEvent = null;
DmnDecisionEvaluationEventImpl decisionEvaluationEvent = new DmnDecisionEvaluationEventImpl();
long executedDecisionElements = 0L;
for(DmnDecisionLogicEvaluationEvent evaluatedEvent: evaluatedEvents) {
|
executedDecisionElements += evaluatedEvent.getExecutedDecisionElements();
rootEvaluatedEvent = evaluatedEvent;
}
decisionEvaluationEvent.setDecisionResult(rootEvaluatedEvent);
decisionEvaluationEvent.setExecutedDecisionInstances(evaluatedEvents.size());
decisionEvaluationEvent.setExecutedDecisionElements(executedDecisionElements);
evaluatedEvents.remove(rootEvaluatedEvent);
decisionEvaluationEvent.setRequiredDecisionResults(evaluatedEvents);
for (DmnDecisionEvaluationListener evaluationListener : evaluationListeners) {
evaluationListener.notify(decisionEvaluationEvent);
}
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DefaultDmnDecisionContext.java
| 1
|
请完成以下Java代码
|
public String getCollectionVariableName() {
return collectionVariableName;
}
public boolean hasCollectionVariable() {
return StringUtils.isNotEmpty(collectionVariableName);
}
public void setCollectionVariableName(String collectionVariableName) {
this.collectionVariableName = collectionVariableName;
}
public String getElementVariableName() {
return elementVariableName;
}
public boolean hasElementVariable() {
return StringUtils.isNotEmpty(elementVariableName);
}
public void setElementVariableName(String elementVariableName) {
this.elementVariableName = elementVariableName;
}
public String getElementIndexVariableName() {
return elementIndexVariableName;
}
public boolean hasElementIndexVariable() {
return StringUtils.isNotEmpty(elementIndexVariableName);
}
public void setElementIndexVariableName(String elementIndexVariableName) {
this.elementIndexVariableName = elementIndexVariableName;
}
public boolean hasLimitedInstanceCount() {
return maxInstanceCount != null && maxInstanceCount > 0;
}
public Integer getMaxInstanceCount() {
return maxInstanceCount;
}
|
public void setMaxInstanceCount(Integer maxInstanceCount) {
this.maxInstanceCount = maxInstanceCount;
}
public VariableAggregationDefinitions getAggregations() {
return aggregations;
}
public void setAggregations(VariableAggregationDefinitions aggregations) {
this.aggregations = aggregations;
}
public void addAggregation(VariableAggregationDefinition aggregation) {
if (this.aggregations == null) {
this.aggregations = new VariableAggregationDefinitions();
}
this.aggregations.getAggregations().add(aggregation);
}
@Override
public String toString() {
return "RepetitionRule{" +
" maxInstanceCount='" + (hasLimitedInstanceCount() ? maxInstanceCount : "unlimited") + "'" +
" repetitionCounterVariableName='" + repetitionCounterVariableName + "'" +
" collectionVariableName='" + collectionVariableName + "'" +
" elementVariableName='" + elementVariableName + "'" +
" elementIndexVariableName='" + elementIndexVariableName + "'" +
" } " + super.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\RepetitionRule.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Job datasourceItemWriterJob() {
return jobBuilderFactory.get("datasourceItemWriterJob")
.start(step())
.build();
}
private Step step() {
return stepBuilderFactory.get("step")
.<TestData, TestData>chunk(2)
.reader(simpleReader)
.writer(dataSourceItemWriter())
.build();
}
private ItemWriter<TestData> dataSourceItemWriter() {
|
// ItemWriter的实现类之一,mysql数据库数据写入使用JdbcBatchItemWriter,
// 其他实现:MongoItemWriter,Neo4jItemWriter等
JdbcBatchItemWriter<TestData> writer = new JdbcBatchItemWriter<>();
writer.setDataSource(dataSource); // 设置数据源
String sql = "insert into TEST(id,field1,field2,field3) values (:id,:field1,:field2,:field3)";
writer.setSql(sql); // 设置插入sql脚本
// 映射TestData对象属性到占位符中的属性
BeanPropertyItemSqlParameterSourceProvider<TestData> provider = new BeanPropertyItemSqlParameterSourceProvider<>();
writer.setItemSqlParameterSourceProvider(provider);
writer.afterPropertiesSet(); // 设置一些额外属性
return writer;
}
}
|
repos\SpringAll-master\69.spring-batch-itemwriter\src\main\java\cc\mrbird\batch\job\DatabaseItemWriterDemo.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getBankOrderNo() {
return bankOrderNo;
}
public void setBankOrderNo(String bankOrderNo) {
this.bankOrderNo = bankOrderNo;
}
public String getBankTrxNo() {
return bankTrxNo;
}
public void setBankTrxNo(String bankTrxNo) {
this.bankTrxNo = bankTrxNo;
}
public String getBankTradeStatus() {
return bankTradeStatus;
}
public void setBankTradeStatus(String bankTradeStatus) {
this.bankTradeStatus = bankTradeStatus;
}
public BigDecimal getBankAmount() {
return bankAmount;
}
public void setBankAmount(BigDecimal bankAmount) {
this.bankAmount = bankAmount;
}
public BigDecimal getBankRefundAmount() {
|
return bankRefundAmount;
}
public void setBankRefundAmount(BigDecimal bankRefundAmount) {
this.bankRefundAmount = bankRefundAmount;
}
public BigDecimal getBankFee() {
return bankFee;
}
public void setBankFee(BigDecimal bankFee) {
this.bankFee = bankFee;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\vo\ReconciliationEntityVo.java
| 2
|
请完成以下Java代码
|
class BitVector
{
/**
* 获取某一位的比特
* @param id 位
* @return 比特是1还是0
*/
boolean get(int id)
{
return (_units.get(id / UNIT_SIZE) >>> (id % UNIT_SIZE) & 1) == 1;
}
/**
* 设置某一位的比特
* @param id 位
* @param bit 比特
*/
void set(int id, boolean bit)
{
if (bit)
{
_units.set(id / UNIT_SIZE, _units.get(id / UNIT_SIZE)
| 1 << (id % UNIT_SIZE));
}
}
/**
*
* @param id
* @return
*/
int rank(int id)
{
int unit_id = id / UNIT_SIZE;
return _ranks[unit_id] + popCount(_units.get(unit_id)
& (~0 >>> (UNIT_SIZE - (id % UNIT_SIZE) - 1)));
}
/**
* 是否为空
* @return
*/
boolean empty()
{
return _units.empty();
}
/**
* 1的数量
* @return
*/
int numOnes()
{
return _numOnes;
}
/**
* 大小
* @return
*/
int size()
{
return _size;
}
/**
* 在末尾追加
*/
void append()
{
if ((_size % UNIT_SIZE) == 0)
{
_units.add(0);
}
|
++_size;
}
/**
* 构建
*/
void build()
{
_ranks = new int[_units.size()];
_numOnes = 0;
for (int i = 0; i < _units.size(); ++i)
{
_ranks[i] = _numOnes;
_numOnes += popCount(_units.get(i));
}
}
/**
* 清空
*/
void clear()
{
_units.clear();
_ranks = null;
}
/**
* 整型大小
*/
private static final int UNIT_SIZE = 32; // sizeof(int) * 8
/**
* 1的数量
* @param unit
* @return
*/
private static int popCount(int unit)
{
unit = ((unit & 0xAAAAAAAA) >>> 1) + (unit & 0x55555555);
unit = ((unit & 0xCCCCCCCC) >>> 2) + (unit & 0x33333333);
unit = ((unit >>> 4) + unit) & 0x0F0F0F0F;
unit += unit >>> 8;
unit += unit >>> 16;
return unit & 0xFF;
}
/**
* 储存空间
*/
private AutoIntPool _units = new AutoIntPool();
/**
* 是每个元素的1的个数的累加
*/
private int[] _ranks;
/**
* 1的数量
*/
private int _numOnes;
/**
* 大小
*/
private int _size;
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\BitVector.java
| 1
|
请完成以下Java代码
|
public void updateShipmentScheduleFromReferencedRecord(@NonNull final I_M_ShipmentSchedule shipmentScheduleRecord)
{
final ShipmentScheduleHandler handler = getHandlerFor(shipmentScheduleRecord);
handler.updateShipmentScheduleFromReferencedRecord(shipmentScheduleRecord);
}
private void saveHandlerLog(
@NonNull final I_M_IolCandHandler handlerRecord,
@Nullable final Object referencedModel,
@NonNull final String status)
{
final Properties ctx = getCtx(handlerRecord);
final String trxName = getTrxName(handlerRecord);
final I_M_IolCandHandler_Log logRecord = create(ctx, I_M_IolCandHandler_Log.class, trxName);
logRecord.setAD_Table_ID(tableDAO.retrieveTableId(handlerRecord.getTableName()));
logRecord.setRecord_ID(getId(referencedModel));
logRecord.setM_IolCandHandler_ID(handlerRecord.getM_IolCandHandler_ID());
logRecord.setStatus(status);
try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(logRecord))
{
saveRecord(logRecord);
logger.debug(status);
}
|
}
@Override
public IDeliverRequest createDeliverRequest(@NonNull final I_M_ShipmentSchedule sched, final I_C_OrderLine salesOrderLine)
{
return getHandlerFor(sched).createDeliverRequest(sched, salesOrderLine);
}
@Override
public ShipmentScheduleHandler getHandlerFor(@NonNull final I_M_ShipmentSchedule sched)
{
final String tableName = adTableDAO.retrieveTableName(sched.getAD_Table_ID());
final ShipmentScheduleHandler shipmentScheduleHandler = tableName2Handler.get(tableName);
if (shipmentScheduleHandler == null)
{
throw new AdempiereException("No shipment schedule handler defined for " + tableName + " (" + sched + ")");
}
return shipmentScheduleHandler;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ShipmentScheduleHandlerBL.java
| 1
|
请完成以下Java代码
|
public class TerminateEventDefinitionParser extends BaseChildElementParser {
public String getElementName() {
return ELEMENT_EVENT_TERMINATEDEFINITION;
}
public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model) throws Exception {
if (!(parentElement instanceof EndEvent)) {
return;
}
TerminateEventDefinition eventDefinition = new TerminateEventDefinition();
parseTerminateAllAttribute(xtr, eventDefinition);
parseTerminateMultiInstanceAttribute(xtr, eventDefinition);
BpmnXMLUtil.addXMLLocation(eventDefinition, xtr);
BpmnXMLUtil.parseChildElements(ELEMENT_EVENT_TERMINATEDEFINITION, eventDefinition, xtr, model);
((Event) parentElement).getEventDefinitions().add(eventDefinition);
}
|
protected void parseTerminateAllAttribute(XMLStreamReader xtr, TerminateEventDefinition eventDefinition) {
String terminateAllValue = xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_TERMINATE_ALL);
if (terminateAllValue != null && "true".equals(terminateAllValue)) {
eventDefinition.setTerminateAll(true);
} else {
eventDefinition.setTerminateAll(false);
}
}
protected void parseTerminateMultiInstanceAttribute(XMLStreamReader xtr, TerminateEventDefinition eventDefinition) {
String terminateMiValue = xtr.getAttributeValue(
ACTIVITI_EXTENSIONS_NAMESPACE,
ATTRIBUTE_TERMINATE_MULTI_INSTANCE
);
if (terminateMiValue != null && "true".equals(terminateMiValue)) {
eventDefinition.setTerminateMultiInstance(true);
} else {
eventDefinition.setTerminateMultiInstance(false);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\child\TerminateEventDefinitionParser.java
| 1
|
请完成以下Java代码
|
public class ThrowSignalEventActivityBehavior extends AbstractBpmnActivityBehavior {
protected final static BpmnBehaviorLogger LOG = ProcessEngineLogger.BPMN_BEHAVIOR_LOGGER;
protected final EventSubscriptionDeclaration signalDefinition;
public ThrowSignalEventActivityBehavior(EventSubscriptionDeclaration signalDefinition) {
this.signalDefinition = signalDefinition;
}
@Override
public void execute(ActivityExecution execution) throws Exception {
String businessKey = signalDefinition.getEventPayload().getBusinessKey(execution);
VariableMap variableMap = signalDefinition.getEventPayload().getInputVariables(execution);
String eventName = signalDefinition.resolveExpressionOfEventName(execution);
// trigger all event subscriptions for the signal (start and intermediate)
List<EventSubscriptionEntity> signalEventSubscriptions =
findSignalEventSubscriptions(eventName, execution.getTenantId());
for (EventSubscriptionEntity signalEventSubscription : signalEventSubscriptions) {
if (isActiveEventSubscription(signalEventSubscription)) {
signalEventSubscription.eventReceived(variableMap, null, null, businessKey, signalDefinition.isAsync());
}
}
leave(execution);
}
protected List<EventSubscriptionEntity> findSignalEventSubscriptions(String signalName, String tenantId) {
EventSubscriptionManager eventSubscriptionManager = Context.getCommandContext().getEventSubscriptionManager();
if (tenantId != null) {
return eventSubscriptionManager
|
.findSignalEventSubscriptionsByEventNameAndTenantIdIncludeWithoutTenantId(signalName, tenantId);
} else {
// find event subscriptions without tenant id
return eventSubscriptionManager.findSignalEventSubscriptionsByEventNameAndTenantId(signalName, null);
}
}
protected boolean isActiveEventSubscription(EventSubscriptionEntity signalEventSubscriptionEntity) {
return isStartEventSubscription(signalEventSubscriptionEntity)
|| isActiveIntermediateEventSubscription(signalEventSubscriptionEntity);
}
protected boolean isStartEventSubscription(EventSubscriptionEntity signalEventSubscriptionEntity) {
return signalEventSubscriptionEntity.getExecutionId() == null;
}
protected boolean isActiveIntermediateEventSubscription(EventSubscriptionEntity signalEventSubscriptionEntity) {
ExecutionEntity execution = signalEventSubscriptionEntity.getExecution();
return execution != null && !execution.isEnded() && !execution.isCanceled();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\ThrowSignalEventActivityBehavior.java
| 1
|
请完成以下Java代码
|
private boolean isAllowBroadcast(final CacheInvalidateMultiRequest multiRequest)
{
return multiRequest.getRequests().stream().anyMatch(this::isAllowBroadcast);
}
private boolean isAllowBroadcast(final CacheInvalidateRequest request)
{
final ImmutableTableNamesGroupsIndex index = this.getTableNamesToBroadcastIndex();
return index.containsTableName(request.getRootTableName())
|| index.containsTableName(request.getChildTableName());
}
/**
* Called when we got a remote cache invalidation request. It tries to invalidate local caches.
*/
@Override
public void onEvent(final IEventBus eventBus, final Event event)
{
// Ignore local events because they were fired from CacheMgt.reset methods.
// If we would not do so, we would have an infinite loop here.
if (event.isLocalEvent())
{
logger.debug("onEvent - ignoring local event={}", event);
return;
}
final CacheInvalidateMultiRequest request = createRequestFromEvent(event);
if (request == null)
{
logger.debug("onEvent - ignoring event without payload; event={}", event);
return;
|
}
//
// Reset cache for TableName/Record_ID
logger.debug("onEvent - resetting local cache for request {} because we got remote event={}", request, event);
CacheMgt.get().reset(request, CacheMgt.ResetMode.LOCAL); // don't broadcast it anymore because else we would introduce recursion
}
@VisibleForTesting
Event createEventFromRequest(@NonNull final CacheInvalidateMultiRequest request)
{
return Event.builder()
.putProperty(EVENT_PROPERTY, jsonSerializer.toJson(request))
.build();
}
@Nullable
private CacheInvalidateMultiRequest createRequestFromEvent(final Event event)
{
final String jsonRequest = event.getProperty(EVENT_PROPERTY);
if (Check.isEmpty(jsonRequest, true))
{
return null;
}
return jsonSerializer.fromJson(jsonRequest);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CacheInvalidationRemoteHandler.java
| 1
|
请完成以下Java代码
|
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (context.isMoreThanOneSelected())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final I_M_Product product = productDAO.getById(getRecord_ID());
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryFilter<I_M_Product> productFilter = queryBL.createCompositeQueryFilter(I_M_Product.class)
.addOnlyActiveRecordsFilter()
.addCompareFilter(
I_M_Product.COLUMNNAME_M_Product_ID,
CompareQueryFilter.Operator.EQUAL,
product.getM_Product_ID());
if (product.isDiscontinued())
{
final ZoneId zoneId = orgDAO.getTimeZone(OrgId.ofRepoId(product.getAD_Org_ID()));
|
final Optional<LocalDate> discontinuedFrom = Optional.ofNullable(product.getDiscontinuedFrom())
.map(discontinuedFromTimestamp -> TimeUtil.asLocalDate(discontinuedFromTimestamp, zoneId));
if (!discontinuedFrom.isPresent())
{
throw new AdempiereException(ERROR_MISSING_DISCONTINUED_FROM)
.appendParametersToMessage()
.setParameter("ProductId", product.getM_Product_ID());
}
priceListDAO.updateProductPricesIsActive(productFilter, discontinuedFrom.get(), false);
}
else
{
priceListDAO.updateProductPricesIsActive(productFilter, null, true);
}
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\process\M_ProductPrice_ActivationBasedOnProductDiscontinuedFlag_Process.java
| 1
|
请完成以下Java代码
|
public class AnonymousAuthenticationProvider implements AuthenticationProvider, MessageSourceAware {
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private String key;
public AnonymousAuthenticationProvider(String key) {
Assert.hasLength(key, "A Key is required");
this.key = key;
}
@Override
public @Nullable Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!supports(authentication.getClass())) {
return null;
}
if (this.key.hashCode() != ((AnonymousAuthenticationToken) authentication).getKeyHash()) {
throw new BadCredentialsException(this.messages.getMessage("AnonymousAuthenticationProvider.incorrectKey",
"The presented AnonymousAuthenticationToken does not contain the expected key"));
}
return authentication;
}
|
public String getKey() {
return this.key;
}
@Override
public void setMessageSource(MessageSource messageSource) {
Assert.notNull(messageSource, "messageSource cannot be null");
this.messages = new MessageSourceAccessor(messageSource);
}
@Override
public boolean supports(Class<?> authentication) {
return (AnonymousAuthenticationToken.class.isAssignableFrom(authentication));
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\AnonymousAuthenticationProvider.java
| 1
|
请完成以下Java代码
|
private boolean isReversal(final I_M_InOut inout)
{
return inout.getReversal_ID() > 0;
}
@DocValidate(timings = { ModelValidator.TIMING_AFTER_REVERSECORRECT, ModelValidator.TIMING_AFTER_REVERSEACCRUAL, ModelValidator.TIMING_AFTER_VOID, ModelValidator.TIMING_AFTER_REACTIVATE })
public void onReverse(final I_M_InOut inout)
{
if (isMaterialReturn(inout))
{
return;
}
final boolean reversal = true;
eventSender.send(createInOutChangedEvent(inout, reversal));
}
private InOutChangedEvent createInOutChangedEvent(final I_M_InOut inout, final boolean reversal)
{
return InOutChangedEvent.builder()
.bpartnerId(BPartnerId.ofRepoId(inout.getC_BPartner_ID()))
.movementDate(TimeUtil.asInstant(inout.getMovementDate()))
.soTrx(SOTrx.ofBoolean(inout.isSOTrx()))
.productIds(extractProductIds(inout))
.reversal(reversal)
|
.build();
}
private boolean isMaterialReturn(final I_M_InOut inout)
{
final String movementType = inout.getMovementType();
return Services.get(IInOutBL.class).isReturnMovementType(movementType);
}
private Set<ProductId> extractProductIds(final I_M_InOut inout)
{
final IInOutDAO inoutsRepo = Services.get(IInOutDAO.class);
return inoutsRepo.retrieveLines(inout)
.stream()
.map(I_M_InOutLine::getM_Product_ID)
.map(ProductId::ofRepoIdOrNull)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\product\stats\interceptor\M_InOut.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WEBUI_M_ReceiptSchedule_RunMaterialReceiptJasper extends ReceiptScheduleBasedProcess
{
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final I_M_ReceiptSchedule receiptSchedule = context.getSelectedModel(I_M_ReceiptSchedule.class);
// guard against null (might happen if the selected ID is not valid)
if (receiptSchedule == null)
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
|
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final I_M_ReceiptSchedule receiptSchedule = getRecord(I_M_ReceiptSchedule.class);
HUReceiptScheduleReportExecutor
.get(receiptSchedule)
.executeHUReport();
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_RunMaterialReceiptJasper.java
| 2
|
请完成以下Java代码
|
public PurchaseCandidatesGroup withProfitInfo(@Nullable final PurchaseProfitInfo newProfitInfo)
{
if (Objects.equals(getProfitInfoOrNull(), newProfitInfo))
{
return this;
}
return toBuilder().profitInfoOrNull(newProfitInfo).build();
}
public BPartnerId getVendorId()
{
return getVendorProductInfo().getVendorId();
}
public String getVendorProductNo()
{
return getVendorProductInfo().getVendorProductNo();
}
public ProductId getProductId()
{
return getVendorProductInfo().getProductId();
}
public AttributeSetInstanceId getAttributeSetInstanceId()
{
return attributeSetInstanceId;
}
public boolean isAggregatePOs()
{
if (!isAllowPOAggregation())
|
{
return false;
}
return getVendorProductInfo().isAggregatePOs();
}
public PurchaseCandidatesGroup allowingPOAggregation(final boolean allowPOAggregation)
{
if (this.isAllowPOAggregation() == allowPOAggregation)
{
return this;
}
return toBuilder().allowPOAggregation(allowPOAggregation).build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseCandidatesGroup.java
| 1
|
请完成以下Java代码
|
private DocOutBoundRecipientCC getMailCC(final I_C_Invoice invoiceRecord)
{
final BPartnerId billPartnerId = BPartnerId.ofRepoId(invoiceRecord.getC_BPartner_ID());
if (!partnerBL.isInvoiceEmailCcToMember(billPartnerId))
{
return null;
}
final OrderId orderId = OrderId.ofRepoIdOrNull(invoiceRecord.getC_Order_ID());
if (orderId == null)
{
return null;
}
final I_C_Order orderRecord = orderBL.getById(orderId);
final UserId shipToContactId = UserId.ofRepoIdOrNull(orderRecord.getAD_User_ID());
if (shipToContactId != null && shipToContactId.isRegularUser())
{
final DocOutBoundRecipient shipToRecipient = recipientRepository.getByUserId(shipToContactId)
.withEmailAddressIfEmpty(() -> orderBL.getLocationEmail(orderRecord));
return shipToRecipient.isEmailAddressSet() ? DocOutBoundRecipientCC.of(shipToRecipient) : null;
}
else
{
final BPartnerId shipBPartnerId = BPartnerId.ofRepoId(orderRecord.getC_BPartner_ID());
final User defaultShipToContact = bpartnerBL.retrieveContactOrNull(
RetrieveContactRequest
.builder()
.bpartnerId(shipBPartnerId)
.bPartnerLocationId(BPartnerLocationId.ofRepoId(shipBPartnerId, invoiceRecord.getC_BPartner_Location_ID()))
|
.contactType(ContactType.SHIP_TO_DEFAULT)
.build());
if (defaultShipToContact != null)
{
final DocOutBoundRecipient defaultShipToRecipient = recipientRepository.ofUser(defaultShipToContact)
.withEmailAddressIfEmpty(() -> orderBL.getLocationEmail(orderRecord));
return defaultShipToRecipient.isEmailAddressSet() ? DocOutBoundRecipientCC.of(defaultShipToRecipient) : null;
}
else
{
return null;
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\mailrecipient\impl\InvoiceDocOutboundLogMailRecipientProvider.java
| 1
|
请完成以下Java代码
|
private void pushToWebUI()
{
trxManager.getTrxListenerManagerOrAutoCommit(ITrx.TRXNAME_ThreadInherited)
.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 -> pushToWebUINow());
}
private void pushToWebUINow()
{
//
// Push new RfQs
final List<SyncRfQ> syncRfQsCopy = copyAndClear(this.syncRfQs);
if (!syncRfQsCopy.isEmpty())
{
webuiPush.pushRfQs(syncRfQsCopy);
}
// Push close events
{
final List<SyncRfQCloseEvent> syncRfQCloseEventsCopy = copyAndClear(this.syncRfQCloseEvents);
if (!syncRfQCloseEventsCopy.isEmpty())
{
webuiPush.pushRfQCloseEvents(syncRfQCloseEventsCopy);
}
// Internally push the planned product supplies, to create the PMM_PurchaseCandidates
serverSyncBL.reportProductSupplies(PutProductSuppliesRequest.of(syncProductSupplies));
|
}
}
private static <T> List<T> copyAndClear(final List<T> list)
{
if (list == null || list.isEmpty())
{
return ImmutableList.of();
}
final List<T> listCopy = ImmutableList.copyOf(list);
list.clear();
return listCopy;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\rfq\PMMWebuiRfQResponsePublisherInstance.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BankAccountQuery
{
@Nullable
@Singular
Set<BPBankAcctUse> bpBankAcctUses;
@Nullable
BPartnerId bPartnerId;
@Nullable
InvoiceId invoiceId;
boolean containsQRIBAN;
@Builder(toBuilder = true)
private BankAccountQuery(
@Nullable @Singular final Collection<BPBankAcctUse> bpBankAcctUses,
@Nullable final BPartnerId bPartnerId,
|
@Nullable final InvoiceId invoiceId,
final Boolean containsQRIBAN)
{
this.bpBankAcctUses = bpBankAcctUses != null && !bpBankAcctUses.isEmpty() ?
ImmutableSet.copyOf(bpBankAcctUses) :
null;
this.bPartnerId = bPartnerId;
this.invoiceId = invoiceId;
this.containsQRIBAN = CoalesceUtil.coalesce(containsQRIBAN, false);
assume(bPartnerId != null || invoiceId != null,
"At least one of the parameters 'bPartnerId, invoiceId and value needs to be non-null/non-empty");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\BankAccountQuery.java
| 2
|
请完成以下Java代码
|
class RemoteUrlPropertyExtractor implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {
private static final String NON_OPTION_ARGS = CommandLinePropertySource.DEFAULT_NON_OPTION_ARGS_PROPERTY_NAME;
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment = event.getEnvironment();
String url = cleanRemoteUrl(environment.getProperty(NON_OPTION_ARGS));
Assert.state(StringUtils.hasLength(url), "No remote URL specified");
Assert.state(url.indexOf(',') == -1, "Multiple URLs specified");
try {
new URI(url);
}
catch (URISyntaxException ex) {
throw new IllegalStateException("Malformed URL '" + url + "'");
}
Map<String, Object> source = Collections.singletonMap("remoteUrl", url);
PropertySource<?> propertySource = new MapPropertySource("remoteUrl", source);
|
environment.getPropertySources().addLast(propertySource);
}
private @Nullable String cleanRemoteUrl(@Nullable String url) {
if (StringUtils.hasText(url) && url.endsWith("/")) {
return url.substring(0, url.length() - 1);
}
return url;
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\RemoteUrlPropertyExtractor.java
| 1
|
请完成以下Java代码
|
public Object[] toArray() {
return new Object[0];
}
@Override
public <T1> T1[] toArray(T1[] a) {
return null;
}
@Override
public boolean add(T t) {
return false;
}
@Override
public boolean remove(Object o) {
return false;
}
@Override
public boolean containsAll(Collection<?> c) {
return false;
}
|
@Override
public boolean addAll(Collection<? extends T> c) {
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
return false;
}
@Override
public boolean retainAll(Collection<?> c) {
return false;
}
@Override
public void clear() {
}
}
|
repos\tutorials-master\core-java-modules\core-java-streams-5\src\main\java\com\baeldung\streams\parallelstream\MyBookContainer.java
| 1
|
请完成以下Java代码
|
@Nullable C unregisterContributor(String name) {
Assert.notNull(name, "'name' must not be null");
synchronized (this.monitor) {
C unregistered = this.contributors.get(name);
if (unregistered != null) {
Map<String, C> contributors = new LinkedHashMap<>(this.contributors);
contributors.remove(name);
this.contributors = Collections.unmodifiableMap(contributors);
}
return unregistered;
}
}
@Nullable C getContributor(String name) {
return this.contributors.get(name);
}
|
Stream<E> stream() {
return this.contributors.entrySet()
.stream()
.map((entry) -> this.entryAdapter.apply(entry.getKey(), entry.getValue()));
}
private void verifyName(String name, C contributor) {
Assert.state(StringUtils.hasText(name),
() -> "Name for contributor '%s' must not be empty".formatted(contributor));
if (!CollectionUtils.isEmpty(this.nameValidators)) {
this.nameValidators.forEach((nameValidator) -> nameValidator.validate(name));
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\registry\AbstractRegistry.java
| 1
|
请完成以下Java代码
|
private HashMap<InvoiceCandidateId, StockQtyAndUOMQty> createInvoiceableQtysMap()
{
// ic2QtyInvoiceable keeps track of the stockQty that we have left to invoice, to make sure that we don't invoice more than the invoice candidate allows us to
final HashMap<InvoiceCandidateId, StockQtyAndUOMQty> ic2QtyInvoicable = new HashMap<>();
// we initialize the map with all ICs' qtyToInvoice values
for (final List<InvoiceCandidateWithInOutLine> icsForKey : aggKey2iciol.values())
{
for (final InvoiceCandidateWithInOutLine ics : icsForKey)
{
final I_C_Invoice_Candidate ic = ics.getC_Invoice_Candidate();
if (!ic2QtyInvoicable.containsKey(ics.getInvoicecandidateId()))
{
// Initialize, if necessary
// task 08507: ic.getQtyToInvoice() is already the "effective" Qty.
// Even if QtyToInvoice_Override is set, the system will decide what to invoice (e.g. based on InvoiceRule and QtyDelivered)
// and update QtyToInvoice accordingly, possibly to a value that is different from QtyToInvoice_Override.
final StockQtyAndUOMQty qtyToInvoice = StockQtyAndUOMQtys.create(
|
ic.getQtyToInvoice(), ics.getProductId(),
ic.getQtyToInvoiceInUOM(), ics.getIcUomId());
ic2QtyInvoicable.put(ics.getInvoicecandidateId(), qtyToInvoice);
}
}
}
return ic2QtyInvoicable;
}
@Override
public void setContext(final Properties ctx, final String trxName)
{
// this implementation has no use for 'ctx' and 'trxName'
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\aggregator\standard\DefaultAggregator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
this.sendEmailSync(to, subject, content, isMultipart, isHtml);
}
private void sendEmailSync(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
log.debug(
"Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
isMultipart,
isHtml,
to,
subject,
content
);
// Prepare message using a Spring helper
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
message.setTo(to);
message.setFrom(jHipsterProperties.getMail().getFrom());
message.setSubject(subject);
message.setText(content, isHtml);
javaMailSender.send(mimeMessage);
log.debug("Sent email to User '{}'", to);
} catch (MailException | MessagingException e) {
log.warn("Email could not be sent to user '{}'", to, e);
}
}
@Async
public void sendEmailFromTemplate(User user, String templateName, String titleKey) {
this.sendEmailFromTemplateSync(user, templateName, titleKey);
}
private void sendEmailFromTemplateSync(User user, String templateName, String titleKey) {
if (user.getEmail() == null) {
log.debug("Email doesn't exist for user '{}'", user.getLogin());
return;
}
Locale locale = Locale.forLanguageTag(user.getLangKey());
Context context = new Context(locale);
context.setVariable(USER, user);
context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
String content = templateEngine.process(templateName, context);
|
String subject = messageSource.getMessage(titleKey, null, locale);
this.sendEmailSync(user.getEmail(), subject, content, false, true);
}
@Async
public void sendActivationEmail(User user) {
log.debug("Sending activation email to '{}'", user.getEmail());
this.sendEmailFromTemplateSync(user, "mail/activationEmail", "email.activation.title");
}
@Async
public void sendCreationEmail(User user) {
log.debug("Sending creation email to '{}'", user.getEmail());
this.sendEmailFromTemplateSync(user, "mail/creationEmail", "email.activation.title");
}
@Async
public void sendPasswordResetMail(User user) {
log.debug("Sending password reset email to '{}'", user.getEmail());
this.sendEmailFromTemplateSync(user, "mail/passwordResetEmail", "email.reset.title");
}
}
|
repos\tutorials-master\jhipster-8-modules\jhipster-8-monolithic\src\main\java\com\baeldung\jhipster8\service\MailService.java
| 2
|
请完成以下Java代码
|
private StagingData retrieveStagingData(@NonNull final APITransactionId transactionId)
{
final ImmutableList<I_PP_Order_ExportAudit> records = queryBL.createQueryBuilder(I_PP_Order_ExportAudit.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_PP_Order_ExportAudit.COLUMNNAME_TransactionIdAPI, transactionId.toJson())
.create()
.listImmutable(I_PP_Order_ExportAudit.class);
return StagingData.builder()
.transactionId(transactionId)
.records(records)
.build();
}
private static PPOrderId extactPPOrderId(@NonNull final I_PP_Order_ExportAudit record)
{
return PPOrderId.ofRepoId(record.getPP_Order_ID());
}
@Value
private static class StagingData
{
private final APITransactionId transactionId;
|
private final ImmutableList<I_PP_Order_ExportAudit> records;
@Getter(AccessLevel.NONE)
ImmutableMap<PPOrderId, I_PP_Order_ExportAudit> recordsByOrderId;
@Builder
private StagingData(
@NonNull final APITransactionId transactionId,
@NonNull final List<I_PP_Order_ExportAudit> records)
{
this.transactionId = transactionId;
this.recordsByOrderId = Maps.uniqueIndex(records, record -> extactPPOrderId(record));
this.records = ImmutableList.copyOf(records);
}
@Nullable
public I_PP_Order_ExportAudit getByOrderIdOrNull(@NonNull final PPOrderId orderId)
{
return recordsByOrderId.get(orderId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\ManufacturingOrderExportAuditRepository.java
| 1
|
请完成以下Java代码
|
static class ActivityInstanceStateImpl implements ActivityInstanceState {
public final int stateCode;
protected final String name;
public ActivityInstanceStateImpl(int suspensionCode, String string) {
this.stateCode = suspensionCode;
this.name = string;
}
public int getStateCode() {
return stateCode;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + stateCode;
return result;
}
@Override
|
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ActivityInstanceStateImpl other = (ActivityInstanceStateImpl) obj;
if (stateCode != other.stateCode)
return false;
return true;
}
@Override
public String toString() {
return name;
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\ActivityInstanceState.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.