instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public List<User> findAllByRsql(@RequestParam(value = "search") String search) {
Node rootNode = new RSQLParser().parse(search);
Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
return dao.findAll(spec);
}
@RequestMapping(method = RequestMethod.GET, value = "/api/myusers")
@ResponseBody
public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) Predicate predicate) {
return myUserRepository.findAll(predicate);
}
// API - WRITE
@RequestMapping(method = RequestMethod.POST, value = "/users")
|
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody User resource) {
Preconditions.checkNotNull(resource);
dao.save(resource);
}
@RequestMapping(method = RequestMethod.POST, value = "/myusers")
@ResponseStatus(HttpStatus.CREATED)
public void addMyUser(@RequestBody MyUser resource) {
Preconditions.checkNotNull(resource);
myUserRepository.save(resource);
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\web\controller\UserController.java
| 2
|
请完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductDesc() {
return productDesc;
}
public void setProductDesc(String productDesc) {
|
this.productDesc = productDesc;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
|
repos\springboot-demo-master\elasticsearch\src\main\java\demo\et59\elaticsearch\document\ProductDocument.java
| 1
|
请完成以下Java代码
|
public class JuelFormEngine implements FormEngine {
@Override
public String getName() {
return "juel";
}
@Override
public Object renderStartForm(StartFormData startForm) {
if (startForm.getFormKey() == null) {
return null;
}
String formTemplateString = getFormTemplateString(startForm, startForm.getFormKey());
ScriptingEngines scriptingEngines = CommandContextUtil.getProcessEngineConfiguration().getScriptingEngines();
ScriptEngineRequest scriptEngineRequest = ScriptEngineRequest.builder()
.language(ScriptingEngines.DEFAULT_SCRIPTING_LANGUAGE)
.script(formTemplateString)
.build();
return scriptingEngines.evaluate(scriptEngineRequest).getResult();
}
@Override
public Object renderTaskForm(TaskFormData taskForm) {
if (taskForm.getFormKey() == null) {
return null;
}
String formTemplateString = getFormTemplateString(taskForm, taskForm.getFormKey());
ScriptingEngines scriptingEngines = CommandContextUtil.getProcessEngineConfiguration().getScriptingEngines();
TaskEntity task = (TaskEntity) taskForm.getTask();
|
ExecutionEntity executionEntity = null;
if (task.getExecutionId() != null) {
executionEntity = CommandContextUtil.getExecutionEntityManager().findById(task.getExecutionId());
}
ScriptEngineRequest.Builder builder = ScriptEngineRequest.builder()
.script(formTemplateString)
.language(ScriptingEngines.DEFAULT_SCRIPTING_LANGUAGE)
.scopeContainer(executionEntity);
return scriptingEngines.evaluate(builder.build()).getResult();
}
protected String getFormTemplateString(FormData formInstance, String formKey) {
String deploymentId = formInstance.getDeploymentId();
ResourceEntity resourceStream = CommandContextUtil.getResourceEntityManager().findResourceByDeploymentIdAndResourceName(deploymentId, formKey);
if (resourceStream == null) {
throw new FlowableObjectNotFoundException("Form with formKey '" + formKey + "' does not exist", String.class);
}
return new String(resourceStream.getBytes(), StandardCharsets.UTF_8);
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\JuelFormEngine.java
| 1
|
请完成以下Java代码
|
public com.baeldung.schema.EmployeeKey.Builder setDepartmentName(java.lang.CharSequence value) {
validate(fields()[1], value);
this.departmentName = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'departmentName' field has been set.
* @return True if the 'departmentName' field has been set, false otherwise.
*/
public boolean hasDepartmentName() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'departmentName' field.
* @return This builder.
*/
public com.baeldung.schema.EmployeeKey.Builder clearDepartmentName() {
departmentName = null;
fieldSetFlags()[1] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public EmployeeKey build() {
|
try {
EmployeeKey record = new EmployeeKey();
record.id = fieldSetFlags()[0] ? this.id : (java.lang.Integer) defaultValue(fields()[0]);
record.departmentName = fieldSetFlags()[1] ? this.departmentName : (java.lang.CharSequence) defaultValue(fields()[1]);
return record;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<EmployeeKey>
WRITER$ = (org.apache.avro.io.DatumWriter<EmployeeKey>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<EmployeeKey>
READER$ = (org.apache.avro.io.DatumReader<EmployeeKey>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-stream\spring-cloud-stream-kafka\src\main\java\com\baeldung\schema\EmployeeKey.java
| 1
|
请完成以下Java代码
|
public int getAD_Window_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Window_ID);
}
@Override
public void setErrorMsg (final @Nullable java.lang.String ErrorMsg)
{
set_Value (COLUMNNAME_ErrorMsg, ErrorMsg);
}
@Override
public java.lang.String getErrorMsg()
{
return get_ValueAsString(COLUMNNAME_ErrorMsg);
}
@Override
public void setIsProcessing (final boolean IsProcessing)
{
set_Value (COLUMNNAME_IsProcessing, IsProcessing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_IsProcessing);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
|
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setResult (final int Result)
{
set_Value (COLUMNNAME_Result, Result);
}
@Override
public int getResult()
{
return get_ValueAsInt(COLUMNNAME_Result);
}
@Override
public void setWhereClause (final @Nullable java.lang.String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
@Override
public java.lang.String getWhereClause()
{
return get_ValueAsString(COLUMNNAME_WhereClause);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_Currency_ID (final int C_Currency_ID)
{
if (C_Currency_ID < 1)
set_Value (COLUMNNAME_C_Currency_ID, null);
else
set_Value (COLUMNNAME_C_Currency_ID, C_Currency_ID);
}
@Override
public int getC_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Currency_ID);
}
@Override
public org.compiere.model.I_C_Region getC_Region()
{
return get_ValueAsPO(COLUMNNAME_C_Region_ID, org.compiere.model.I_C_Region.class);
}
@Override
public void setC_Region(final org.compiere.model.I_C_Region C_Region)
{
set_ValueFromPO(COLUMNNAME_C_Region_ID, org.compiere.model.I_C_Region.class, C_Region);
}
@Override
public void setC_Region_ID (final int C_Region_ID)
{
if (C_Region_ID < 1)
set_Value (COLUMNNAME_C_Region_ID, null);
else
set_Value (COLUMNNAME_C_Region_ID, C_Region_ID);
}
@Override
public int getC_Region_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Region_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);
|
}
@Override
public void setFreight_Cost_Calc_Price (final BigDecimal Freight_Cost_Calc_Price)
{
set_Value (COLUMNNAME_Freight_Cost_Calc_Price, Freight_Cost_Calc_Price);
}
@Override
public BigDecimal getFreight_Cost_Calc_Price()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Freight_Cost_Calc_Price);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_DiscountSchema_Calculated_Surcharge_Price_ID (final int M_DiscountSchema_Calculated_Surcharge_Price_ID)
{
if (M_DiscountSchema_Calculated_Surcharge_Price_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_Price_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_Price_ID, M_DiscountSchema_Calculated_Surcharge_Price_ID);
}
@Override
public int getM_DiscountSchema_Calculated_Surcharge_Price_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_Price_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchema_Calculated_Surcharge_Price.java
| 1
|
请完成以下Java代码
|
public static Collector<Money, ?, Stream<Money>> sumByCurrencyAndStream()
{
return sumByCurrencyAnd(map -> map.values().stream());
}
public static Collector<Money, ?, ImmutableMap<CurrencyId, Money>> sumByCurrency()
{
return sumByCurrencyAnd(ImmutableMap::copyOf);
}
public static <T> Collector<Money, ?, T> sumByCurrencyAnd(final Function<Map<CurrencyId, Money>, T> finisher)
{
final Supplier<Map<CurrencyId, Money>> supplier = HashMap::new;
final BiConsumer<Map<CurrencyId, Money>, Money> accumulator = (map, money) -> map.compute(money.getCurrencyId(), (currency, moneyOld) -> moneyOld != null ? moneyOld.add(money) : money);
final BinaryOperator<Map<CurrencyId, Money>> combiner = (l, r) -> {
r.values().forEach(money -> accumulator.accept(l, money));
return l;
};
return Collector.of(supplier, accumulator, combiner, finisher);
}
public Amount toAmount(@NonNull final Function<CurrencyId, CurrencyCode> currencyCodeMapper)
{
return Amount.of(toBigDecimal(), currencyCodeMapper.apply(getCurrencyId()));
}
public Money round(@NonNull final CurrencyPrecision precision)
{
return withValue(precision.round(this.value));
}
public Money roundIfNeeded(@NonNull final CurrencyPrecision precision)
{
return withValue(precision.roundIfNeeded(this.value));
}
public Money round(@NonNull final Function<CurrencyId, CurrencyPrecision> precisionProvider)
{
final CurrencyPrecision precision = precisionProvider.apply(currencyId);
if (precision == null)
{
throw new AdempiereException("No precision was returned by " + precisionProvider + " for " + currencyId);
|
}
return round(precision);
}
private Money withValue(@NonNull final BigDecimal newValue)
{
return value.compareTo(newValue) != 0 ? of(newValue, currencyId) : this;
}
public static int countNonZero(final Money... array)
{
if (array == null || array.length == 0)
{
return 0;
}
int count = 0;
for (final Money money : array)
{
if (money != null && money.signum() != 0)
{
count++;
}
}
return count;
}
public static boolean equals(@Nullable Money money1, @Nullable Money money2) {return Objects.equals(money1, money2);}
public Percent percentageOf(@NonNull final Money whole)
{
assertCurrencyIdMatching(whole);
return Percent.of(toBigDecimal(), whole.toBigDecimal());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\money\Money.java
| 1
|
请完成以下Java代码
|
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public I_M_InOut_Cost getReversal()
{
return get_ValueAsPO(COLUMNNAME_Reversal_ID, I_M_InOut_Cost.class);
}
@Override
public void setReversal(final I_M_InOut_Cost Reversal)
{
|
set_ValueFromPO(COLUMNNAME_Reversal_ID, I_M_InOut_Cost.class, Reversal);
}
@Override
public void setReversal_ID (final int Reversal_ID)
{
if (Reversal_ID < 1)
set_Value (COLUMNNAME_Reversal_ID, null);
else
set_Value (COLUMNNAME_Reversal_ID, Reversal_ID);
}
@Override
public int getReversal_ID()
{
return get_ValueAsInt(COLUMNNAME_Reversal_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOut_Cost.java
| 1
|
请完成以下Java代码
|
protected void doStart() throws Exception {
if (this.initializer == null) {
return;
}
if (ClassUtils.isPresent("org.apache.catalina.webresources.TomcatURLStreamHandlerFactory",
getClass().getClassLoader())) {
org.apache.catalina.webresources.TomcatURLStreamHandlerFactory.register();
}
else {
try {
URL.setURLStreamHandlerFactory(new WarUrlStreamHandlerFactory());
}
catch (Error ex) {
// Ignore
}
}
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(this.context.getClassLoader());
try {
this.context.getContext().setExtendedListenerTypes(true);
this.initializer.onStartup(null, this.context.getServletContext());
}
finally {
this.context.getContext().setExtendedListenerTypes(false);
}
}
finally {
Thread.currentThread().setContextClassLoader(classLoader);
}
}
/**
* {@link URLStreamHandlerFactory} to support {@literal war} protocol.
*/
private static final class WarUrlStreamHandlerFactory implements URLStreamHandlerFactory {
@Override
public @Nullable URLStreamHandler createURLStreamHandler(String protocol) {
if ("war".equals(protocol)) {
return new WarUrlStreamHandler();
}
return null;
}
}
/**
* {@link URLStreamHandler} for {@literal war} protocol compatible with jasper's
* {@link URL urls} produced by
* {@link org.apache.tomcat.util.scan.JarFactory#getJarEntryURL(URL, String)}.
*/
private static final class WarUrlStreamHandler extends URLStreamHandler {
@Override
protected void parseURL(URL u, String spec, int start, int limit) {
String path = "jar:" + spec.substring("war:".length());
int separator = path.indexOf("*/");
if (separator >= 0) {
path = path.substring(0, separator) + "!/" + path.substring(separator + 2);
}
setURL(u, u.getProtocol(), "", -1, null, null, path, null, null);
}
@Override
protected URLConnection openConnection(URL u) throws IOException {
return new WarURLConnection(u);
}
}
|
/**
* {@link URLConnection} to support {@literal war} protocol.
*/
private static class WarURLConnection extends URLConnection {
private final URLConnection connection;
protected WarURLConnection(URL url) throws IOException {
super(url);
this.connection = new URL(url.getFile()).openConnection();
}
@Override
public void connect() throws IOException {
if (!this.connected) {
this.connection.connect();
this.connected = true;
}
}
@Override
public InputStream getInputStream() throws IOException {
connect();
return this.connection.getInputStream();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\servlet\JasperInitializer.java
| 1
|
请完成以下Java代码
|
private String getProcessClassname()
{
return processClassname;
}
@Nullable private Class<?> getProcessClassOrNull()
{
return processClass.orElse(null);
}
private static Optional<Class<?>> loadProcessClass(@Nullable final String classname)
{
if (classname == null || Check.isBlank(classname))
{
return Optional.empty();
}
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try
{
final Class<?> processClass = classLoader.loadClass(classname);
return Optional.of(processClass);
}
catch (final ClassNotFoundException e)
{
logger.warn("Cannot load process class: {}", classname, e);
return Optional.empty();
}
}
@Nullable private Class<? extends IProcessDefaultParametersProvider> getProcessDefaultParametersProvider()
{
final Class<?> processClass = getProcessClassOrNull();
if (processClass == null || !IProcessDefaultParametersProvider.class.isAssignableFrom(processClass))
{
return null;
}
try
{
return processClass.asSubclass(IProcessDefaultParametersProvider.class);
}
catch (final Exception e)
{
logger.warn(e.getLocalizedMessage(), e);
return null;
}
}
public Builder setParametersDescriptor(final DocumentEntityDescriptor parametersDescriptor)
{
this.parametersDescriptor = parametersDescriptor;
return this;
}
|
private DocumentEntityDescriptor getParametersDescriptor()
{
return parametersDescriptor;
}
public Builder setLayout(final ProcessLayout layout)
{
this.layout = layout;
return this;
}
private ProcessLayout getLayout()
{
Check.assumeNotNull(layout, "Parameter layout is not null");
return layout;
}
public Builder setStartProcessDirectly(final boolean startProcessDirectly)
{
this.startProcessDirectly = startProcessDirectly;
return this;
}
private boolean isStartProcessDirectly()
{
if (startProcessDirectly != null)
{
return startProcessDirectly;
}
else
{
return computeIsStartProcessDirectly();
}
}
private boolean computeIsStartProcessDirectly()
{
return (getParametersDescriptor() == null || getParametersDescriptor().getFields().isEmpty())
&& TranslatableStrings.isEmpty(getLayout().getDescription());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\descriptor\ProcessDescriptor.java
| 1
|
请完成以下Java代码
|
public void setIsReceipt (final boolean IsReceipt)
{
set_Value (COLUMNNAME_IsReceipt, IsReceipt);
}
@Override
public boolean isReceipt()
{
return get_ValueAsBoolean(COLUMNNAME_IsReceipt);
}
@Override
public void setIsReconciled (final boolean IsReconciled)
{
set_Value (COLUMNNAME_IsReconciled, IsReconciled);
}
@Override
public boolean isReconciled()
{
return get_ValueAsBoolean(COLUMNNAME_IsReconciled);
}
@Override
public void setIsValid (final boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, IsValid);
}
@Override
public boolean isValid()
{
return get_ValueAsBoolean(COLUMNNAME_IsValid);
}
|
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
throw new IllegalArgumentException ("Processing is virtual column"); }
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_Import.java
| 1
|
请完成以下Java代码
|
public void assertLockedBy(@NonNull final UserId expectedLockedBy)
{
if (isEmpty())
{
return;
}
final List<ShipmentScheduleLock> locksByOtherUser = locks.values()
.stream()
.filter(lock -> lock.isNotLockedBy(expectedLockedBy))
.collect(ImmutableList.toImmutableList());
if (!locksByOtherUser.isEmpty())
{
throw new AdempiereException("Following locks are not owned by " + expectedLockedBy + ": " + locksByOtherUser);
}
}
public void assertLockType(@NonNull final ShipmentScheduleLockType expectedLockType)
{
if (isEmpty())
{
return;
}
final List<ShipmentScheduleLock> locksWithDifferentLockType = locks.values()
.stream()
.filter(lock -> !lock.isLockType(expectedLockType))
.collect(ImmutableList.toImmutableList());
if (!locksWithDifferentLockType.isEmpty())
|
{
throw new AdempiereException("Following locks are not for " + expectedLockType + ": " + locksWithDifferentLockType);
}
}
public Set<ShipmentScheduleId> getShipmentScheduleIdsNotLocked(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIdsToCheck)
{
if (isEmpty())
{
return shipmentScheduleIdsToCheck;
}
return shipmentScheduleIdsToCheck.stream()
.filter(this::isNotLocked)
.collect(ImmutableSet.toImmutableSet());
}
public Set<ShipmentScheduleId> getShipmentScheduleIdsLocked()
{
return locks.keySet();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\lock\ShipmentScheduleLocksMap.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SAP_GLJournalLine implements ITabCallout
{
private final SAPGLJournalService glJournalService;
public SAP_GLJournalLine(
@NonNull final SAPGLJournalService glJournalService)
{
this.glJournalService = glJournalService;
}
@PostConstruct
public void postConstruct()
{
Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this);
}
@Override
public void onNew(final ICalloutRecord calloutRecord)
{
final I_SAP_GLJournalLine glJournalLine = calloutRecord.getModel(I_SAP_GLJournalLine.class);
final SAPGLJournalId glJournalId = SAPGLJournalId.ofRepoId(glJournalLine.getSAP_GLJournal_ID());
final SeqNo seqNo = glJournalService.getNextSeqNo(glJournalId);
glJournalLine.setLine(seqNo.toInt());
}
@CalloutMethod(columnNames = I_SAP_GLJournalLine.COLUMNNAME_PostingSign)
public void onPostingSign(final I_SAP_GLJournalLine glJournalLine)
{
updateAmtAcct(glJournalLine);
}
@CalloutMethod(columnNames = I_SAP_GLJournalLine.COLUMNNAME_C_ValidCombination_ID)
public void onC_ValidCombination_ID(final I_SAP_GLJournalLine glJournalLine)
{
glJournalService.updateTrxInfo(glJournalLine);
}
|
@CalloutMethod(columnNames = I_SAP_GLJournalLine.COLUMNNAME_Amount)
public void onAmount(final I_SAP_GLJournalLine glJournalLine)
{
updateAmtAcct(glJournalLine);
}
private void updateAmtAcct(final I_SAP_GLJournalLine glJournalLine)
{
final SAPGLJournalCurrencyConversionCtx conversionCtx = getConversionCtx(glJournalLine);
final Money amtAcct = glJournalService.getCurrencyConverter().convertToAcctCurrency(glJournalLine.getAmount(), conversionCtx);
glJournalLine.setAmtAcct(amtAcct.toBigDecimal());
}
private static SAPGLJournalCurrencyConversionCtx getConversionCtx(final I_SAP_GLJournalLine glJournalLine)
{
// NOTE: calling model getter because we expect to be fetched from webui Document
final I_SAP_GLJournal glJournal = glJournalLine.getSAP_GLJournal();
return SAPGLJournalLoaderAndSaver.extractConversionCtx(glJournal);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\callout\SAP_GLJournalLine.java
| 2
|
请完成以下Java代码
|
protected String doIt() throws Exception
{
final ClientId clientId = ClientId.ofRepoId(getAD_Client_ID());
if(Services.get(IClientDAO.class).isMultilingualDocumentsEnabled(clientId))
{
throw new AdempiereException("@AD_Client_ID@: @IsMultiLingualDocument@");
}
//
String sql = "SELECT * FROM AD_Table "
+ "WHERE TableName LIKE '%_Trl' AND TableName NOT LIKE 'AD%' "
+ "ORDER BY TableName";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
rs = pstmt.executeQuery ();
while (rs.next ())
{
processTable (new MTable(getCtx(), rs, null), clientId);
}
}
catch (Exception e)
{
log.error(sql, e);
}
finally
{
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
return "OK";
} // doIt
/**
* Process Translation Table
* @param table table
*/
private void processTable (MTable table, ClientId clientId)
{
StringBuffer sql = new StringBuffer();
MColumn[] columns = table.getColumns(false);
for (MColumn column : columns)
{
if (column.getAD_Reference_ID() == DisplayType.String
|| column.getAD_Reference_ID() == DisplayType.Text)
|
{
String columnName = column.getColumnName();
if (sql.length() != 0)
{
sql.append(",");
}
sql.append(columnName);
}
}
String baseTable = table.getTableName();
baseTable = baseTable.substring(0, baseTable.length()-4);
log.info(baseTable + ": " + sql);
String columnNames = sql.toString();
sql = new StringBuffer();
sql.append("UPDATE ").append(table.getTableName()).append(" t SET (")
.append(columnNames).append(") = (SELECT ").append(columnNames)
.append(" FROM ").append(baseTable).append(" b WHERE t.")
.append(baseTable).append("_ID=b.").append(baseTable).append("_ID) WHERE AD_Client_ID=")
.append(clientId.getRepoId());
int no = DB.executeUpdateAndSaveErrorOnFail(DB.convertSqlToNative(sql.toString()), get_TrxName());
addLog(0, null, new BigDecimal(no), baseTable);
} // processTable
} // TranslationDocSync
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\TranslationDocSync.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public InternalEntityLinkQuery<HistoricEntityLink> createInternalHistoricEntityLinkQuery() {
return (InternalEntityLinkQuery) getHistoricEntityLinkEntityManager().createInternalHistoricEntityLinkQuery();
}
@Override
public HistoricEntityLink createHistoricEntityLink() {
return getHistoricEntityLinkEntityManager().create();
}
@Override
public void insertHistoricEntityLink(HistoricEntityLink entityLink, boolean fireCreateEvent) {
getHistoricEntityLinkEntityManager().insert((HistoricEntityLinkEntity) entityLink, fireCreateEvent);
}
@Override
public void deleteHistoricEntityLink(String id) {
getHistoricEntityLinkEntityManager().delete(id);
}
@Override
public void deleteHistoricEntityLink(HistoricEntityLink entityLink) {
getHistoricEntityLinkEntityManager().delete((HistoricEntityLinkEntity) entityLink);
}
@Override
public void deleteHistoricEntityLinksByScopeIdAndScopeType(String scopeId, String scopeType) {
getHistoricEntityLinkEntityManager().deleteHistoricEntityLinksByScopeIdAndScopeType(scopeId, scopeType);
}
@Override
public void deleteHistoricEntityLinksByScopeDefinitionIdAndScopeType(String scopeDefinitionId, String scopeType) {
getHistoricEntityLinkEntityManager().deleteHistoricEntityLinksByScopeDefinitionIdAndScopeType(scopeDefinitionId, scopeType);
|
}
@Override
public void bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(String scopeType, Collection<String> scopeIds) {
getHistoricEntityLinkEntityManager().bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(scopeType, scopeIds);
}
@Override
public void deleteHistoricEntityLinksForNonExistingProcessInstances() {
getHistoricEntityLinkEntityManager().deleteHistoricEntityLinksForNonExistingProcessInstances();
}
@Override
public void deleteHistoricEntityLinksForNonExistingCaseInstances() {
getHistoricEntityLinkEntityManager().deleteHistoricEntityLinksForNonExistingCaseInstances();
}
public HistoricEntityLinkEntityManager getHistoricEntityLinkEntityManager() {
return configuration.getHistoricEntityLinkEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\HistoricEntityLinkServiceImpl.java
| 2
|
请完成以下Java代码
|
public static ILock lockInvoiceCandidatesForSelection(@NonNull final PInstanceId pinstanceId)
{
final ILockManager lockManager = Services.get(ILockManager.class);
final LockOwner lockOwner = LockOwner.newOwner(LOCK_OWNER_PREFIX, "AD_PInstance_ID=" + pinstanceId.getRepoId());
return lockManager.lock()
.setOwner(lockOwner)
// allow these locks to be cleaned-up on server starts.
// NOTE: when we will add the ICs to workpackages we will move the ICs to another owner and we will also set AutoCleanup=false
.setAutoCleanup(true)
.setFailIfAlreadyLocked(true)
.setRecordsBySelection(I_C_Invoice_Candidate.class, pinstanceId)
.acquire();
}
public static ILock lockInvoiceCandidates(
|
@NonNull final Collection<I_C_Invoice_Candidate> invoiceCandidateRecords,
@NonNull final String uniqueLockOwnerSuffix)
{
final ILockManager lockManager = Services.get(ILockManager.class);
final LockOwner lockOwner = LockOwner.newOwner(LOCK_OWNER_PREFIX, assumeNotEmpty(uniqueLockOwnerSuffix, "uniqueLockOwnerSuffix"));
return lockManager.lock()
.setOwner(lockOwner)
.setAutoCleanup(false)
.setFailIfAlreadyLocked(true)
.addRecordsByModel(invoiceCandidateRecords)
.acquire();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\InvoiceCandidateLockingUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public FlatFileItemReader<Product> reader() {
return new FlatFileItemReaderBuilder<Product>().name("productReader")
.resource(new FileSystemResource("products.csv"))
.delimited()
.names("id", "name", "category", "price", "stock")
.fieldSetMapper(new BeanWrapperFieldSetMapper<>() {{
setTargetType(Product.class);
}})
.build();
}
@Bean
public ItemWriter<Product> writer(RestHighLevelClient restHighLevelClient) {
return products -> {
for (Product product : products) {
try {
IndexRequest request = new IndexRequest("products").id(product.getId())
.source(Map.of("name", product.getName(), "category", product.getCategory(), "price", product.getPrice(), "stock", product.getStock()));
restHighLevelClient.index(request, RequestOptions.DEFAULT);
} catch (Exception e) {
System.err.println("Failed to index product: " + product.getId() + ", error: " + e.getMessage());
}
|
}
};
}
@Bean
public Job importJob(JobRepository jobRepository, PlatformTransactionManager transactionManager, RestHighLevelClient restHighLevelClient) {
return new JobBuilder("importJob", jobRepository)
.start(new StepBuilder("importStep", jobRepository)
.<Product, Product>chunk(10, transactionManager)
.reader(reader())
.writer(writer(restHighLevelClient))
.build())
.build();
}
}
|
repos\tutorials-master\persistence-modules\spring-data-elasticsearch\src\main\java\com\baeldung\elasticsearch\importcsv\BatchConfig.java
| 2
|
请完成以下Java代码
|
public void setData_Export_Audit_ID (final int Data_Export_Audit_ID)
{
if (Data_Export_Audit_ID < 1)
set_Value (COLUMNNAME_Data_Export_Audit_ID, null);
else
set_Value (COLUMNNAME_Data_Export_Audit_ID, Data_Export_Audit_ID);
}
@Override
public int getData_Export_Audit_ID()
{
return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_ID);
}
@Override
public void setData_Export_Audit_Log_ID (final int Data_Export_Audit_Log_ID)
{
if (Data_Export_Audit_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_Log_ID, Data_Export_Audit_Log_ID);
}
@Override
public int getData_Export_Audit_Log_ID()
{
return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_Log_ID);
}
|
@Override
public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID)
{
if (ExternalSystem_Config_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_Config_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID);
}
@Override
public int getExternalSystem_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Data_Export_Audit_Log.java
| 1
|
请完成以下Java代码
|
public void setGL_JournalLine_ID (final int GL_JournalLine_ID)
{
if (GL_JournalLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_JournalLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_JournalLine_ID, GL_JournalLine_ID);
}
@Override
public int getGL_JournalLine_ID()
{
return get_ValueAsInt(COLUMNNAME_GL_JournalLine_ID);
}
@Override
public void setIsAllowAccountCR (final boolean IsAllowAccountCR)
{
set_Value (COLUMNNAME_IsAllowAccountCR, IsAllowAccountCR);
}
@Override
public boolean isAllowAccountCR()
{
return get_ValueAsBoolean(COLUMNNAME_IsAllowAccountCR);
}
@Override
public void setIsAllowAccountDR (final boolean IsAllowAccountDR)
{
set_Value (COLUMNNAME_IsAllowAccountDR, IsAllowAccountDR);
}
@Override
public boolean isAllowAccountDR()
{
return get_ValueAsBoolean(COLUMNNAME_IsAllowAccountDR);
}
@Override
public void setIsGenerated (final boolean IsGenerated)
{
set_ValueNoCheck (COLUMNNAME_IsGenerated, IsGenerated);
}
@Override
public boolean isGenerated()
{
return get_ValueAsBoolean(COLUMNNAME_IsGenerated);
}
@Override
public void setIsSplitAcctTrx (final boolean IsSplitAcctTrx)
{
set_Value (COLUMNNAME_IsSplitAcctTrx, IsSplitAcctTrx);
}
@Override
public boolean isSplitAcctTrx()
{
return get_ValueAsBoolean(COLUMNNAME_IsSplitAcctTrx);
}
@Override
public void setLine (final int Line)
{
set_Value (COLUMNNAME_Line, Line);
}
@Override
public int getLine()
{
return get_ValueAsInt(COLUMNNAME_Line);
}
@Override
public void setProcessed (final boolean Processed)
|
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* Type AD_Reference_ID=540534
* Reference name: GL_JournalLine_Type
*/
public static final int TYPE_AD_Reference_ID=540534;
/** Normal = N */
public static final String TYPE_Normal = "N";
/** Tax = T */
public static final String TYPE_Tax = "T";
@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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_JournalLine.java
| 1
|
请完成以下Spring Boot application配置
|
management.endpoints.web.exposure.include=httptrace,loggers,health,info,metrics
management.trace.http.include=RESPONSE_HEADERS
management.endpoint.loggers.enabled=true
#basic auth creddentials
spring.security.user.name=client
spring.security.user.password=client
#configs to connect to a secured server
spring.boot.admin.client.url=http://localhost:8080
spring.boot.admin.client.username=admin
spring.boot.admin.client.password=admin
#configs to give secured server info
spring.boot.admin.client.instan
|
ce.metadata.user.name=${spring.security.user.name}
spring.boot.admin.client.instance.metadata.user.password=${spring.security.user.password}
#app config
spring.application.name=spring-boot-management
server.port=8081
|
repos\tutorials-master\spring-boot-modules\spring-boot-runtime\src\main\resources\application-logging.properties
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public FlatFileItemReader<Coffee> reader() {
return new FlatFileItemReaderBuilder<Coffee>().name("coffeeItemReader")
.resource(new ClassPathResource(fileInput))
.delimited()
.names(new String[] { "brand", "origin", "characteristics" })
.fieldSetMapper(new BeanWrapperFieldSetMapper<Coffee>() {{
setTargetType(Coffee.class);
}})
.build();
}
@Bean
public CoffeeItemProcessor processor() {
return new CoffeeItemProcessor();
}
@Bean
public JdbcBatchItemWriter<Coffee> writer(DataSource dataSource) {
return new JdbcBatchItemWriterBuilder<Coffee>().itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
.sql("INSERT INTO coffee (brand, origin, characteristics) VALUES (:brand, :origin, :characteristics)")
.dataSource(dataSource)
.build();
}
@Bean
public Job importUserJob(JobRepository jobRepository, JobCompletionNotificationListener listener, Step step1) {
|
return new JobBuilder("importUserJob", jobRepository)
.incrementer(new RunIdIncrementer())
.listener(listener)
.flow(step1)
.end()
.build();
}
@Bean
public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager, JdbcBatchItemWriter<Coffee> writer, VirtualThreadTaskExecutor taskExecutor) {
return new StepBuilder("step1", jobRepository)
.<Coffee, Coffee> chunk(10, transactionManager)
.reader(reader())
.processor(processor())
.writer(writer)
.taskExecutor(taskExecutor)
.build();
}
}
|
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\bootbatch\BatchConfiguration.java
| 2
|
请完成以下Java代码
|
public void setReplicationIssueSolver(final IReplicationIssueSolver<? extends IReplicationIssueAware> issueSolver)
{
this.issueSolver = issueSolver;
}
@Override
public void setTrxItemProcessorCtx(final ITrxItemProcessorContext processorCtx)
{
// this.processorCtx = processorCtx;
}
@Override
public ReplicationTrxLinesProcessorResult getResult()
{
return result;
}
@Override
public boolean isSameChunk(final I_EXP_ReplicationTrxLine item)
{
return false;
}
@Override
public void newChunk(final I_EXP_ReplicationTrxLine item)
{
currentTrxLines = new ArrayList<I_EXP_ReplicationTrxLine>();
}
@Override
public void process(final I_EXP_ReplicationTrxLine item) throws Exception
{
final IReplicationIssueAware issueAware = Services.get(IReplicationIssueSolverDAO.class).retrieveReplicationIssueAware(item);
issueSolver.solveIssues(issueAware, params);
|
currentTrxLines.add(item);
result.addReplicationIssueAware(issueAware);
}
@Override
public void completeChunk()
{
for (final I_EXP_ReplicationTrxLine line : currentTrxLines)
{
line.setReplicationTrxStatus(X_EXP_ReplicationTrxLine.REPLICATIONTRXSTATUS_Vollstaendig);
InterfaceWrapperHelper.save(line);
}
}
@Override
public void cancelChunk()
{
currentTrxLines = null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\trx\api\impl\ReplicationTrxLinesProcessor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BankStatementImportFileLogRepository
{
public void insertLogs(@NonNull final List<BankStatementImportFileRequestLog> logEntries)
{
if (logEntries.isEmpty())
{
return;
}
final String sql = "INSERT INTO " + I_C_BankStatement_Import_File_Log.Table_Name + "("
+ I_C_BankStatement_Import_File_Log.COLUMNNAME_AD_Client_ID + "," // 1
+ I_C_BankStatement_Import_File_Log.COLUMNNAME_AD_Org_ID + "," // 2
+ I_C_BankStatement_Import_File_Log.COLUMNNAME_Created + "," // 3
+ I_C_BankStatement_Import_File_Log.COLUMNNAME_CreatedBy + "," // 4
+ I_C_BankStatement_Import_File_Log.COLUMNNAME_IsActive + "," // 5
+ I_C_BankStatement_Import_File_Log.COLUMNNAME_Logmessage + "," // 6
+ I_C_BankStatement_Import_File_Log.COLUMNNAME_Updated + "," // 7
+ I_C_BankStatement_Import_File_Log.COLUMNNAME_UpdatedBy + "," // 8
+ I_C_BankStatement_Import_File_Log.COLUMNNAME_AD_Issue_ID + "," // 9
+ I_C_BankStatement_Import_File_Log.COLUMNNAME_C_BankStatement_Import_File_ID + "," // 10
+ I_C_BankStatement_Import_File_Log.COLUMNNAME_C_BankStatement_Import_File_Log_ID // 11
+ ")"
+ " VALUES ("
+ "?," // 1 - AD_Client_ID
+ "?," // 2 - AD_Org_ID
+ "?," // 3 - Created
+ "?," // 4 - CreatedBy
+ "'Y'," // 5 - IsActive
+ "?," // 6 - LogMessage
+ "?," // 7 - Updated
+ "?," // 8 - UpdatedBy
+ "?," // 9 - AD_Issue_ID
+ "?," // 10 - C_BankStatement_Import_File_ID
+ DB.TO_TABLESEQUENCE_NEXTVAL(I_C_BankStatement_Import_File_Log.Table_Name) // 11 - C_BankStatement_Import_File_Log_ID
+ ")";
PreparedStatement pstmt = null;
try
{
|
// NOTE: always create the logs out of transaction because we want them to be persisted even if the api processing trx fails
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
for (final BankStatementImportFileRequestLog logEntry : logEntries)
{
DB.setParameters(pstmt,
logEntry.getClientId(), // 1 - AD_Client_ID
OrgId.ANY, // 2 - AD_Org_ID
logEntry.getTimestamp(), // 3 - Created
logEntry.getUserId(), // 4 - CreatedBy
// + "'Y'," // 5 - IsActive
logEntry.getMessage(), // 6 - LogMessage
logEntry.getTimestamp(), // 7 - Updated
logEntry.getUserId(), // 8 - UpdatedBy
logEntry.getAdIssueId(), // 9 - AD_Issue_ID
logEntry.getBankStatementImportFileId() // 10 - C_BankStatement_Import_File_ID
);
pstmt.addBatch();
}
pstmt.executeBatch();
}
catch (final SQLException ex)
{
throw new DBException(ex, sql);
}
finally
{
DB.close(pstmt);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\importfile\log\BankStatementImportFileLogRepository.java
| 2
|
请完成以下Java代码
|
public BigDecimal getPayAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PayAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
@Override
public void setProcessing (boolean Processing)
|
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Transaction Code.
@param TransactionCode
The transaction code represents the search definition
*/
@Override
public void setTransactionCode (java.lang.String TransactionCode)
{
set_Value (COLUMNNAME_TransactionCode, TransactionCode);
}
/** Get Transaction Code.
@return The transaction code represents the search definition
*/
@Override
public java.lang.String getTransactionCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_I_Datev_Payment.java
| 1
|
请完成以下Java代码
|
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** 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);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getValue());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_SubAcct.java
| 1
|
请完成以下Java代码
|
public byte[] serializeAvroHttpRequestJSON(AvroHttpRequest request) {
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder jsonEncoder = null;
try {
jsonEncoder = EncoderFactory.get()
.jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
writer.write(request, jsonEncoder);
jsonEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
logger.error("Serialization error " + e.getMessage());
}
return data;
}
public byte[] serializeAvroHttpRequestBinary(AvroHttpRequest request) {
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
|
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder jsonEncoder = EncoderFactory.get()
.binaryEncoder(stream, null);
try {
writer.write(request, jsonEncoder);
jsonEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
logger.error("Serialization error " + e.getMessage());
}
return data;
}
}
|
repos\tutorials-master\apache-libraries\src\main\java\com\baeldung\apache\avro\util\serialization\AvroSerializer.java
| 1
|
请完成以下Java代码
|
private Mono<Void> sendContent(ServerWebExchange exchange) {
exchange.getResponse().setStatusCode(HttpStatus.OK);
ResourceHttpMessageWriter writer = new ResourceHttpMessageWriter();
return writer.write(Mono.just(this.resource), ResolvableType.forClass(Resource.class),
ResolvableType.forClass(Resource.class), this.mediaType, exchange.getRequest(), exchange.getResponse(),
Collections.emptyMap());
}
@Override
public String toString() {
return "%s{matcher=%s, resource='%s'}".formatted(getClass().getSimpleName(), this.matcher,
this.resource.getPath());
}
/**
* Create an instance of {@link DefaultResourcesWebFilter} serving Spring Security's
|
* default CSS stylesheet.
* <p>
* The created {@link DefaultResourcesFilter} matches requests
* {@code HTTP GET /default-ui.css}, and returns the default stylesheet at
* {@code org/springframework/security/default-ui.css} with content-type
* {@code text/css;charset=UTF-8}.
* @return -
*/
public static DefaultResourcesWebFilter css() {
return new DefaultResourcesWebFilter(
new PathPatternParserServerWebExchangeMatcher("/default-ui.css", HttpMethod.GET),
new ClassPathResource("org/springframework/security/default-ui.css"),
new MediaType("text", "css", StandardCharsets.UTF_8));
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\ui\DefaultResourcesWebFilter.java
| 1
|
请完成以下Java代码
|
public class DbUserQueryImpl extends UserQueryImpl {
private static final long serialVersionUID = 1L;
public DbUserQueryImpl(CommandExecutor commandExecutor) {
super(commandExecutor);
}
public DbUserQueryImpl() {
super();
}
// results //////////////////////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
checkQueryOk();
final DbReadOnlyIdentityServiceProvider identityProvider = getIdentityProvider(commandContext);
|
return identityProvider.findUserCountByQueryCriteria(this);
}
public List<User> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
final DbReadOnlyIdentityServiceProvider identityProvider = getIdentityProvider(commandContext);
return identityProvider.findUserByQueryCriteria(this);
}
private DbReadOnlyIdentityServiceProvider getIdentityProvider(CommandContext commandContext) {
return (DbReadOnlyIdentityServiceProvider) commandContext.getReadOnlyIdentityProvider();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\identity\db\DbUserQueryImpl.java
| 1
|
请完成以下Java代码
|
private PickingPlanLine updateAlternativeKeys(@NonNull final PickingPlanLine line)
{
final PickFromHU pickFromHU = line.getPickFromHU();
if (pickFromHU == null)
{
return line;
}
final AlternativePickFromKeys alternativeKeys = pickFromHU.getAlternatives()
.filter(alternativeKey -> storages.getStorage(alternativeKey.getHuId(), alternativeKey.getProductId()).hasQtyFreeToAllocate());
return line.withPickFromHU(pickFromHU.withAlternatives(alternativeKeys));
}
private AlternativePickFromsList getRelevantAlternativesFor(final List<PickingPlanLine> lines)
{
final HashSet<AlternativePickFromKey> keysConsidered = new HashSet<>();
final ArrayList<AlternativePickFrom> alternatives = new ArrayList<>();
for (final PickingPlanLine line : lines)
{
final PickFromHU pickFromHU = line.getPickFromHU();
|
if (pickFromHU == null)
{
continue;
}
for (final AlternativePickFromKey key : pickFromHU.getAlternatives())
{
if (keysConsidered.add(key))
{
storages.getStorage(key.getHuId(), key.getProductId())
.getQtyFreeToAllocate()
.filter(Quantity::isPositive)
.map(availableQty -> AlternativePickFrom.of(key, availableQty))
.ifPresent(alternatives::add);
}
}
}
return AlternativePickFromsList.ofList(alternatives);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\CreatePickingPlanCommand.java
| 1
|
请完成以下Java代码
|
private int getC_UOM_ID()
{
final int uomId = uom == null ? -1 : uom.getC_UOM_ID();
return uomId > 0 ? uomId : -1;
}
public I_M_Locator getM_Locator()
{
return locator;
}
private int getM_Locator_ID()
{
final int locatorId = locator == null ? -1 : locator.getM_Locator_ID();
return locatorId > 0 ? locatorId : -1;
}
public I_M_Material_Tracking getM_MaterialTracking()
{
return materialTracking;
}
private int getM_MaterialTracking_ID()
{
final int materialTrackingId = materialTracking == null ? -1 : materialTracking.getM_Material_Tracking_ID();
return materialTrackingId > 0 ? materialTrackingId : -1;
}
protected void add(@NonNull final HUPackingMaterialDocumentLineCandidate candidateToAdd)
{
if (this == candidateToAdd)
{
throw new IllegalArgumentException("Cannot add to it self: " + candidateToAdd);
}
if (!Objects.equals(getProductId(), candidateToAdd.getProductId())
|
|| getC_UOM_ID() != candidateToAdd.getC_UOM_ID()
|| getM_Locator_ID() != candidateToAdd.getM_Locator_ID()
|| getM_MaterialTracking_ID() != candidateToAdd.getM_MaterialTracking_ID())
{
throw new HUException("Candidates are not matching."
+ "\nthis: " + this
+ "\ncandidate to add: " + candidateToAdd);
}
qty = qty.add(candidateToAdd.qty);
// add sources; might be different
addSources(candidateToAdd.getSources());
}
public void addSourceIfNotNull(final IHUPackingMaterialCollectorSource huPackingMaterialCollectorSource)
{
if (huPackingMaterialCollectorSource != null)
{
sources.add(huPackingMaterialCollectorSource);
}
}
private void addSources(final Set<IHUPackingMaterialCollectorSource> huPackingMaterialCollectorSources)
{
if (!huPackingMaterialCollectorSources.isEmpty())
{
sources.addAll(huPackingMaterialCollectorSources);
}
}
public Set<IHUPackingMaterialCollectorSource> getSources()
{
return ImmutableSet.copyOf(sources);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\spi\impl\HUPackingMaterialDocumentLineCandidate.java
| 1
|
请完成以下Java代码
|
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setRemittanceAmt (final BigDecimal RemittanceAmt)
{
set_Value (COLUMNNAME_RemittanceAmt, RemittanceAmt);
}
@Override
public BigDecimal getRemittanceAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_RemittanceAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setService_BPartner_ID (final int Service_BPartner_ID)
{
if (Service_BPartner_ID < 1)
set_Value (COLUMNNAME_Service_BPartner_ID, null);
else
set_Value (COLUMNNAME_Service_BPartner_ID, Service_BPartner_ID);
}
@Override
public int getService_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_Service_BPartner_ID);
}
@Override
public void setServiceFeeAmount (final @Nullable BigDecimal ServiceFeeAmount)
{
set_Value (COLUMNNAME_ServiceFeeAmount, ServiceFeeAmount);
}
@Override
public BigDecimal getServiceFeeAmount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ServiceFeeAmount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public org.compiere.model.I_C_Invoice getService_Fee_Invoice()
{
return get_ValueAsPO(COLUMNNAME_Service_Fee_Invoice_ID, org.compiere.model.I_C_Invoice.class);
}
@Override
public void setService_Fee_Invoice(final org.compiere.model.I_C_Invoice Service_Fee_Invoice)
{
set_ValueFromPO(COLUMNNAME_Service_Fee_Invoice_ID, org.compiere.model.I_C_Invoice.class, Service_Fee_Invoice);
}
@Override
public void setService_Fee_Invoice_ID (final int Service_Fee_Invoice_ID)
{
if (Service_Fee_Invoice_ID < 1)
set_Value (COLUMNNAME_Service_Fee_Invoice_ID, null);
else
set_Value (COLUMNNAME_Service_Fee_Invoice_ID, Service_Fee_Invoice_ID);
}
@Override
public int getService_Fee_Invoice_ID()
{
return get_ValueAsInt(COLUMNNAME_Service_Fee_Invoice_ID);
}
@Override
public void setServiceFeeVatRate (final @Nullable BigDecimal ServiceFeeVatRate)
{
|
set_Value (COLUMNNAME_ServiceFeeVatRate, ServiceFeeVatRate);
}
@Override
public BigDecimal getServiceFeeVatRate()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ServiceFeeVatRate);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setService_Product_ID (final int Service_Product_ID)
{
if (Service_Product_ID < 1)
set_Value (COLUMNNAME_Service_Product_ID, null);
else
set_Value (COLUMNNAME_Service_Product_ID, Service_Product_ID);
}
@Override
public int getService_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Service_Product_ID);
}
@Override
public void setService_Tax_ID (final int Service_Tax_ID)
{
if (Service_Tax_ID < 1)
set_Value (COLUMNNAME_Service_Tax_ID, null);
else
set_Value (COLUMNNAME_Service_Tax_ID, Service_Tax_ID);
}
@Override
public int getService_Tax_ID()
{
return get_ValueAsInt(COLUMNNAME_Service_Tax_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RemittanceAdvice_Line.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ReactiveApiService {
private final WebClient webClient;
public ReactiveApiService(String baseUrl) {
this.webClient = WebClient.builder()
.baseUrl(baseUrl)
.build();
}
public Mono<Map<String, List<User>>> fetchUsersByDepartment() {
ParameterizedTypeReference<Map<String, List<User>>> typeRef = new ParameterizedTypeReference<Map<String, List<User>>>() {
};
return webClient.get()
|
.uri("/users/by-department")
.retrieve()
.bodyToMono(typeRef);
}
public Mono<ApiResponse<List<User>>> fetchUsersWithWrapper() {
ParameterizedTypeReference<ApiResponse<List<User>>> typeRef = new ParameterizedTypeReference<ApiResponse<List<User>>>() {
};
return webClient.get()
.uri("/users/wrapped")
.retrieve()
.bodyToMono(typeRef);
}
}
|
repos\tutorials-master\spring-core-4\src\main\java\com\baeldung\parametrizedtypereference\ReactiveApiService.java
| 2
|
请完成以下Java代码
|
private static InvoiceProcessingContext extractInvoiceProcessingContext(@NonNull final PaymentDocument paymentDocument)
{
return InvoiceProcessingContext.builder()
.serviceCompanyId(paymentDocument.getBpartnerId())
.paymentDate(TimeUtil.asZonedDateTime(paymentDocument.getDateTrx()))
.build();
}
private PaymentDocument toPaymentDocument(@NonNull final PaymentRow row)
{
return toPaymentDocument(row, moneyService);
}
@VisibleForTesting
static PaymentDocument toPaymentDocument(
@NonNull final PaymentRow row,
@NonNull final MoneyService moneyService)
{
|
final PaymentAmtMultiplier amtMultiplier = row.getPaymentAmtMultiplier();
final Money openAmt = amtMultiplier.convertToRealValue(row.getOpenAmt())
.toMoney(moneyService::getCurrencyIdByCurrencyCode);
return PaymentDocument.builder()
.paymentId(row.getPaymentId())
.bpartnerId(row.getBPartnerId())
.documentNo(row.getDocumentNo())
.paymentDirection(row.getPaymentDirection())
.openAmt(openAmt)
.amountToAllocate(openAmt)
.dateTrx(row.getDateTrx())
.clientAndOrgId(row.getClientAndOrgId())
.paymentCurrencyContext(row.getPaymentCurrencyContext())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentsViewAllocateCommand.java
| 1
|
请完成以下Java代码
|
public ListenableFutureTask<String> fetchConfigListenableTask(String configKey) {
return ListenableFutureTask.create(() -> {
TimeUnit.MILLISECONDS.sleep(500);
return String.format("%s.%d", configKey, new Random().nextInt(Integer.MAX_VALUE));
});
}
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
|
请完成以下Java代码
|
protected void executeParse(BpmnParse bpmnParse, MessageEventDefinition messageDefinition) {
BpmnModel bpmnModel = bpmnParse.getBpmnModel();
String messageRef = messageDefinition.getMessageRef();
if (bpmnModel.containsMessageId(messageRef)) {
Message message = bpmnModel.getMessage(messageRef);
messageDefinition.setMessageRef(message.getName());
messageDefinition.setExtensionElements(message.getExtensionElements());
}
if (bpmnParse.getCurrentFlowElement() instanceof IntermediateCatchEvent) {
IntermediateCatchEvent intermediateCatchEvent = (IntermediateCatchEvent) bpmnParse.getCurrentFlowElement();
intermediateCatchEvent.setBehavior(
bpmnParse
.getActivityBehaviorFactory()
.createIntermediateCatchMessageEventActivityBehavior(intermediateCatchEvent, messageDefinition)
);
} else if (bpmnParse.getCurrentFlowElement() instanceof BoundaryEvent) {
|
BoundaryEvent boundaryEvent = (BoundaryEvent) bpmnParse.getCurrentFlowElement();
boundaryEvent.setBehavior(
bpmnParse
.getActivityBehaviorFactory()
.createBoundaryMessageEventActivityBehavior(
boundaryEvent,
messageDefinition,
boundaryEvent.isCancelActivity()
)
);
} else {
// What to do here?
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\MessageEventDefinitionParseHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class StudentResource {
private final StudentRepository studentRepository;
public StudentResource(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
@GetMapping()
public List<Student> retrieveAllStudents() {
return studentRepository.findAll();
}
@GetMapping("/{id}")
public EntityModel<Student> retrieveStudent(@PathVariable long id) {
Optional<Student> student = studentRepository.findById(id);
if (student.isEmpty())
throw new StudentNotFoundException("id-" + id);
EntityModel<Student> resource = EntityModel.of(student.get());
WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllStudents());
resource.add(linkTo.withRel("all-students"));
return resource;
}
@DeleteMapping("/{id}")
public void deleteStudent(@PathVariable long id) {
studentRepository.deleteById(id);
}
@PostMapping()
public ResponseEntity<Student> createStudent(@Valid @RequestBody Student student) {
Student newStudent = studentRepository.save(student);
|
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(newStudent.getId()).toUri();
return ResponseEntity.created(location).build();
}
@PutMapping("/{id}")
public ResponseEntity<Student> updateStudent(@Valid @RequestBody Student student, @PathVariable long id) {
Optional<Student> studentDetails = studentRepository.findById(id);
if (studentDetails.isEmpty())
return ResponseEntity.notFound().build();
student.setId(id);
studentRepository.save(student);
return ResponseEntity.noContent().build();
}
}
|
repos\spring-boot-examples-master\spring-boot-2-rest-service-validation\src\main\java\com\in28minutes\springboot\rest\example\student\StudentResource.java
| 2
|
请完成以下Java代码
|
public class ArrayAndArrayListPerformance {
public static void main(String[] args) throws Exception {
org.openjdk.jmh.runner.Runner runner = new org.openjdk.jmh.runner.Runner(new OptionsBuilder().include(ArrayAndArrayListPerformance.class.getSimpleName()).forks(1).build());
runner.run();
}
public static Integer[] array = Collections.nCopies(1000000, 1).toArray(new Integer[0]);
public static ArrayList<Integer> list = new ArrayList<Integer>(
Arrays.asList(array));
@Benchmark
public Integer[] arrayCreation() {
return new Integer[1000000];
}
@Benchmark
public ArrayList<Integer> arrayListCreation() {
return new ArrayList<>(1000000);
}
@Benchmark
public Integer[] arrayItemsSetting() {
for (int i = 0; i < 1000000; i++) {
array[i] = i;
}
return array;
}
@Benchmark
public ArrayList<Integer> arrayListItemsSetting() {
for (int i = 0; i < 1000000; i++) {
list.add(i);
}
|
return list;
}
@Benchmark
public void arrayItemsRetrieval(Blackhole blackhole) {
for (int i = 0; i < 1000000; i++) {
int item = array[i];
blackhole.consume(item);
}
}
@Benchmark
public void arrayListItemsRetrieval(Blackhole blackhole) {
for (int i = 0; i < 1000000; i++) {
int item = list.get(i);
blackhole.consume(item);
}
}
@Benchmark
public void arrayCloning(Blackhole blackhole) {
Integer[] newArray = array.clone();
blackhole.consume(newArray);
}
@Benchmark
public void arrayListCloning(Blackhole blackhole) {
ArrayList<Integer> newList = new ArrayList<>(list);
blackhole.consume(newList);
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\arrayandlistperformance\ArrayAndArrayListPerformance.java
| 1
|
请完成以下Java代码
|
/* package */class VPAttributeWindowContext implements IVPAttributeContext
{
public static final VPAttributeWindowContext of(final Properties ctx, final int windowNo, final int tabNo)
{
return new VPAttributeWindowContext(ctx, windowNo, tabNo);
}
public static final VPAttributeWindowContext of(final GridField gridField)
{
final Properties ctx = gridField.getCtx();
final int windowNo = gridField.getWindowNo();
final int tabNo = gridField.getTabNo();
return new VPAttributeWindowContext(ctx, windowNo, tabNo);
}
private final Properties ctx;
private final int windowNo;
private final int tabNo;
private VPAttributeWindowContext(final Properties ctx, final int windowNo, final int tabNo)
{
super();
Check.assumeNotNull(ctx, "ctx not null");
this.ctx = ctx;
this.windowNo = windowNo;
this.tabNo = tabNo;
}
private final int getContextAsInt(final String columnName)
{
return Env.getContextAsInt(ctx, windowNo, tabNo, columnName);
}
@Override
public final int getWindowNo()
{
return windowNo;
}
@Override
public final int getTabNo()
{
return tabNo;
}
@Override
public BPartnerId getBpartnerId()
{
return BPartnerId.ofRepoIdOrNull(getContextAsInt("C_BPartner_ID"));
}
@Override
public ProductId getProductId()
{
|
return ProductId.ofRepoIdOrNull(getContextAsInt("M_Product_ID"));
}
@Override
public boolean isSOTrx()
{
return SOTrx.toBoolean(getSoTrx());
}
@Override
public SOTrx getSoTrx()
{
final Boolean soTrx = Env.getSOTrxOrNull(ctx, windowNo);
return SOTrx.ofBoolean(soTrx);
}
@Override
public WarehouseId getWarehouseId()
{
return WarehouseId.ofRepoIdOrNull(getContextAsInt("M_Warehouse_ID"));
}
@Override
public int getM_Locator_ID()
{
return getContextAsInt("M_Locator_ID");
}
@Override
public DocTypeId getDocTypeId()
{
return DocTypeId.ofRepoIdOrNull(getContextAsInt("C_DocType_ID"));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\VPAttributeWindowContext.java
| 1
|
请完成以下Java代码
|
private Set<String> getPackagesToScan(AnnotationMetadata metadata) {
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(metadata.getAnnotationAttributes(ConfigurationPropertiesScan.class.getName()));
Assert.state(attributes != null, "'attributes' must not be null");
String[] basePackages = attributes.getStringArray("basePackages");
Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses");
Set<String> packagesToScan = new LinkedHashSet<>(Arrays.asList(basePackages));
for (Class<?> basePackageClass : basePackageClasses) {
packagesToScan.add(ClassUtils.getPackageName(basePackageClass));
}
if (packagesToScan.isEmpty()) {
packagesToScan.add(ClassUtils.getPackageName(metadata.getClassName()));
}
packagesToScan.removeIf((candidate) -> !StringUtils.hasText(candidate));
return packagesToScan;
}
private void scan(BeanDefinitionRegistry registry, Set<String> packages) {
ConfigurationPropertiesBeanRegistrar registrar = new ConfigurationPropertiesBeanRegistrar(registry);
ClassPathScanningCandidateComponentProvider scanner = getScanner(registry);
for (String basePackage : packages) {
for (BeanDefinition candidate : scanner.findCandidateComponents(basePackage)) {
String beanClassName = candidate.getBeanClassName();
Assert.state(beanClassName != null, "'beanClassName' must not be null");
register(registrar, beanClassName);
}
}
}
private ClassPathScanningCandidateComponentProvider getScanner(BeanDefinitionRegistry registry) {
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.setEnvironment(this.environment);
scanner.setResourceLoader(this.resourceLoader);
scanner.addIncludeFilter(new AnnotationTypeFilter(ConfigurationProperties.class));
TypeExcludeFilter typeExcludeFilter = new TypeExcludeFilter();
typeExcludeFilter.setBeanFactory((BeanFactory) registry);
scanner.addExcludeFilter(typeExcludeFilter);
return scanner;
|
}
private void register(ConfigurationPropertiesBeanRegistrar registrar, String className) throws LinkageError {
try {
register(registrar, ClassUtils.forName(className, null));
}
catch (ClassNotFoundException ex) {
// Ignore
}
}
private void register(ConfigurationPropertiesBeanRegistrar registrar, Class<?> type) {
if (!isComponent(type)) {
registrar.register(type);
}
}
private boolean isComponent(Class<?> type) {
return MergedAnnotations.from(type, SearchStrategy.TYPE_HIERARCHY).isPresent(Component.class);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\ConfigurationPropertiesScanRegistrar.java
| 1
|
请完成以下Java代码
|
public class SysAnnouncementSend implements Serializable {
private static final long serialVersionUID = 1L;
/**id*/
@TableId(type = IdType.ASSIGN_ID)
private java.lang.String id;
/**通告id*/
private java.lang.String anntId;
/**用户id*/
private java.lang.String userId;
/**阅读状态(0未读,1已读)*/
private java.lang.Integer readFlag;
/**阅读时间*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private java.util.Date readTime;
/**创建人*/
|
private java.lang.String createBy;
/**创建时间*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private java.util.Date createTime;
/**更新人*/
private java.lang.String updateBy;
/**更新时间*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private java.util.Date updateTime;
/**
* 是否标星 当值为1是标星消息
*/
private String starFlag;
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysAnnouncementSend.java
| 1
|
请完成以下Java代码
|
private static final class InvoiceCandidateInfo
{
private final int invoiceCandidateId;
private final BigDecimal netAmtToInvoice;
private final int taxId;
public InvoiceCandidateInfo(@NonNull final I_C_Invoice_Candidate ic)
{
this.invoiceCandidateId = ic.getC_Invoice_Candidate_ID();
this.netAmtToInvoice = ic.getNetAmtToInvoice();
final int taxId = ic.getC_Tax_ID();
this.taxId = taxId <= 0 ? -1 : taxId;
}
@Override
public String toString()
{
return invoiceCandidateId + ": " + "@NetAmtToInvoice@: " + netAmtToInvoice + ", @C_Tax_ID@: " + taxId;
}
/**
* Compares this invoice candidate info (old version) object with given info (new version) and logs if there are any differences.
*
* @return <code>true</code> if the objects are equal.
*/
public boolean checkEquals(final InvoiceCandidateInfo infoAfterChange)
{
final InvoiceCandidateInfo infoBeforeChange = this;
Check.assume(infoAfterChange.getC_Invoice_Candidate_ID() == infoBeforeChange.getC_Invoice_Candidate_ID(),
"Old info {} and New info {} shall share the same C_Invoice_Candidate_ID", infoBeforeChange, infoAfterChange);
boolean hasChanges = false;
final TokenizedStringBuilder changesInfo = new TokenizedStringBuilder(", ");
if (infoAfterChange.getLineNetAmt().compareTo(infoBeforeChange.getLineNetAmt()) != 0)
{
changesInfo.append("@LineNetAmt@: " + infoBeforeChange.getLineNetAmt() + "->" + infoAfterChange.getLineNetAmt());
hasChanges = true;
}
if (infoAfterChange.getC_Tax_ID() != infoBeforeChange.getC_Tax_ID())
{
|
changesInfo.append("@C_Tax_ID@: " + infoBeforeChange.getC_Tax_ID() + "->" + infoAfterChange.getC_Tax_ID());
hasChanges = true;
}
if (hasChanges)
{
Loggables.addLog(infoAfterChange.getC_Invoice_Candidate_ID() + ": " + changesInfo);
}
return !hasChanges;
}
public int getC_Invoice_Candidate_ID()
{
return invoiceCandidateId;
}
public BigDecimal getLineNetAmt()
{
return netAmtToInvoice;
}
public int getC_Tax_ID()
{
return taxId;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidatesChangesChecker.java
| 1
|
请完成以下Java代码
|
public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
return new RsaKeyPair(publicKeyString, privateKeyString);
}
/**
* RSA密钥对对象
*/
public static class RsaKeyPair {
private final String publicKey;
|
private final String privateKey;
public RsaKeyPair(String publicKey, String privateKey) {
this.publicKey = publicKey;
this.privateKey = privateKey;
}
public String getPublicKey() {
return publicKey;
}
public String getPrivateKey() {
return privateKey;
}
}
}
|
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\RsaUtils.java
| 1
|
请完成以下Java代码
|
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
| 1
|
请完成以下Java代码
|
protected void registerDefinition(DeploymentEntity deployment, DefinitionEntity definition, Properties properties) {
DeploymentCache deploymentCache = getDeploymentCache();
// Add to cache
addDefinitionToDeploymentCache(deploymentCache, definition);
definitionAddedToDeploymentCache(deployment, definition, properties);
// Add to deployment for further usage
deployment.addDeployedArtifact(definition);
}
/**
* Add a definition to the deployment cache
*
* @param deploymentCache the deployment cache
* @param definition the definition to add
*/
protected abstract void addDefinitionToDeploymentCache(DeploymentCache deploymentCache, DefinitionEntity definition);
/**
* Called after a definition was added to the deployment cache.
*
* @param deployment the deployment of the definition
* @param definition the definition entity
*/
protected void definitionAddedToDeploymentCache(DeploymentEntity deployment, DefinitionEntity definition, Properties properties) {
// do nothing
}
/**
* per default we increment the latest definition version by one - but you
* might want to hook in some own logic here, e.g. to align definition
* versions with deployment / build versions.
*/
protected int getNextVersion(DeploymentEntity deployment, DefinitionEntity newDefinition, DefinitionEntity latestDefinition) {
int result = 1;
if (latestDefinition != null) {
int latestVersion = latestDefinition.getVersion();
result = latestVersion + 1;
}
|
return result;
}
/**
* create an id for the definition. The default is to ask the {@link IdGenerator}
* and add the definition key and version if that does not exceed 64 characters.
* You might want to hook in your own implementation here.
*/
protected String generateDefinitionId(DeploymentEntity deployment, DefinitionEntity newDefinition, DefinitionEntity latestDefinition) {
String nextId = idGenerator.getNextId();
String definitionKey = newDefinition.getKey();
int definitionVersion = newDefinition.getVersion();
String definitionId = definitionKey
+ ":" + definitionVersion
+ ":" + nextId;
// ACT-115: maximum id length is 64 characters
if (definitionId.length() > 64) {
definitionId = nextId;
}
return definitionId;
}
protected ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return Context.getProcessEngineConfiguration();
}
protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected DeploymentCache getDeploymentCache() {
return getProcessEngineConfiguration().getDeploymentCache();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\AbstractDefinitionDeployer.java
| 1
|
请完成以下Java代码
|
public Object getParameterComponent(final int index)
{
return checkbox;
}
@Override
public Object getParameterToComponent(final int index)
{
return null;
}
@Override
public Object getParameterValue(final int index, final boolean returnValueTo)
{
return null;
}
@Override
public String[] getWhereClauses(final List<Object> params)
{
if (!checkbox.isEnabled() || !checkbox.isSelected())
{
return null;
}
if (record2productId.isEmpty())
{
return new String[] { "1=2" };
}
final String productColumnName = org.compiere.model.I_M_Product.Table_Name + "." + org.compiere.model.I_M_Product.COLUMNNAME_M_Product_ID;
final StringBuilder whereClause = new StringBuilder(productColumnName + " IN " + DB.buildSqlList(record2productId.values(), params));
if (gridConvertAfterLoadDelegate != null)
{
final String productComb = gridConvertAfterLoadDelegate.getProductCombinations();
if (productComb != null)
{
whereClause.append(productComb);
}
}
|
//
// 05135: We need just to display rows that have Qtys, but DON'T discard other filtering criterias
// return new String[] { WHERECLAUSE_CLEAR_PREVIOUS, whereClause, WHERECLAUSE_STOP};
return new String[] { whereClause.toString() };
}
@Override
public String getText()
{
return null;
}
@Override
public void prepareEditor(final CEditor editor, final Object value, final int rowIndexModel, final int columnIndexModel)
{
// nothing
}
@Override
public String getProductCombinations()
{
// nothing to do
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\InfoProductQtyController.java
| 1
|
请完成以下Java代码
|
public class QueryVariableValue implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private Object value;
private QueryOperator operator;
private VariableInstanceEntity variableInstanceEntity;
private boolean local;
public QueryVariableValue(String name, Object value, QueryOperator operator, boolean local) {
this.name = name;
this.value = value;
this.operator = operator;
this.local = local;
}
public void initialize(VariableTypes types) {
if (variableInstanceEntity == null) {
VariableType type = types.findVariableType(value);
if (type instanceof ByteArrayType) {
throw new ActivitiIllegalArgumentException("Variables of type ByteArray cannot be used to query");
} else if (type instanceof JPAEntityVariableType && operator != QueryOperator.EQUALS) {
throw new ActivitiIllegalArgumentException(
"JPA entity variables can only be used in 'variableValueEquals'"
);
} else if (type instanceof JPAEntityListVariableType) {
throw new ActivitiIllegalArgumentException(
"Variables containing a list of JPA entities cannot be used to query"
);
} else {
// Type implementation determines which fields are set on the entity
variableInstanceEntity = Context.getCommandContext()
.getVariableInstanceEntityManager()
.create(name, type, value);
}
}
}
public String getName() {
return name;
}
public String getOperator() {
|
if (operator != null) {
return operator.toString();
}
return QueryOperator.EQUALS.toString();
}
public String getTextValue() {
if (variableInstanceEntity != null) {
return variableInstanceEntity.getTextValue();
}
return null;
}
public Long getLongValue() {
if (variableInstanceEntity != null) {
return variableInstanceEntity.getLongValue();
}
return null;
}
public Double getDoubleValue() {
if (variableInstanceEntity != null) {
return variableInstanceEntity.getDoubleValue();
}
return null;
}
public String getTextValue2() {
if (variableInstanceEntity != null) {
return variableInstanceEntity.getTextValue2();
}
return null;
}
public String getType() {
if (variableInstanceEntity != null) {
return variableInstanceEntity.getType().getTypeName();
}
return null;
}
public boolean isLocal() {
return local;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\QueryVariableValue.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Firewall {
/**
* 数据源安全 (开启后,Online报表和图表的数据源为必填)
*/
private Boolean dataSourceSafe = false;
/**
* 是否禁止使用 * 查询所有字段
*/
private Boolean disableSelectAll = false;
/**
* 低代码模式(dev:开发模式,prod:发布模式——关闭所有在线开发配置能力)
*/
private String lowCodeMode;
/**
* 是否允许同一账号多地同时登录 (为 true 时允许一起登录, 为 false 时新登录挤掉旧登录)
*/
private Boolean isConcurrent = true;
/**
* 是否开启默认密码登录提醒(true 登录后提示必须修改默认密码)
*/
private Boolean enableDefaultPwdCheck = false;
/**
* 是否开启登录验证码校验(true 开启;false 关闭并跳过验证码逻辑)
*/
private Boolean enableLoginCaptcha = true;
// /**
// * 表字典安全模式(white:白名单——配置了白名单的表才能通过表字典方式访问,black:黑名单——配置了黑名单的表不允许表字典方式访问)
// */
// private String tableDictMode;
public Boolean getEnableLoginCaptcha() {
return enableLoginCaptcha;
}
public void setEnableLoginCaptcha(Boolean enableLoginCaptcha) {
this.enableLoginCaptcha = enableLoginCaptcha;
}
public Boolean getEnableDefaultPwdCheck() {
return enableDefaultPwdCheck;
}
public void setEnableDefaultPwdCheck(Boolean enableDefaultPwdCheck) {
this.enableDefaultPwdCheck = enableDefaultPwdCheck;
|
}
public Boolean getDataSourceSafe() {
return dataSourceSafe;
}
public void setDataSourceSafe(Boolean dataSourceSafe) {
this.dataSourceSafe = dataSourceSafe;
}
public String getLowCodeMode() {
return lowCodeMode;
}
public void setLowCodeMode(String lowCodeMode) {
this.lowCodeMode = lowCodeMode;
}
public Boolean getDisableSelectAll() {
return disableSelectAll;
}
public void setDisableSelectAll(Boolean disableSelectAll) {
this.disableSelectAll = disableSelectAll;
}
public Boolean getIsConcurrent() {
return isConcurrent;
}
public void setIsConcurrent(Boolean isConcurrent) {
this.isConcurrent = isConcurrent;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\vo\Firewall.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Application {
private DataSource inventoryDataSource;
private DataSource orderDataSource;
public Application(DataSource inventoryDataSource, DataSource orderDataSource) {
this.inventoryDataSource = inventoryDataSource;
this.orderDataSource = orderDataSource;
}
@Transactional(rollbackFor = Exception.class)
public void placeOrder(String productId, int amount) throws Exception {
String orderId = UUID.randomUUID()
.toString();
Connection inventoryConnection = inventoryDataSource.getConnection();
|
Connection orderConnection = orderDataSource.getConnection();
Statement s1 = inventoryConnection.createStatement();
String q1 = "update Inventory set balance = balance - " + amount + " where productId ='" + productId + "'";
s1.executeUpdate(q1);
s1.close();
Statement s2 = orderConnection.createStatement();
String q2 = "insert into Orders values ( '" + orderId + "', '" + productId + "', " + amount + " )";
s2.executeUpdate(q2);
s2.close();
inventoryConnection.close();
orderConnection.close();
}
}
|
repos\tutorials-master\persistence-modules\atomikos\src\main\java\com\baeldung\atomikos\spring\Application.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ResourceId implements RepoIdAware
{
public static final ResourceId NO_RESOURCE = new ResourceId(540011);
@JsonCreator
public static ResourceId ofRepoId(final int repoId)
{
if (repoId == NO_RESOURCE.repoId)
{
return NO_RESOURCE;
}
else
{
return new ResourceId(repoId);
}
}
@Nullable
public static ResourceId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? ofRepoId(repoId) : null;
}
public static Optional<ResourceId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static ImmutableSet<ResourceId> ofRepoIds(@NonNull final Collection<Integer> repoIds)
{
if (repoIds.isEmpty())
{
return ImmutableSet.of();
}
|
return repoIds.stream().map(ResourceId::ofRepoIdOrNull).filter(Objects::nonNull).collect(ImmutableSet.toImmutableSet());
}
public static int toRepoId(@Nullable final ResourceId ResourceId)
{
return ResourceId != null ? ResourceId.getRepoId() : -1;
}
public static boolean equals(@Nullable final ResourceId o1, @Nullable final ResourceId o2)
{
return Objects.equals(o1, o2);
}
int repoId;
private ResourceId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "S_Resource_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public boolean isNoResource() {return this.repoId == NO_RESOURCE.repoId;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\product\ResourceId.java
| 2
|
请完成以下Java代码
|
public void validate(Source xmlToValidate) throws SAXException, IOException {
Validator validator = getEmbeddedLwM2mSchema().newValidator();
validator.validate(xmlToValidate);
}
/**
* Get the Embedded the LWM2M.xsd Schema.
*
* @throws SAXException see {@link SchemaFactory#newSchema(Source)}
*/
protected Schema getEmbeddedLwM2mSchema() throws SAXException {
InputStream inputStream = DDFFileValidator.class.getResourceAsStream(schema);
Source source = new StreamSource(inputStream);
SchemaFactory schemaFactory = createSchemaFactory();
return schemaFactory.newSchema(source);
}
protected SchemaFactory createSchemaFactory() {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
try {
// Create Safe SchemaFactory (not vulnerable to XXE Attacks)
// --------------------------------------------------------
|
// There is several recommendation from different source we try to apply all, even if some are maybe
// redundant.
// from :
// https://semgrep.dev/docs/cheat-sheets/java-xxe/
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// from :
// https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#schemafactory
// factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
// factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
} catch (SAXNotRecognizedException | SAXNotSupportedException e) {
throw new IllegalStateException("Unable to create SchemaFactory", e);
}
return factory;
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\util\TbDefaultDDFFileValidator.java
| 1
|
请完成以下Java代码
|
protected AstParameters params() throws Scanner.ScanException, ParseException {
consumeToken(Scanner.Symbol.LPAREN);
List<AstNode> l = Collections.emptyList();
AstNode v = expr(false);
if (v != null) {
l = new ArrayList<AstNode>();
l.add(v);
while (token.getSymbol() == Scanner.Symbol.COMMA) {
consumeToken();
l.add(expr(true));
}
}
consumeToken(Scanner.Symbol.RPAREN);
return new AstParameters(l);
}
/**
* literal := <TRUE> | <FALSE> | <STRING> | <INTEGER> | <FLOAT> | <NULL>
*/
protected AstNode literal() throws Scanner.ScanException, ParseException {
AstNode v = null;
switch (token.getSymbol()) {
case TRUE:
v = new AstBoolean(true);
consumeToken();
break;
case FALSE:
v = new AstBoolean(false);
consumeToken();
break;
case STRING:
v = new AstString(token.getImage());
consumeToken();
break;
case INTEGER:
v = new AstNumber(parseInteger(token.getImage()));
consumeToken();
break;
case FLOAT:
v = new AstNumber(parseFloat(token.getImage()));
consumeToken();
break;
case NULL:
v = new AstNull();
consumeToken();
break;
case EXTENSION:
|
if (getExtensionHandler(token).getExtensionPoint() == ExtensionPoint.LITERAL) {
v = getExtensionHandler(consumeToken()).createAstNode();
break;
}
}
return v;
}
protected final AstFunction function(String name, AstParameters params) {
if (functions.isEmpty()) {
functions = new ArrayList<FunctionNode>(4);
}
AstFunction function = createAstFunction(name, functions.size(), params);
functions.add(function);
return function;
}
protected final AstIdentifier identifier(String name) {
if (identifiers.isEmpty()) {
identifiers = new ArrayList<IdentifierNode>(4);
}
AstIdentifier identifier = createAstIdentifier(name, identifiers.size());
identifiers.add(identifier);
return identifier;
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\Parser.java
| 1
|
请完成以下Java代码
|
public org.compiere.model.I_S_Resource getS_Resource()
{
return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setS_Resource(final org.compiere.model.I_S_Resource S_Resource)
{
set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource);
}
@Override
public void setS_Resource_ID (final int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, S_Resource_ID);
}
@Override
public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
@Override
public org.compiere.model.I_S_Resource getWorkStation()
{
return get_ValueAsPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class);
}
@Override
|
public void setWorkStation(final org.compiere.model.I_S_Resource WorkStation)
{
set_ValueFromPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class, WorkStation);
}
@Override
public void setWorkStation_ID (final int WorkStation_ID)
{
if (WorkStation_ID < 1)
set_Value (COLUMNNAME_WorkStation_ID, null);
else
set_Value (COLUMNNAME_WorkStation_ID, WorkStation_ID);
}
@Override
public int getWorkStation_ID()
{
return get_ValueAsInt(COLUMNNAME_WorkStation_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Candidate.java
| 1
|
请完成以下Spring Boot application配置
|
logging.level.com.gf=trace
#logging.path 和 logging.path 是冲突设置 ,两者都设置时只有 logging.path 起作用
#指定文件名,就在项目下生产springboot.log日志
#logging.file=springboot.log
# 在当前磁盘路径下创建spring文件夹和里面的log文件夹;使用spring.log 作为默认文件
logging.path=/Users/huanchu/Documents/spring/log
# 指定控制台输出的日志格式
logging.pattern.console=%d{yyyy-MM-dd} [%thread
|
] %-5level %logger{50} -%msg%n
# 指定文件中日志输出的格式
logging.pattern.file=%d{yyyy-MM-dd} === [%thread] === %-5level === %logger{50} === %msg%n
|
repos\SpringBootLearning-master (1)\springboot-logging\src\main\resources\application.properties
| 2
|
请在Spring Boot框架中完成以下Java代码
|
@Override public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
Request compressedRequest = originalRequest.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method(), forceContentLength(gzip(originalRequest.body())))
.build();
return chain.proceed(compressedRequest);
}
private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
final Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
return new RequestBody() {
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() {
return buffer.size();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.write(buffer.snapshot());
}
};
}
|
private RequestBody gzip(final RequestBody body) {
return new RequestBody() {
@Override public MediaType contentType() {
return body.contentType();
}
@Override public long contentLength() {
return -1; // We don't know the compressed length in advance!
}
@Override public void writeTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\GzipRequestInterceptor.java
| 2
|
请完成以下Java代码
|
public void updateDefaultValue(@NonNull final IProcessDefaultParameter parameter)
{
for (final IProcessDefaultParametersProvider provider : defaultParametersProviders)
{
//
// Ask provider for default value
Object value = null;
try
{
value = provider.getParameterDefaultValue(parameter);
}
catch (final Exception e)
{
// ignore the error, but log it
final String parameterName = parameter.getColumnName();
logger.error("Failed retrieving the parameters default value from defaults provider: ParameterName={}, Provider={}", parameterName, provider, e);
continue;
}
// If the provider cannot provide a default value, we are skipping it and we will ask the next provider if any.
if (value == IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE)
{
continue;
}
// We got a default value from provider.
// Set it and stop here.
defaultValueConsumer.accept(parameter, Null.unbox(value));
break;
}
}
/**
* Asks this updater to
* <ul>
* <li>iterate given <code>parameterObjs</code> collection
* <li>convert the parameter object to {@link IProcessDefaultParameter} using given <code>processDefaultParameterConverter</code>
* <li>fetch the default value for each parameter
|
* <li>forward the default value to default value consumer configured by {@link #onDefaultValue(BiConsumer)}.
* </ul>
*
* @param parameterObjs
* @param processDefaultParameterConverter
*/
public <T> void updateDefaultValue(final Collection<T> parameterObjs, final Function<T, IProcessDefaultParameter> processDefaultParameterConverter)
{
if(defaultParametersProviders.isEmpty())
{
return;
}
if (parameterObjs == null || parameterObjs.isEmpty())
{
return;
}
parameterObjs.stream() // stream parameter objects
.map(processDefaultParameterConverter) // convert parameter object to IProcessDefaultParameter
.forEach(this::updateDefaultValue) // update the default value if available
;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessDefaultParametersUpdater.java
| 1
|
请完成以下Java代码
|
public java.lang.String getPassword ()
{
return (java.lang.String)get_Value(COLUMNNAME_Password);
}
/** Set PIN.
@param PIN
Personal Identification Number
*/
@Override
public void setPIN (java.lang.String PIN)
{
set_Value (COLUMNNAME_PIN, PIN);
}
/** Get PIN.
@return Personal Identification Number
*/
@Override
public java.lang.String getPIN ()
{
return (java.lang.String)get_Value(COLUMNNAME_PIN);
}
/** Set Proxy address.
@param ProxyAddress
Address of your proxy server
*/
@Override
public void setProxyAddress (java.lang.String ProxyAddress)
{
set_Value (COLUMNNAME_ProxyAddress, ProxyAddress);
}
/** Get Proxy address.
@return Address of your proxy server
*/
@Override
public java.lang.String getProxyAddress ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProxyAddress);
}
/** Set Proxy logon.
@param ProxyLogon
Logon of your proxy server
*/
@Override
public void setProxyLogon (java.lang.String ProxyLogon)
{
set_Value (COLUMNNAME_ProxyLogon, ProxyLogon);
}
/** Get Proxy logon.
@return Logon of your proxy server
*/
@Override
public java.lang.String getProxyLogon ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProxyLogon);
}
/** Set Proxy-Passwort.
@param ProxyPassword
Password of your proxy server
*/
@Override
public void setProxyPassword (java.lang.String ProxyPassword)
{
set_Value (COLUMNNAME_ProxyPassword, ProxyPassword);
}
/** Get Proxy-Passwort.
@return Password of your proxy server
*/
@Override
|
public java.lang.String getProxyPassword ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProxyPassword);
}
/** Set Proxy port.
@param ProxyPort
Port of your proxy server
*/
@Override
public void setProxyPort (int ProxyPort)
{
set_Value (COLUMNNAME_ProxyPort, Integer.valueOf(ProxyPort));
}
/** Get Proxy port.
@return Port of your proxy server
*/
@Override
public int getProxyPort ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ProxyPort);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Statement Loader Class.
@param StmtLoaderClass
Class name of the bank statement loader
*/
@Override
public void setStmtLoaderClass (java.lang.String StmtLoaderClass)
{
set_Value (COLUMNNAME_StmtLoaderClass, StmtLoaderClass);
}
/** Get Statement Loader Class.
@return Class name of the bank statement loader
*/
@Override
public java.lang.String getStmtLoaderClass ()
{
return (java.lang.String)get_Value(COLUMNNAME_StmtLoaderClass);
}
/** Set User ID.
@param UserID
User ID or account number
*/
@Override
public void setUserID (java.lang.String UserID)
{
set_Value (COLUMNNAME_UserID, UserID);
}
/** Get User ID.
@return User ID or account number
*/
@Override
public java.lang.String getUserID ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementLoader.java
| 1
|
请完成以下Java代码
|
public void setK_Topic_ID (int K_Topic_ID)
{
if (K_Topic_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Topic_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Topic_ID, Integer.valueOf(K_Topic_ID));
}
/** Get Knowledge Topic.
@return Knowledge Topic
*/
public int getK_Topic_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Topic_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Rating.
@param Rating
Classification or Importance
*/
public void setRating (int Rating)
{
set_Value (COLUMNNAME_Rating, Integer.valueOf(Rating));
}
/** Get Rating.
@return Classification or Importance
*/
public int getRating ()
{
|
Integer ii = (Integer)get_Value(COLUMNNAME_Rating);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Entry.java
| 1
|
请完成以下Java代码
|
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public Pet status(StatusEnum status) {
this.status = status;
return this;
}
/**
* pet status in the store
* @return status
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "pet status in the store")
@JsonProperty(JSON_PROPERTY_STATUS)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public StatusEnum getStatus() {
return status;
}
public void setStatus(StatusEnum status) {
this.status = status;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pet pet = (Pet) o;
return Objects.equals(this.id, pet.id) &&
Objects.equals(this.category, pet.category) &&
Objects.equals(this.name, pet.name) &&
Objects.equals(this.photoUrls, pet.photoUrls) &&
Objects.equals(this.tags, pet.tags) &&
Objects.equals(this.status, pet.status);
}
@Override
public int hashCode() {
return Objects.hash(id, category, name, photoUrls, tags, status);
}
|
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Pet {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" category: ").append(toIndentedString(category)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n");
sb.append(" tags: ").append(toIndentedString(tags)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\Pet.java
| 1
|
请完成以下Java代码
|
public HistoricActivityInstanceEntity create() {
return new HistoricActivityInstanceEntityImpl();
}
@Override
public List<HistoricActivityInstanceEntity> findUnfinishedHistoricActivityInstancesByExecutionAndActivityId(
final String executionId,
final String activityId
) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("executionId", executionId);
params.put("activityId", activityId);
return getList(
"selectUnfinishedHistoricActivityInstanceExecutionIdAndActivityId",
params,
unfinishedHistoricActivityInstanceMatcher,
true
);
}
@Override
public List<HistoricActivityInstanceEntity> findUnfinishedHistoricActivityInstancesByProcessInstanceId(
final String processInstanceId
) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("processInstanceId", processInstanceId);
return getList(
"selectUnfinishedHistoricActivityInstanceExecutionIdAndActivityId",
params,
unfinishedHistoricActivityInstanceMatcher,
true
);
}
@Override
public void deleteHistoricActivityInstancesByProcessInstanceId(String historicProcessInstanceId) {
getDbSqlSession().delete(
"deleteHistoricActivityInstancesByProcessInstanceId",
historicProcessInstanceId,
HistoricActivityInstanceEntityImpl.class
);
}
@Override
public long findHistoricActivityInstanceCountByQueryCriteria(
HistoricActivityInstanceQueryImpl historicActivityInstanceQuery
) {
return (Long) getDbSqlSession().selectOne(
"selectHistoricActivityInstanceCountByQueryCriteria",
historicActivityInstanceQuery
);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricActivityInstance> findHistoricActivityInstancesByQueryCriteria(
HistoricActivityInstanceQueryImpl historicActivityInstanceQuery,
Page page
|
) {
return getDbSqlSession().selectList(
"selectHistoricActivityInstancesByQueryCriteria",
historicActivityInstanceQuery,
page
);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricActivityInstance> findHistoricActivityInstancesByNativeQuery(
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return getDbSqlSession().selectListWithRawParameter(
"selectHistoricActivityInstanceByNativeQuery",
parameterMap,
firstResult,
maxResults
);
}
@Override
public long findHistoricActivityInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectHistoricActivityInstanceCountByNativeQuery", parameterMap);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisHistoricActivityInstanceDataManager.java
| 1
|
请完成以下Java代码
|
public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricPlanItemInstance with id: ")
.append(id);
if (getName() != null) {
sb.append(", name: ").append(getName());
|
}
sb.append(", definitionId: ")
.append(planItemDefinitionId)
.append(", state: ")
.append(state);
sb
.append(", caseInstanceId: ")
.append(caseInstanceId)
.append(", caseDefinitionId: ")
.append(caseDefinitionId);
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricPlanItemInstanceEntityImpl.java
| 1
|
请完成以下Java代码
|
public class CoordinateKey {
private final int x;
private final int y;
private final int hashCode;
public CoordinateKey(int x, int y) {
this.x = x;
this.y = y;
this.hashCode = Objects.hash(x, y);
}
public int getX() {
return x;
}
public int getY() {
|
return y;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
CoordinateKey that = (CoordinateKey) o;
return x == that.x && y == that.y;
}
@Override
public int hashCode() {
return this.hashCode;
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-maps-4\src\main\java\com\baeldung\maps\CoordinateKey.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class EntityManagerFactoryConfig {
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder, DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages(packagesToScan())
.persistenceUnit("ds-pu")
.properties(hibernateProperties())
.build();
}
@Bean
@Primary
public PlatformTransactionManager transactionManager(
@Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
protected String[] packagesToScan() {
|
return new String[]{
"com.bookstore.*"
};
}
protected Map<String, Object> hibernateProperties() {
return new HashMap<String, Object>() {
{
put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
put("hibernate.hbm2ddl.auto", "create");
put("hibernate.integrator_provider",
(IntegratorProvider) () -> Collections.singletonList(
DatabaseTableMetadataExtractor.EXTRACTOR
));
}
};
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootTablesMetadata\src\main\java\com\bookstore\config\EntityManagerFactoryConfig.java
| 2
|
请完成以下Java代码
|
protected Optional<Set<IExternalSystemChildConfigId>> getAdditionalExternalSystemConfigIds(@NonNull final BPartnerId bPartnerId)
{
final I_C_BPartner bPartner = bPartnerDAO.getById(bPartnerId);
final boolean isVendor = bPartner.isVendor();
final boolean isCustomer = bPartner.isCustomer();
if (!isCustomer && !isVendor)
{
return Optional.empty();
}
final ImmutableList<ExternalSystemParentConfig> grsParentConfigs = externalSystemConfigRepo.getActiveByType(ExternalSystemType.GRSSignum);
return Optional.of(grsParentConfigs.stream()
.filter(ExternalSystemParentConfig::isActive)
.map(ExternalSystemParentConfig::getChildConfig)
.map(ExternalSystemGRSSignumConfig::cast)
.filter(grsConfig -> (grsConfig.isAutoSendVendors() && isVendor) || (grsConfig.isAutoSendCustomers() && isCustomer))
.map(IExternalSystemChildConfig::getId)
.collect(ImmutableSet.toImmutableSet()));
}
@NonNull
private static Optional<String> getJsonExportDirectorySettings(@NonNull final ExternalSystemGRSSignumConfig grsSignumConfig)
{
if (!grsSignumConfig.isCreateBPartnerFolders())
{
return Optional.empty();
}
if (Check.isBlank(grsSignumConfig.getBPartnerExportDirectories()) || Check.isBlank(grsSignumConfig.getBasePathForExportDirectories()))
{
throw new AdempiereException("BPartnerExportDirectories and BasePathForExportDirectories must be set!")
.appendParametersToMessage()
|
.setParameter("ExternalSystem_Config_GRSSignum_ID", grsSignumConfig.getId());
}
final List<String> directories = Arrays
.stream(grsSignumConfig.getBPartnerExportDirectories().split(","))
.filter(Check::isNotBlank)
.collect(ImmutableList.toImmutableList());
final JsonExportDirectorySettings exportDirectorySettings = JsonExportDirectorySettings.builder()
.basePath(grsSignumConfig.getBasePathForExportDirectories())
.directories(directories)
.build();
try
{
final String serializedExportDirectorySettings = JsonObjectMapperHolder.sharedJsonObjectMapper()
.writeValueAsString(exportDirectorySettings);
return Optional.of(serializedExportDirectorySettings);
}
catch (final JsonProcessingException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\ExportBPartnerToGRSService.java
| 1
|
请完成以下Java代码
|
protected I_AD_Migration createMigration(final Properties ctx, final String entityType)
{
// this record shall be created out of transaction since it will accessible in more then one transaction
final String trxName = null;
final I_AD_Migration migration = InterfaceWrapperHelper.create(ctx, I_AD_Migration.class, trxName);
migration.setEntityType(entityType);
Services.get(IMigrationBL.class).setSeqNo(migration);
setName(migration);
InterfaceWrapperHelper.save(migration);
return migration;
}
protected void setName(final I_AD_Migration migration)
{
final String name = Services.get(ISysConfigBL.class).getValue("DICTIONARY_ID_COMMENTS");
migration.setName(name);
}
protected String getDefaultEntityType()
{
|
boolean dict = Ini.isPropertyBool(Ini.P_ADEMPIERESYS);
return dict ? "D" : "U";
}
protected IMigrationLoggerContext getSessionMigrationLoggerContext(final MFSession session)
{
final String key = getClass().getCanonicalName();
IMigrationLoggerContext mctx = session.getTransientProperty(key);
if (mctx == null)
{
mctx = new SessionMigrationLoggerContext();
session.putTransientProperty(key, mctx);
}
return mctx;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\impl\MigrationLogger.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Gridfs getGridfs() {
return this.gridfs;
}
public Representation getRepresentation() {
return this.representation;
}
public static class Gridfs {
/**
* GridFS database name.
*/
private @Nullable String database;
/**
* GridFS bucket name.
*/
private @Nullable String bucket;
public @Nullable String getDatabase() {
return this.database;
}
public void setDatabase(@Nullable String database) {
this.database = database;
}
public @Nullable String getBucket() {
return this.bucket;
}
|
public void setBucket(@Nullable String bucket) {
this.bucket = bucket;
}
}
public static class Representation {
/**
* Representation to use when converting a BigDecimal.
*/
private @Nullable BigDecimalRepresentation bigDecimal = BigDecimalRepresentation.UNSPECIFIED;
public @Nullable BigDecimalRepresentation getBigDecimal() {
return this.bigDecimal;
}
public void setBigDecimal(@Nullable BigDecimalRepresentation bigDecimal) {
this.bigDecimal = bigDecimal;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-data-mongodb\src\main\java\org\springframework\boot\data\mongodb\autoconfigure\DataMongoProperties.java
| 2
|
请完成以下Java代码
|
public void addEnforcer(@NonNull final IPriceLimitRule enforcer)
{
enforcers.addIfAbsent(enforcer);
}
@Override
public PriceLimitRuleResult compute(@NonNull final PriceLimitRuleContext context)
{
final BigDecimal priceActual = context.getPriceActual();
//
// Check each enforcer
PriceLimitRuleResult applicableResultWithMaxPriceLimit = null;
final ArrayList<PriceLimitRuleResult> notApplicableResults = new ArrayList<>();
for (final IPriceLimitRule enforcer : enforcers)
{
final PriceLimitRuleResult result = enforcer.compute(context);
final BooleanWithReason applicable = result.checkApplicableAndBelowPriceLimit(priceActual);
if (applicable.isTrue())
{
if (applicableResultWithMaxPriceLimit == null)
{
applicableResultWithMaxPriceLimit = result;
}
else if (applicableResultWithMaxPriceLimit.getPriceLimit().compareTo(result.getPriceLimit()) < 0)
{
applicableResultWithMaxPriceLimit = result;
}
else
{
// keep current applicableResultWithMaxPriceLimit
}
}
else
{
notApplicableResults.add(result);
}
}
//
// Case: we have a applicable limit:
if (applicableResultWithMaxPriceLimit != null)
{
return applicableResultWithMaxPriceLimit;
}
//
// Case: we don't have an applicable limit but we have a limit from price list
else if (context.getPriceLimit().signum() != 0)
{
return PriceLimitRuleResult.priceLimit(context.getPriceLimit(), "pricing PriceLimit (context/default)");
}
//
// Case: found nothing applicable
|
else
{
if (notApplicableResults.isEmpty())
{
return PriceLimitRuleResult.notApplicable("default PriceLimit=0 is not eligible");
}
else
{
return mergeNotApplicableResults(notApplicableResults);
}
}
}
private static PriceLimitRuleResult mergeNotApplicableResults(final List<PriceLimitRuleResult> notApplicableResults)
{
if (notApplicableResults.size() == 1)
{
return notApplicableResults.get(0);
}
final TranslatableStringBuilder builder = TranslatableStrings.builder();
for (final PriceLimitRuleResult notApplicableResult : notApplicableResults)
{
if (!builder.isEmpty())
{
builder.append("; ");
}
builder.append(notApplicableResult.getNotApplicableReason());
}
return PriceLimitRuleResult.notApplicable(builder.build());
}
@Override
public Set<CountryId> getPriceCountryIds()
{
return enforcers.stream()
.flatMap(enforcer -> enforcer.getPriceCountryIds().stream())
.collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\limit\CompositePriceLimitRule.java
| 1
|
请完成以下Java代码
|
public Object circuitBreakerAround(final ProceedingJoinPoint aJoinPoint) {
return new RemoteServiceCommand(config, aJoinPoint).execute();
}
@PostConstruct
private void setup() {
this.config = HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey));
this.config = config.andCommandKey(HystrixCommandKey.Factory.asKey(key));
this.commandProperties = HystrixCommandProperties.Setter();
this.commandProperties.withExecutionTimeoutInMilliseconds(executionTimeout);
this.commandProperties.withCircuitBreakerSleepWindowInMilliseconds(sleepWindow);
this.threadPoolProperties = HystrixThreadPoolProperties.Setter();
this.threadPoolProperties.withMaxQueueSize(maxThreadCount).withCoreSize(coreThreadCount).withMaxQueueSize(queueCount);
this.config.andCommandPropertiesDefaults(commandProperties);
this.config.andThreadPoolPropertiesDefaults(threadPoolProperties);
}
private static class RemoteServiceCommand extends HystrixCommand<String> {
|
private final ProceedingJoinPoint joinPoint;
RemoteServiceCommand(final Setter config, final ProceedingJoinPoint joinPoint) {
super(config);
this.joinPoint = joinPoint;
}
@Override
protected String run() throws Exception {
try {
return (String) joinPoint.proceed();
} catch (final Throwable th) {
throw new Exception(th);
}
}
}
}
|
repos\tutorials-master\hystrix\src\main\java\com\baeldung\hystrix\HystrixAspect.java
| 1
|
请完成以下Java代码
|
public void setOrg_ID (int Org_ID)
{
if (Org_ID < 1)
set_Value (COLUMNNAME_Org_ID, null);
else
set_Value (COLUMNNAME_Org_ID, Integer.valueOf(Org_ID));
}
/** Get Organization.
@return Organizational entity within client
*/
public int getOrg_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Org_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_ReportLine getPA_ReportLine() throws RuntimeException
{
return (I_PA_ReportLine)MTable.get(getCtx(), I_PA_ReportLine.Table_Name)
.getPO(getPA_ReportLine_ID(), get_TrxName()); }
/** Set Report Line.
@param PA_ReportLine_ID Report Line */
public void setPA_ReportLine_ID (int PA_ReportLine_ID)
{
if (PA_ReportLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, Integer.valueOf(PA_ReportLine_ID));
}
/** Get Report Line.
@return Report Line */
public int getPA_ReportLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Report Source.
@param PA_ReportSource_ID
Restriction of what will be shown in Report Line
*/
public void setPA_ReportSource_ID (int PA_ReportSource_ID)
{
if (PA_ReportSource_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_ReportSource_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_ReportSource_ID, Integer.valueOf(PA_ReportSource_ID));
}
/** Get Report Source.
@return Restriction of what will be shown in Report Line
*/
public int getPA_ReportSource_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportSource_ID);
if (ii == null)
return 0;
return ii.intValue();
}
|
/** Set User Element 1.
@param UserElement1_ID
User defined accounting Element
*/
public void setUserElement1_ID (int UserElement1_ID)
{
if (UserElement1_ID < 1)
set_Value (COLUMNNAME_UserElement1_ID, null);
else
set_Value (COLUMNNAME_UserElement1_ID, Integer.valueOf(UserElement1_ID));
}
/** Get User Element 1.
@return User defined accounting Element
*/
public int getUserElement1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 2.
@param UserElement2_ID
User defined accounting Element
*/
public void setUserElement2_ID (int UserElement2_ID)
{
if (UserElement2_ID < 1)
set_Value (COLUMNNAME_UserElement2_ID, null);
else
set_Value (COLUMNNAME_UserElement2_ID, Integer.valueOf(UserElement2_ID));
}
/** Get User Element 2.
@return User defined accounting Element
*/
public int getUserElement2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement2_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_PA_ReportSource.java
| 1
|
请完成以下Java代码
|
public String getEngineVersion() {
return engineVersion;
}
@Override
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
@Override
public String getDerivedFrom() {
return derivedFrom;
}
@Override
public void setDerivedFrom(String derivedFrom) {
this.derivedFrom = derivedFrom;
}
@Override
public String getDerivedFromRoot() {
return derivedFromRoot;
}
@Override
public void setDerivedFromRoot(String derivedFromRoot) {
|
this.derivedFromRoot = derivedFromRoot;
}
@Override
public String getParentDeploymentId() {
return parentDeploymentId;
}
@Override
public void setParentDeploymentId(String parentDeploymentId) {
this.parentDeploymentId = parentDeploymentId;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "DeploymentEntity[id=" + id + ", name=" + name + "]";
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\DeploymentEntityImpl.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuilder sb = new StringBuilder();
for (Sentence sentence : sentenceList)
{
sb.append(sentence);
sb.append(' ');
}
if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
public static Document create(File file)
{
IOUtil.LineIterator lineIterator = new IOUtil.LineIterator(file.getAbsolutePath());
|
List<Sentence> sentenceList = new LinkedList<Sentence>();
for (String line : lineIterator)
{
line = line.trim();
if (line.isEmpty()) continue;
Sentence sentence = Sentence.create(line);
if (sentence == null)
{
Predefine.logger.warning("使用 " + line + " 创建句子失败");
return null;
}
sentenceList.add(sentence);
}
return new Document(sentenceList);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\document\Document.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 5002
spring:
data:
redis:
##redis 单机环境配置
host: localhost
port: 6379
database: 0
password:
ssl:
enabled: false
application:
name: seata-account
cloud:
nacos:
config:
import-check:
enabled: false
main:
allow-bean-definition-overriding: true
autoconfigure:
exclude: com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration
datasource:
url: jdbc:mysql://127.0.0.1:3306/jeecg_account?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
sql:
init:
schema-locations
|
: classpath:sql/schema-account.sql
seata:
enable-auto-data-source-proxy: false
service:
grouplist:
default: 127.0.0.1:8091
vgroup-mapping:
springboot-seata-group: default
# seata 事务组编号 用于TC集群名
tx-service-group: springboot-seata-group
# 无用配置,为了避免扫码全代码导致启动慢
minidao:
base-package: org.jeecg.modules.jmreport.*
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-test\jeecg-cloud-test-seata\jeecg-cloud-test-seata-account\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public void setIsApproved (boolean IsApproved)
{
set_Value (COLUMNNAME_IsApproved, Boolean.valueOf(IsApproved));
}
/** Get Approved.
@return Indicates if this document requires approval
*/
public boolean isApproved ()
{
Object oo = get_Value(COLUMNNAME_IsApproved);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Change Notice.
@param M_ChangeNotice_ID
Bill of Materials (Engineering) Change Notice (Version)
*/
public void setM_ChangeNotice_ID (int M_ChangeNotice_ID)
{
if (M_ChangeNotice_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ChangeNotice_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ChangeNotice_ID, Integer.valueOf(M_ChangeNotice_ID));
}
/** Get Change Notice.
@return Bill of Materials (Engineering) Change Notice (Version)
*/
public int getM_ChangeNotice_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ChangeNotice_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
|
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ChangeNotice.java
| 1
|
请完成以下Java代码
|
public void setDateFrom (java.sql.Timestamp DateFrom)
{
set_Value (COLUMNNAME_DateFrom, DateFrom);
}
/** Get Datum von.
@return Startdatum eines Abschnittes
*/
@Override
public java.sql.Timestamp getDateFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DateFrom);
}
/** Set Freigegeben.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
|
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Freigegeben.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_CreditLimit.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setRoutesMap(LinkedHashMap<String, RouteProperties> routesMap) {
this.routesMap = routesMap;
}
public List<MediaType> getStreamingMediaTypes() {
return streamingMediaTypes;
}
public void setStreamingMediaTypes(List<MediaType> streamingMediaTypes) {
this.streamingMediaTypes = streamingMediaTypes;
}
public boolean isUseFrameworkRetryFilter() {
return useFrameworkRetryFilter;
}
public void setUseFrameworkRetryFilter(boolean useFrameworkRetryFilter) {
this.useFrameworkRetryFilter = useFrameworkRetryFilter;
}
public int getStreamingBufferSize() {
return streamingBufferSize;
}
public void setStreamingBufferSize(int streamingBufferSize) {
this.streamingBufferSize = streamingBufferSize;
}
|
public @Nullable String getTrustedProxies() {
return trustedProxies;
}
public void setTrustedProxies(String trustedProxies) {
this.trustedProxies = trustedProxies;
}
@Override
public String toString() {
return new ToStringCreator(this).append("routes", routes)
.append("routesMap", routesMap)
.append("streamingMediaTypes", streamingMediaTypes)
.append("streamingBufferSize", streamingBufferSize)
.append("trustedProxies", trustedProxies)
.toString();
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\GatewayMvcProperties.java
| 2
|
请完成以下Java代码
|
public void start() {
synchronized (lifeCycleMonitor) {
if (!isRunning()) {
enginesBuild.forEach(name -> {
ProcessEngine processEngine = ProcessEngines.getProcessEngine(name);
processEngine.startExecutors();
autoDeployResources(processEngine);
});
running = true;
}
}
}
@Override
public void stop() {
|
synchronized (lifeCycleMonitor) {
running = false;
}
}
@Override
public boolean isRunning() {
return running;
}
@Override
public int getPhase() {
return SpringEngineConfiguration.super.getPhase() + SpringEngineConfiguration.PHASE_DELTA * 2;
}
}
|
repos\flowable-engine-main\modules\flowable-spring\src\main\java\org\flowable\spring\SpringProcessEngineConfiguration.java
| 1
|
请完成以下Java代码
|
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** 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());
}
/** POSKeyLayoutType AD_Reference_ID=53351 */
public static final int POSKEYLAYOUTTYPE_AD_Reference_ID=53351;
/** Keyboard = K */
|
public static final String POSKEYLAYOUTTYPE_Keyboard = "K";
/** Numberpad = N */
public static final String POSKEYLAYOUTTYPE_Numberpad = "N";
/** Product = P */
public static final String POSKEYLAYOUTTYPE_Product = "P";
/** Set POS Key Layout Type.
@param POSKeyLayoutType
The type of Key Layout
*/
public void setPOSKeyLayoutType (String POSKeyLayoutType)
{
set_Value (COLUMNNAME_POSKeyLayoutType, POSKeyLayoutType);
}
/** Get POS Key Layout Type.
@return The type of Key Layout
*/
public String getPOSKeyLayoutType ()
{
return (String)get_Value(COLUMNNAME_POSKeyLayoutType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_POSKeyLayout.java
| 1
|
请完成以下Java代码
|
public void execute(final ActivityExecution execution) throws Exception {
this.executeWithErrorPropagation(execution, new Callable<Void>() {
@Override
public Void call() throws Exception {
getActivityBehaviorInstance(execution).execute(execution);
return null;
}
});
}
// Signallable activity behavior
@Override
public void signal(final ActivityExecution execution, final String signalName, final Object signalData) throws Exception {
ProcessApplicationReference targetProcessApplication = ProcessApplicationContextUtil.getTargetProcessApplication((ExecutionEntity) execution);
if(ProcessApplicationContextUtil.requiresContextSwitch(targetProcessApplication)) {
Context.executeWithinProcessApplication(new Callable<Void>() {
public Void call() throws Exception {
signal(execution, signalName, signalData);
return null;
}
}, targetProcessApplication, new InvocationContext(execution));
}
else {
doSignal(execution, signalName, signalData);
}
}
protected void doSignal(final ActivityExecution execution, final String signalName, final Object signalData) throws Exception {
final ActivityBehavior activityBehaviorInstance = getActivityBehaviorInstance(execution);
if (activityBehaviorInstance instanceof CustomActivityBehavior) {
CustomActivityBehavior behavior = (CustomActivityBehavior) activityBehaviorInstance;
ActivityBehavior delegate = behavior.getDelegateActivityBehavior();
if (!(delegate instanceof SignallableActivityBehavior)) {
|
throw LOG.incorrectlyUsedSignalException(SignallableActivityBehavior.class.getName() );
}
}
executeWithErrorPropagation(execution, new Callable<Void>() {
@Override
public Void call() throws Exception {
((SignallableActivityBehavior) activityBehaviorInstance).signal(execution, signalName, signalData);
return null;
}
});
}
protected ActivityBehavior getActivityBehaviorInstance(ActivityExecution execution) {
Object delegateInstance = instantiateDelegate(className, fieldDeclarations);
if (delegateInstance instanceof ActivityBehavior) {
return new CustomActivityBehavior((ActivityBehavior) delegateInstance);
} else if (delegateInstance instanceof JavaDelegate) {
return new ServiceTaskJavaDelegateActivityBehavior((JavaDelegate) delegateInstance);
} else {
throw LOG.missingDelegateParentClassException(
delegateInstance.getClass().getName(),
JavaDelegate.class.getName(),
ActivityBehavior.class.getName()
);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\ClassDelegateActivityBehavior.java
| 1
|
请完成以下Java代码
|
public void setReversal_ID (int Reversal_ID)
{
if (Reversal_ID < 1)
set_Value (COLUMNNAME_Reversal_ID, null);
else
set_Value (COLUMNNAME_Reversal_ID, Integer.valueOf(Reversal_ID));
}
/** Get Reversal ID.
@return ID of document reversal
*/
@Override
public int getReversal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Reversal_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Total Credit.
@param TotalCr
Total Credit in document currency
*/
@Override
public void setTotalCr (java.math.BigDecimal TotalCr)
{
set_ValueNoCheck (COLUMNNAME_TotalCr, TotalCr);
}
/** Get Total Credit.
@return Total Credit in document currency
*/
@Override
public java.math.BigDecimal getTotalCr ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalCr);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Total Debit.
|
@param TotalDr
Total debit in document currency
*/
@Override
public void setTotalDr (java.math.BigDecimal TotalDr)
{
set_ValueNoCheck (COLUMNNAME_TotalDr, TotalDr);
}
/** Get Total Debit.
@return Total debit in document currency
*/
@Override
public java.math.BigDecimal getTotalDr ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalDr);
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_GL_JournalBatch.java
| 1
|
请完成以下Java代码
|
public final class DefaultCsrfToken implements CsrfToken {
@Serial
private static final long serialVersionUID = 6552658053267913685L;
private final String token;
private final String parameterName;
private final String headerName;
/**
* Creates a new instance
* @param headerName the HTTP header name to use
* @param parameterName the HTTP parameter name to use
* @param token the value of the token (i.e. expected value of the HTTP parameter of
* parametername).
*/
public DefaultCsrfToken(String headerName, String parameterName, String token) {
Assert.hasLength(headerName, "headerName cannot be null or empty");
Assert.hasLength(parameterName, "parameterName cannot be null or empty");
Assert.hasLength(token, "token cannot be null or empty");
this.headerName = headerName;
this.parameterName = parameterName;
this.token = token;
}
|
@Override
public String getHeaderName() {
return this.headerName;
}
@Override
public String getParameterName() {
return this.parameterName;
}
@Override
public String getToken() {
return this.token;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\DefaultCsrfToken.java
| 1
|
请完成以下Java代码
|
private void setActivityToOrderLine(final I_C_OrderLine compensationLinePO)
{
compensationLinePO.setC_Activity_ID(ActivityId.toRepoId(activityId));
}
public I_C_OrderLine getOrderLineByIdIfPresent(final OrderLineId orderLineId)
{
return orderLinesById.get(orderLineId);
}
public void deleteAllNotIn(final Collection<OrderLineId> orderLineIdsToSkipDeleting)
{
if (!performDatabaseChanges)
{
return;
}
final List<I_C_OrderLine> orderLinesToDelete = orderLinesById.values()
.stream()
.filter(orderLine -> !orderLineIdsToSkipDeleting.contains(OrderLineId.ofRepoId(orderLine.getC_OrderLine_ID())))
.collect(ImmutableList.toImmutableList());
orderLinesToDelete.forEach(this::deleteOrderLineRecord);
|
}
private void deleteOrderLineRecord(final I_C_OrderLine orderLine)
{
ATTR_IsRepoUpdate.setValue(orderLine, Boolean.TRUE);
try
{
delete(orderLine);
}
finally
{
ATTR_IsRepoUpdate.reset(orderLine);
}
}
static boolean isRepositoryUpdate(final I_C_OrderLine orderLine)
{
return ATTR_IsRepoUpdate.isSet(orderLine);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\OrderLinesStorage.java
| 1
|
请完成以下Java代码
|
public void setData_Export_Action (final java.lang.String Data_Export_Action)
{
set_Value (COLUMNNAME_Data_Export_Action, Data_Export_Action);
}
@Override
public java.lang.String getData_Export_Action()
{
return get_ValueAsString(COLUMNNAME_Data_Export_Action);
}
@Override
public org.compiere.model.I_Data_Export_Audit getData_Export_Audit()
{
return get_ValueAsPO(COLUMNNAME_Data_Export_Audit_ID, org.compiere.model.I_Data_Export_Audit.class);
}
@Override
public void setData_Export_Audit(final org.compiere.model.I_Data_Export_Audit Data_Export_Audit)
{
set_ValueFromPO(COLUMNNAME_Data_Export_Audit_ID, org.compiere.model.I_Data_Export_Audit.class, Data_Export_Audit);
}
@Override
public void setData_Export_Audit_ID (final int Data_Export_Audit_ID)
{
if (Data_Export_Audit_ID < 1)
set_Value (COLUMNNAME_Data_Export_Audit_ID, null);
else
set_Value (COLUMNNAME_Data_Export_Audit_ID, Data_Export_Audit_ID);
}
@Override
public int getData_Export_Audit_ID()
{
return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_ID);
}
@Override
public void setData_Export_Audit_Log_ID (final int Data_Export_Audit_Log_ID)
{
if (Data_Export_Audit_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_Log_ID, Data_Export_Audit_Log_ID);
|
}
@Override
public int getData_Export_Audit_Log_ID()
{
return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_Log_ID);
}
@Override
public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID)
{
if (ExternalSystem_Config_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_Config_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID);
}
@Override
public int getExternalSystem_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Data_Export_Audit_Log.java
| 1
|
请完成以下Java代码
|
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public ProcessEngine getObject() throws Exception {
configureExpressionManager();
configureExternallyManagedTransactions();
if (processEngineConfiguration.getBeans() == null) {
processEngineConfiguration.setBeans(new SpringBeanFactoryProxyMap(applicationContext));
}
this.processEngine = processEngineConfiguration.buildProcessEngine();
return this.processEngine;
}
protected void configureExpressionManager() {
if (processEngineConfiguration.getExpressionManager() == null && applicationContext != null) {
SpringExpressionManager expressionManager = new SpringExpressionManager(
applicationContext,
processEngineConfiguration.getBeans()
);
List<CustomFunctionProvider> customFunctionProviders =
processEngineConfiguration.getCustomFunctionProviders();
List<ELResolver> customELResolvers = processEngineConfiguration.getCustomELResolvers();
if (customFunctionProviders != null) {
expressionManager.setCustomFunctionProviders(customFunctionProviders);
}
if (customELResolvers != null) {
expressionManager.setCustomELResolvers(customELResolvers);
}
processEngineConfiguration.setExpressionManager(expressionManager);
}
}
protected void configureExternallyManagedTransactions() {
if (processEngineConfiguration instanceof SpringProcessEngineConfiguration) {
// remark: any config can be injected, so we cannot have SpringConfiguration as member
SpringProcessEngineConfiguration engineConfiguration =
(SpringProcessEngineConfiguration) processEngineConfiguration;
if (engineConfiguration.getTransactionManager() != null) {
processEngineConfiguration.setTransactionsExternallyManaged(true);
}
|
}
}
public Class<ProcessEngine> getObjectType() {
return ProcessEngine.class;
}
public boolean isSingleton() {
return true;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\ProcessEngineFactoryBean.java
| 1
|
请完成以下Java代码
|
/* package */final class UnmodifiableIterator<T> implements Iterator<T>
// , IteratorWrapper<E> // don't implement it because we want to hide the implementation
{
private final Iterator<T> iterator;
public UnmodifiableIterator(final Iterator<T> iterator)
{
super();
this.iterator = iterator;
}
@Override
public boolean hasNext()
{
return iterator.hasNext();
}
|
@Override
public T next()
{
return iterator.next();
}
/**
* @throws UnsupportedOperationException
*/
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\UnmodifiableIterator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable String getAuthoritiesClaimName() {
return this.authoritiesClaimName;
}
public void setAuthoritiesClaimName(@Nullable String authoritiesClaimName) {
this.authoritiesClaimName = authoritiesClaimName;
}
public @Nullable String getPrincipalClaimName() {
return this.principalClaimName;
}
public void setPrincipalClaimName(@Nullable String principalClaimName) {
this.principalClaimName = principalClaimName;
}
public String readPublicKey() throws IOException {
String key = "spring.security.oauth2.resourceserver.jwt.public-key-location";
if (this.publicKeyLocation == null) {
throw new InvalidConfigurationPropertyValueException(key, this.publicKeyLocation,
"No public key location specified");
}
if (!this.publicKeyLocation.exists()) {
throw new InvalidConfigurationPropertyValueException(key, this.publicKeyLocation,
"Public key location does not exist");
}
try (InputStream inputStream = this.publicKeyLocation.getInputStream()) {
return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
}
}
}
public static class Opaquetoken {
/**
* Client id used to authenticate with the token introspection endpoint.
*/
private @Nullable String clientId;
/**
* Client secret used to authenticate with the token introspection endpoint.
*/
|
private @Nullable String clientSecret;
/**
* OAuth 2.0 endpoint through which token introspection is accomplished.
*/
private @Nullable String introspectionUri;
public @Nullable String getClientId() {
return this.clientId;
}
public void setClientId(@Nullable String clientId) {
this.clientId = clientId;
}
public @Nullable String getClientSecret() {
return this.clientSecret;
}
public void setClientSecret(@Nullable String clientSecret) {
this.clientSecret = clientSecret;
}
public @Nullable String getIntrospectionUri() {
return this.introspectionUri;
}
public void setIntrospectionUri(@Nullable String introspectionUri) {
this.introspectionUri = introspectionUri;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-resource-server\src\main\java\org\springframework\boot\security\oauth2\server\resource\autoconfigure\OAuth2ResourceServerProperties.java
| 2
|
请完成以下Java代码
|
public Long getLngValue() {
return dataType == DataType.LONG ? lngValue : null;
}
public void setLngValue(Long lngValue) {
this.dataType = DataType.LONG;
this.lngValue = lngValue;
}
public Double getDblValue() {
return dataType == DataType.DOUBLE ? dblValue : null;
}
public void setDblValue(Double dblValue) {
this.dataType = DataType.DOUBLE;
this.dblValue = dblValue;
}
public Boolean getBoolValue() {
return dataType == DataType.BOOLEAN ? boolValue : null;
}
public void setBoolValue(Boolean boolValue) {
this.dataType = DataType.BOOLEAN;
this.boolValue = boolValue;
}
public String getStrValue() {
return dataType == DataType.STRING ? strValue : null;
}
public void setStrValue(String strValue) {
this.dataType = DataType.STRING;
this.strValue = strValue;
}
public void setJsonValue(String jsonValue) {
this.dataType = DataType.JSON;
this.strValue = jsonValue;
}
public String getJsonValue() {
return dataType == DataType.JSON ? strValue : null;
}
boolean isSet() {
return dataType != null;
}
static EntityKeyValue fromString(String s) {
EntityKeyValue result = new EntityKeyValue();
result.setStrValue(s);
return result;
}
|
static EntityKeyValue fromBool(boolean b) {
EntityKeyValue result = new EntityKeyValue();
result.setBoolValue(b);
return result;
}
static EntityKeyValue fromLong(long l) {
EntityKeyValue result = new EntityKeyValue();
result.setLngValue(l);
return result;
}
static EntityKeyValue fromDouble(double d) {
EntityKeyValue result = new EntityKeyValue();
result.setDblValue(d);
return result;
}
static EntityKeyValue fromJson(String s) {
EntityKeyValue result = new EntityKeyValue();
result.setJsonValue(s);
return result;
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\profile\EntityKeyValue.java
| 1
|
请完成以下Java代码
|
public static Comparator<WorkflowLauncherCaption> orderBy(@NonNull final String adLanguage, @NonNull final List<OrderBy> orderBys)
{
//
// Order by each given field
Comparator<WorkflowLauncherCaption> result = null;
for (final OrderBy orderBy : orderBys)
{
final Comparator<WorkflowLauncherCaption> cmp = toComparator(adLanguage, orderBy);
result = result != null
? result.thenComparing(cmp)
: cmp;
}
// Last, order by complete caption
final Comparator<WorkflowLauncherCaption> completeCaptionComparator = toCompleteCaptionComparator(adLanguage);
result = result != null
? result.thenComparing(completeCaptionComparator)
: completeCaptionComparator;
return result;
}
private static Comparator<WorkflowLauncherCaption> toComparator(@NonNull final String adLanguage, @NonNull final OrderBy orderBy)
{
final String field = orderBy.getField();
final Function<WorkflowLauncherCaption, Comparable<?>> keyExtractor = caption -> caption.getFieldComparingKey(field, adLanguage);
//noinspection unchecked
Comparator<Comparable<?>> keyComparator = (Comparator<Comparable<?>>)Comparator.naturalOrder();
if (!orderBy.isAscending())
{
keyComparator = keyComparator.reversed();
}
keyComparator = Comparator.nullsLast(keyComparator);
return Comparator.comparing(keyExtractor, keyComparator);
}
private static Comparator<WorkflowLauncherCaption> toCompleteCaptionComparator(@NonNull final String adLanguage)
{
final Function<WorkflowLauncherCaption, String> keyExtractor = caption -> caption.translate(adLanguage);
Comparator<String> keyComparator = Comparator.nullsLast(Comparator.naturalOrder());
|
return Comparator.comparing(keyExtractor, keyComparator);
}
//
//
//
@Value
@Builder
public static class OrderBy
{
@NonNull String field;
@Builder.Default boolean ascending = true;
public static OrderBy descending(@NonNull final ReferenceListAwareEnum field)
{
return descending(field.getCode());
}
public static OrderBy descending(@NonNull final String field)
{
return builder().field(field).ascending(false).build();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WorkflowLauncherCaption.java
| 1
|
请完成以下Java代码
|
public void afterPropertiesSet() {
Assert.hasLength(this.service, "service cannot be empty.");
Assert.hasLength(this.artifactParameter, "artifactParameter cannot be empty.");
Assert.hasLength(this.serviceParameter, "serviceParameter cannot be empty.");
}
/**
* Represents the service the user is authenticating to.
* <p>
* This service is the callback URL belonging to the local Spring Security System for
* Spring secured application. For example,
*
* <pre>
* https://www.mycompany.com/application/login/cas
* </pre>
* @return the URL of the service the user is authenticating to
*/
public final @Nullable String getService() {
return this.service;
}
/**
* Indicates whether the <code>renew</code> parameter should be sent to the CAS login
* URL and CAS validation URL.
* <p>
* If <code>true</code>, it will force CAS to authenticate the user again (even if the
* user has previously authenticated). During ticket validation it will require the
* ticket was generated as a consequence of an explicit login. High security
* applications would probably set this to <code>true</code>. Defaults to
* <code>false</code>, providing automated single sign on.
* @return whether to send the <code>renew</code> parameter to CAS
*/
public final boolean isSendRenew() {
return this.sendRenew;
}
public final void setSendRenew(final boolean sendRenew) {
this.sendRenew = sendRenew;
}
public final void setService(final String service) {
this.service = service;
}
public final String getArtifactParameter() {
return this.artifactParameter;
}
/**
* Configures the Request Parameter to look for when attempting to see if a CAS ticket
* was sent from the server.
* @param artifactParameter the id to use. Default is "ticket".
*/
public final void setArtifactParameter(final String artifactParameter) {
this.artifactParameter = artifactParameter;
}
/**
|
* Configures the Request parameter to look for when attempting to send a request to
* CAS.
* @return the service parameter to use. Default is "service".
*/
public final String getServiceParameter() {
return this.serviceParameter;
}
public final void setServiceParameter(final String serviceParameter) {
this.serviceParameter = serviceParameter;
}
public final boolean isAuthenticateAllArtifacts() {
return this.authenticateAllArtifacts;
}
/**
* If true, then any non-null artifact (ticket) should be authenticated. Additionally,
* the service will be determined dynamically in order to ensure the service matches
* the expected value for this artifact.
* @param authenticateAllArtifacts
*/
public final void setAuthenticateAllArtifacts(final boolean authenticateAllArtifacts) {
this.authenticateAllArtifacts = authenticateAllArtifacts;
}
}
|
repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\ServiceProperties.java
| 1
|
请完成以下Java代码
|
public void setPrevious_ID (final int Previous_ID)
{
if (Previous_ID < 1)
set_Value (COLUMNNAME_Previous_ID, null);
else
set_Value (COLUMNNAME_Previous_ID, Previous_ID);
}
@Override
public int getPrevious_ID()
{
return get_ValueAsInt(COLUMNNAME_Previous_ID);
}
@Override
public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No)
{
set_Value (COLUMNNAME_Setup_Place_No, Setup_Place_No);
}
@Override
public java.lang.String getSetup_Place_No()
{
return get_ValueAsString(COLUMNNAME_Setup_Place_No);
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
|
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
@Override
public void setVisitorsAddress (final boolean VisitorsAddress)
{
set_Value (COLUMNNAME_VisitorsAddress, VisitorsAddress);
}
@Override
public boolean isVisitorsAddress()
{
return get_ValueAsBoolean(COLUMNNAME_VisitorsAddress);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Location.java
| 1
|
请完成以下Java代码
|
public class MenuDto extends BaseDTO implements Serializable {
@ApiModelProperty(value = "ID")
private Long id;
@ApiModelProperty(value = "子节点")
private List<MenuDto> children;
@ApiModelProperty(value = "类型")
private Integer type;
@ApiModelProperty(value = "权限")
private String permission;
@ApiModelProperty(value = "菜单标题")
private String title;
@ApiModelProperty(value = "排序")
private Integer menuSort;
@ApiModelProperty(value = "路径")
private String path;
@ApiModelProperty(value = "组件")
private String component;
@ApiModelProperty(value = "PID")
private Long pid;
@ApiModelProperty(value = "子节点数目")
private Integer subCount;
@ApiModelProperty(value = "是否为Iframe")
@JsonProperty("iFrame")
private Boolean iFrame;
@ApiModelProperty(value = "是否缓存")
private Boolean cache;
@ApiModelProperty(value = "是否隐藏")
private Boolean hidden;
@ApiModelProperty(value = "组件名称")
private String componentName;
@ApiModelProperty(value = "图标")
private String icon;
@ApiModelProperty(value = "是否存在子节点")
public Boolean getHasChildren() {
return subCount > 0;
}
@ApiModelProperty(value = "是否叶子节点")
public Boolean getLeaf() {
|
return subCount <= 0;
}
@ApiModelProperty(value = "标题")
public String getLabel() {
return title;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MenuDto menuDto = (MenuDto) o;
return Objects.equals(id, menuDto.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\dto\MenuDto.java
| 1
|
请完成以下Java代码
|
public static void main(String[] args) {
Subscriber<Integer> subscriber = new Subscriber<Integer>() {
private Subscription subscription;
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
this.subscription.request(1);
}
@Override
public void onNext(Integer item) {
System.out.println("接受到数据: " + item);
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.subscription.request(1);
}
@Override
|
public void onError(Throwable throwable) {
throwable.printStackTrace();
this.subscription.cancel();
}
@Override
public void onComplete() {
System.out.println("处理完了!");
}
};
String[] strs = {"1", "2", "3"};
Flux.fromArray(strs).map(Integer::parseInt).subscribe(subscriber);
Mono.fromSupplier(() -> 1).map(s -> s + 1).subscribe(subscriber);
}
}
|
repos\SpringAll-master\57.Spring-Boot-WebFlux\webflux\src\main\java\com\example\webflux\MonoFluxTest.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<Developer> getAllDevelopers(){
return developerRepository.findAll();
}
@GetMapping("/dev/{id}")
public ResponseEntity<Developer> getDeveloperById(@PathVariable(value = "id") Long devId) throws ResourceNotFoundException{
Developer developer = developerRepository.findById(devId)
.orElseThrow(()-> new ResourceNotFoundException("Developer could not find on::" + devId));
return ResponseEntity.ok().body(developer);
}
@PostMapping("/dev")
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 ZonedDateTime getObservationStartTime() {
return observationStartTime;
}
public void setObservationStartTime(ZonedDateTime observationStartTime) {
this.observationStartTime = observationStartTime;
}
public OffsetDateTime getPeakVisibilityTime() {
return peakVisibilityTime;
}
public void setPeakVisibilityTime(OffsetDateTime peakVisibilityTime) {
this.peakVisibilityTime = peakVisibilityTime;
}
public Integer getPeakVisibilityTimeOffset() {
return peakVisibilityTimeOffset;
}
public void setPeakVisibilityTimeOffset(Integer peakVisibilityTimeOffset) {
|
this.peakVisibilityTimeOffset = peakVisibilityTimeOffset;
}
public ZonedDateTime getNextExpectedAppearance() {
return nextExpectedAppearance;
}
public void setNextExpectedAppearance(ZonedDateTime nextExpectedAppearance) {
this.nextExpectedAppearance = nextExpectedAppearance;
}
public OffsetDateTime getLastRecordedSighting() {
return lastRecordedSighting;
}
public void setLastRecordedSighting(OffsetDateTime lastRecordedSighting) {
this.lastRecordedSighting = lastRecordedSighting;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\timezonestorage\AstronomicalObservation.java
| 1
|
请完成以下Java代码
|
private static String createAvailabilityText(@NonNull final StockAvailabilityResponseItemPart reponseItemPart)
{
final StringBuilder availabilityText = new StringBuilder();
availabilityText.append(reponseItemPart.getType());
final boolean hasTour = !Check.isEmpty(reponseItemPart.getTour(), true);
final StockAvailabilitySubstitutionReason reason = reponseItemPart.getReason();
final boolean hasDefectReason = !StockAvailabilitySubstitutionReason.NO_INFO.equals(reason);
if (hasTour || hasDefectReason)
{
availabilityText.append(" ( ");
}
if (hasTour)
|
{
availabilityText.append("Tour " + reponseItemPart.getTour());
}
if (hasDefectReason)
{
availabilityText.append("Grund " + reason);
}
if (hasTour || hasDefectReason)
{
availabilityText.append(" )");
}
return availabilityText.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\availability\MSV3AvailiabilityClientImpl.java
| 1
|
请完成以下Java代码
|
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start No.
@param StartNo
Starting number/position
*/
@Override
public void setStartNo (int StartNo)
{
|
set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo));
}
/** Get Start No.
@return Starting number/position
*/
@Override
public int getStartNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StartNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ImpFormat_Row.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class EDIExpCUOMType {
@XmlElement(name = "Name", required = true)
protected String name;
@XmlElement(name = "UOMSymbol")
protected String uomSymbol;
@XmlElement(name = "X12DE355", required = true)
protected String x12DE355;
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the uomSymbol property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUOMSymbol() {
return uomSymbol;
}
|
/**
* Sets the value of the uomSymbol property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUOMSymbol(String value) {
this.uomSymbol = value;
}
/**
* Gets the value of the x12DE355 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getX12DE355() {
return x12DE355;
}
/**
* Sets the value of the x12DE355 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setX12DE355(String value) {
this.x12DE355 = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpCUOMType.java
| 2
|
请完成以下Java代码
|
public synchronized T computeIfNull(@NonNull final Supplier<T> supplier)
{
if (value == null)
{
this.value = supplier.get();
}
return this.value;
}
@Nullable
public synchronized T computeIfNotNull(@NonNull final UnaryOperator<T> remappingFunction)
{
if (value != null)
{
this.value = remappingFunction.apply(this.value);
}
return this.value;
}
public synchronized OldAndNewValues<T> computeIfNotNullReturningOldAndNew(@NonNull final UnaryOperator<T> remappingFunction)
{
|
if (value != null)
{
final T oldValue = this.value;
this.value = remappingFunction.apply(oldValue);
return OldAndNewValues.<T>builder()
.oldValue(oldValue)
.newValue(this.value)
.build();
}
else
{
return OldAndNewValues.nullValues();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\SynchronizedMutable.java
| 1
|
请完成以下Java代码
|
public class HikariDataSourcePoolMetadata extends AbstractDataSourcePoolMetadata<HikariDataSource> {
public HikariDataSourcePoolMetadata(HikariDataSource dataSource) {
super(dataSource);
}
@Override
public @Nullable Integer getActive() {
try {
HikariPool hikariPool = getHikariPool();
return (hikariPool != null) ? hikariPool.getActiveConnections() : null;
}
catch (Exception ex) {
return null;
}
}
@Override
public @Nullable Integer getIdle() {
try {
HikariPool hikariPool = getHikariPool();
return (hikariPool != null) ? hikariPool.getIdleConnections() : null;
}
catch (Exception ex) {
return null;
}
}
private @Nullable HikariPool getHikariPool() {
return (HikariPool) new DirectFieldAccessor(getDataSource()).getPropertyValue("pool");
|
}
@Override
public @Nullable Integer getMax() {
return getDataSource().getMaximumPoolSize();
}
@Override
public @Nullable Integer getMin() {
return getDataSource().getMinimumIdle();
}
@Override
public @Nullable String getValidationQuery() {
return getDataSource().getConnectionTestQuery();
}
@Override
public @Nullable Boolean getDefaultAutoCommit() {
return getDataSource().isAutoCommit();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\metadata\HikariDataSourcePoolMetadata.java
| 1
|
请完成以下Java代码
|
public String moveToArchive(final File importedFile,
final String archiveFolder)
{
final File archiveDir = new File(archiveFolder);
checkArchiveDir(archiveDir);
final File destFile = new File(archiveDir, importedFile.getName());
if (!importedFile
.renameTo(destFile))
{
ConfigException.throwNew(ConfigException.ARCHIVE_RENAME_FAILED_2P,
importedFile.getAbsolutePath(), archiveDir
.getAbsolutePath());
}
|
return null;
}
private void checkArchiveDir(final File archiveDir)
{
if (!archiveDir.isDirectory())
{
ConfigException.throwNew(ConfigException.ARCHIVE_NOT_A_DIR_1P,
archiveDir.getAbsolutePath());
}
if (!archiveDir.canWrite())
{
ConfigException.throwNew(ConfigException.ARCHIVE_CANT_WRITE_1P,
archiveDir.getAbsolutePath());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\impex\api\impl\InboundProcessorBL.java
| 1
|
请完成以下Java代码
|
public int getMark4Percent ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Mark4Percent);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Color Schema.
@param PA_ColorSchema_ID
Performance Color Schema
*/
public void setPA_ColorSchema_ID (int PA_ColorSchema_ID)
|
{
if (PA_ColorSchema_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_ColorSchema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_ColorSchema_ID, Integer.valueOf(PA_ColorSchema_ID));
}
/** Get Color Schema.
@return Performance Color Schema
*/
public int getPA_ColorSchema_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ColorSchema_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_PA_ColorSchema.java
| 1
|
请完成以下Java代码
|
public static ParseExceptionDto fromException(ParseException exception) {
ParseExceptionDto dto = new ParseExceptionDto();
dto.setType(ParseException.class.getSimpleName());
dto.setMessage(exception.getMessage());
for (ResourceReport report : exception.getResorceReports()) {
List<ProblemDto> errorDtos = new ArrayList<>();
for (Problem error : report.getErrors()) {
errorDtos.add(ProblemDto.fromProblem(error));
}
List<ProblemDto> warningDtos = new ArrayList<>();
for (Problem warning : report.getWarnings()) {
warningDtos.add(ProblemDto.fromProblem(warning));
}
ResourceReportDto resourceReportDto = new ResourceReportDto(errorDtos, warningDtos);
dto.details.put(report.getResourceName(), resourceReportDto);
|
}
return dto;
}
// getter / setters ////////////////////////
public Map<String, ResourceReportDto> getDetails() {
return details;
}
public void setDetails(Map<String, ResourceReportDto> details) {
this.details = details;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\ParseExceptionDto.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.