instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void setMSV3_FaultInfo_ID (int MSV3_FaultInfo_ID)
{
if (MSV3_FaultInfo_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_FaultInfo_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MSV3_FaultInfo_ID, Integer.valueOf(MSV3_FaultInfo_ID));
}
/** Get MSV3_FaultInfo.
@return MSV3_FaultInfo */
@Override
public int getMSV3_FaultInfo_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_FaultInfo_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* MSV3_FaultInfoType AD_Reference_ID=540827
* Reference name: MSV3_FaultInfoType
*/
public static final int MSV3_FAULTINFOTYPE_AD_Reference_ID=540827;
/** AuthorizationFaultInfo = AuthorizationFaultInfo */
public static final String MSV3_FAULTINFOTYPE_AuthorizationFaultInfo = "AuthorizationFaultInfo";
/** DenialOfServiceFault = DenialOfServiceFault */
public static final String MSV3_FAULTINFOTYPE_DenialOfServiceFault = "DenialOfServiceFault";
/** LieferscheinOderBarcodeUnbekanntFaultInfo = LieferscheinOderBarcodeUnbekanntFaultInfo */
public static final String MSV3_FAULTINFOTYPE_LieferscheinOderBarcodeUnbekanntFaultInfo = "LieferscheinOderBarcodeUnbekanntFaultInfo";
/** ServerFaultInfo = ServerFaultInfo */
public static final String MSV3_FAULTINFOTYPE_ServerFaultInfo = "ServerFaultInfo";
/** ValidationFaultInfo = ValidationFaultInfo */ | public static final String MSV3_FAULTINFOTYPE_ValidationFaultInfo = "ValidationFaultInfo";
/** Set FaultInfoType.
@param MSV3_FaultInfoType FaultInfoType */
@Override
public void setMSV3_FaultInfoType (java.lang.String MSV3_FaultInfoType)
{
set_Value (COLUMNNAME_MSV3_FaultInfoType, MSV3_FaultInfoType);
}
/** Get FaultInfoType.
@return FaultInfoType */
@Override
public java.lang.String getMSV3_FaultInfoType ()
{
return (java.lang.String)get_Value(COLUMNNAME_MSV3_FaultInfoType);
}
/** Set TechnischerFehlertext.
@param MSV3_TechnischerFehlertext TechnischerFehlertext */
@Override
public void setMSV3_TechnischerFehlertext (java.lang.String MSV3_TechnischerFehlertext)
{
set_Value (COLUMNNAME_MSV3_TechnischerFehlertext, MSV3_TechnischerFehlertext);
}
/** Get TechnischerFehlertext.
@return TechnischerFehlertext */
@Override
public java.lang.String getMSV3_TechnischerFehlertext ()
{
return (java.lang.String)get_Value(COLUMNNAME_MSV3_TechnischerFehlertext);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_FaultInfo.java | 1 |
请完成以下Java代码 | public class StringToNumericModifier implements IQueryFilterModifier
{
@Override
public @NonNull String getColumnSql(@NonNull final String columnName)
{
return " cast_to_numeric_or_null (" + columnName + ") " ;
}
@Override
public String getValueSql(final Object value, final List<Object> params)
{
if (value instanceof ModelColumnNameValue<?>)
{
final ModelColumnNameValue<?> modelValue = (ModelColumnNameValue<?>)value;
return modelValue.getColumnName();
} | params.add(value);
return "?";
}
@Nullable
@Override
public Object convertValue(@Nullable final String columnName, @Nullable final Object value, @Nullable final Object model)
{
if (value == null)
{
return null;
}
return NumberUtils.asBigDecimal(value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\StringToNumericModifier.java | 1 |
请完成以下Java代码 | public CaseSentryPartQueryImpl sourceCaseExecutionId(String sourceCaseExecutionId) {
ensureNotNull(NotValidException.class, "sourceCaseExecutionId", sourceCaseExecutionId);
this.sourceCaseExecutionId = sourceCaseExecutionId;
return this;
}
public CaseSentryPartQueryImpl standardEvent(String standardEvent) {
ensureNotNull(NotValidException.class, "standardEvent", standardEvent);
this.standardEvent = standardEvent;
return this;
}
public CaseSentryPartQueryImpl variableEvent(String variableEvent) {
ensureNotNull(NotValidException.class, "variableEvent", variableEvent);
this.variableEvent = variableEvent;
return this;
}
public CaseSentryPartQueryImpl variableName(String variableName) {
ensureNotNull(NotValidException.class, "variableName", variableName);
this.variableName = variableName;
return this;
}
public CaseSentryPartQueryImpl satisfied() {
this.satisfied = true;
return this;
}
// order by ///////////////////////////////////////////
public CaseSentryPartQueryImpl orderByCaseSentryId() {
orderBy(CaseSentryPartQueryProperty.CASE_SENTRY_PART_ID);
return this;
}
public CaseSentryPartQueryImpl orderByCaseInstanceId() {
orderBy(CaseSentryPartQueryProperty.CASE_INSTANCE_ID);
return this;
}
public CaseSentryPartQueryImpl orderByCaseExecutionId() {
orderBy(CaseSentryPartQueryProperty.CASE_EXECUTION_ID);
return this;
}
public CaseSentryPartQueryImpl orderBySentryId() {
orderBy(CaseSentryPartQueryProperty.SENTRY_ID);
return this;
}
public CaseSentryPartQueryImpl orderBySource() {
orderBy(CaseSentryPartQueryProperty.SOURCE);
return this;
}
// results ////////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getCaseSentryPartManager() | .findCaseSentryPartCountByQueryCriteria(this);
}
public List<CaseSentryPartEntity> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
List<CaseSentryPartEntity> result = commandContext
.getCaseSentryPartManager()
.findCaseSentryPartByQueryCriteria(this, page);
return result;
}
// getters /////////////////////////////////////////////
public String getId() {
return id;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getSentryId() {
return sentryId;
}
public String getType() {
return type;
}
public String getSourceCaseExecutionId() {
return sourceCaseExecutionId;
}
public String getStandardEvent() {
return standardEvent;
}
public String getVariableEvent() {
return variableEvent;
}
public String getVariableName() {
return variableName;
}
public boolean isSatisfied() {
return satisfied;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseSentryPartQueryImpl.java | 1 |
请完成以下Java代码 | public Garnishment1 getGrnshmtRmt() {
return grnshmtRmt;
}
/**
* Sets the value of the grnshmtRmt property.
*
* @param value
* allowed object is
* {@link Garnishment1 }
*
*/
public void setGrnshmtRmt(Garnishment1 value) {
this.grnshmtRmt = value;
}
/**
* Gets the value of the addtlRmtInf property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the addtlRmtInf property.
*
* <p>
* For example, to add a new item, do as follows: | * <pre>
* getAddtlRmtInf().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAddtlRmtInf() {
if (addtlRmtInf == null) {
addtlRmtInf = new ArrayList<String>();
}
return this.addtlRmtInf;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\StructuredRemittanceInformation13.java | 1 |
请完成以下Java代码 | default ProjectDescription createCopy() {
throw new UnsupportedOperationException();
}
/**
* Return an immutable mapping of requested {@link Dependency dependencies}.
* @return the requested dependencies
*/
Map<String, Dependency> getRequestedDependencies();
/**
* Return the requested platform {@link Version}.
* @return the requested platform version or {@code null}
*/
Version getPlatformVersion();
/**
* Return the {@link BuildSystem} to use.
* @return the build system or {@code null}
*/
BuildSystem getBuildSystem();
/**
* Return the build {@link Packaging} to use.
* @return the build packaging or {@code null}
*/
Packaging getPackaging();
/**
* Return the primary {@link Language} of the project.
* @return the primary language or {@code null}
*/
Language getLanguage();
/**
* Return the {@link ConfigurationFileFormat} of the project.
* @return the configuration file format or {@code null}
*/
ConfigurationFileFormat getConfigurationFileFormat();
/**
* Return the build {@code groupId}.
* @return the groupId or {@code null}
*/
String getGroupId();
/**
* Return the build {@code artifactId}.
* @return the artifactId or {@code null}
*/
String getArtifactId();
/**
* Return the version of the project.
* @return the version of {@code null}
*/
String getVersion();
/**
* Return a simple name for the project.
* @return the name of the project or {@code null}
*/ | String getName();
/**
* Return a human-readable description of the project.
* @return the description of the project or {@code null}
*/
String getDescription();
/**
* Return the name of the application as a standard Java identifier.
* @return the name of the application or {@code null}
*/
String getApplicationName();
/**
* Return the root package name of the project.
* @return the package name or {@code null}
*/
String getPackageName();
/**
* Return the base directory of the project or {@code null} to use the root directory.
* @return the base directory
*/
String getBaseDirectory();
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\project\ProjectDescription.java | 1 |
请完成以下Java代码 | private Map<String, List<PropertyMigration>> getContent(
Function<LegacyProperties, List<PropertyMigration>> extractor) {
return this.content.entrySet()
.stream()
.filter((entry) -> !extractor.apply(entry.getValue()).isEmpty())
.collect(
Collectors.toMap(Map.Entry::getKey, (entry) -> new ArrayList<>(extractor.apply(entry.getValue()))));
}
private void append(StringBuilder report, Map<String, List<PropertyMigration>> content) {
content.forEach((name, properties) -> {
report.append(String.format("Property source '%s':%n", name));
properties.sort(PropertyMigration.COMPARATOR);
properties.forEach((property) -> {
report.append(String.format("\tKey: %s%n", property.getProperty().getName()));
if (property.getLineNumber() != null) {
report.append(String.format("\t\tLine: %d%n", property.getLineNumber()));
}
report.append(String.format("\t\t%s%n", property.determineReason()));
});
report.append(String.format("%n"));
});
}
/**
* Register a new property source.
* @param name the name of the property source
* @param properties the {@link PropertyMigration} instances
*/ | void add(String name, List<PropertyMigration> properties) {
this.content.put(name, new LegacyProperties(properties));
}
private static class LegacyProperties {
private final List<PropertyMigration> properties;
LegacyProperties(List<PropertyMigration> properties) {
this.properties = new ArrayList<>(properties);
}
List<PropertyMigration> getRenamed() {
return this.properties.stream().filter(PropertyMigration::isCompatibleType).toList();
}
List<PropertyMigration> getUnsupported() {
return this.properties.stream().filter((property) -> !property.isCompatibleType()).toList();
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-properties-migrator\src\main\java\org\springframework\boot\context\properties\migrator\PropertiesMigrationReport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DpdClientLogEvent
{
/**
* Regexp explanation: .*? means ungreedy (while .* means greedy).
*/
private static final String PARCELLABELS_PDF_REGEX = "(?m)<parcellabelsPDF>(.*?\\s*?)</parcellabelsPDF>";
private static final String PARCELLABELS_PDF_REPLACEMENT_TEXT = "<parcellabelsPDF>PDF TEXT REMOVED!</parcellabelsPDF>";
int deliveryOrderRepoId;
DpdClientConfig config;
Marshaller marshaller;
Object requestElement;
@Nullable
Object responseElement;
@Nullable
Exception responseException;
long durationMillis;
String getConfigSummary()
{
return config != null ? config.toString() : "";
}
@Nullable
String getRequestAsString()
{
return elementToString(requestElement);
}
@Nullable
String getResponseAsString() | {
return elementToString(responseElement);
}
@Nullable
private String elementToString(@Nullable final Object element)
{
if (element == null)
{
return null;
}
try
{
final StringResult result = new StringResult();
marshaller.marshal(element, result);
return cleanupPdfData(result.toString());
}
catch (final Exception ex)
{
throw new AdempiereException("Failed converting " + element + " to String", ex);
}
}
/**
* remove the pdfdata since it's long and useless and we also attach it to the PO record
*/
@NonNull
@VisibleForTesting
static String cleanupPdfData(@NonNull final String s)
{
return s.replaceAll(PARCELLABELS_PDF_REGEX, PARCELLABELS_PDF_REPLACEMENT_TEXT);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java\de\metas\shipper\gateway\dpd\logger\DpdClientLogEvent.java | 2 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_BankStatementMatcher[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Bank Statement Matcher.
@param C_BankStatementMatcher_ID
Algorithm to match Bank Statement Info to Business Partners, Invoices and Payments
*/
public void setC_BankStatementMatcher_ID (int C_BankStatementMatcher_ID)
{
if (C_BankStatementMatcher_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BankStatementMatcher_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BankStatementMatcher_ID, Integer.valueOf(C_BankStatementMatcher_ID));
}
/** Get Bank Statement Matcher.
@return Algorithm to match Bank Statement Info to Business Partners, Invoices and Payments
*/
public int getC_BankStatementMatcher_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BankStatementMatcher_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Classname.
@param Classname
Java Classname
*/
public void setClassname (String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Classname.
@return Java Classname
*/
public String getClassname ()
{
return (String)get_Value(COLUMNNAME_Classname);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description); | }
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementMatcher.java | 1 |
请完成以下Java代码 | public int getRemovalTimeUpdateChunkSize() {
return removalTimeUpdateChunkSize;
}
public ProcessEngineConfigurationImpl setRemovalTimeUpdateChunkSize(int removalTimeUpdateChunkSize) {
this.removalTimeUpdateChunkSize = removalTimeUpdateChunkSize;
return this;
}
/**
* @return a exception code interceptor. The interceptor is not registered in case
* {@code disableExceptionCode} is configured to {@code true}.
*/
protected ExceptionCodeInterceptor getExceptionCodeInterceptor() {
return new ExceptionCodeInterceptor(builtinExceptionCodeProvider, customExceptionCodeProvider);
}
public DiagnosticsRegistry getDiagnosticsRegistry() {
return diagnosticsRegistry;
} | public ProcessEngineConfiguration setDiagnosticsRegistry(DiagnosticsRegistry diagnosticsRegistry) {
this.diagnosticsRegistry = diagnosticsRegistry;
return this;
}
public boolean isLegacyJobRetryBehaviorEnabled() {
return legacyJobRetryBehaviorEnabled;
}
public ProcessEngineConfiguration setLegacyJobRetryBehaviorEnabled(boolean legacyJobRetryBehaviorEnabled) {
this.legacyJobRetryBehaviorEnabled = legacyJobRetryBehaviorEnabled;
return this;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\ProcessEngineConfigurationImpl.java | 1 |
请完成以下Java代码 | public int getC_BP_Group_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BP_Group_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set CS Creditpass business partner group.
@param CS_Creditpass_BP_Group_ID CS Creditpass business partner group */
@Override
public void setCS_Creditpass_BP_Group_ID (int CS_Creditpass_BP_Group_ID)
{
if (CS_Creditpass_BP_Group_ID < 1)
set_ValueNoCheck (COLUMNNAME_CS_Creditpass_BP_Group_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CS_Creditpass_BP_Group_ID, Integer.valueOf(CS_Creditpass_BP_Group_ID));
}
/** Get CS Creditpass business partner group.
@return CS Creditpass business partner group */
@Override
public int getCS_Creditpass_BP_Group_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CS_Creditpass_BP_Group_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config getCS_Creditpass_Config() throws RuntimeException | {
return get_ValueAsPO(COLUMNNAME_CS_Creditpass_Config_ID, de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config.class);
}
@Override
public void setCS_Creditpass_Config(de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config CS_Creditpass_Config)
{
set_ValueFromPO(COLUMNNAME_CS_Creditpass_Config_ID, de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config.class, CS_Creditpass_Config);
}
/** Get Creditpass Einstellung.
@return Creditpass Einstellung */
@Override
public int getCS_Creditpass_Config_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CS_Creditpass_Config_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Creditpass Einstellung.
@param CS_Creditpass_Config_ID Creditpass Einstellung */
@Override
public void setCS_Creditpass_Config_ID (int CS_Creditpass_Config_ID)
{
if (CS_Creditpass_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_CS_Creditpass_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CS_Creditpass_Config_ID, Integer.valueOf(CS_Creditpass_Config_ID));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_BP_Group.java | 1 |
请完成以下Java代码 | public void handleBpmnError(String externalTaskId, String workerId, String errorCode, String errorMessage, Map<String, Object> variables) {
commandExecutor.execute(new HandleExternalTaskBpmnErrorCmd(externalTaskId, workerId, errorCode, errorMessage, variables));
}
@Override
public void unlock(String externalTaskId) {
commandExecutor.execute(new UnlockExternalTaskCmd(externalTaskId));
}
public void setRetries(String externalTaskId, int retries, boolean writeUserOperationLog) {
commandExecutor.execute(new SetExternalTaskRetriesCmd(externalTaskId, retries, writeUserOperationLog));
}
@Override
public void setPriority(String externalTaskId, long priority) {
commandExecutor.execute(new SetExternalTaskPriorityCmd(externalTaskId, priority));
}
public ExternalTaskQuery createExternalTaskQuery() {
return new ExternalTaskQueryImpl(commandExecutor);
}
@Override
public List<String> getTopicNames() {
return commandExecutor.execute(new GetTopicNamesCmd(false,false,false));
}
@Override
public List<String> getTopicNames(boolean withLockedTasks, boolean withUnlockedTasks, boolean withRetriesLeft) {
return commandExecutor.execute(new GetTopicNamesCmd(withLockedTasks, withUnlockedTasks, withRetriesLeft));
}
public String getExternalTaskErrorDetails(String externalTaskId) {
return commandExecutor.execute(new GetExternalTaskErrorDetailsCmd(externalTaskId));
}
@Override | public void setRetries(String externalTaskId, int retries) {
setRetries(externalTaskId, retries, true);
}
@Override
public void setRetries(List<String> externalTaskIds, int retries) {
updateRetries()
.externalTaskIds(externalTaskIds)
.set(retries);
}
@Override
public Batch setRetriesAsync(List<String> externalTaskIds, ExternalTaskQuery externalTaskQuery, int retries) {
return updateRetries()
.externalTaskIds(externalTaskIds)
.externalTaskQuery(externalTaskQuery)
.setAsync(retries);
}
@Override
public UpdateExternalTaskRetriesSelectBuilder updateRetries() {
return new UpdateExternalTaskRetriesBuilderImpl(commandExecutor);
}
@Override
public void extendLock(String externalTaskId, String workerId, long lockDuration) {
commandExecutor.execute(new ExtendLockOnExternalTaskCmd(externalTaskId, workerId, lockDuration));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExternalTaskServiceImpl.java | 1 |
请完成以下Java代码 | public abstract class BpmnModelElementInstanceImpl extends ModelElementInstanceImpl implements BpmnModelElementInstance {
public BpmnModelElementInstanceImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
@SuppressWarnings("rawtypes")
public AbstractBaseElementBuilder builder() {
throw new BpmnModelException("No builder implemented for " + this);
}
public boolean isScope() {
return this instanceof org.camunda.bpm.model.bpmn.instance.Process || this instanceof SubProcess;
} | public BpmnModelElementInstance getScope() {
BpmnModelElementInstance parentElement = (BpmnModelElementInstance) getParentElement();
if (parentElement != null) {
if (parentElement.isScope()) {
return parentElement;
}
else {
return parentElement.getScope();
}
}
else {
return null;
}
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\BpmnModelElementInstanceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Map<String, String> getTaxiOrderStatus(Long orderId, Retailer retailer) throws ParseException
{
Gson gson = new Gson();
Map<String, String> resultMap = new HashMap<>();
OrderState orderState = null;
DriverInfo driverInfo = null;
String request = "order_id=" + orderId;
String result = api.call("get_order_state", request, "GET", "", retailer.getTaxiPropertiesList().get(0));
try {
orderState = gson.fromJson(result, OrderState.class);
} catch (JsonSyntaxException jse) {
jse.printStackTrace();
}
if(orderState != null && orderState.getDescr().equals("OK"))
{
Integer driverId = orderState.getData().getDriverId();
if (driverId != null) {
String requestParam = "driver_id=" + driverId +"&need_photo=false";
String resultInfoDriver = api.call("get_driver_info", requestParam, "GET", "", retailer.getTaxiPropertiesList().get(0));
if (resultInfoDriver != null) {
try {
driverInfo = gson.fromJson(resultInfoDriver, DriverInfo.class);
} catch (JsonSyntaxException jse) {
jse.printStackTrace();
}
if (driverInfo != null && driverInfo.getDescr().equals("OK")){
resultMap.put("name", driverInfo.getData().getName()); | List<Phone> phoneList = driverInfo.getData().getPhones().stream().filter(Phone::getUseForCall).collect(Collectors.toList());
if (phoneList.size() > 0)
resultMap.put("phones", phoneList.get(0).getPhone());
else
resultMap.put("phones", "телефон не указан");
} else
{
resultMap.put("name", "Фио не указано");
resultMap.put("phones", "телефон не указан");
}
}
}
resultMap.put("get_order_state", orderState.getData().getStateKind());
resultMap.put("car_mark", orderState.getData().getCarMark());
resultMap.put("car_model", orderState.getData().getCarModel());
resultMap.put("car_color", orderState.getData().getCarColor());
resultMap.put("car_number", orderState.getData().getCarNumber());
return resultMap;
}
else
{
return null;
}
}
} | repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\service\taxiMaster\TaxiOrderProcess.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class C_AllocationHdr
{
private final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class);
private final IAllocationDAO allocationDAO = Services.get(IAllocationDAO.class);
private final ITrxManager trxManager = Services.get(ITrxManager.class);
/**
* Updates C_Invoice.IsPaid on all referenced invoices each time an allocation is completed, reversed etc.
* Background: when a credit memo was allocated against a zpayment and a service-invoice, the check was not done, so the credit memo remained with Paid=N.
* TODO: see if we can get rid of all other calls to {@link IInvoiceBL#testAllocation(I_C_Invoice, boolean)}.
*/
@DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE,
ModelValidator.TIMING_AFTER_REACTIVATE,
ModelValidator.TIMING_AFTER_REVERSECORRECT,
ModelValidator.TIMING_AFTER_VOID })
public void testInvoiceAllocation(@NonNull final I_C_AllocationHdr allocationHdr)
{
trxManager.runAfterCommit(() -> testInvoiceAllocation0(PaymentAllocationId.ofRepoId(allocationHdr.getC_AllocationHdr_ID())));
} | private void testInvoiceAllocation0(@NonNull final PaymentAllocationId allocationId)
{
final I_C_AllocationHdr allocationHdrRecord = allocationDAO.getById(allocationId);
final List<I_C_AllocationLine> allocationLineRecords = allocationDAO.retrieveLines(allocationHdrRecord);
for (final I_C_AllocationLine allocationLineRecord : allocationLineRecords)
{
if (allocationLineRecord.getC_Invoice_ID() > 0)
{
final boolean ignoreProcessed = false;
invoiceBL.testAllocation(allocationLineRecord.getC_Invoice(), ignoreProcessed);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\interceptor\C_AllocationHdr.java | 2 |
请完成以下Java代码 | private static GlobalQRCode getScannedQRCode(final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity)
{
final ManufacturingJob job = ManufacturingMobileApplication.getManufacturingJob(wfProcess);
final ManufacturingJobActivityId jobActivityId = wfActivity.getId().getAsId(ManufacturingJobActivityId.class);
final ManufacturingJobActivity jobActivity = job.getActivityById(jobActivityId);
return jobActivity.getScannedQRCode();
}
private static void validateScannedQRCode(
@NonNull final ManufacturingJobActivity activity,
@NonNull final GlobalQRCode qrCode)
{
final ValidateLocatorInfo validateLocatorInfo = activity.getSourceLocatorValidate();
if (validateLocatorInfo == null)
{
throw new AdempiereException(NO_SOURCE_LOCATOR_ERR_MSG); | }
if (!LocatorQRCode.isTypeMatching(qrCode))
{
throw new AdempiereException(QR_CODE_INVALID_TYPE_ERR_MSG);
}
final LocatorId scannedLocatorId = LocatorQRCode.ofGlobalQRCode(qrCode).getLocatorId();
if (!validateLocatorInfo.isLocatorIdValid(scannedLocatorId))
{
throw new AdempiereException(QR_CODE_DOES_NOT_MATCH_ERR_MSG);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\validateLocator\ValidateLocatorActivityHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getMinAmount() {
return minAmount;
}
public void setMinAmount(String minAmount) {
this.minAmount = minAmount;
}
public String getMaxAmount() {
return maxAmount;
}
public void setMaxAmount(String maxAmount) {
this.maxAmount = maxAmount;
}
public String getBeginTime() {
return beginTime;
}
public void setBeginTime(String beginTime) {
this.beginTime = beginTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
private BusCategoryEnum(String code,String desc,String minAmount,String maxAmount,String beginTime,String endTime) {
this.code = code;
this.desc = desc;
this.minAmount = minAmount;
this.maxAmount = maxAmount;
this.beginTime = beginTime;
this.endTime = endTime;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public static BusCategoryEnum getEnum(String enumName) {
BusCategoryEnum resultEnum = null;
BusCategoryEnum[] enumAry = BusCategoryEnum.values();
for (int i = 0; i < enumAry.length; i++) {
if (enumAry[i].name().equals(enumName)) {
resultEnum = enumAry[i];
break;
}
}
return resultEnum;
}
public static Map<String, Map<String, Object>> toMap() { | BusCategoryEnum[] ary = BusCategoryEnum.values();
Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>();
for (int num = 0; num < ary.length; num++) {
Map<String, Object> map = new HashMap<String, Object>();
String key = ary[num].name();
map.put("desc", ary[num].getDesc());
enumMap.put(key, map);
}
return enumMap;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List toList() {
BusCategoryEnum[] ary = BusCategoryEnum.values();
List list = new ArrayList();
for (int i = 0; i < ary.length; i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("name", ary[i].name());
map.put("desc", ary[i].getDesc());
map.put("minAmount", ary[i].getMinAmount());
map.put("maxAmount", ary[i].getMaxAmount());
map.put("beginTime", ary[i].getBeginTime());
map.put("endTime", ary[i].getEndTime());
list.add(map);
}
return list;
}
/**
* 取枚举的json字符串
*
* @return
*/
public static String getJsonStr() {
BusCategoryEnum[] enums = BusCategoryEnum.values();
StringBuffer jsonStr = new StringBuffer("[");
for (BusCategoryEnum senum : enums) {
if (!"[".equals(jsonStr.toString())) {
jsonStr.append(",");
}
jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}");
}
jsonStr.append("]");
return jsonStr.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\enums\BusCategoryEnum.java | 2 |
请完成以下Java代码 | public SqlAndParams getSqlValuesCommaSeparated()
{
final SqlAndParams.Builder sqlBuilder = SqlAndParams.builder();
for (final String keyColumnName : keyColumnNames)
{
final Object value = getValue(keyColumnName);
if (!sqlBuilder.isEmpty())
{
sqlBuilder.append(", ");
}
sqlBuilder.append("?", value);
}
return sqlBuilder.build();
}
public String getSqlWhereClauseById(@NonNull final String tableAlias)
{
final StringBuilder sql = new StringBuilder();
for (final String keyFieldName : keyColumnNames)
{
final Object idPart = getValue(keyFieldName);
if (sql.length() > 0)
{ | sql.append(" AND ");
}
sql.append(tableAlias).append(".").append(keyFieldName);
if (!JSONNullValue.isNull(idPart))
{
sql.append("=").append(DB.TO_SQL(idPart));
}
else
{
sql.append(" IS NULL");
}
}
return sql.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlComposedKey.java | 1 |
请完成以下Java代码 | public class DBRes_in extends ListResourceBundle
{
/** Data */
static final Object[][] contents = new String[][]{
{ "CConnectionDialog", "Koneksi Ke Server" },
{ "Name", "Nama" },
{ "AppsHost", "Pusat Aplikasi" },
{ "AppsPort", "Port Aplikasi" },
{ "TestApps", "Uji Server Aplikasi" },
{ "DBHost", "Pusat Database" },
{ "DBPort", "Port Database" },
{ "DBName", "Nama Database" },
{ "DBUidPwd", "ID Pengguna / Kata Sandi" },
{ "ViaFirewall", "lewat Firewall" },
{ "FWHost", "Pusat Firewall" },
{ "FWPort", "Port Firewall" },
{ "TestConnection", "Uji Koneksi" },
{ "Type", "Tipe Database" },
{ "BequeathConnection", "Koneksi Warisan" },
{ "Overwrite", "Timpakan" },
{ "ConnectionProfile", "Connection" }, | { "LAN", "LAN" },
{ "TerminalServer", "Terminal Server" },
{ "VPN", "VPN" },
{ "WAN", "WAN" },
{ "ConnectionError", "Kesalahan Koneksi" },
{ "ServerNotActive", "Server tidak aktif" }
};
/**
* Get Contsnts
* @return contents
*/
public Object[][] getContents()
{
return contents;
} // getContent
} // Res | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\connectiondialog\i18n\DBRes_in.java | 1 |
请完成以下Java代码 | public HitPolicy getHitPolicy() {
return hitPolicyAttribute.getValue(this);
}
public void setHitPolicy(HitPolicy hitPolicy) {
hitPolicyAttribute.setValue(this, hitPolicy);
}
public BuiltinAggregator getAggregation() {
return aggregationAttribute.getValue(this);
}
public void setAggregation(BuiltinAggregator aggregation) {
aggregationAttribute.setValue(this, aggregation);
}
public DecisionTableOrientation getPreferredOrientation() {
return preferredOrientationAttribute.getValue(this);
}
public void setPreferredOrientation(DecisionTableOrientation preferredOrientation) {
preferredOrientationAttribute.setValue(this, preferredOrientation);
}
public String getOutputLabel() {
return outputLabelAttribute.getValue(this);
}
public void setOutputLabel(String outputLabel) {
outputLabelAttribute.setValue(this, outputLabel);
}
public Collection<Input> getInputs() {
return inputCollection.get(this);
}
public Collection<Output> getOutputs() {
return outputCollection.get(this);
}
public Collection<Rule> getRules() {
return ruleCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DecisionTable.class, DMN_ELEMENT_DECISION_TABLE)
.namespaceUri(LATEST_DMN_NS)
.extendsType(Expression.class)
.instanceProvider(new ModelTypeInstanceProvider<DecisionTable>() {
public DecisionTable newInstance(ModelTypeInstanceContext instanceContext) {
return new DecisionTableImpl(instanceContext);
}
}); | hitPolicyAttribute = typeBuilder.namedEnumAttribute(DMN_ATTRIBUTE_HIT_POLICY, HitPolicy.class)
.defaultValue(HitPolicy.UNIQUE)
.build();
aggregationAttribute = typeBuilder.enumAttribute(DMN_ATTRIBUTE_AGGREGATION, BuiltinAggregator.class)
.build();
preferredOrientationAttribute = typeBuilder.namedEnumAttribute(DMN_ATTRIBUTE_PREFERRED_ORIENTATION, DecisionTableOrientation.class)
.defaultValue(DecisionTableOrientation.Rule_as_Row)
.build();
outputLabelAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_OUTPUT_LABEL)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
inputCollection = sequenceBuilder.elementCollection(Input.class)
.build();
outputCollection = sequenceBuilder.elementCollection(Output.class)
.required()
.build();
ruleCollection = sequenceBuilder.elementCollection(Rule.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DecisionTableImpl.java | 1 |
请完成以下Java代码 | public void setDn(String dn) {
this.instance.dn = dn;
}
public void setDn(Name dn) {
this.instance.dn = dn.toString();
}
public void setEnabled(boolean enabled) {
this.instance.enabled = enabled;
}
public void setPassword(String password) {
this.instance.password = password;
} | public void setUsername(String username) {
this.instance.username = username;
}
public void setTimeBeforeExpiration(int timeBeforeExpiration) {
this.instance.timeBeforeExpiration = timeBeforeExpiration;
}
public void setGraceLoginsRemaining(int graceLoginsRemaining) {
this.instance.graceLoginsRemaining = graceLoginsRemaining;
}
}
} | repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\LdapUserDetailsImpl.java | 1 |
请完成以下Java代码 | public void logTaskWithoutExecution(String taskId) {
logDebug("108",
"Execution of external task {} is null. This indicates that the task was concurrently completed or deleted. "
+ "It is not returned by the current fetch and lock command.",
taskId);
}
public ProcessEngineException multipleTenantsForCamundaFormDefinitionKeyException(String camundaFormDefinitionKey) {
return new ProcessEngineException(exceptionMessage(
"109",
"Cannot resolve a unique Camunda Form definition for key '{}' because it exists for multiple tenants.",
camundaFormDefinitionKey
));
}
public void concurrentModificationFailureIgnored(DbOperation operation) {
logDebug(
"110",
"An OptimisticLockingListener attempted to ignore a failure of: {}. "
+ "Since the database aborted the transaction, ignoring the failure "
+ "is not possible and an exception is thrown instead.",
operation
);
}
// exception code 110 is already taken. See requiredCamundaAdminOrPermissionException() for details.
public static List<SQLException> findRelatedSqlExceptions(Throwable exception) {
List<SQLException> sqlExceptionList = new ArrayList<>();
Throwable cause = exception;
do {
if (cause instanceof SQLException) {
SQLException sqlEx = (SQLException) cause;
sqlExceptionList.add(sqlEx);
while (sqlEx.getNextException() != null) {
sqlExceptionList.add(sqlEx.getNextException());
sqlEx = sqlEx.getNextException();
}
} | cause = cause.getCause();
} while (cause != null);
return sqlExceptionList;
}
public static String collectExceptionMessages(Throwable cause) {
StringBuilder message = new StringBuilder(cause.getMessage());
//collect real SQL exception messages in case of batch processing
Throwable exCause = cause;
do {
if (exCause instanceof BatchExecutorException) {
final List<SQLException> relatedSqlExceptions = findRelatedSqlExceptions(exCause);
StringBuilder sb = new StringBuilder();
for (SQLException sqlException : relatedSqlExceptions) {
sb.append(sqlException).append("\n");
}
message.append("\n").append(sb);
}
exCause = exCause.getCause();
} while (exCause != null);
return message.toString();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\EnginePersistenceLogger.java | 1 |
请完成以下Java代码 | public void deleteTenant() {
ensureNotReadOnly();
identityService.deleteTenant(resourceId);
}
public ResourceOptionsDto availableOperations(UriInfo context) {
ResourceOptionsDto dto = new ResourceOptionsDto();
// add links if operations are authorized
URI uri = context.getBaseUriBuilder()
.path(rootResourcePath)
.path(TenantRestService.PATH)
.path(resourceId)
.build();
dto.addReflexiveLink(uri, HttpMethod.GET, "self");
if(!identityService.isReadOnly() && isAuthorized(DELETE)) {
dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete");
}
if(!identityService.isReadOnly() && isAuthorized(UPDATE)) {
dto.addReflexiveLink(uri, HttpMethod.PUT, "update");
}
return dto;
}
public TenantUserMembersResource getTenantUserMembersResource() {
return new TenantUserMembersResourceImpl(getProcessEngine().getName(), resourceId, rootResourcePath, getObjectMapper()); | }
public TenantGroupMembersResource getTenantGroupMembersResource() {
return new TenantGroupMembersResourceImpl(getProcessEngine().getName(), resourceId, rootResourcePath, getObjectMapper());
}
protected Tenant findTenantObject() {
try {
return identityService.createTenantQuery()
.tenantId(resourceId)
.singleResult();
} catch(ProcessEngineException e) {
throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR,
"Exception while performing tenant query: " + e.getMessage());
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\identity\impl\TenantResourceImpl.java | 1 |
请完成以下Java代码 | public void setLdapCacheListener(LDAPGroupCacheListener ldapCacheListener) {
this.ldapCacheListener = ldapCacheListener;
}
// Helper classes ////////////////////////////////////
static class LDAPGroupCacheEntry {
protected Date timestamp;
protected List<Group> groups;
public LDAPGroupCacheEntry() {
}
public LDAPGroupCacheEntry(Date timestamp, List<Group> groups) {
this.timestamp = timestamp;
this.groups = groups;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public List<Group> getGroups() { | return groups;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
}
// Cache listeners. Currently not yet exposed (only programmatically for the
// moment)
// Experimental stuff!
public static interface LDAPGroupCacheListener {
void cacheHit(String userId);
void cacheMiss(String userId);
void cacheEviction(String userId);
void cacheExpired(String userId);
}
} | repos\flowable-engine-main\modules\flowable-ldap\src\main\java\org\flowable\ldap\LDAPGroupCache.java | 1 |
请完成以下Java代码 | public String getPropertyKeyWithValue(int lineNumber) throws IOException {
List<String> fileLines = getFileLines();
// depending on the system, sometimes the first line will be a comment with a timestamp of the file read
// the next line will make this method compatible with all systems
if (fileLines.get(0).startsWith("#")) {
lineNumber++;
}
return fileLines.get(lineNumber);
}
public String getLastPropertyKeyWithValue() throws IOException {
List<String> fileLines = getFileLines();
return fileLines.get(fileLines.size() - 1);
}
public void addPropertyKeyWithValue(String keyAndValue) throws IOException {
File propertiesFile = new File(propertyLoader.getFilePathFromResources(propertyFileName));
List<String> fileContent = getFileLines(propertiesFile);
fileContent.add(keyAndValue);
Files.write(propertiesFile.toPath(), fileContent, StandardCharsets.UTF_8);
}
public int updateProperty(String oldKeyValuePair, String newKeyValuePair) throws IOException {
File propertiesFile = new File(propertyLoader.getFilePathFromResources(propertyFileName));
List<String> fileContent = getFileLines(propertiesFile);
int updatedIndex = -1;
for (int i = 0; i < fileContent.size(); i++) {
if (fileContent.get(i)
.replaceAll("\\s+", "")
.equals(oldKeyValuePair)) {
fileContent.set(i, newKeyValuePair);
updatedIndex = i;
break;
} | }
Files.write(propertiesFile.toPath(), fileContent, StandardCharsets.UTF_8);
// depending on the system, sometimes the first line will be a comment with a timestamp of the file read
// the next line will make this method compatible with all systems
if (fileContent.get(0).startsWith("#")) {
updatedIndex--;
}
return updatedIndex;
}
private List<String> getFileLines() throws IOException {
File propertiesFile = new File(propertyLoader.getFilePathFromResources(propertyFileName));
return getFileLines(propertiesFile);
}
private List<String> getFileLines(File propertiesFile) throws IOException {
return new ArrayList<>(Files.readAllLines(propertiesFile.toPath(), StandardCharsets.UTF_8));
}
} | repos\tutorials-master\core-java-modules\core-java-properties\src\main\java\com\baeldung\core\java\properties\FileAPIPropertyMutator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Map<String, Object> startDepositWorkflow(DepositDetail depositDetail) {
StartWorkflowRequest request = new StartWorkflowRequest();
request.setName("microservice_orchestration");
Map<String, Object> inputData = new HashMap<>();
inputData.put("amount", depositDetail.getAmount());
inputData.put("accountId", depositDetail.getAccountId());
request.setInput(inputData);
String workflowId = workflowClient.startWorkflow(request);
log.info("Workflow id: {}", workflowId);
return Map.of("workflowId", workflowId);
}
/**
* Executes the workflow, waits for it to complete and returns the output of the workflow
* @param depositDetail
* @return
* @throws ExecutionException
* @throws InterruptedException
* @throws TimeoutException
*/
public Map<String, Object> executeWorkflow(DepositDetail depositDetail) throws ExecutionException, InterruptedException, TimeoutException {
StartWorkflowRequest request = new StartWorkflowRequest(); | request.setName("microservice_orchestration");
request.setVersion(1);
Map<String, Object> inputData = new HashMap<>();
inputData.put("amount", depositDetail.getAmount());
inputData.put("accountId", depositDetail.getAccountId());
request.setInput(inputData);
CompletableFuture<WorkflowRun> workflowRun = workflowClient.executeWorkflow(request, UUID.randomUUID()
.toString(), 10);
log.info("Workflow id: {}", workflowRun);
return workflowRun.get(10, TimeUnit.SECONDS)
.getOutput();
}
} | repos\tutorials-master\microservices-modules\event-driven-microservice\src\main\java\io\orkes\demo\banking\service\WorkflowService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SqlComponentDescriptorInsertRepository extends AbstractComponentDescriptorInsertRepository {
private static final String ID = "id = :id";
private static final String CLAZZ_CLAZZ = "clazz = :clazz";
private static final String P_KEY_CONFLICT_STATEMENT = "(id)";
private static final String UNQ_KEY_CONFLICT_STATEMENT = "(clazz)";
private static final String ON_P_KEY_CONFLICT_UPDATE_STATEMENT = getUpdateStatement(CLAZZ_CLAZZ);
private static final String ON_UNQ_KEY_CONFLICT_UPDATE_STATEMENT = getUpdateStatement(ID);
private static final String INSERT_OR_UPDATE_ON_P_KEY_CONFLICT = getInsertOrUpdateStatement(P_KEY_CONFLICT_STATEMENT, ON_P_KEY_CONFLICT_UPDATE_STATEMENT);
private static final String INSERT_OR_UPDATE_ON_UNQ_KEY_CONFLICT = getInsertOrUpdateStatement(UNQ_KEY_CONFLICT_STATEMENT, ON_UNQ_KEY_CONFLICT_UPDATE_STATEMENT);
@Override
public ComponentDescriptorEntity saveOrUpdate(ComponentDescriptorEntity entity) { | return saveAndGet(entity, INSERT_OR_UPDATE_ON_P_KEY_CONFLICT, INSERT_OR_UPDATE_ON_UNQ_KEY_CONFLICT);
}
@Override
protected ComponentDescriptorEntity doProcessSaveOrUpdate(ComponentDescriptorEntity entity, String query) {
return (ComponentDescriptorEntity) getQuery(entity, query).getSingleResult();
}
private static String getInsertOrUpdateStatement(String conflictKeyStatement, String updateKeyStatement) {
return "INSERT INTO component_descriptor (id, created_time, actions, clazz, configuration_descriptor, configuration_version, name, scope, type, clustering_mode, has_queue_name) VALUES (:id, :created_time, :actions, :clazz, :configuration_descriptor, :configuration_version, :name, :scope, :type, :clustering_mode, :has_queue_name) ON CONFLICT " + conflictKeyStatement + " DO UPDATE SET " + updateKeyStatement + " returning *";
}
private static String getUpdateStatement(String id) {
return "actions = :actions, " + id + ",created_time = :created_time, configuration_descriptor = :configuration_descriptor, configuration_version = :configuration_version, name = :name, scope = :scope, type = :type, clustering_mode = :clustering_mode, has_queue_name = :has_queue_name";
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\component\SqlComponentDescriptorInsertRepository.java | 2 |
请完成以下Spring Boot application配置 | # SSL
server.port=8443
server.ssl.key-store=src/main/resources/securePC.p12
server.ssl.key-store-password=123456
# PKCS12
server.ssl.key-store-type=pkcs12
# server | .ssl.key-alias=securePC
# Spring Security
# security.require-ssl=true | repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\6. SpringSecureSSLHttps\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Product Price Vendor Break.
@param M_ProductPriceVendorBreak_ID Product Price Vendor Break */
public void setM_ProductPriceVendorBreak_ID (int M_ProductPriceVendorBreak_ID)
{
if (M_ProductPriceVendorBreak_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ProductPriceVendorBreak_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ProductPriceVendorBreak_ID, Integer.valueOf(M_ProductPriceVendorBreak_ID));
}
/** Get Product Price Vendor Break.
@return Product Price Vendor Break */
public int getM_ProductPriceVendorBreak_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPriceVendorBreak_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Limit Price.
@param PriceLimit
Lowest price for a product
*/
public void setPriceLimit (BigDecimal PriceLimit)
{
set_Value (COLUMNNAME_PriceLimit, PriceLimit);
}
/** Get Limit Price.
@return Lowest price for a product
*/
public BigDecimal getPriceLimit ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceLimit);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set List Price.
@param PriceList
List Price
*/
public void setPriceList (BigDecimal PriceList) | {
set_Value (COLUMNNAME_PriceList, PriceList);
}
/** Get List Price.
@return List Price
*/
public BigDecimal getPriceList ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceList);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Standard Price.
@param PriceStd
Standard Price
*/
public void setPriceStd (BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
/** Get Standard Price.
@return Standard Price
*/
public BigDecimal getPriceStd ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ProductPriceVendorBreak.java | 1 |
请完成以下Java代码 | public PickingBOMsReversedIndex getPickingBOMsReversedIndex()
{
return pickingBOMsReversedIndexCache.getOrLoad(0, this::retrievePickingBOMsReversedIndex);
}
private PickingBOMsReversedIndex retrievePickingBOMsReversedIndex()
{
final Set<ProductBOMVersionsId> pickingBOMVersionsIds = productPlanningsRepo.retrieveAllPickingBOMVersionsIds();
final Set<ProductBOMId> pickingBOMIds = getPickingBOMIds(pickingBOMVersionsIds);
if (pickingBOMIds.isEmpty())
{
return PickingBOMsReversedIndex.EMPTY;
}
final ImmutableMap<ProductBOMId, I_PP_Product_BOM> bomsById = bomsRepo.getByIds(pickingBOMIds)
.stream()
.collect(ImmutableMap.toImmutableMap(
record -> ProductBOMId.ofRepoId(record.getPP_Product_BOM_ID()),
record -> record));
if (bomsById.isEmpty())
{
return PickingBOMsReversedIndex.EMPTY;
}
final List<I_PP_Product_BOMLine> bomLines = bomsRepo.retrieveLinesByBOMIds(pickingBOMIds);
if (bomLines.isEmpty())
{
return PickingBOMsReversedIndex.EMPTY;
}
final SetMultimap<ProductId, ProductId> bomProductIdsByComponentId = HashMultimap.create();
for (final I_PP_Product_BOMLine bomLine : bomLines)
{ | final ProductId componentId = ProductId.ofRepoId(bomLine.getM_Product_ID());
final ProductBOMId bomId = ProductBOMId.ofRepoId(bomLine.getPP_Product_BOM_ID());
final I_PP_Product_BOM bom = bomsById.get(bomId);
final ProductId bomProductId = ProductId.ofRepoId(bom.getM_Product_ID());
bomProductIdsByComponentId.put(componentId, bomProductId);
}
return PickingBOMsReversedIndex.ofBOMProductIdsByComponentId(bomProductIdsByComponentId);
}
@NonNull
private Set<ProductBOMId> getPickingBOMIds(@NonNull final Set<ProductBOMVersionsId> bomVersionsIds)
{
return bomVersionsIds.stream()
.map(bomsRepo::getLatestBOMByVersion)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\picking_bom\PickingBOMService.java | 1 |
请完成以下Java代码 | public java.lang.String getPassword ()
{
return (java.lang.String)get_Value(COLUMNNAME_Password);
}
/** Set Port.
@param Port Port */
@Override
public void setPort (int Port)
{
set_Value (COLUMNNAME_Port, Integer.valueOf(Port));
}
/** Get Port.
@return Port */
@Override
public int getPort ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Port);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* Protocol AD_Reference_ID=540906
* Reference name: C_InboundMailConfig_Protocol
*/
public static final int PROTOCOL_AD_Reference_ID=540906;
/** IMAP = imap */
public static final String PROTOCOL_IMAP = "imap";
/** IMAPS = imaps */
public static final String PROTOCOL_IMAPS = "imaps";
/** Set Protocol.
@param Protocol
Protocol
*/
@Override
public void setProtocol (java.lang.String Protocol)
{
set_Value (COLUMNNAME_Protocol, Protocol);
}
/** Get Protocol.
@return Protocol
*/
@Override
public java.lang.String getProtocol ()
{
return (java.lang.String)get_Value(COLUMNNAME_Protocol);
}
@Override
public org.compiere.model.I_R_RequestType getR_RequestType() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class);
}
@Override
public void setR_RequestType(org.compiere.model.I_R_RequestType R_RequestType)
{
set_ValueFromPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class, R_RequestType);
}
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
@Override
public void setR_RequestType_ID (int R_RequestType_ID)
{ | if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null);
else
set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
@Override
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Nutzer-ID/Login.
@param UserName Nutzer-ID/Login */
@Override
public void setUserName (java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
/** Get Nutzer-ID/Login.
@return Nutzer-ID/Login */
@Override
public java.lang.String getUserName ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java-gen\de\metas\inbound\mail\model\X_C_InboundMailConfig.java | 1 |
请完成以下Java代码 | private static KPIField extractOpenTargetField(final List<KPIField> fields, @Nullable final KPIField... excludeFields)
{
final List<KPIField> remainingFields = excludeFields(fields, excludeFields);
for (final KPIField field : remainingFields)
{
final String fieldName = field.getFieldName();
if ("Target".equals(fieldName)
|| "OpenTarget".equals(fieldName))
{
return field;
}
}
return null;
}
private static List<KPIField> excludeFields(final List<KPIField> fields, @Nullable final KPIField... excludeFields)
{
final List<KPIField> excludeFieldsList = excludeFields != null && excludeFields.length > 0
? Stream.of(excludeFields).filter(Objects::nonNull).collect(Collectors.toList())
: null;
if (excludeFieldsList == null || excludeFieldsList.isEmpty())
{
return fields;
}
return fields.stream()
.filter(field -> !excludeFieldsList.contains(field))
.collect(ImmutableList.toImmutableList());
}
@Override
public void loadRowToResult(@NonNull final KPIDataResult.Builder data, @NonNull final ResultSet rs) throws SQLException
{
final KPIDataValue url = SQLRowLoaderUtils.retrieveValue(rs, urlField); | final KPIDataSetValuesMap.KPIDataSetValuesMapBuilder resultEntry = data
.dataSet("URLs")
.dataSetValue(KPIDataSetValuesAggregationKey.of(url))
.put("url", url);
loadField(resultEntry, rs, "caption", captionField);
loadField(resultEntry, rs, "target", openTargetField);
}
public static void loadField(
@NonNull final KPIDataSetValuesMap.KPIDataSetValuesMapBuilder resultEntry,
@NonNull final ResultSet rs,
@NonNull final String targetFieldName,
@Nullable final KPIField field) throws SQLException
{
if (field == null)
{
return;
}
final KPIDataValue value = SQLRowLoaderUtils.retrieveValue(rs, field);
resultEntry.put(targetFieldName, value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\sql\URLsSQLRowLoader.java | 1 |
请完成以下Java代码 | public class CommonSuffixExtractor
{
TFDictionary tfDictionary;
public CommonSuffixExtractor()
{
tfDictionary = new TFDictionary();
}
public void add(String key)
{
tfDictionary.add(key);
}
public List<String> extractSuffixExtended(int length, int size)
{
return extractSuffix(length, size, true);
}
/**
* 提取公共后缀
* @param length 公共后缀长度
* @param size 频率最高的前多少个公共后缀
* @param extend 长度是否拓展为从1到length为止的后缀
* @return 公共后缀列表
*/
public List<String> extractSuffix(int length, int size, boolean extend)
{
TFDictionary suffixTreeSet = new TFDictionary();
for (String key : tfDictionary.keySet())
{
if (key.length() > length)
{
suffixTreeSet.add(key.substring(key.length() - length, key.length()));
if (extend)
{
for (int l = 1; l < length; ++l)
{
suffixTreeSet.add(key.substring(key.length() - l, key.length()));
}
}
}
}
if (extend)
{
size *= length;
}
return extract(suffixTreeSet, size);
}
private static List<String> extract(TFDictionary suffixTreeSet, int size)
{ | List<String> suffixList = new ArrayList<String>(size);
for (TermFrequency termFrequency : suffixTreeSet.values())
{
if (suffixList.size() >= size) break;
suffixList.add(termFrequency.getKey());
}
return suffixList;
}
/**
* 此方法认为后缀一定是整个的词语,所以length是以词语为单位的
* @param length
* @param size
* @param extend
* @return
*/
public List<String> extractSuffixByWords(int length, int size, boolean extend)
{
TFDictionary suffixTreeSet = new TFDictionary();
for (String key : tfDictionary.keySet())
{
List<Term> termList = StandardTokenizer.segment(key);
if (termList.size() > length)
{
suffixTreeSet.add(combine(termList.subList(termList.size() - length, termList.size())));
if (extend)
{
for (int l = 1; l < length; ++l)
{
suffixTreeSet.add(combine(termList.subList(termList.size() - l, termList.size())));
}
}
}
}
return extract(suffixTreeSet, size);
}
private static String combine(List<Term> termList)
{
StringBuilder sbResult = new StringBuilder();
for (Term term : termList)
{
sbResult.append(term.word);
}
return sbResult.toString();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\CommonSuffixExtractor.java | 1 |
请完成以下Java代码 | public class FlowableElContext extends ELContext {
protected ELResolver elResolver;
protected FlowableFunctionResolver functionResolver;
protected ExpressionFactory expressionFactory;
public FlowableElContext(ELResolver elResolver, FlowableFunctionResolver functionResolver, ExpressionFactory expressionFactory) {
this.elResolver = elResolver;
this.functionResolver = functionResolver;
this.expressionFactory = expressionFactory;
}
@Override
public ELResolver getELResolver() {
return elResolver;
} | @Override
public FunctionMapper getFunctionMapper() {
return new FlowableFunctionMapper(functionResolver);
}
@Override
public VariableMapper getVariableMapper() {
return null;
}
@Override
protected ExpressionFactory getDefaultExpressionFactory() {
return expressionFactory;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\FlowableElContext.java | 1 |
请完成以下Java代码 | public int getW_Inventory_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Inventory_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getW_Revaluation_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getW_Revaluation_Acct(), get_TrxName()); }
/** Set Inventory Revaluation.
@param W_Revaluation_Acct
Account for Inventory Revaluation | */
public void setW_Revaluation_Acct (int W_Revaluation_Acct)
{
set_Value (COLUMNNAME_W_Revaluation_Acct, Integer.valueOf(W_Revaluation_Acct));
}
/** Get Inventory Revaluation.
@return Account for Inventory Revaluation
*/
public int getW_Revaluation_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Revaluation_Acct);
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_M_Warehouse_Acct.java | 1 |
请完成以下Java代码 | private static GLCategory fromRecord(@NonNull final I_GL_Category record)
{
return GLCategory.builder()
.id(GLCategoryId.ofRepoId(record.getGL_Category_ID()))
.name(record.getName())
.categoryType(GLCategoryType.ofCode(record.getCategoryType()))
.isDefault(record.isDefault())
.clientId(ClientId.ofRepoId(record.getAD_Client_ID()))
.build();
}
private static class DefaultGLCategories
{
private final ImmutableMap<GLCategoryType, GLCategory> byCategoryType;
private final ImmutableList<GLCategory> list;
DefaultGLCategories(final ImmutableList<GLCategory> list)
{
this.byCategoryType = Maps.uniqueIndex(list, GLCategory::getCategoryType);
this.list = list;
} | public Optional<GLCategoryId> getByCategoryType(@NonNull final GLCategoryType categoryType)
{
final GLCategory category = byCategoryType.get(categoryType);
if (category != null)
{
return Optional.of(category.getId());
}
return getDefaultId();
}
public Optional<GLCategoryId> getDefaultId()
{
return !list.isEmpty()
? Optional.of(list.get(0).getId())
: Optional.empty();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\GLCategoryRepository.java | 1 |
请完成以下Java代码 | private void createDirectories(@NonNull final Path path)
{
try
{
Files.createDirectories(path);
}
catch (final IOException e)
{
throw new AdempiereException("IOException trying to create output directory", e)
.setParameter("path", path);
}
}
private ImmutableMultimap<Path, PrintingSegment> extractAndAssignPaths(
@NonNull final String baseDirectory,
@NonNull final PrintingData printingData)
{
final ImmutableMultimap.Builder<Path, PrintingSegment> path2Segments = new ImmutableMultimap.Builder<>();
for (final PrintingSegment segment : printingData.getSegments())
{
final HardwarePrinter printer = segment.getPrinter();
if (!OutputType.Store.equals(printer.getOutputType()))
{
logger.debug("Printer with id={} has outputType={}; -> skipping it", printer.getId().getRepoId(), printer.getOutputType());
continue;
}
final Path path;
if (segment.getTrayId() != null) | {
final HardwareTray tray = printer.getTray(segment.getTrayId());
path = Paths.get(baseDirectory,
FileUtil.stripIllegalCharacters(printer.getName()),
FileUtil.stripIllegalCharacters(tray.getTrayNumber() + "-" + tray.getName()));
}
else
{
path = Paths.get(baseDirectory,
FileUtil.stripIllegalCharacters(printer.getName()));
}
path2Segments.put(path, segment);
}
return path2Segments.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingDataToPDFFileStorer.java | 1 |
请完成以下Java代码 | public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Object getVal() {
return val;
}
public void setVal(Object val) {
this.val = val;
}
public long getTimeoutTime() {
return timeoutTime;
}
public void setTimeoutTime(long timeoutTime) {
this.timeoutTime = timeoutTime;
}
}
/**
* set cache
*
* @param key
* @param val
* @param cacheTime
* @return
*/
public static boolean set(String key, Object val, long cacheTime){
// clean timeout cache, before set new cache (avoid cache too much)
cleanTimeoutCache();
// set new cache
if (key==null || key.trim().length()==0) {
return false;
}
if (val == null) {
remove(key);
}
if (cacheTime <= 0) {
remove(key);
}
long timeoutTime = System.currentTimeMillis() + cacheTime;
LocalCacheData localCacheData = new LocalCacheData(key, val, timeoutTime);
cacheRepository.put(localCacheData.getKey(), localCacheData);
return true;
}
/**
* remove cache
*
* @param key
* @return
*/
public static boolean remove(String key){
if (key==null || key.trim().length()==0) {
return false;
}
cacheRepository.remove(key);
return true;
}
/**
* get cache
*
* @param key
* @return | */
public static Object get(String key){
if (key==null || key.trim().length()==0) {
return null;
}
LocalCacheData localCacheData = cacheRepository.get(key);
if (localCacheData!=null && System.currentTimeMillis()<localCacheData.getTimeoutTime()) {
return localCacheData.getVal();
} else {
remove(key);
return null;
}
}
/**
* clean timeout cache
*
* @return
*/
public static boolean cleanTimeoutCache(){
if (!cacheRepository.keySet().isEmpty()) {
for (String key: cacheRepository.keySet()) {
LocalCacheData localCacheData = cacheRepository.get(key);
if (localCacheData!=null && System.currentTimeMillis()>=localCacheData.getTimeoutTime()) {
cacheRepository.remove(key);
}
}
}
return true;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\util\LocalCacheUtil.java | 1 |
请完成以下Java代码 | public Optional<String> getIsbn() {
return Optional.ofNullable(isbn);
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Optional<Author> getAuthor() {
return Optional.ofNullable(author);
}
public void setAuthor(Author author) {
this.author = author;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} | if (!(obj instanceof Book)) {
return false;
}
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootOptional\src\main\java\com\bookstore\entity\Book.java | 1 |
请完成以下Java代码 | public class WatchPods {
private static Logger log = LoggerFactory.getLogger(WatchPods.class);
public static void main(String[] args) throws Exception {
ApiClient client = Config.defaultClient();
// Optional, put helpful during tests: disable client timeout and enable
// HTTP wire-level logs
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> log.info(message));
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient newClient = client.getHttpClient()
.newBuilder()
.addInterceptor(interceptor)
.readTimeout(0, TimeUnit.SECONDS)
.build();
client.setHttpClient(newClient);
CoreV1Api api = new CoreV1Api(client);
// Create the watch object that monitors pod creation/deletion/update events
while (true) {
log.info("[I46] Creating watch...");
try (Watch<V1Pod> watch = Watch.createWatch(
client,
api.listPodForAllNamespacesCall(false, null, null, null, null, "false", null, null, 10, true, null),
new TypeToken<Response<V1Pod>>(){}.getType())) { | log.info("[I52] Receiving events:");
for (Response<V1Pod> event : watch) {
V1Pod pod = event.object;
V1ObjectMeta meta = pod.getMetadata();
switch (event.type) {
case "ADDED":
case "MODIFIED":
case "DELETED":
log.info("event.type: {}, namespace={}, name={}",
event.type,
meta.getNamespace(),
meta.getName());
break;
default:
log.warn("[W66] Unknown event type: {}", event.type);
}
}
} catch (ApiException ex) {
log.error("[E70] ApiError", ex);
}
}
}
} | repos\tutorials-master\kubernetes-modules\k8s-intro\src\main\java\com\baeldung\kubernetes\intro\WatchPods.java | 1 |
请完成以下Java代码 | public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
/**
* Return any exception thrown when attempting to bind the queue to the event exchange.
* @return the exception.
*/
public @Nullable Exception getBindingsFailedException() {
return this.bindingsFailedException;
}
@Override
public void start() {
this.lock.lock();
try {
if (!this.running) {
if (this.stopInvoked) {
// redeclare auto-delete queue
this.stopInvoked = false;
onCreate(null);
}
if (this.ownContainer) {
this.container.start();
}
this.running = true;
}
}
finally {
this.lock.unlock();
}
}
@Override
public void stop() {
this.lock.lock();
try {
if (this.running) {
if (this.ownContainer) {
this.container.stop();
}
this.running = false;
this.stopInvoked = true;
}
}
finally {
this.lock.unlock();
}
}
@Override
public boolean isRunning() {
this.lock.lock();
try {
return this.running;
}
finally {
this.lock.unlock();
}
}
@Override
public int getPhase() {
return this.phase;
}
public void setPhase(int phase) {
this.phase = phase; | }
@Override
public boolean isAutoStartup() {
return this.autoStartup;
}
public void setAutoStartup(boolean autoStartup) {
this.autoStartup = autoStartup;
}
@Override
public void onMessage(Message message) {
if (this.applicationEventPublisher != null) {
this.applicationEventPublisher.publishEvent(new BrokerEvent(this, message.getMessageProperties()));
}
else {
if (logger.isWarnEnabled()) {
logger.warn("No event publisher available for " + message + "; if the BrokerEventListener "
+ "is not defined as a bean, you must provide an ApplicationEventPublisher");
}
}
}
@Override
public void onCreate(@Nullable Connection connection) {
this.bindingsFailedException = null;
TopicExchange exchange = new TopicExchange("amq.rabbitmq.event");
try {
this.admin.declareQueue(this.eventQueue);
Arrays.stream(this.eventKeys).forEach(k -> {
Binding binding = BindingBuilder.bind(this.eventQueue).to(exchange).with(k);
this.admin.declareBinding(binding);
});
}
catch (Exception e) {
logger.error("failed to declare event queue/bindings - is the plugin enabled?", e);
this.bindingsFailedException = e;
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\core\BrokerEventListener.java | 1 |
请完成以下Java代码 | public class FixedOrderComparator<T> implements Comparator<T>
{
private List<T> fixedOrderList;
// private T notMatchedMarker;
private int notMatchedMarkerIndex;
public FixedOrderComparator(final T notMatchedMarker, final List<T> fixedOrderList)
{
Check.assumeNotNull(fixedOrderList, "fixedOrderList not null");
Check.assume(!fixedOrderList.isEmpty(), "fixedOrderList not empty");
Check.assumeNotNull(notMatchedMarker, "notMatchedMarker not null");
this.fixedOrderList = fixedOrderList;
// this.notMatchedMarker = notMatchedMarker;
notMatchedMarkerIndex = fixedOrderList.indexOf(notMatchedMarker);
Check.assume(notMatchedMarkerIndex >= 0, "notMatchedMarker '{}' shall be present in fixed order list: {}", notMatchedMarker, fixedOrderList);
}
@SafeVarargs
public FixedOrderComparator(final T notMatchedMarker, final T... fixedOrderElements)
{
this(notMatchedMarker, Arrays.asList(fixedOrderElements));
}
@Override | public int compare(T o1, T o2)
{
int idx1 = fixedOrderList.indexOf(o1);
if (idx1 < 0)
{
idx1 = notMatchedMarkerIndex;
}
int idx2 = fixedOrderList.indexOf(o2);
if (idx2 < 0)
{
idx2 = notMatchedMarkerIndex;
}
return idx1 - idx2;
}
@Override
public String toString()
{
return "FixedOrderComparator [fixedOrderList=" + fixedOrderList + ", notMatchedMarkerIndex=" + notMatchedMarkerIndex + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\comparator\FixedOrderComparator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Developer createDev(@Valid @RequestBody Developer developer){
return developerRepository.save(developer);
}
@PutMapping("/dev/{id}")
public ResponseEntity<Developer> updateDeveloper (
@PathVariable(value = "id") Long devId,
@Valid @RequestBody Developer developerDetails) throws ResourceNotFoundException{
Developer developer = developerRepository.findById(devId)
.orElseThrow(() -> new ResourceNotFoundException("Developer not found on:: " + devId));
developer.setEmailId(developerDetails.getEmailId());
developer.setLastName(developerDetails.getLastName());
developerDetails.setFirstName(developerDetails.getFirstName());
developerDetails.setCreateAt(developerDetails.getCreateAt());
// developer.setUpdatedAt(new Date());
final Developer updateDev = developerRepository.save(developer);
return ResponseEntity.ok(updateDev); | }
@DeleteMapping("/dev/{id}")
public Map<String, Boolean> deleteDev(
@PathVariable(value = "id") Long devId) throws Exception{
Developer developer = developerRepository.findById(devId)
.orElseThrow(()-> new ResourceNotFoundException("Developer cannot found on:: " + devId));
developerRepository.delete(developer);
Map<String, Boolean> response = new HashMap<>();
response.put("delete", Boolean.TRUE);
return response;
}
} | repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringMySQL\src\main\java\spring\restapi\controller\DeveloperController.java | 2 |
请完成以下Java代码 | public BigDecimal getMinimumAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinimumAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_M_PromotionGroup getM_PromotionGroup() throws RuntimeException
{
return (I_M_PromotionGroup)MTable.get(getCtx(), I_M_PromotionGroup.Table_Name)
.getPO(getM_PromotionGroup_ID(), get_TrxName()); }
/** Set Promotion Group.
@param M_PromotionGroup_ID Promotion Group */
public void setM_PromotionGroup_ID (int M_PromotionGroup_ID)
{
if (M_PromotionGroup_ID < 1)
set_Value (COLUMNNAME_M_PromotionGroup_ID, null);
else
set_Value (COLUMNNAME_M_PromotionGroup_ID, Integer.valueOf(M_PromotionGroup_ID));
}
/** Get Promotion Group.
@return Promotion Group */
public int getM_PromotionGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Promotion getM_Promotion() throws RuntimeException
{
return (I_M_Promotion)MTable.get(getCtx(), I_M_Promotion.Table_Name)
.getPO(getM_Promotion_ID(), get_TrxName()); }
/** Set Promotion.
@param M_Promotion_ID Promotion */
public void setM_Promotion_ID (int M_Promotion_ID)
{
if (M_Promotion_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, Integer.valueOf(M_Promotion_ID));
} | /** Get Promotion.
@return Promotion */
public int getM_Promotion_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Promotion_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Promotion Line.
@param M_PromotionLine_ID Promotion Line */
public void setM_PromotionLine_ID (int M_PromotionLine_ID)
{
if (M_PromotionLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PromotionLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PromotionLine_ID, Integer.valueOf(M_PromotionLine_ID));
}
/** Get Promotion Line.
@return Promotion Line */
public int getM_PromotionLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionLine_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_M_PromotionLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DaoAuthenticationProvider authenticationProvider() {
final DaoAuthenticationProvider bean = new CustomDaoAuthenticationProvider();
bean.setUserDetailsService(customUserDetailsService);
bean.setPasswordEncoder(encoder());
return bean;
}
/**
* Order of precedence is very important.
* <p>
* Matching occurs from top to bottom - so, the topmost match succeeds first.
*/
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers("/", "/index", "/authenticate")
.permitAll()
.requestMatchers("/secured/**/**", "/secured/**/**/**", "/secured/socket", "/secured/success")
.authenticated()
.anyRequest()
.authenticated())
.formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/login")
.permitAll()
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/authenticate")
.successHandler(loginSuccessHandler())
.failureUrl("/denied")
.permitAll())
.logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutSuccessHandler(logoutSuccessHandler()))
/**
* Applies to User Roles - not to login failures or unauthenticated access attempts.
*/
.exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer.accessDeniedHandler(accessDeniedHandler())) | .authenticationProvider(authenticationProvider());
/** Disabled for local testing */
http.csrf(AbstractHttpConfigurer::disable);
/** This is solely required to support H2 console viewing in Spring MVC with Spring Security */
http.headers(headers -> headers.frameOptions(frameOptions -> frameOptions.sameOrigin()))
.authorizeHttpRequests(Customizer.withDefaults());
return http.build();
}
@Bean
public AuthenticationManager authManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.authenticationProvider(authenticationProvider())
.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers("/resources/**");
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-sockets\src\main\java\com\baeldung\springsecuredsockets\config\SecurityConfig.java | 2 |
请完成以下Java代码 | public ListenableFuture<Integer> succeedingTask() {
return Futures.immediateFuture(new Random().nextInt(Integer.MAX_VALUE));
}
public <T> ListenableFuture<T> failingTask() {
return Futures.immediateFailedFuture(new ListenableFutureException());
}
public ListenableFuture<Integer> getCartId() {
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
return new Random().nextInt(Integer.MAX_VALUE);
});
}
public ListenableFuture<String> getCustomerName() {
String[] names = new String[] { "Mark", "Jane", "June" };
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
return names[new Random().nextInt(names.length)];
});
}
public ListenableFuture<List<String>> getCartItems() {
String[] items = new String[] { "Apple", "Orange", "Mango", "Pineapple" };
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
int noOfItems = new Random().nextInt(items.length);
if (noOfItems == 0) ++noOfItems;
return Arrays.stream(items, 0, noOfItems).collect(Collectors.toList());
});
} | public ListenableFuture<String> generateUsername(String firstName) {
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
return firstName.replaceAll("[^a-zA-Z]+","")
.concat("@service.com");
});
}
public ListenableFuture<String> generatePassword(String username) {
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
if (username.contains("@")) {
String[] parts = username.split("@");
return parts[0] + "123@" + parts[1];
} else {
return username + "123";
}
});
}
} | repos\tutorials-master\guava-modules\guava-concurrency\src\main\java\com\baeldung\guava\future\ListenableFutureService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void start() {
final RuntimeContainerDelegateImpl containerDelegate = getContainerDelegate();
containerDelegate.getServiceContainer().createDeploymentOperation("deploying Camunda Platform")
.addStep(new EjbJarParsePlatformXmlStep())
.addStep(new DiscoverBpmPlatformPluginsStep())
.addStep(new StartJcaExecutorServiceStep(executorServiceBean))
.addStep(new StartJobExecutorStep())
.addStep(new PlatformXmlStartProcessEnginesStep())
.execute();
processEngineService = containerDelegate.getProcessEngineService();
processApplicationService = containerDelegate.getProcessApplicationService();
LOGGER.log(Level.INFO, "Camunda Platform started successfully.");
}
@PreDestroy
protected void stop() {
final RuntimeContainerDelegateImpl containerDelegate = getContainerDelegate();
containerDelegate.getServiceContainer().createUndeploymentOperation("undeploying Camunda Platform")
.addStep(new StopProcessApplicationsStep())
.addStep(new StopProcessEnginesStep())
.addStep(new StopJobExecutorStep())
.addStep(new StopJcaExecutorServiceStep())
.addStep(new UnregisterBpmPlatformPluginsStep())
.execute(); | LOGGER.log(Level.INFO, "Camunda Platform stopped.");
}
protected RuntimeContainerDelegateImpl getContainerDelegate() {
return (RuntimeContainerDelegateImpl) RuntimeContainerDelegate.INSTANCE.get();
}
// getters //////////////////////////////////////////////
public ProcessEngineService getProcessEngineService() {
return processEngineService;
}
public ProcessApplicationService getProcessApplicationService() {
return processApplicationService;
}
} | repos\camunda-bpm-platform-master\javaee\ejb-service\src\main\java\org\camunda\bpm\container\impl\ejb\EjbBpmPlatformBootstrap.java | 2 |
请完成以下Java代码 | public Integer component1() {
return getId();
}
@Override
public String component2() {
return getFirstName();
}
@Override
public String component3() {
return getLastName();
}
@Override
public Integer component4() {
return getAge();
}
@Override
public Integer value1() {
return getId();
}
@Override
public String value2() {
return getFirstName();
}
@Override
public String value3() {
return getLastName();
}
@Override
public Integer value4() {
return getAge();
}
@Override
public AuthorRecord value1(Integer value) {
setId(value);
return this;
}
@Override
public AuthorRecord value2(String value) {
setFirstName(value);
return this;
}
@Override
public AuthorRecord value3(String value) {
setLastName(value);
return this;
}
@Override
public AuthorRecord value4(Integer value) {
setAge(value);
return this;
}
@Override
public AuthorRecord values(Integer value1, String value2, String value3, Integer value4) { | value1(value1);
value2(value2);
value3(value3);
value4(value4);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached AuthorRecord
*/
public AuthorRecord() {
super(Author.AUTHOR);
}
/**
* Create a detached, initialised AuthorRecord
*/
public AuthorRecord(Integer id, String firstName, String lastName, Integer age) {
super(Author.AUTHOR);
set(0, id);
set(1, firstName);
set(2, lastName);
set(3, age);
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\records\AuthorRecord.java | 1 |
请完成以下Java代码 | public Integer getMatchStrategy() {
return matchStrategy;
}
public void setMatchStrategy(Integer matchStrategy) {
this.matchStrategy = matchStrategy;
}
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
ApiPredicateItemEntity that = (ApiPredicateItemEntity) o;
return Objects.equals(pattern, that.pattern) &&
Objects.equals(matchStrategy, that.matchStrategy); | }
@Override
public int hashCode() {
return Objects.hash(pattern, matchStrategy);
}
@Override
public String toString() {
return "ApiPredicateItemEntity{" +
"pattern='" + pattern + '\'' +
", matchStrategy=" + matchStrategy +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\gateway\ApiPredicateItemEntity.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this).addValue(applicationContext).toString();
}
@Override
public <T extends IService> T provideServiceImpl(@NonNull final Class<T> serviceClazz)
{
try
{
return applicationContext.getBean(serviceClazz);
}
catch (final NoUniqueBeanDefinitionException e)
{
// not ok; we have > 1 matching beans defined in the spring context. So far that always indicated some sort of mistake, so let's escalate.
throw e;
}
catch (final NoSuchBeanDefinitionException e)
{ | // ok; the bean is not in the spring context, so let's just return null
return null;
}
catch (final IllegalStateException e)
{
if (Adempiere.isUnitTestMode())
{
// added for @SpringBootTests starting up with a 'Marked for closing' Context, mostly due to DirtiesContext.ClassMode.BEFORE_CLASS
return null;
}
throw e;
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\StartupListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the pageDescription
*/
public String getPageDescription() {
return pageDescription;
}
/**
* @param pageDescription the pageDescription to set
*/
public void setPageDescription(String pageDescription) {
this.pageDescription = pageDescription; | }
/**
* @return the pageCounter
*/
public int getPageCounter() {
return pageCounter;
}
/**
* @param pageCounter the pageCounter to set
*/
public void setPageCounter(int pageCounter) {
this.pageCounter = pageCounter;
}
} | repos\tutorials-master\web-modules\jsf\src\main\java\com\baeldung\springintegration\controllers\ELSampleBean.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;
public User() {
}
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
} | public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
} | repos\tutorials-master\persistence-modules\hibernate-exceptions\src\main\java\com\baeldung\hibernate\exception\transientobject\entity\User.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int getC_POS_Payment_ID()
{
return get_ValueAsInt(COLUMNNAME_C_POS_Payment_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* Type AD_Reference_ID=541892
* Reference name: C_POS_JournalLine_Type
*/
public static final int TYPE_AD_Reference_ID=541892;
/** CashPayment = CASH_PAY */
public static final String TYPE_CashPayment = "CASH_PAY"; | /** CardPayment = CARD_PAY */
public static final String TYPE_CardPayment = "CARD_PAY";
/** CashInOut = CASH_INOUT */
public static final String TYPE_CashInOut = "CASH_INOUT";
/** CashClosingDifference = CASH_DIFF */
public static final String TYPE_CashClosingDifference = "CASH_DIFF";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_JournalLine.java | 2 |
请完成以下Java代码 | public void setIsExclude (boolean IsExclude)
{
set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude));
}
/** Get Exclude.
@return Exclude access to the data - if not selected Include access to the data
*/
public boolean isExclude ()
{
Object oo = get_Value(COLUMNNAME_IsExclude);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | /** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_AccessProfile.java | 1 |
请完成以下Java代码 | class ModelClassInfo implements IModelClassInfo
{
private final ModelClassIntrospector introspector;
private final Class<?> modelClass;
private final String tableName;
private Map<Method, IModelMethodInfo> _modelMethodInfos;
private final ReentrantLock modelMethodInfosLock = new ReentrantLock();
private Set<String> _definedColumnNames = null;
public ModelClassInfo(final ModelClassIntrospector introspector, @NonNull final Class<?> modelClass, final String tableName)
{
// shall not be null, but because it's created only from introspector, we are not checking it again
this.introspector = introspector;
this.modelClass = modelClass;
// NOTE: could be null in case we are dealing with an interface which is not bounded to a TableName
this.tableName = tableName;
}
@Override
public String toString()
{
return "ModelClassInfo ["
+ "modelClass=" + modelClass
+ ", tableName=" + tableName
+ "]";
}
@Override
public Class<?> getModelClass()
{
return modelClass;
}
@Override
public String getTableName()
{
return tableName;
}
@Override
public final IModelMethodInfo getMethodInfo(final Method method)
{
modelMethodInfosLock.lock();
try
{
final Map<Method, IModelMethodInfo> methodInfos = getMethodInfos0();
IModelMethodInfo methodInfo = methodInfos.get(method);
//
// If methodInfo was not found, try to create it now
if (methodInfo == null)
{
methodInfo = introspector.createModelMethodInfo(method);
if (methodInfo == null)
{
throw new IllegalStateException("No method info was found for " + method + " in " + this);
}
methodInfos.put(method, methodInfo);
}
return methodInfo;
}
finally
{
modelMethodInfosLock.unlock();
}
} | /**
* Gets the inner map of {@link Method} to {@link IModelMethodInfo}.
*
* NOTE: this method is not thread safe
*
* @return
*/
private final Map<Method, IModelMethodInfo> getMethodInfos0()
{
if (_modelMethodInfos == null)
{
_modelMethodInfos = introspector.createModelMethodInfos(getModelClass());
}
return _modelMethodInfos;
}
@Override
public synchronized final Set<String> getDefinedColumnNames()
{
if (_definedColumnNames == null)
{
_definedColumnNames = findDefinedColumnNames();
}
return _definedColumnNames;
}
@SuppressWarnings("unchecked")
private final Set<String> findDefinedColumnNames()
{
//
// Collect all columnnames
final ImmutableSet.Builder<String> columnNamesBuilder = ImmutableSet.builder();
ReflectionUtils.getAllFields(modelClass, new Predicate<Field>()
{
@Override
public boolean apply(final Field field)
{
final String fieldName = field.getName();
if (fieldName.startsWith("COLUMNNAME_"))
{
final String columnName = fieldName.substring("COLUMNNAME_".length());
columnNamesBuilder.add(columnName);
}
return false;
}
});
return columnNamesBuilder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\ModelClassInfo.java | 1 |
请完成以下Java代码 | protected String getStartCorrelationConfiguration(EventSubscription eventSubscription) {
BpmnModel bpmnModel = processEngineConfiguration.getRepositoryService().getBpmnModel(eventSubscription.getProcessDefinitionId());
if (bpmnModel != null) {
// There are potentially multiple start events, with different configurations.
// The one that has the matching eventType needs to be used
List<StartEvent> startEvents = bpmnModel.getMainProcess().findFlowElementsOfType(StartEvent.class);
for (StartEvent startEvent : startEvents) {
List<ExtensionElement> eventTypes = startEvent.getExtensionElements().get(BpmnXMLConstants.ELEMENT_EVENT_TYPE);
if (eventTypes != null && !eventTypes.isEmpty()
&& Objects.equals(eventSubscription.getEventType(), eventTypes.get(0).getElementText())) {
List<ExtensionElement> correlationCfgExtensions = startEvent.getExtensionElements()
.getOrDefault(BpmnXMLConstants.START_EVENT_CORRELATION_CONFIGURATION, Collections.emptyList());
if (!correlationCfgExtensions.isEmpty()) { | return correlationCfgExtensions.get(0).getElementText();
}
}
}
}
return null;
}
@Override
protected EventSubscriptionQuery createEventSubscriptionQuery() {
return new EventSubscriptionQueryImpl(commandExecutor, processEngineConfiguration.getEventSubscriptionServiceConfiguration());
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\eventregistry\BpmnEventRegistryEventConsumer.java | 1 |
请完成以下Java代码 | public static ApiResponse of(Integer code, String message, Object data) {
return new ApiResponse(code, message, data);
}
/**
* 构造一个成功且带数据的API返回
*
* @param data 返回数据
* @return ApiResponse
*/
public static ApiResponse ofSuccess(Object data) {
return ofStatus(Status.OK, data);
}
/**
* 构造一个成功且自定义消息的API返回
*
* @param message 返回内容
* @return ApiResponse
*/
public static ApiResponse ofMessage(String message) {
return of(Status.OK.getCode(), message, null);
}
/**
* 构造一个有状态的API返回
*
* @param status 状态 {@link Status}
* @return ApiResponse
*/
public static ApiResponse ofStatus(Status status) {
return ofStatus(status, null);
}
/**
* 构造一个有状态且带数据的API返回
* | * @param status 状态 {@link Status}
* @param data 返回数据
* @return ApiResponse
*/
public static ApiResponse ofStatus(Status status, Object data) {
return of(status.getCode(), status.getMessage(), data);
}
/**
* 构造一个异常且带数据的API返回
*
* @param t 异常
* @param data 返回数据
* @param <T> {@link BaseException} 的子类
* @return ApiResponse
*/
public static <T extends BaseException> ApiResponse ofException(T t, Object data) {
return of(t.getCode(), t.getMessage(), data);
}
/**
* 构造一个异常且带数据的API返回
*
* @param t 异常
* @param <T> {@link BaseException} 的子类
* @return ApiResponse
*/
public static <T extends BaseException> ApiResponse ofException(T t) {
return ofException(t, null);
}
} | repos\spring-boot-demo-master\demo-exception-handler\src\main\java\com\xkcoding\exception\handler\model\ApiResponse.java | 1 |
请完成以下Java代码 | public void setThreadLocalContextAware(boolean threadLocalContextAware) {
this.threadLocalContextAware = threadLocalContextAware;
}
/**
* Whether ThreadLocal context needs to be restored for this resolver.
*/
public boolean isThreadLocalContextAware() {
return this.threadLocalContextAware;
}
@SuppressWarnings({"unused", "try"})
@Override
public final Mono<List<GraphQLError>> resolveException(Throwable exception) {
if (this.threadLocalContextAware) {
return Mono.deferContextual((contextView) -> {
ContextSnapshot snapshot = ContextPropagationHelper.captureFrom(contextView);
try {
List<GraphQLError> errors = snapshot.wrap(() -> resolveToMultipleErrors(exception)).call();
return Mono.justOrEmpty(errors);
}
catch (Exception ex2) {
this.logger.warn("Failed to resolve " + exception, ex2);
return Mono.empty();
}
});
}
else { | return Mono.justOrEmpty(resolveToMultipleErrors(exception));
}
}
/**
* Override this method to resolve the Exception to multiple GraphQL errors.
* @param exception the exception to resolve
* @return the resolved errors or {@code null} if unresolved
*/
protected @Nullable List<GraphQLError> resolveToMultipleErrors(Throwable exception) {
GraphQLError error = resolveToSingleError(exception);
return (error != null) ? Collections.singletonList(error) : null;
}
/**
* Override this method to resolve the Exception to a single GraphQL error.
* @param exception the exception to resolve
* @return the resolved error or {@code null} if unresolved
*/
protected @Nullable GraphQLError resolveToSingleError(Throwable exception) {
return null;
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\SubscriptionExceptionResolverAdapter.java | 1 |
请完成以下Java代码 | public boolean hasSingleElement(Collection<?> value) {
return value != null && value.size() == 1;
}
@Override
protected void serializeContents(Collection<?> value, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.setCurrentValue(value);
PropertySerializerMap serializers = this._dynamicSerializers;
TypeSerializer typeSerializer = this._valueTypeSerializer;
int index = -1;
try {
for (Object element : CollectionUtils.nullSafeCollection(value)) {
index++;
if (Objects.isNull(element)) {
serializerProvider.defaultSerializeNull(jsonGenerator);
}
else {
Class<?> elementType = element.getClass();
JsonSerializer<Object> serializer = resolveSerializer(serializerProvider, elementType);
if (typeSerializer != null) {
serializer.serializeWithType(element, jsonGenerator, serializerProvider, typeSerializer);
}
else {
serializer.serialize(element, jsonGenerator, serializerProvider);
}
}
}
}
catch(Exception cause) {
wrapAndThrow(serializerProvider, cause, value, index);
}
}
private JavaType constructSpecializedType(SerializerProvider serializerProvider, JavaType baseType, Class<?> subclass) {
return serializerProvider.constructSpecializedType(baseType, subclass);
}
private JsonSerializer<Object> resolveSerializer(SerializerProvider serializerProvider, Class<?> type)
throws JsonMappingException {
JsonSerializer<Object> resolvedSerializer = this._elementSerializer;
if (Objects.isNull(resolvedSerializer)) {
PropertySerializerMap dynamicSerializers = this._dynamicSerializers;
resolvedSerializer = dynamicSerializers.serializerFor(type); | if (Objects.isNull(resolvedSerializer)) {
resolvedSerializer = Objects.nonNull(this._elementType) && this._elementType.hasGenericTypes()
? this._findAndAddDynamic(dynamicSerializers,
constructSpecializedType(serializerProvider, this._elementType, type), serializerProvider)
: this._findAndAddDynamic(dynamicSerializers, type, serializerProvider);
}
}
return resolvedSerializer;
}
@Override
public TypelessCollectionSerializer withResolved(BeanProperty property, TypeSerializer typeSerializer,
JsonSerializer<?> elementSerializer, Boolean unwrapSingle) {
return new TypelessCollectionSerializer(this, property, typeSerializer, elementSerializer);
}
@Override
public TypelessCollectionSerializer _withValueTypeSerializer(TypeSerializer typeSerializer) {
return new TypelessCollectionSerializer(this, this._property, typeSerializer, this._elementSerializer);
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\jackson\databind\serializer\TypelessCollectionSerializer.java | 1 |
请完成以下Java代码 | public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String getFullMessage() {
return fullMessage;
}
public void setFullMessage(String fullMessage) {
this.fullMessage = fullMessage;
}
@Override
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override | public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
public String toEventMessage(String message) {
String eventMessage = message.replaceAll("\\s+", " ");
if (eventMessage.length() > 163) {
eventMessage = eventMessage.substring(0, 160) + "...";
}
return eventMessage;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", type=" + type
+ ", userId=" + userId
+ ", time=" + time
+ ", taskId=" + taskId
+ ", processInstanceId=" + processInstanceId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", revision= "+ revision
+ ", removalTime=" + removalTime
+ ", action=" + action
+ ", message=" + message
+ ", fullMessage=" + fullMessage
+ ", tenantId=" + tenantId
+ "]";
}
@Override
public void setRevision(int revision) {
this.revision = revision;
}
@Override
public int getRevision() {
return revision;
}
@Override
public int getRevisionNext() {
return revision + 1;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CommentEntity.java | 1 |
请完成以下Java代码 | private int computeFromNotAdjustedAmountMultiplier()
{
int multiplier = 1;
// Do we have to SO adjust?
if (isAPAdjusted)
{
final int multiplierAP = soTrx.isPurchase() ? -1 : +1;
multiplier *= multiplierAP;
}
// Do we have to adjust by Credit Memo?
if (isCreditMemoAdjusted)
{
final int multiplierCM = isCreditMemo ? -1 : +1;
multiplier *= multiplierCM;
}
return multiplier;
}
/** | * @return {@code true} for purchase-invoice and sales-creditmemo. {@code false} otherwise.
*/
public boolean isOutgoingMoney()
{
return isCreditMemo ^ soTrx.isPurchase();
}
public InvoiceAmtMultiplier withAPAdjusted(final boolean isAPAdjustedNew)
{
return isAPAdjusted == isAPAdjustedNew ? this : toBuilder().isAPAdjusted(isAPAdjustedNew).build().intern();
}
public InvoiceAmtMultiplier withCMAdjusted(final boolean isCreditMemoAdjustedNew)
{
return isCreditMemoAdjusted == isCreditMemoAdjustedNew ? this : toBuilder().isCreditMemoAdjusted(isCreditMemoAdjustedNew).build().intern();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceAmtMultiplier.java | 1 |
请完成以下Java代码 | public final class SqlDocumentFilterConverters
{
/**
* Convenient method to create the effective converter instance from the given <code>entityBinding</code>.
* It will use
* <ul>
* <li>entity binding's registered converters list: {@link SqlEntityBinding#getFilterConverters()}
* <li>{@link SqlDefaultDocumentFilterConverter} as a fallback/default converter.
* </ul>
*/
public static SqlDocumentFilterConverter createEntityBindingEffectiveConverter(@NonNull final SqlEntityBinding entityBinding)
{
final SqlDocumentFilterConverter converters = entityBinding.getFilterConverters()
.withFallback(SqlDefaultDocumentFilterConverter.newInstance(entityBinding));
final SqlDocumentFilterConverterDecorator decoratorOrNull = entityBinding.getFilterConverterDecorator().orElse(null); | return decoratorOrNull != null
? decoratorOrNull.decorate(converters)
: converters;
}
public static SqlDocumentFilterConvertersList.Builder listBuilder()
{
return SqlDocumentFilterConvertersList.builder();
}
public static SqlDocumentFilterConvertersList emptyList()
{
return SqlDocumentFilterConvertersList.EMPTY;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\SqlDocumentFilterConverters.java | 1 |
请完成以下Java代码 | public String getActivityId() {
return activityId;
}
public String getFailedActivityId() {
return failedActivityId;
}
public String getExecutionId() {
return executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getDeploymentId() {
return deploymentId;
}
public String getTenantId() {
return tenantId;
}
public String getHostname() {
return hostname;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public String getBatchId() {
return batchId;
}
public boolean isCreationLog() {
return creationLog;
}
public boolean isFailureLog() {
return failureLog;
}
public boolean isSuccessLog() {
return successLog;
}
public boolean isDeletionLog() {
return deletionLog;
}
public static HistoricJobLogDto fromHistoricJobLog(HistoricJobLog historicJobLog) {
HistoricJobLogDto result = new HistoricJobLogDto();
result.id = historicJobLog.getId();
result.timestamp = historicJobLog.getTimestamp(); | result.removalTime = historicJobLog.getRemovalTime();
result.jobId = historicJobLog.getJobId();
result.jobDueDate = historicJobLog.getJobDueDate();
result.jobRetries = historicJobLog.getJobRetries();
result.jobPriority = historicJobLog.getJobPriority();
result.jobExceptionMessage = historicJobLog.getJobExceptionMessage();
result.jobDefinitionId = historicJobLog.getJobDefinitionId();
result.jobDefinitionType = historicJobLog.getJobDefinitionType();
result.jobDefinitionConfiguration = historicJobLog.getJobDefinitionConfiguration();
result.activityId = historicJobLog.getActivityId();
result.failedActivityId = historicJobLog.getFailedActivityId();
result.executionId = historicJobLog.getExecutionId();
result.processInstanceId = historicJobLog.getProcessInstanceId();
result.processDefinitionId = historicJobLog.getProcessDefinitionId();
result.processDefinitionKey = historicJobLog.getProcessDefinitionKey();
result.deploymentId = historicJobLog.getDeploymentId();
result.tenantId = historicJobLog.getTenantId();
result.hostname = historicJobLog.getHostname();
result.rootProcessInstanceId = historicJobLog.getRootProcessInstanceId();
result.batchId = historicJobLog.getBatchId();
result.creationLog = historicJobLog.isCreationLog();
result.failureLog = historicJobLog.isFailureLog();
result.successLog = historicJobLog.isSuccessLog();
result.deletionLog = historicJobLog.isDeletionLog();
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricJobLogDto.java | 1 |
请完成以下Java代码 | public void caretUpdate(CaretEvent e)
{
if(log.isTraceEnabled())
log.trace("Dot=" + e.getDot() + ",Last=" + m_lastDot + ", Mark=" + e.getMark());
// Selection
if (e.getDot() != e.getMark())
{
m_lastDot = e.getDot();
return;
}
//
// Is the current position a fixed character?
if (e.getDot()+1 > m_mask.length()
|| m_mask.charAt(e.getDot()) != DELIMITER)
{
m_lastDot = e.getDot();
return;
}
// Direction?
int newDot = -1;
if (m_lastDot > e.getDot()) // <-
newDot = e.getDot() - 1;
else // -> (or same)
newDot = e.getDot() + 1;
if (e.getDot() == 0) // first
newDot = 1;
else if (e.getDot() == m_mask.length()-1) // last
newDot = e.getDot() - 1;
//
if (log.isDebugEnabled()) | log.debug("OnFixedChar=" + m_mask.charAt(e.getDot()) + ", newDot=" + newDot + ", last=" + m_lastDot);
//
m_lastDot = e.getDot();
if (newDot >= 0 && newDot < getText().length())
m_tc.setCaretPosition(newDot);
} // caretUpdate
/**
* Get Full Text
* @return text
*/
private String getText()
{
String str = "";
try
{
str = getContent().getString(0, getContent().length() - 1); // cr at end
}
catch (Exception e)
{
str = "";
}
return str;
}
private final void provideErrorFeedback()
{
UIManager.getLookAndFeel().provideErrorFeedback(m_tc);
}
} // MDocDate | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\MDocDate.java | 1 |
请完成以下Java代码 | public void setM_Securpharm_Productdata_Result(de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result M_Securpharm_Productdata_Result)
{
set_ValueFromPO(COLUMNNAME_M_Securpharm_Productdata_Result_ID, de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result.class, M_Securpharm_Productdata_Result);
}
/** Set Securpharm Produktdaten Ergebnise.
@param M_Securpharm_Productdata_Result_ID Securpharm Produktdaten Ergebnise */
@Override
public void setM_Securpharm_Productdata_Result_ID (int M_Securpharm_Productdata_Result_ID)
{
if (M_Securpharm_Productdata_Result_ID < 1)
set_Value (COLUMNNAME_M_Securpharm_Productdata_Result_ID, null);
else
set_Value (COLUMNNAME_M_Securpharm_Productdata_Result_ID, Integer.valueOf(M_Securpharm_Productdata_Result_ID));
}
/** Get Securpharm Produktdaten Ergebnise.
@return Securpharm Produktdaten Ergebnise */
@Override
public int getM_Securpharm_Productdata_Result_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Securpharm_Productdata_Result_ID);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set TransaktionsID Server.
@param TransactionIDServer TransaktionsID Server */
@Override
public void setTransactionIDServer (java.lang.String TransactionIDServer)
{
set_Value (COLUMNNAME_TransactionIDServer, TransactionIDServer);
}
/** Get TransaktionsID Server.
@return TransaktionsID Server */
@Override
public java.lang.String getTransactionIDServer ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionIDServer);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Action_Result.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PackToHUsProducer newPackToHUsProducer()
{
return PackToHUsProducer.builder()
.handlingUnitsBL(handlingUnitsBL)
.huPIItemProductBL(hupiItemProductBL)
.uomConversionBL(uomConversionBL)
.inventoryService(inventoryService)
.build();
}
public IAutoCloseable newContext()
{
return HUContextHolder.temporarySet(handlingUnitsBL.createMutableHUContextForProcessing());
}
public ProductId getSingleProductId(@NonNull final HUQRCode huQRCode)
{
final HuId huId = huQRCodesService.getHuIdByQRCode(huQRCode);
return getSingleHUProductStorage(huId).getProductId();
}
public IHUProductStorage getSingleHUProductStorage(@NonNull final HuId huId)
{
return handlingUnitsBL.getSingleHUProductStorage(huId);
}
public Quantity getProductQuantity(@NonNull final HuId huId, @NonNull ProductId productId)
{
return getHUProductStorage(huId, productId)
.map(IHUProductStorage::getQty)
.filter(Quantity::isPositive)
.orElseThrow(() -> new AdempiereException(PRODUCT_DOES_NOT_MATCH));
}
private Optional<IHUProductStorage> getHUProductStorage(final @NotNull HuId huId, final @NotNull ProductId productId)
{ | final I_M_HU hu = handlingUnitsBL.getById(huId);
final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory();
return Optional.ofNullable(storageFactory.getStorage(hu).getProductStorageOrNull(productId));
}
public void assetHUContainsProduct(@NonNull final HUQRCode huQRCode, @NonNull final ProductId productId)
{
final HuId huId = huQRCodesService.getHuIdByQRCode(huQRCode);
getProductQuantity(huId, productId); // shall throw exception if no qty found
}
public void deleteReservationsByDocumentRefs(final ImmutableSet<HUReservationDocRef> huReservationDocRefs)
{
huReservationService.deleteReservationsByDocumentRefs(huReservationDocRefs);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\external_services\hu\DistributionHUService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class TopMenuController extends BladeController {
private final ITopMenuService topMenuService;
/**
* 详情
*/
@GetMapping("/detail")
@ApiOperationSupport(order = 1)
@Operation(summary = "详情", description = "传入topMenu")
public R<TopMenu> detail(TopMenu topMenu) {
TopMenu detail = topMenuService.getOne(Condition.getQueryWrapper(topMenu));
return R.data(detail);
}
/**
* 分页 顶部菜单表
*/
@GetMapping("/list")
@ApiOperationSupport(order = 2)
@Operation(summary = "分页", description = "传入topMenu")
public R<IPage<TopMenu>> list(TopMenu topMenu, Query query) {
IPage<TopMenu> pages = topMenuService.page(Condition.getPage(query), Condition.getQueryWrapper(topMenu).lambda().orderByAsc(TopMenu::getSort));
return R.data(pages);
}
/**
* 新增 顶部菜单表
*/
@PostMapping("/save")
@ApiOperationSupport(order = 4)
@Operation(summary = "新增", description = "传入topMenu")
public R save(@Valid @RequestBody TopMenu topMenu) {
return R.status(topMenuService.save(topMenu));
}
/**
* 修改 顶部菜单表
*/
@PostMapping("/update")
@ApiOperationSupport(order = 5)
@Operation(summary = "修改", description = "传入topMenu")
public R update(@Valid @RequestBody TopMenu topMenu) {
return R.status(topMenuService.updateById(topMenu));
}
/**
* 新增或修改 顶部菜单表
*/
@PostMapping("/submit")
@ApiOperationSupport(order = 6)
@Operation(summary = "新增或修改", description = "传入topMenu")
public R submit(@Valid @RequestBody TopMenu topMenu) {
return R.status(topMenuService.saveOrUpdate(topMenu));
} | /**
* 删除 顶部菜单表
*/
@PostMapping("/remove")
@ApiOperationSupport(order = 7)
@Operation(summary = "逻辑删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
return R.status(topMenuService.deleteLogic(Func.toLongList(ids)));
}
/**
* 设置顶部菜单
*/
@PostMapping("/grant")
@ApiOperationSupport(order = 8)
@Operation(summary = "顶部菜单配置", description = "传入topMenuId集合以及menuId集合")
public R grant(@RequestBody GrantVO grantVO) {
CacheUtil.clear(SYS_CACHE);
CacheUtil.clear(MENU_CACHE);
CacheUtil.clear(MENU_CACHE);
boolean temp = topMenuService.grant(grantVO.getTopMenuIds(), grantVO.getMenuIds());
return R.status(temp);
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\TopMenuController.java | 2 |
请完成以下Java代码 | public ImmutableList<I_PP_Order_Candidate> getByProductBOMId(@NonNull final ProductBOMId productBOMId)
{
return queryBL
.createQueryBuilder(I_PP_Order_Candidate.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_PP_Product_BOM_ID, productBOMId.getRepoId())
.create()
.listImmutable(I_PP_Order_Candidate.class);
}
public void deletePPOrderCandidates(@NonNull final DeletePPOrderCandidatesQuery deletePPOrderCandidatesQuery)
{
final IQueryBuilder<I_PP_Order_Candidate> deleteQuery = queryBL.createQueryBuilder(I_PP_Order_Candidate.class);
if (deletePPOrderCandidatesQuery.isOnlySimulated())
{
deleteQuery.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_IsSimulated, true);
}
if (deletePPOrderCandidatesQuery.getSalesOrderLineId() != null)
{
deleteQuery.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_C_OrderLine_ID, deletePPOrderCandidatesQuery.getSalesOrderLineId());
}
if (deleteQuery.getCompositeFilter().isEmpty())
{
throw new AdempiereException("Deleting all PP_Order_Candidate records is not allowed!");
}
final boolean failIfProcessed = false;
deleteQuery
.create()
.iterateAndStream()
.peek(this::deleteLines)
.forEach(simulatedOrder -> InterfaceWrapperHelper.delete(simulatedOrder, failIfProcessed));
}
private void deleteLines(@NonNull final I_PP_Order_Candidate ppOrderCandidate)
{
deleteLines(PPOrderCandidateId.ofRepoId(ppOrderCandidate.getPP_Order_Candidate_ID()));
} | public void deleteLines(@NonNull final PPOrderCandidateId ppOrderCandidateId)
{
queryBL.createQueryBuilder(I_PP_OrderLine_Candidate.class)
.addEqualsFilter(I_PP_OrderLine_Candidate.COLUMNNAME_PP_Order_Candidate_ID, ppOrderCandidateId)
.create()
.deleteDirectly();
}
public List<PPOrderCandidateId> listIdsByQuery(@NonNull final PPOrderCandidatesQuery query)
{
final IQueryBuilder<I_PP_Order_Candidate> builder = queryBL.createQueryBuilder(I_PP_Order_Candidate.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_M_Product_ID, query.getProductId())
.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_M_Warehouse_ID, query.getWarehouseId())
.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_AD_Org_ID, query.getOrgId())
.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_M_AttributeSetInstance_ID, query.getAttributesKey().getAsString(), ASIQueryFilterModifier.instance);
if (query.isOnlyNonZeroQty())
{
builder.addNotEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_QtyToProcess, 0);
}
return builder.create()
.listIds(PPOrderCandidateId::ofRepoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\model\dao\PPOrderCandidateDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void applyFilters(CaseDefinitionQuery query) {
if (caseDefinitionId != null) {
query.caseDefinitionId(caseDefinitionId);
}
if (caseDefinitionIdIn != null && !caseDefinitionIdIn.isEmpty()) {
query.caseDefinitionIdIn(caseDefinitionIdIn.toArray(new String[caseDefinitionIdIn.size()]));
}
if (category != null) {
query.caseDefinitionCategory(category);
}
if (categoryLike != null) {
query.caseDefinitionCategoryLike(categoryLike);
}
if (name != null) {
query.caseDefinitionName(name);
}
if (nameLike != null) {
query.caseDefinitionNameLike(nameLike);
}
if (deploymentId != null) {
query.deploymentId(deploymentId);
}
if (key != null) {
query.caseDefinitionKey(key);
}
if (keyLike != null) {
query.caseDefinitionKeyLike(keyLike);
}
if (resourceName != null) {
query.caseDefinitionResourceName(resourceName);
}
if (resourceNameLike != null) {
query.caseDefinitionResourceNameLike(resourceNameLike);
}
if (version != null) { | query.caseDefinitionVersion(version);
}
if (TRUE.equals(latestVersion)) {
query.latestVersion();
}
if (tenantIds != null && !tenantIds.isEmpty()) {
query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()]));
}
if (TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (TRUE.equals(includeDefinitionsWithoutTenantId)) {
query.includeCaseDefinitionsWithoutTenantId();
}
}
@Override
protected void applySortBy(CaseDefinitionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_CATEGORY_VALUE)) {
query.orderByCaseDefinitionCategory();
} else if (sortBy.equals(SORT_BY_KEY_VALUE)) {
query.orderByCaseDefinitionKey();
} else if (sortBy.equals(SORT_BY_ID_VALUE)) {
query.orderByCaseDefinitionId();
} else if (sortBy.equals(SORT_BY_VERSION_VALUE)) {
query.orderByCaseDefinitionVersion();
} else if (sortBy.equals(SORT_BY_NAME_VALUE)) {
query.orderByCaseDefinitionName();
} else if (sortBy.equals(SORT_BY_DEPLOYMENT_ID_VALUE)) {
query.orderByDeploymentId();
} else if (sortBy.equals(SORT_BY_TENANT_ID)) {
query.orderByTenantId();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\CaseDefinitionQueryDto.java | 2 |
请完成以下Java代码 | public String getName() {
return this.name;
}
@Override
public String getDescription() {
return this.description;
}
@Override
public @Nullable String getUsageHelp() {
return null;
}
@Override | public @Nullable String getHelp() {
return null;
}
@Override
public Collection<OptionHelp> getOptionsHelp() {
return Collections.emptyList();
}
@Override
public @Nullable Collection<HelpExample> getExamples() {
return null;
}
} | repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\AbstractCommand.java | 1 |
请完成以下Java代码 | public int getC_TaxPostal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxPostal_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set ZIP.
@param Postal
Postal code
*/
public void setPostal (String Postal)
{
set_Value (COLUMNNAME_Postal, Postal);
}
/** Get ZIP.
@return Postal code
*/
public String getPostal ()
{
return (String)get_Value(COLUMNNAME_Postal);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getPostal());
}
/** Set ZIP To. | @param Postal_To
Postal code to
*/
public void setPostal_To (String Postal_To)
{
set_Value (COLUMNNAME_Postal_To, Postal_To);
}
/** Get ZIP To.
@return Postal code to
*/
public String getPostal_To ()
{
return (String)get_Value(COLUMNNAME_Postal_To);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxPostal.java | 1 |
请完成以下Java代码 | public T getVariable(String name) {
return getVariablesMap().get(name);
}
public List<T> getVariables() {
return new ArrayList<>(getVariablesMap().values());
}
public List<T> getVariables(Collection<String> variableNames) {
return new ArrayList<>(getVariablesMap(variableNames).values());
}
public void addVariable(T value) {
if (containsKey(value.getName())) {
throw ProcessEngineLogger.CORE_LOGGER.duplicateVariableInstanceException(value);
}
getVariablesMap().put(value.getName(), value);
for (VariableStoreObserver<T> listener : observers) {
listener.onAdd(value);
}
if(removedVariables.containsKey(value.getName())){
removedVariables.remove(value.getName());
}
}
public void updateVariable(T value)
{
if (!containsKey(value.getName()))
{
throw ProcessEngineLogger.CORE_LOGGER.duplicateVariableInstanceException(value);
}
}
public boolean isEmpty() {
return getVariablesMap().isEmpty();
}
public boolean containsValue(T value) {
return getVariablesMap().containsValue(value);
}
public boolean containsKey(String key) {
return getVariablesMap().containsKey(key);
}
public Set<String> getKeys() {
return new HashSet<>(getVariablesMap().keySet());
}
public boolean isInitialized() {
return variables != null;
}
public void forceInitialization() {
if (!isInitialized()) {
variables = new HashMap<>();
for (T variable : variablesProvider.provideVariables()) {
variables.put(variable.getName(), variable);
}
}
}
public T removeVariable(String variableName) {
if (!getVariablesMap().containsKey(variableName)) {
return null;
} | T value = getVariablesMap().remove(variableName);
for (VariableStoreObserver<T> observer : observers) {
observer.onRemove(value);
}
removedVariables.put(variableName, value);
return value;
}
public void removeVariables() {
Iterator<T> valuesIt = getVariablesMap().values().iterator();
removedVariables.putAll(variables);
while (valuesIt.hasNext()) {
T nextVariable = valuesIt.next();
valuesIt.remove();
for (VariableStoreObserver<T> observer : observers) {
observer.onRemove(nextVariable);
}
}
}
public void addObserver(VariableStoreObserver<T> observer) {
observers.add(observer);
}
public void removeObserver(VariableStoreObserver<T> observer) {
observers.remove(observer);
}
public static interface VariableStoreObserver<T extends CoreVariableInstance> {
void onAdd(T variable);
void onRemove(T variable);
}
public static interface VariablesProvider<T extends CoreVariableInstance> {
Collection<T> provideVariables();
Collection<T> provideVariables(Collection<String> variableNames);
}
public boolean isRemoved(String variableName) {
return removedVariables.containsKey(variableName);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\VariableStore.java | 1 |
请完成以下Java代码 | public EventSubscriptionQuery eventSubscriptionId(String id) {
ensureNotNull("event subscription id", id);
this.eventSubscriptionId = id;
return this;
}
public EventSubscriptionQuery eventName(String eventName) {
ensureNotNull("event name", eventName);
this.eventName = eventName;
return this;
}
public EventSubscriptionQueryImpl executionId(String executionId) {
ensureNotNull("execution id", executionId);
this.executionId = executionId;
return this;
}
public EventSubscriptionQuery processInstanceId(String processInstanceId) {
ensureNotNull("process instance id", processInstanceId);
this.processInstanceId = processInstanceId;
return this;
}
public EventSubscriptionQueryImpl activityId(String activityId) {
ensureNotNull("activity id", activityId);
this.activityId = activityId;
return this;
}
public EventSubscriptionQuery tenantIdIn(String... tenantIds) {
ensureNotNull("tenantIds", (Object[]) tenantIds);
this.tenantIds = tenantIds;
isTenantIdSet = true;
return this;
}
public EventSubscriptionQuery withoutTenantId() {
isTenantIdSet = true;
this.tenantIds = null;
return this;
}
public EventSubscriptionQuery includeEventSubscriptionsWithoutTenantId() {
this.includeEventSubscriptionsWithoutTenantId = true;
return this;
}
public EventSubscriptionQueryImpl eventType(String eventType) {
ensureNotNull("event type", eventType);
this.eventType = eventType;
return this;
}
public EventSubscriptionQuery orderByCreated() { | return orderBy(EventSubscriptionQueryProperty.CREATED);
}
public EventSubscriptionQuery orderByTenantId() {
return orderBy(EventSubscriptionQueryProperty.TENANT_ID);
}
//results //////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getEventSubscriptionManager()
.findEventSubscriptionCountByQueryCriteria(this);
}
@Override
public List<EventSubscription> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getEventSubscriptionManager()
.findEventSubscriptionsByQueryCriteria(this,page);
}
//getters //////////////////////////////////////////
public String getEventSubscriptionId() {
return eventSubscriptionId;
}
public String getEventName() {
return eventName;
}
public String getEventType() {
return eventType;
}
public String getExecutionId() {
return executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getActivityId() {
return activityId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\EventSubscriptionQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<AiragApp> queryById(@RequestParam(name = "id", required = true) String id) {
AiragApp airagApp = airagAppService.getById(id);
if (airagApp == null) {
return Result.error("未找到对应数据");
}
return Result.OK(airagApp);
}
/**
* 调试应用
*
* @param appDebugParams
* @return
* @author chenrui
* @date 2025/2/28 10:49
*/
@PostMapping(value = "/debug")
public SseEmitter debugApp(@RequestBody AppDebugParams appDebugParams) {
return airagChatService.debugApp(appDebugParams);
}
/**
* 根据需求生成提示词
*
* @param prompt
* @return | * @author chenrui
* @date 2025/3/12 15:30
*/
@GetMapping(value = "/prompt/generate")
public Result<?> generatePrompt(@RequestParam(name = "prompt", required = true) String prompt) {
return (Result<?>) airagAppService.generatePrompt(prompt,true);
}
/**
* 根据需求生成提示词
*
* @param prompt
* @return
* @author chenrui
* @date 2025/3/12 15:30
*/
@PostMapping(value = "/prompt/generate")
public SseEmitter generatePromptSse(@RequestParam(name = "prompt", required = true) String prompt) {
return (SseEmitter) airagAppService.generatePrompt(prompt,false);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\app\controller\AiragAppController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<IdentityLinkEntity> getQueryIdentityLinks() {
if (queryIdentityLinks == null) {
queryIdentityLinks = new LinkedList<>();
}
return queryIdentityLinks;
}
public void setQueryIdentityLinks(List<IdentityLinkEntity> identityLinks) {
queryIdentityLinks = identityLinks;
}
@Override
public String toString() {
StringBuilder strb = new StringBuilder();
strb.append("Task[");
strb.append("id=").append(id);
strb.append(", key=").append(taskDefinitionKey);
strb.append(", name=").append(name);
if (executionId != null) {
strb.append(", processInstanceId=").append(processInstanceId)
.append(", executionId=").append(executionId)
.append(", processDefinitionId=").append(processDefinitionId);
} else if (scopeId != null) {
strb.append(", scopeInstanceId=").append(scopeId)
.append(", subScopeId=").append(subScopeId)
.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
strb.append("]");
return strb.toString();
}
@Override
public boolean isCountEnabled() {
return isCountEnabled;
}
public boolean getIsCountEnabled() {
return isCountEnabled;
}
@Override
public void setCountEnabled(boolean isCountEnabled) {
this.isCountEnabled = isCountEnabled;
}
public void setIsCountEnabled(boolean isCountEnabled) {
this.isCountEnabled = isCountEnabled;
} | @Override
public void setVariableCount(int variableCount) {
this.variableCount = variableCount;
}
@Override
public int getVariableCount() {
return variableCount;
}
@Override
public void setIdentityLinkCount(int identityLinkCount) {
this.identityLinkCount = identityLinkCount;
}
@Override
public int getIdentityLinkCount() {
return identityLinkCount;
}
@Override
public int getSubTaskCount() {
return subTaskCount;
}
@Override
public void setSubTaskCount(int subTaskCount) {
this.subTaskCount = subTaskCount;
}
@Override
public boolean isIdentityLinksInitialized() {
return isIdentityLinksInitialized;
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\TaskEntityImpl.java | 2 |
请完成以下Java代码 | private URLConnection openConnection(JarFile jarFile) throws IOException {
URL url = this.cache.get(jarFile);
return (url != null) ? url.openConnection() : null;
}
private void onClose(JarFile jarFile) {
this.cache.remove(jarFile);
}
void clearCache() {
this.cache.clear();
}
/**
* Internal cache.
*/
private static final class Cache {
private final Map<JarFileUrlKey, JarFile> jarFileUrlToJarFile = new HashMap<>();
private final Map<JarFile, URL> jarFileToJarFileUrl = new HashMap<>();
/**
* Get a {@link JarFile} from the cache given a jar file URL.
* @param jarFileUrl the jar file URL
* @return the cached {@link JarFile} or {@code null}
*/
JarFile get(URL jarFileUrl) {
JarFileUrlKey urlKey = new JarFileUrlKey(jarFileUrl);
synchronized (this) {
return this.jarFileUrlToJarFile.get(urlKey);
}
}
/**
* Get a jar file URL from the cache given a jar file.
* @param jarFile the jar file
* @return the cached {@link URL} or {@code null}
*/
URL get(JarFile jarFile) {
synchronized (this) {
return this.jarFileToJarFileUrl.get(jarFile);
}
}
/**
* Put the given jar file URL and jar file into the cache if they aren't already
* there.
* @param jarFileUrl the jar file URL
* @param jarFile the jar file
* @return {@code true} if the items were added to the cache or {@code false} if
* they were already there
*/
boolean putIfAbsent(URL jarFileUrl, JarFile jarFile) {
JarFileUrlKey urlKey = new JarFileUrlKey(jarFileUrl); | synchronized (this) {
JarFile cached = this.jarFileUrlToJarFile.get(urlKey);
if (cached == null) {
this.jarFileUrlToJarFile.put(urlKey, jarFile);
this.jarFileToJarFileUrl.put(jarFile, jarFileUrl);
return true;
}
return false;
}
}
/**
* Remove the given jar and any related URL file from the cache.
* @param jarFile the jar file to remove
*/
void remove(JarFile jarFile) {
synchronized (this) {
URL removedUrl = this.jarFileToJarFileUrl.remove(jarFile);
if (removedUrl != null) {
this.jarFileUrlToJarFile.remove(new JarFileUrlKey(removedUrl));
}
}
}
void clear() {
synchronized (this) {
this.jarFileToJarFileUrl.clear();
this.jarFileUrlToJarFile.clear();
}
}
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\UrlJarFiles.java | 1 |
请完成以下Java代码 | public class X_C_DataImport extends org.compiere.model.PO implements I_C_DataImport, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 1991628502L;
/** Standard Constructor */
public X_C_DataImport (final Properties ctx, final int C_DataImport_ID, @Nullable final String trxName)
{
super (ctx, C_DataImport_ID, trxName);
}
/** Load Constructor */
public X_C_DataImport (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_AD_ImpFormat getAD_ImpFormat()
{
return get_ValueAsPO(COLUMNNAME_AD_ImpFormat_ID, org.compiere.model.I_AD_ImpFormat.class);
}
@Override
public void setAD_ImpFormat(final org.compiere.model.I_AD_ImpFormat AD_ImpFormat)
{
set_ValueFromPO(COLUMNNAME_AD_ImpFormat_ID, org.compiere.model.I_AD_ImpFormat.class, AD_ImpFormat);
}
@Override
public void setAD_ImpFormat_ID (final int AD_ImpFormat_ID)
{
if (AD_ImpFormat_ID < 1)
set_Value (COLUMNNAME_AD_ImpFormat_ID, null);
else
set_Value (COLUMNNAME_AD_ImpFormat_ID, AD_ImpFormat_ID);
}
@Override
public int getAD_ImpFormat_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_ImpFormat_ID);
}
@Override
public void setC_DataImport_ID (final int C_DataImport_ID)
{
if (C_DataImport_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DataImport_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DataImport_ID, C_DataImport_ID);
}
@Override
public int getC_DataImport_ID() | {
return get_ValueAsInt(COLUMNNAME_C_DataImport_ID);
}
/**
* DataImport_ConfigType AD_Reference_ID=541535
* Reference name: C_DataImport_ConfigType
*/
public static final int DATAIMPORT_CONFIGTYPE_AD_Reference_ID=541535;
/** Standard = S */
public static final String DATAIMPORT_CONFIGTYPE_Standard = "S";
/** Bank Statement Import = BSI */
public static final String DATAIMPORT_CONFIGTYPE_BankStatementImport = "BSI";
@Override
public void setDataImport_ConfigType (final java.lang.String DataImport_ConfigType)
{
set_Value (COLUMNNAME_DataImport_ConfigType, DataImport_ConfigType);
}
@Override
public java.lang.String getDataImport_ConfigType()
{
return get_ValueAsString(COLUMNNAME_DataImport_ConfigType);
}
@Override
public void setInternalName (final @Nullable java.lang.String InternalName)
{
set_Value (COLUMNNAME_InternalName, InternalName);
}
@Override
public java.lang.String getInternalName()
{
return get_ValueAsString(COLUMNNAME_InternalName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DataImport.java | 1 |
请完成以下Java代码 | public static void handleTaskIdentityLinkDeletions(TaskEntity taskEntity, List<IdentityLinkEntity> identityLinks, boolean cascaseHistory,
CmmnEngineConfiguration cmmnEngineConfiguration) {
for (IdentityLinkEntity identityLinkEntity : identityLinks) {
CountingTaskEntity countingTaskEntity = (CountingTaskEntity) taskEntity;
if (countingTaskEntity.isCountEnabled()) {
countingTaskEntity.setIdentityLinkCount(countingTaskEntity.getIdentityLinkCount() - 1);
}
if (cascaseHistory) {
CommandContextUtil.getCmmnHistoryManager().recordIdentityLinkDeleted(identityLinkEntity);
}
logTaskIdentityLinkEvent(HistoricTaskLogEntryType.USER_TASK_IDENTITY_LINK_REMOVED.name(), taskEntity,
identityLinkEntity, cmmnEngineConfiguration);
}
taskEntity.getIdentityLinks().removeAll(identityLinks);
}
protected static void logTaskIdentityLinkEvent(String eventType, TaskEntity taskEntity, IdentityLinkEntity identityLinkEntity,
CmmnEngineConfiguration cmmnEngineConfiguration) {
TaskServiceConfiguration taskServiceConfiguration = cmmnEngineConfiguration.getTaskServiceConfiguration();
if (taskServiceConfiguration.isEnableHistoricTaskLogging()) { | BaseHistoricTaskLogEntryBuilderImpl taskLogEntryBuilder = new BaseHistoricTaskLogEntryBuilderImpl(taskEntity);
ObjectNode data = taskServiceConfiguration.getObjectMapper().createObjectNode();
if (identityLinkEntity.isUser()) {
data.put("userId", identityLinkEntity.getUserId());
} else if (identityLinkEntity.isGroup()) {
data.put("groupId", identityLinkEntity.getGroupId());
}
data.put("type", identityLinkEntity.getType());
taskLogEntryBuilder.timeStamp(taskServiceConfiguration.getClock().getCurrentTime());
taskLogEntryBuilder.userId(Authentication.getAuthenticatedUserId());
taskLogEntryBuilder.data(data.toString());
taskLogEntryBuilder.type(eventType);
taskServiceConfiguration.getInternalHistoryTaskManager().recordHistoryUserTaskLog(taskLogEntryBuilder);
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\IdentityLinkUtil.java | 1 |
请完成以下Java代码 | public void onModelChange(@NonNull final Object model, @NonNull final ModelChangeType changeType)
{
//
// Create missing invoice candidates for given pseudo-document
if (!isDocument && changeType.isNewOrChange() && changeType.isAfter())
{
createMissingInvoiceCandidates(model);
}
}
/**
* Creates missing invoice candidates for given model, if this is enabled.
*/
private void createMissingInvoiceCandidates(@NonNull final Object model)
{
final CandidatesAutoCreateMode modeForCurrentModel = handler.getSpecificCandidatesAutoCreateMode(model);
switch (modeForCurrentModel)
{
case DONT: // just for completeness. we actually aren't called in this case | break;
case CREATE_CANDIDATES:
CreateMissingInvoiceCandidatesWorkpackageProcessor.schedule(model);
break;
case CREATE_CANDIDATES_AND_INVOICES:
generateIcsAndInvoices(model);
break;
}
}
private void generateIcsAndInvoices(@NonNull final Object model)
{
final TableRecordReference modelReference = TableRecordReference.of(model);
collector.collect(modelReference);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\ilhandler\ILHandlerModelInterceptor.java | 1 |
请完成以下Java代码 | public class SysUserTenant implements Serializable {
private static final long serialVersionUID = 1L;
/**主键id*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "主键id")
private String id;
/**用户id*/
@Excel(name = "用户id", width = 15)
@Schema(description = "用户id")
private String userId;
/**租户id*/
@Excel(name = "租户id", width = 15)
@Schema(description = "租户id")
private Integer tenantId;
/**状态(1 正常 2 冻结 3 待审核 4 拒绝)*/
@Excel(name = "状态(1 正常 2 冻结 3 待审核 4 拒绝)", width = 15)
@Schema(description = "状态(1 正常 2 冻结 3 待审核 4 拒绝)")
private String status;
/**创建人登录名称*/ | @Schema(description = "创建人登录名称")
private String createBy;
/**创建日期*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd")
@DateTimeFormat(pattern="yyyy-MM-dd")
@Schema(description = "创建日期")
private Date createTime;
/**更新人登录名称*/
@Schema(description = "更新人登录名称")
private String updateBy;
/**更新日期*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd")
@DateTimeFormat(pattern="yyyy-MM-dd")
@Schema(description = "更新日期")
private Date updateTime;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysUserTenant.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CommentQueryService {
private CommentReadService commentReadService;
private UserRelationshipQueryService userRelationshipQueryService;
public Optional<CommentData> findById(String id, User user) {
CommentData commentData = commentReadService.findById(id);
if (commentData == null) {
return Optional.empty();
} else {
commentData
.getProfileData()
.setFollowing(
userRelationshipQueryService.isUserFollowing(
user.getId(), commentData.getProfileData().getId()));
}
return Optional.ofNullable(commentData);
}
public List<CommentData> findByArticleId(String articleId, User user) {
List<CommentData> comments = commentReadService.findByArticleId(articleId);
if (comments.size() > 0 && user != null) {
Set<String> followingAuthors =
userRelationshipQueryService.followingAuthors(
user.getId(),
comments.stream()
.map(commentData -> commentData.getProfileData().getId())
.collect(Collectors.toList()));
comments.forEach(
commentData -> {
if (followingAuthors.contains(commentData.getProfileData().getId())) {
commentData.getProfileData().setFollowing(true);
}
});
}
return comments;
}
public CursorPager<CommentData> findByArticleIdWithCursor(
String articleId, User user, CursorPageParameter<DateTime> page) {
List<CommentData> comments = commentReadService.findByArticleIdWithCursor(articleId, page);
if (comments.isEmpty()) {
return new CursorPager<>(new ArrayList<>(), page.getDirection(), false);
}
if (user != null) {
Set<String> followingAuthors =
userRelationshipQueryService.followingAuthors( | user.getId(),
comments.stream()
.map(commentData -> commentData.getProfileData().getId())
.collect(Collectors.toList()));
comments.forEach(
commentData -> {
if (followingAuthors.contains(commentData.getProfileData().getId())) {
commentData.getProfileData().setFollowing(true);
}
});
}
boolean hasExtra = comments.size() > page.getLimit();
if (hasExtra) {
comments.remove(page.getLimit());
}
if (!page.isNext()) {
Collections.reverse(comments);
}
return new CursorPager<>(comments, page.getDirection(), hasExtra);
}
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\application\CommentQueryService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class DATEVExportFormat
{
int id;
String name;
String csvEncoding;
String csvFieldDelimiter;
String csvFieldQuote;
List<DATEVExportFormatColumn> columns;
@Builder
private DATEVExportFormat(
final int id,
final String name,
final String csvEncoding,
final String csvFieldDelimiter, | final String csvFieldQuote,
@Singular final List<DATEVExportFormatColumn> columns)
{
Check.assumeNotEmpty(name, "name is not empty");
Check.assumeNotEmpty(columns, "columns is not empty");
this.id = id;
this.name = name;
this.csvEncoding = !Check.isEmpty(csvEncoding, true) ? csvEncoding : "UTF-8";
this.csvFieldDelimiter = csvFieldDelimiter != null ? csvFieldDelimiter : "\t";
this.csvFieldQuote = !Check.isEmpty(csvFieldQuote, true) ? csvFieldQuote : "";
this.columns = ImmutableList.copyOf(columns);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java\de\metas\datev\DATEVExportFormat.java | 2 |
请完成以下Java代码 | public GenericEventListenerInstanceQuery orderByName() {
innerQuery.orderByName();
return this;
}
@Override
public GenericEventListenerInstanceQuery asc() {
innerQuery.asc();
return this;
}
@Override
public GenericEventListenerInstanceQuery desc() {
innerQuery.desc();
return this;
}
@Override
public GenericEventListenerInstanceQuery orderBy(QueryProperty property) {
innerQuery.orderBy(property);
return this;
}
@Override
public GenericEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
innerQuery.orderBy(property, nullHandlingOnOrder);
return this;
}
@Override
public long count() {
return innerQuery.count(); | }
@Override
public GenericEventListenerInstance singleResult() {
PlanItemInstance instance = innerQuery.singleResult();
return GenericEventListenerInstanceImpl.fromPlanItemInstance(instance);
}
@Override
public List<GenericEventListenerInstance> list() {
return convertPlanItemInstances(innerQuery.list());
}
@Override
public List<GenericEventListenerInstance> listPage(int firstResult, int maxResults) {
return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults));
}
protected List<GenericEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) {
if (instances == null) {
return null;
}
return instances.stream().map(GenericEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList());
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\GenericEventListenerInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getOrderStateCode() {
return orderStateCode;
}
public void setOrderStateCode(Integer orderStateCode) {
this.orderStateCode = orderStateCode;
}
public String getExpressNo() {
return expressNo;
}
public void setExpressNo(String expressNo) {
this.expressNo = expressNo;
}
public Integer getPayModeCode() {
return payModeCode;
}
public void setPayModeCode(Integer payModeCode) {
this.payModeCode = payModeCode; | }
public String getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(String totalPrice) {
this.totalPrice = totalPrice;
}
@Override
public String toString() {
return "OrderUpdateReq{" +
"id='" + id + '\'' +
", orderStateCode=" + orderStateCode +
", expressNo='" + expressNo + '\'' +
", payModeCode=" + payModeCode +
", totalPrice='" + totalPrice + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\order\OrderUpdateReq.java | 2 |
请完成以下Java代码 | public class CalloutAssignment extends CalloutEngine
{
/**
* Assignment_Product.
* - called from S_ResourceAssignment_ID
* - sets M_Product_ID, Description
* - Qty..
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String product (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive() || value == null)
return "";
// get value
int S_ResourceAssignment_ID = ((Integer)value).intValue();
if (S_ResourceAssignment_ID == 0)
return "";
int M_Product_ID = 0;
String Name = null;
String Description = null;
BigDecimal Qty = null;
String sql = "SELECT p.M_Product_ID, ra.Name, ra.Description, ra.Qty "
+ "FROM S_ResourceAssignment ra"
+ " INNER JOIN M_Product p ON (p.S_Resource_ID=ra.S_Resource_ID) "
+ "WHERE ra.S_ResourceAssignment_ID=?";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, S_ResourceAssignment_ID);
rs = pstmt.executeQuery();
if (rs.next())
{
M_Product_ID = rs.getInt (1);
Name = rs.getString(2); | Description = rs.getString(3);
Qty = rs.getBigDecimal(4);
}
}
catch (SQLException e)
{
log.error("product", e);
}
finally
{
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
log.debug("S_ResourceAssignment_ID=" + S_ResourceAssignment_ID + " - M_Product_ID=" + M_Product_ID);
if (M_Product_ID != 0)
{
mTab.setValue ("M_Product_ID", new Integer (M_Product_ID));
if (Description != null)
Name += " (" + Description + ")";
if (!".".equals(Name))
mTab.setValue("Description", Name);
//
String variable = "Qty"; // TimeExpenseLine
if (mTab.getTableName().startsWith("C_Order"))
variable = "QtyOrdered";
else if (mTab.getTableName().startsWith("C_Invoice"))
variable = "QtyInvoiced";
if (Qty != null)
mTab.setValue(variable, Qty);
mTab.setValue("QtyEntered", Qty); //red1 BR2836655-Resource Assignment always return Qty 1
}
return "";
} // product
} // CalloutAssignment | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\CalloutAssignment.java | 1 |
请完成以下Java代码 | public DeploymentQueryImpl createDeploymentQuery() {
return new DeploymentQueryImpl();
}
public ProcessDefinitionQueryImpl createProcessDefinitionQuery() {
return new ProcessDefinitionQueryImpl();
}
public CaseDefinitionQueryImpl createCaseDefinitionQuery() {
return new CaseDefinitionQueryImpl();
}
public ProcessInstanceQueryImpl createProcessInstanceQuery() {
return new ProcessInstanceQueryImpl();
}
public ExecutionQueryImpl createExecutionQuery() {
return new ExecutionQueryImpl();
}
public TaskQueryImpl createTaskQuery() {
return new TaskQueryImpl();
}
public JobQueryImpl createJobQuery() {
return new JobQueryImpl();
}
public HistoricProcessInstanceQueryImpl createHistoricProcessInstanceQuery() {
return new HistoricProcessInstanceQueryImpl();
}
public HistoricActivityInstanceQueryImpl createHistoricActivityInstanceQuery() {
return new HistoricActivityInstanceQueryImpl();
}
public HistoricTaskInstanceQueryImpl createHistoricTaskInstanceQuery() {
return new HistoricTaskInstanceQueryImpl();
}
public HistoricDetailQueryImpl createHistoricDetailQuery() {
return new HistoricDetailQueryImpl();
}
public HistoricVariableInstanceQueryImpl createHistoricVariableInstanceQuery() {
return new HistoricVariableInstanceQueryImpl(); | }
public HistoricJobLogQueryImpl createHistoricJobLogQuery() {
return new HistoricJobLogQueryImpl();
}
public UserQueryImpl createUserQuery() {
return new DbUserQueryImpl();
}
public GroupQueryImpl createGroupQuery() {
return new DbGroupQueryImpl();
}
public void registerOptimisticLockingListener(OptimisticLockingListener optimisticLockingListener) {
if(optimisticLockingListeners == null) {
optimisticLockingListeners = new ArrayList<>();
}
optimisticLockingListeners.add(optimisticLockingListener);
}
public List<String> getTableNamesPresentInDatabase() {
return persistenceSession.getTableNamesPresent();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\DbEntityManager.java | 1 |
请完成以下Java代码 | public int getAge() {
return age;
}
public Author age(int age) {
this.age = age;
return this;
}
public void setAge(int age) {
this.age = age;
}
public List<Book> getBooks() {
return books;
} | public Author books(List<Book> books) {
this.books = books;
return this;
}
public void setBooks(List<Book> books) {
this.books = books;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", name=" + name
+ ", genre=" + genre + ", age=" + age + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootFluentApiAdditionalMethods\src\main\java\com\bookstore\entity\Author.java | 1 |
请完成以下Java代码 | public void setC_Tax_ID (int C_Tax_ID)
{
if (C_Tax_ID < 1)
set_Value (COLUMNNAME_C_Tax_ID, null);
else
set_Value (COLUMNNAME_C_Tax_ID, Integer.valueOf(C_Tax_ID));
}
/** Get Steuer.
@return Steuerart
*/
@Override
public int getC_Tax_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Tax_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set VAT Code.
@param C_VAT_Code_ID VAT Code */
@Override
public void setC_VAT_Code_ID (int C_VAT_Code_ID)
{
if (C_VAT_Code_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_VAT_Code_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_VAT_Code_ID, Integer.valueOf(C_VAT_Code_ID));
}
/** Get VAT Code.
@return VAT Code */
@Override
public int getC_VAT_Code_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_VAT_Code_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/**
* IsSOTrx AD_Reference_ID=319
* Reference name: _YesNo
*/
public static final int ISSOTRX_AD_Reference_ID=319;
/** Yes = Y */
public static final String ISSOTRX_Yes = "Y";
/** No = N */
public static final String ISSOTRX_No = "N";
/** Set Sales Transaction.
@param IsSOTrx
This is a Sales Transaction
*/
@Override
public void setIsSOTrx (java.lang.String IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, IsSOTrx);
}
/** Get Sales Transaction.
@return This is a Sales Transaction
*/
@Override
public java.lang.String getIsSOTrx ()
{
return (java.lang.String)get_Value(COLUMNNAME_IsSOTrx);
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override | public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
/** Set VAT Code.
@param VATCode VAT Code */
@Override
public void setVATCode (java.lang.String VATCode)
{
set_Value (COLUMNNAME_VATCode, VATCode);
}
/** Get VAT Code.
@return VAT Code */
@Override
public java.lang.String getVATCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_VATCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_C_VAT_Code.java | 1 |
请完成以下Java代码 | public class PerformanceIndicatorImpl extends BusinessContextElementImpl implements PerformanceIndicator {
protected static ElementReferenceCollection<Decision, ImpactingDecisionReference> impactingDecisionRefCollection;
public PerformanceIndicatorImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public Collection<Decision> getImpactingDecisions() {
return impactingDecisionRefCollection.getReferenceTargetElements(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PerformanceIndicator.class, DMN_ELEMENT_PERFORMANCE_INDICATOR)
.namespaceUri(LATEST_DMN_NS)
.extendsType(BusinessContextElement.class) | .instanceProvider(new ModelTypeInstanceProvider<PerformanceIndicator>() {
public PerformanceIndicator newInstance(ModelTypeInstanceContext instanceContext) {
return new PerformanceIndicatorImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
impactingDecisionRefCollection = sequenceBuilder.elementCollection(ImpactingDecisionReference.class)
.uriElementReferenceCollection(Decision.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\PerformanceIndicatorImpl.java | 1 |
请完成以下Java代码 | public String getAmtInWords (String amount) throws Exception
{
if (amount == null)
return amount;
//
StringBuffer sb = new StringBuffer ();
sb.append("RINGGIT ");
int pos = amount.lastIndexOf ('.');
int pos2 = amount.lastIndexOf (',');
if (pos2 > pos)
pos = pos2;
String oldamt = amount;
amount = amount.replaceAll (",", "");
int newpos = amount.lastIndexOf ('.');
long dollars = Long.parseLong(amount.substring (0, newpos));
sb.append (convert (dollars));
for (int i = 0; i < oldamt.length (); i++)
{
if (pos == i) // we are done
{
String cents = oldamt.substring (i + 1);
long sen = Long.parseLong(cents); //red1 convert cents to words
sb.append(" dan SEN");
sb.append (' ').append (convert(sen));
break;
}
}
return sb.toString ();
} // getAmtInWords
/**
* Test Print
* @param amt amount
*/
private void print (String amt)
{
try
{
System.out.println(amt + " = " + getAmtInWords(amt));
}
catch (Exception e)
{ | e.printStackTrace();
}
} // print
/**
* Test
* @param args ignored
*/
public static void main (String[] args)
{
AmtInWords_MS aiw = new AmtInWords_MS();
// aiw.print (".23"); Error
aiw.print ("0.23");
aiw.print ("1.23");
aiw.print ("12.34");
aiw.print ("123.45");
aiw.print ("1,234.56");
aiw.print ("12,345.78");
aiw.print ("123,457.89");
aiw.print ("1,234,578.90");
aiw.print ("100.00");
} // main
} // AmtInWords_MY | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\AmtInWords_MS.java | 1 |
请在Spring Boot框架中完成以下Java代码 | FanoutExchange parkingLotExchange() {
return new FanoutExchange(EXCHANGE_PARKING_LOT);
}
@Bean
Queue parkingLotQueue() {
return QueueBuilder.durable(QUEUE_PARKING_LOT).build();
}
@Bean
Binding parkingLotBinding() {
return BindingBuilder.bind(parkingLotQueue()).to(parkingLotExchange());
}
@Bean
Queue messagesQueue() {
return QueueBuilder.durable(QUEUE_MESSAGES)
.withArgument("x-dead-letter-exchange", DLX_EXCHANGE_MESSAGES)
.build();
}
@Bean
FanoutExchange deadLetterExchange() { | return new FanoutExchange(DLX_EXCHANGE_MESSAGES);
}
@Bean
Queue deadLetterQueue() {
return QueueBuilder.durable(QUEUE_MESSAGES_DLQ).build();
}
@Bean
Binding deadLetterBinding() {
return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange());
}
@Bean
DirectExchange messagesExchange() {
return new DirectExchange(EXCHANGE_MESSAGES);
}
@Bean
Binding bindingMessages() {
return BindingBuilder.bind(messagesQueue()).to(messagesExchange()).with(QUEUE_MESSAGES);
}
} | repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\errorhandling\configuration\DLXParkingLotAmqpConfiguration.java | 2 |
请完成以下Java代码 | public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Autowired
BookRepository bookRepository;
// Run this if app.db.init.enabled = true
@Bean
@ConditionalOnProperty(prefix = "app", name = "db.init.enabled", havingValue = "true")
public CommandLineRunner demoCommandLineRunner() {
return args -> {
System.out.println("Running.....");
Book b1 = new Book("Book A",
BigDecimal.valueOf(9.99), | LocalDate.of(2023, 8, 31));
Book b2 = new Book("Book B",
BigDecimal.valueOf(19.99),
LocalDate.of(2023, 7, 31));
Book b3 = new Book("Book C",
BigDecimal.valueOf(29.99),
LocalDate.of(2023, 6, 10));
Book b4 = new Book("Book D",
BigDecimal.valueOf(39.99),
LocalDate.of(2023, 5, 5));
bookRepository.saveAll(List.of(b1, b2, b3, b4));
};
}
} | repos\spring-boot-master\spring-data-jpa-postgresql\src\main\java\com\mkyong\MainApplication.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CloseableHttpClient httpClient() {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(p.getRequestTimeout())
.setConnectTimeout(p.getConnectTimeout())
.setSocketTimeout(p.getSocketTimeout()).build();
return HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(poolingConnectionManager())
.setKeepAliveStrategy(connectionKeepAliveStrategy())
.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)) // 重试次数
.build();
}
@Bean
public Runnable idleConnectionMonitor(final PoolingHttpClientConnectionManager connectionManager) {
return new Runnable() {
@Override
@Scheduled(fixedDelay = 10000)
public void run() {
try {
if (connectionManager != null) {
LOGGER.trace("run IdleConnectionMonitor - Closing expired and idle connections...");
connectionManager.closeExpiredConnections();
connectionManager.closeIdleConnections(p.getCloseIdleConnectionWaitTimeSecs(), TimeUnit.SECONDS);
} else { | LOGGER.trace("run IdleConnectionMonitor - Http Client Connection manager is not initialised");
}
} catch (Exception e) {
LOGGER.error("run IdleConnectionMonitor - Exception occurred. msg={}, e={}", e.getMessage(), e);
}
}
};
}
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setThreadNamePrefix("poolScheduler");
scheduler.setPoolSize(50);
return scheduler;
}
} | repos\SpringBootBucket-master\springboot-resttemplate\src\main\java\com\xncoding\pos\config\HttpClientConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CmmnDeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
@Override
public CmmnDeploymentBuilder parentDeploymentId(String parentDeploymentId) {
deployment.setParentDeploymentId(parentDeploymentId);
return this;
}
@Override
public CmmnDeploymentBuilder enableDuplicateFiltering() {
this.isDuplicateFilterEnabled = true;
return this;
} | @Override
public CmmnDeployment deploy() {
return repositoryService.deploy(this);
}
public CmmnDeploymentEntity getDeployment() {
return deployment;
}
public boolean isCmmnXsdValidationEnabled() {
return isCmmn20XsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\repository\CmmnDeploymentBuilderImpl.java | 2 |
请完成以下Java代码 | public class PeriodClosedException extends AdempiereException
{
/**
*
*/
private static final long serialVersionUID = -2798371272365454799L;
/**
*
*/
public PeriodClosedException(final Timestamp dateAcct, final DocBaseType docBaseType)
{
super(buildMsg(dateAcct, docBaseType));
}
private static ITranslatableString buildMsg(@Nullable final Timestamp dateAcct, @Nullable final DocBaseType docBaseType) | {
final ITranslatableString dateAcctTrl = dateAcct != null
? TranslatableStrings.dateAndTime(dateAcct)
: TranslatableStrings.anyLanguage("?");
final ITranslatableString docBaseTypeTrl = docBaseType != null
? TranslatableStrings.adRefList(ReferenceId.ofRepoId(X_C_DocType.DOCBASETYPE_AD_Reference_ID), docBaseType.getCode())
: TranslatableStrings.anyLanguage("?");
return TranslatableStrings.builder()
.appendADMessage(AdMessageKey.of("PeriodClosed"))
.append(" ").appendADElement("DateAcct").append(": ").append(dateAcctTrl)
.append(", ").appendADElement("DocBaseType").append(": ").append(docBaseTypeTrl)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\PeriodClosedException.java | 1 |
请完成以下Java代码 | private WindowId getWindowId()
{
return WindowId.of(getProcessInfo().getAdWindowId().getRepoId());
}
@NonNull
private DocumentFilter createAreaSearchFilter(final I_C_Location location)
{
final DocumentEntityDescriptor entityDescriptor = documentCollection.getDocumentEntityDescriptor(getWindowId());
final GeoLocationDocumentQuery query = createGeoLocationQuery(location);
return geoLocationDocumentService.createDocumentFilter(entityDescriptor, query);
}
private GeoLocationDocumentQuery createGeoLocationQuery(final I_C_Location location)
{
final CountryId countryId = CountryId.ofRepoId(location.getC_Country_ID());
final ITranslatableString countryName = countriesRepo.getCountryNameById(countryId);
return GeoLocationDocumentQuery.builder()
.country(IntegerLookupValue.of(countryId, countryName))
.address1(location.getAddress1())
.city(location.getCity())
.postal(location.getPostal())
.distanceInKm(distanceInKm) | .visitorsAddress(visitorsAddress)
.build();
}
private I_C_Location getSelectedLocationOrFirstAvailable()
{
final Set<Integer> bpLocationIds = getSelectedIncludedRecordIds(I_C_BPartner_Location.class);
if (!bpLocationIds.isEmpty())
{
// retrieve the selected location
final LocationId locationId = bpartnersRepo.getBPartnerLocationAndCaptureIdInTrx(BPartnerLocationId.ofRepoId(getRecord_ID(), bpLocationIds.iterator().next())).getLocationCaptureId();
return locationsRepo.getById(locationId);
}
else
{
// retrieve the first bpartner location available
final List<I_C_BPartner_Location> partnerLocations = bpartnersRepo.retrieveBPartnerLocations(BPartnerId.ofRepoId(getRecord_ID()));
if (!partnerLocations.isEmpty())
{
return locationsRepo.getById(LocationId.ofRepoId(partnerLocations.get(0).getC_Location_ID()));
}
}
throw new AdempiereException("@NotFound@ @C_Location_ID@");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\location\geocoding\process\C_BPartner_Window_AreaSearchProcess.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SessionDataRedisProperties {
/**
* Namespace for keys used to store sessions.
*/
private String namespace = "spring:session";
/**
* Sessions flush mode. Determines when session changes are written to the session
* store. Not supported with a reactive session repository.
*/
private FlushMode flushMode = FlushMode.ON_SAVE;
/**
* Sessions save mode. Determines how session changes are tracked and saved to the
* session store.
*/
private SaveMode saveMode = SaveMode.ON_SET_ATTRIBUTE;
/**
* The configure action to apply when no user-defined ConfigureRedisAction or
* ConfigureReactiveRedisAction bean is present.
*/
private ConfigureAction configureAction = ConfigureAction.NOTIFY_KEYSPACE_EVENTS;
/**
* Cron expression for expired session cleanup job. Only supported when
* repository-type is set to indexed. Not supported with a reactive session
* repository.
*/
private @Nullable String cleanupCron;
/**
* Type of Redis session repository to configure.
*/
private RepositoryType repositoryType = RepositoryType.DEFAULT;
public String getNamespace() {
return this.namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public FlushMode getFlushMode() {
return this.flushMode;
}
public void setFlushMode(FlushMode flushMode) {
this.flushMode = flushMode;
}
public SaveMode getSaveMode() {
return this.saveMode;
}
public void setSaveMode(SaveMode saveMode) {
this.saveMode = saveMode;
}
public @Nullable String getCleanupCron() {
return this.cleanupCron;
}
public void setCleanupCron(@Nullable String cleanupCron) {
this.cleanupCron = cleanupCron;
}
public ConfigureAction getConfigureAction() {
return this.configureAction;
} | public void setConfigureAction(ConfigureAction configureAction) {
this.configureAction = configureAction;
}
public RepositoryType getRepositoryType() {
return this.repositoryType;
}
public void setRepositoryType(RepositoryType repositoryType) {
this.repositoryType = repositoryType;
}
/**
* Strategies for configuring and validating Redis.
*/
public enum ConfigureAction {
/**
* Ensure that Redis Keyspace events for Generic commands and Expired events are
* enabled.
*/
NOTIFY_KEYSPACE_EVENTS,
/**
* No not attempt to apply any custom Redis configuration.
*/
NONE
}
/**
* Type of Redis session repository to auto-configure.
*/
public enum RepositoryType {
/**
* Auto-configure a RedisSessionRepository or ReactiveRedisSessionRepository.
*/
DEFAULT,
/**
* Auto-configure a RedisIndexedSessionRepository or
* ReactiveRedisIndexedSessionRepository.
*/
INDEXED
}
} | repos\spring-boot-4.0.1\module\spring-boot-session-data-redis\src\main\java\org\springframework\boot\session\data\redis\autoconfigure\SessionDataRedisProperties.java | 2 |
请完成以下Java代码 | private CostElement extractCostElement(final @NonNull I_M_Cost record)
{
return costElementCache.computeIfAbsent(extractCostElementId(record), costElementRepo::getById);
}
@NonNull
private static CostElementId extractCostElementId(final @NonNull I_M_Cost record)
{
return CostElementId.ofRepoId(record.getM_CostElement_ID());
}
private AcctSchema getAcctSchema(final AcctSchemaId acctSchemaId)
{
return acctSchemaCache.computeIfAbsent(acctSchemaId, acctSchemasRepo::getById);
}
@NonNull
private static AcctSchemaId extractAcctSchemaId(final @NonNull I_M_Cost record)
{
return AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID());
}
private I_C_UOM extractUOM(final @NonNull I_M_Cost record)
{
return uomCache.computeIfAbsent(extractUomId(record), uomsRepo::getById);
} | private static UomId extractUomId(final @NonNull I_M_Cost record)
{
return UomId.ofRepoId(record.getC_UOM_ID());
}
//
//
//
@Value(staticConstructor = "of")
private static class ProductAndAcctSchemaId
{
@NonNull ProductId productId;
@NonNull AcctSchemaId acctSchemaId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\impl\CurrentCostsLoader.java | 1 |
请完成以下Java代码 | private boolean isProcessVariableNull(Object variable) {
return variable == null || NullNode.getInstance().equals(variable);
}
private Map<String, Object> resolveExpressions(
MappingExecutionContext mappingExecutionContext,
Map<String, Object> availableVariables,
Map<String, Object> outboundVariables
) {
if (mappingExecutionContext.hasExecution()) {
return resolveExecutionExpressions(mappingExecutionContext, availableVariables, outboundVariables);
} else {
return expressionResolver.resolveExpressionsMap(
new SimpleMapExpressionEvaluator(availableVariables),
outboundVariables
);
}
}
private Map<String, Object> resolveExecutionExpressions(
MappingExecutionContext mappingExecutionContext,
Map<String, Object> availableVariables,
Map<String, Object> outboundVariables
) {
if (availableVariables != null && !availableVariables.isEmpty()) {
return expressionResolver.resolveExpressionsMap(
new CompositeVariableExpressionEvaluator(
new SimpleMapExpressionEvaluator(availableVariables),
new VariableScopeExpressionEvaluator(mappingExecutionContext.getExecution())
), | outboundVariables
);
}
return expressionResolver.resolveExpressionsMap(
new VariableScopeExpressionEvaluator(mappingExecutionContext.getExecution()),
outboundVariables
);
}
private boolean isTargetProcessVariableDefined(
Extension extensions,
DelegateExecution execution,
String variableName
) {
return (
extensions.getPropertyByName(variableName) != null ||
(execution != null && execution.getVariable(variableName) != null)
);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\impl\ExtensionsVariablesMappingProvider.java | 1 |
请完成以下Java代码 | protected @Nullable CorsConfiguration getCorsConfiguration(Object handler, ServerWebExchange exchange) {
// TODO: support cors configuration via properties on a route see gh-229
// see RequestMappingHandlerMapping.initCorsConfiguration()
// also see
// https://github.com/spring-projects/spring-framework/blob/master/spring-web/src/test/java/org/springframework/web/cors/reactive/CorsWebFilterTests.java
return super.getCorsConfiguration(handler, exchange);
}
// TODO: get desc from factory?
private String getExchangeDesc(ServerWebExchange exchange) {
StringBuilder out = new StringBuilder();
out.append("Exchange: ");
out.append(exchange.getRequest().getMethod());
out.append(" ");
out.append(exchange.getRequest().getURI());
return out.toString();
}
protected Mono<Route> lookupRoute(ServerWebExchange exchange) {
return this.routeLocator.getRoutes().filterWhen(route -> {
// add the current route we are testing
exchange.getAttributes().put(GATEWAY_PREDICATE_ROUTE_ATTR, route.getId());
try {
return route.getPredicate().apply(exchange);
}
catch (Exception e) {
logger.error("Error applying predicate for route: " + route.getId(), e);
}
return Mono.just(false);
})
.next()
// TODO: error handling
.map(route -> {
if (logger.isDebugEnabled()) {
logger.debug("Route matched: " + route.getId());
}
validateRoute(route, exchange);
return route;
});
/*
* TODO: trace logging if (logger.isTraceEnabled()) { | * logger.trace("RouteDefinition did not match: " + routeDefinition.getId()); }
*/
}
/**
* Validate the given handler against the current request.
* <p>
* The default implementation is empty. Can be overridden in subclasses, for example
* to enforce specific preconditions expressed in URL mappings.
* @param route the Route object to validate
* @param exchange current exchange
* @throws Exception if validation failed
*/
@SuppressWarnings("UnusedParameters")
protected void validateRoute(Route route, ServerWebExchange exchange) {
}
protected String getSimpleName() {
return "RoutePredicateHandlerMapping";
}
public enum ManagementPortType {
/**
* The management port has been disabled.
*/
DISABLED,
/**
* The management port is the same as the server port.
*/
SAME,
/**
* The management port and server port are different.
*/
DIFFERENT;
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\RoutePredicateHandlerMapping.java | 1 |
请完成以下Java代码 | public void disconnect(boolean onError) throws InterruptedException {
if (!onError) {
try {
if (inputStream != null) {
inputStream.onCompleted();
}
} catch (Exception e) {
log.error("Exception during onCompleted", e);
}
}
if (channel != null) {
channel.shutdown();
int attempt = 0;
do {
try {
channel.awaitTermination(timeoutSecs, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("Channel await termination was interrupted", e);
}
if (attempt > 5) {
log.warn("We had reached maximum of termination attempts. Force closing channel");
try {
channel.shutdownNow();
} catch (Exception e) {
log.error("Exception during shutdownNow", e);
}
break;
}
attempt++;
} while (!channel.isTerminated());
}
}
@Override
public void sendUplinkMsg(UplinkMsg msg) {
uplinkMsgLock.lock();
try {
this.inputStream.onNext(RequestMsg.newBuilder()
.setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE)
.setUplinkMsg(msg)
.build());
} finally {
uplinkMsgLock.unlock(); | }
}
@Override
public void sendSyncRequestMsg(boolean fullSyncRequired) {
uplinkMsgLock.lock();
try {
SyncRequestMsg syncRequestMsg = SyncRequestMsg.newBuilder()
.setFullSync(fullSyncRequired)
.build();
this.inputStream.onNext(RequestMsg.newBuilder()
.setMsgType(RequestMsgType.SYNC_REQUEST_RPC_MESSAGE)
.setSyncRequestMsg(syncRequestMsg)
.build());
} finally {
uplinkMsgLock.unlock();
}
}
@Override
public void sendDownlinkResponseMsg(DownlinkResponseMsg downlinkResponseMsg) {
uplinkMsgLock.lock();
try {
this.inputStream.onNext(RequestMsg.newBuilder()
.setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE)
.setDownlinkResponseMsg(downlinkResponseMsg)
.build());
} finally {
uplinkMsgLock.unlock();
}
}
} | repos\thingsboard-master\common\edge-api\src\main\java\org\thingsboard\edge\rpc\EdgeGrpcClient.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.