instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
protected IntegerStringExpression createGeneralExpression(final ExpressionContext context, final String expressionStr, final List<Object> expressionChunks)
{
return new GeneralExpression(context, this, expressionStr, expressionChunks);
}
});
}
private static final class IntegerValueConverter implements ValueConverter<Integer, IntegerStringExpression>
{
@Override
public Integer convertFrom(final Object valueObj, final ExpressionContext context)
{
if (valueObj == null)
{
return null;
}
else if (valueObj instanceof Integer)
{
return (Integer)valueObj;
}
else
{
String valueStr = valueObj.toString();
if (valueStr == null)
{
return null; // shall not happen
}
valueStr = valueStr.trim();
return new Integer(valueStr);
}
}
}
private static final class NullExpression extends NullExpressionTemplate<Integer, IntegerStringExpression>implements IntegerStringExpression
{
public NullExpression(final Compiler<Integer, IntegerStringExpression> compiler)
{
super(compiler);
}
}
private static final class ConstantExpression extends ConstantExpressionTemplate<Integer, IntegerStringExpression>implements IntegerStringExpression
{
public ConstantExpression(final Compiler<Integer, IntegerStringExpression> compiler, final String expressionStr, final Integer constantValue)
{
super(ExpressionContext.EMPTY, compiler, expressionStr, constantValue);
}
}
private static final class SingleParameterExpression extends SingleParameterExpressionTemplate<Integer, IntegerStringExpression>implements IntegerStringExpression
|
{
public SingleParameterExpression(final ExpressionContext context, final Compiler<Integer, IntegerStringExpression> compiler, final String expressionStr, final CtxName parameter)
{
super(context, compiler, expressionStr, parameter);
}
@Override
protected Integer extractParameterValue(final Evaluatee ctx)
{
return parameter.getValueAsInteger(ctx);
}
}
private static final class GeneralExpression extends GeneralExpressionTemplate<Integer, IntegerStringExpression>implements IntegerStringExpression
{
public GeneralExpression(final ExpressionContext context, final Compiler<Integer, IntegerStringExpression> compiler, final String expressionStr, final List<Object> expressionChunks)
{
super(context, compiler, expressionStr, expressionChunks);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\IntegerStringExpressionSupport.java
| 1
|
请完成以下Java代码
|
public void patchRow(final RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
changeRow(ctx.getRowId(), row -> applyFieldChangeRequests(row, fieldChangeRequests));
}
private ProductsToPickRow applyFieldChangeRequests(@NonNull final ProductsToPickRow row, final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
Check.assumeNotEmpty(fieldChangeRequests, "fieldChangeRequests is not empty");
fieldChangeRequests.forEach(JSONDocumentChangedEvent::assertReplaceOperation);
ProductsToPickRow changedRow = row;
for (final JSONDocumentChangedEvent fieldChangeRequest : fieldChangeRequests)
{
final String fieldName = fieldChangeRequest.getPath();
if (ProductsToPickRow.FIELD_QtyOverride.equals(fieldName))
{
if (!row.isQtyOverrideEditableByUser())
{
throw new AdempiereException("QtyOverride is not editable")
.setParameter("row", row);
}
final BigDecimal qtyOverride = fieldChangeRequest.getValueAsBigDecimal();
changedRow = changedRow.withQtyOverride(qtyOverride);
}
else if (ProductsToPickRow.FIELD_QtyReview.equals(fieldName))
{
final BigDecimal qtyReviewed = fieldChangeRequest.getValueAsBigDecimal();
final PickingCandidate pickingCandidate = pickingCandidateService.setQtyReviewed(row.getPickingCandidateId(), qtyReviewed);
changedRow = changedRow.withUpdatesFromPickingCandidate(pickingCandidate);
}
else
{
throw new AdempiereException("Field " + fieldName + " is not editable");
}
}
return changedRow;
}
@Override
public DocumentIdsSelection getDocumentIdsToInvalidate(final TableRecordReferenceSet recordRefs)
{
final Set<PickingCandidateId> pickingCandidateIds = recordRefs
.streamIds(I_M_Picking_Candidate.Table_Name, PickingCandidateId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
if (pickingCandidateIds.isEmpty())
{
return DocumentIdsSelection.EMPTY;
|
}
return getAllRowsByIdNoUpdate()
.values()
.stream()
.filter(row -> pickingCandidateIds.contains(row.getPickingCandidateId()))
.map(ProductsToPickRow::getId)
.collect(DocumentIdsSelection.toDocumentIdsSelection());
}
@Override
public void invalidateAll()
{
rowIdsInvalid = true;
}
public void updateViewRowFromPickingCandidate(@NonNull final DocumentId rowId, @NonNull final PickingCandidate pickingCandidate)
{
changeRow(rowId, row -> row.withUpdatesFromPickingCandidate(pickingCandidate));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\ProductsToPickRowsData.java
| 1
|
请完成以下Java代码
|
private ImmutableList<RefundInvoiceCandidate> orderCandidatesByConfigMinQty(@NonNull final List<RefundInvoiceCandidate> refundCandidatesToAssign)
{
return refundCandidatesToAssign
.stream()
.sorted(Comparator.comparing(c -> singleElement(c.getRefundConfigs()).getMinQty()))
.collect(ImmutableList.toImmutableList());
}
/**
* @return the assignable candidate with its new additional assignment, and the quantity that is still left to be assigned.
*/
@VisibleForTesting
IPair<AssignableInvoiceCandidate, Quantity> assignCandidates(
@NonNull final AssignCandidatesRequest assignCandidatesRequest,
@NonNull final Quantity quantityToAssign)
{
final AssignableInvoiceCandidate assignableCandidate = assignCandidatesRequest.getAssignableInvoiceCandidate();
final RefundInvoiceCandidate refundCandidate = assignCandidatesRequest.getRefundInvoiceCandidate();
final RefundConfig refundConfig = assignCandidatesRequest.getRefundConfig();
final Quantity assignableQuantity = refundCandidate.computeAssignableQuantity(refundConfig);
final Quantity quantityToAssignEffective = quantityToAssign.min(assignableQuantity);
final AssignableInvoiceCandidate candidateToAssign;
final boolean partialAssignRequired = assignableCandidate.getQuantity().compareTo(quantityToAssignEffective) > 0;
if (partialAssignRequired)
{
final SplitResult splitResult = assignableCandidate.splitQuantity(quantityToAssignEffective.toBigDecimal());
candidateToAssign = splitResult.getNewCandidate();
}
else
{
candidateToAssign = assignableCandidate;
}
final boolean assignableQtyIsEnough = assignableQuantity.compareTo(quantityToAssign) >= 0;
final Quantity remainingQty;
if (assignableQtyIsEnough)
{
remainingQty = Quantity.zero(assignableCandidate.getQuantity().getUOM());
|
}
else
{
remainingQty = quantityToAssign.subtract(quantityToAssignEffective);
}
final AssignmentToRefundCandidate assignmentToRefundCandidate = refundInvoiceCandidateService
.addAssignableMoney(
refundCandidate,
refundConfig,
candidateToAssign);
refundInvoiceCandidateRepository.save(assignmentToRefundCandidate.getRefundInvoiceCandidate());
assignmentToRefundCandidateRepository.save(assignmentToRefundCandidate);
return ImmutablePair.of(
assignableCandidate
.toBuilder()
.assignmentToRefundCandidate(assignmentToRefundCandidate)
.build(),
remainingQty);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\exceedingqty\CandidateAssignServiceExceedingQty.java
| 1
|
请完成以下Java代码
|
public List<ArtikelMenge> getArtikel() {
if (artikel == null) {
artikel = new ArrayList<ArtikelMenge>();
}
return this.artikel;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
|
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\Ruecknahmeangebot.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected boolean isJndiAvailable() {
return JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable();
}
protected JndiLocator getJndiLocator(String[] locations) {
return new JndiLocator(locations);
}
protected static class JndiLocator extends JndiLocatorSupport {
private final String[] locations;
public JndiLocator(String[] locations) {
this.locations = locations;
}
|
public @Nullable String lookupFirstLocation() {
for (String location : this.locations) {
try {
lookup(location);
return location;
}
catch (NamingException ex) {
// Swallow and continue
}
}
return null;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\OnJndiCondition.java
| 2
|
请完成以下Java代码
|
public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID)
{
if (M_HU_PI_Version_ID < 1)
set_Value (COLUMNNAME_M_HU_PI_Version_ID, null);
else
set_Value (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID);
}
@Override
public int getM_HU_PI_Version_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_ID);
}
@Override
public void setM_Locator_ID (final int M_Locator_ID)
{
if (M_Locator_ID < 1)
set_Value (COLUMNNAME_M_Locator_ID, null);
else
set_Value (COLUMNNAME_M_Locator_ID, M_Locator_ID);
}
@Override
public int getM_Locator_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Locator_ID);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
throw new IllegalArgumentException ("M_Product_Category_ID is virtual column"); }
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
throw new IllegalArgumentException ("M_Product_ID is virtual column"); }
|
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setSerialNo (final @Nullable java.lang.String SerialNo)
{
throw new IllegalArgumentException ("SerialNo is virtual column"); }
@Override
public java.lang.String getSerialNo()
{
return get_ValueAsString(COLUMNNAME_SerialNo);
}
@Override
public void setServiceContract (final @Nullable java.lang.String ServiceContract)
{
throw new IllegalArgumentException ("ServiceContract is virtual column"); }
@Override
public java.lang.String getServiceContract()
{
return get_ValueAsString(COLUMNNAME_ServiceContract);
}
@Override
public void setValue (final java.lang.String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable String getRetentionDuration() {
return this.retentionDuration;
}
public void setRetentionDuration(@Nullable String retentionDuration) {
this.retentionDuration = retentionDuration;
}
public @Nullable Integer getRetentionReplicationFactor() {
return this.retentionReplicationFactor;
}
public void setRetentionReplicationFactor(@Nullable Integer retentionReplicationFactor) {
this.retentionReplicationFactor = retentionReplicationFactor;
}
public @Nullable String getRetentionShardDuration() {
return this.retentionShardDuration;
}
public void setRetentionShardDuration(@Nullable String retentionShardDuration) {
this.retentionShardDuration = retentionShardDuration;
}
public String getUri() {
return this.uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public boolean isCompressed() {
return this.compressed;
}
public void setCompressed(boolean compressed) {
this.compressed = compressed;
}
public boolean isAutoCreateDb() {
return this.autoCreateDb;
}
public void setAutoCreateDb(boolean autoCreateDb) {
this.autoCreateDb = autoCreateDb;
}
public @Nullable InfluxApiVersion getApiVersion() {
return this.apiVersion;
}
|
public void setApiVersion(@Nullable InfluxApiVersion apiVersion) {
this.apiVersion = apiVersion;
}
public @Nullable String getOrg() {
return this.org;
}
public void setOrg(@Nullable String org) {
this.org = org;
}
public @Nullable String getBucket() {
return this.bucket;
}
public void setBucket(@Nullable String bucket) {
this.bucket = bucket;
}
public @Nullable String getToken() {
return this.token;
}
public void setToken(@Nullable String token) {
this.token = token;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\influx\InfluxProperties.java
| 2
|
请完成以下Java代码
|
public void setPickFrom_HU_ID (final int PickFrom_HU_ID)
{
if (PickFrom_HU_ID < 1)
set_Value (COLUMNNAME_PickFrom_HU_ID, null);
else
set_Value (COLUMNNAME_PickFrom_HU_ID, PickFrom_HU_ID);
}
@Override
public int getPickFrom_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_HU_ID);
}
@Override
public void setPickFrom_HUQRCode (final @Nullable java.lang.String PickFrom_HUQRCode)
{
set_Value (COLUMNNAME_PickFrom_HUQRCode, PickFrom_HUQRCode);
}
@Override
public java.lang.String getPickFrom_HUQRCode()
{
return get_ValueAsString(COLUMNNAME_PickFrom_HUQRCode);
}
/**
* PickingJobAggregationType AD_Reference_ID=541931
* Reference name: PickingJobAggregationType
*/
public static final int PICKINGJOBAGGREGATIONTYPE_AD_Reference_ID=541931;
/** sales_order = sales_order */
public static final String PICKINGJOBAGGREGATIONTYPE_Sales_order = "sales_order";
/** product = product */
public static final String PICKINGJOBAGGREGATIONTYPE_Product = "product";
/** delivery_location = delivery_location */
public static final String PICKINGJOBAGGREGATIONTYPE_Delivery_location = "delivery_location";
@Override
public void setPickingJobAggregationType (final java.lang.String PickingJobAggregationType)
{
set_Value (COLUMNNAME_PickingJobAggregationType, PickingJobAggregationType);
}
@Override
public java.lang.String getPickingJobAggregationType()
{
return get_ValueAsString(COLUMNNAME_PickingJobAggregationType);
}
@Override
public void setPicking_User_ID (final int Picking_User_ID)
|
{
if (Picking_User_ID < 1)
set_Value (COLUMNNAME_Picking_User_ID, null);
else
set_Value (COLUMNNAME_Picking_User_ID, Picking_User_ID);
}
@Override
public int getPicking_User_ID()
{
return get_ValueAsInt(COLUMNNAME_Picking_User_ID);
}
@Override
public void setPreparationDate (final @Nullable java.sql.Timestamp PreparationDate)
{
set_Value (COLUMNNAME_PreparationDate, PreparationDate);
}
@Override
public java.sql.Timestamp getPreparationDate()
{
return get_ValueAsTimestamp(COLUMNNAME_PreparationDate);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job.java
| 1
|
请完成以下Java代码
|
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** FieldGroupType AD_Reference_ID=53000 */
public static final int FIELDGROUPTYPE_AD_Reference_ID=53000;
/** Tab = T */
public static final String FIELDGROUPTYPE_Tab = "T";
/** Label = L */
public static final String FIELDGROUPTYPE_Label = "L";
/** Collapse = C */
public static final String FIELDGROUPTYPE_Collapse = "C";
/** Set Field Group Type.
@param FieldGroupType Field Group Type */
public void setFieldGroupType (String FieldGroupType)
{
set_Value (COLUMNNAME_FieldGroupType, FieldGroupType);
}
/** Get Field Group Type.
@return Field Group Type */
public String getFieldGroupType ()
{
return (String)get_Value(COLUMNNAME_FieldGroupType);
}
/** Set Collapsed By Default.
@param IsCollapsedByDefault
Flag to set the initial state of collapsible field group.
*/
public void setIsCollapsedByDefault (boolean IsCollapsedByDefault)
{
set_Value (COLUMNNAME_IsCollapsedByDefault, Boolean.valueOf(IsCollapsedByDefault));
}
/** Get Collapsed By Default.
@return Flag to set the initial state of collapsible field group.
*/
public boolean isCollapsedByDefault ()
{
Object oo = get_Value(COLUMNNAME_IsCollapsedByDefault);
if (oo != null)
{
|
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_FieldGroup.java
| 1
|
请完成以下Java代码
|
public String getTableAlias()
{
return _tableAlias;
}
public Builder setChildToParentLinkColumnNames(@Nullable final IPair<String, String> childToParentLinkColumnNames)
{
assertNotBuilt();
if (childToParentLinkColumnNames != null)
{
_sqlLinkColumnName = childToParentLinkColumnNames.getLeft();
_sqlParentLinkColumnName = childToParentLinkColumnNames.getRight();
}
else
{
_sqlLinkColumnName = null;
_sqlParentLinkColumnName = null;
}
return this;
}
public String getSqlLinkColumnName()
{
return _sqlLinkColumnName;
}
public String getSqlParentLinkColumnName()
{
return _sqlParentLinkColumnName;
}
public Builder setSqlWhereClause(final String sqlWhereClause)
{
assertNotBuilt();
Check.assumeNotNull(sqlWhereClause, "Parameter sqlWhereClause is not null");
_sqlWhereClause = sqlWhereClause;
return this;
}
public Builder addField(@NonNull final DocumentFieldDataBindingDescriptor field)
{
assertNotBuilt();
final SqlDocumentFieldDataBindingDescriptor sqlField = SqlDocumentFieldDataBindingDescriptor.cast(field);
_fieldsByFieldName.put(sqlField.getFieldName(), sqlField);
return this;
}
private Map<String, SqlDocumentFieldDataBindingDescriptor> getFieldsByFieldName()
{
return _fieldsByFieldName;
}
public SqlDocumentFieldDataBindingDescriptor getField(final String fieldName)
{
final SqlDocumentFieldDataBindingDescriptor field = getFieldsByFieldName().get(fieldName);
if (field == null)
{
throw new AdempiereException("Field " + fieldName + " not found in " + this);
}
return field;
}
|
private List<SqlDocumentFieldDataBindingDescriptor> getKeyFields()
{
return getFieldsByFieldName()
.values()
.stream()
.filter(SqlDocumentFieldDataBindingDescriptor::isKeyColumn)
.collect(ImmutableList.toImmutableList());
}
private Optional<String> getSqlSelectVersionById()
{
if (getFieldsByFieldName().get(FIELDNAME_Version) == null)
{
return Optional.empty();
}
final List<SqlDocumentFieldDataBindingDescriptor> keyColumns = getKeyFields();
if (keyColumns.size() != 1)
{
return Optional.empty();
}
final String keyColumnName = keyColumns.get(0).getColumnName();
final String sql = "SELECT " + FIELDNAME_Version + " FROM " + getTableName() + " WHERE " + keyColumnName + "=?";
return Optional.of(sql);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlDocumentEntityDataBindingDescriptor.java
| 1
|
请完成以下Java代码
|
public class FlattenUtils {
public static Map<String, Object> flatten(Map<String, Object> map) {
return flatten(map, null);
}
private static Map<String, Object> flatten(Map<String, Object> map, String prefix) {
Map<String, Object> flatMap = new HashMap<>();
map.forEach((key, value) -> {
String newKey = prefix != null ? prefix + "." + key : key;
if (value instanceof Map) {
flatMap.putAll(flatten((Map<String, Object>) value, newKey));
} else if (value instanceof List) {
// check for list of primitives
Object element = ((List<?>) value).get(0);
if (element instanceof String || element instanceof Number || element instanceof Boolean) {
|
flatMap.put(newKey, value);
} else {
// check for list of objects
List<Map<String, Object>> list = (List<Map<String, Object>>) value;
for (int i = 0; i < list.size(); i++) {
flatMap.putAll(flatten(list.get(i), newKey + "[" + i + "]"));
}
}
} else {
flatMap.put(newKey, value);
}
});
return flatMap;
}
}
|
repos\tutorials-master\json-modules\json-conversion\src\main\java\com\baeldung\jsontomap\FlattenUtils.java
| 1
|
请完成以下Java代码
|
public class SettThreadPoolExecutor {
private static final Log LOG = LogFactory.getLog(SettThreadPoolExecutor.class);
/**
* 针对核心Thread的Max比率 ,以10为基数,8表示0.8
*/
private int notifyRadio = 4;
/**
* 最少线程数.<br/>
* 当池子大小小于corePoolSize就新建线程,并处理请求.
*/
private int corePoolSize;
/**
* 线程池缓冲队列大小.<br/>
* 当池子大小等于corePoolSize,把请求放入workQueue中,池子里的空闲线程就去从workQueue中取任务并处理.
*/
private int workQueueSize;
/**
* 最大线程数.<br/>
* 当workQueue放不下新入的任务时,新建线程入池,并处理请求,<br/>
* 如果池子大小撑到了maximumPoolSize就用RejectedExecutionHandler来做拒绝处理.
*/
private int maxPoolSize;
/**
* 允许线程闲置时间,单位:秒.<br/>
* 当池子的线程数大于corePoolSize的时候,多余的线程会等待keepAliveTime长的时间,如果无请求可处理就自行销毁.
*/
private long keepAliveTime;
private ThreadPoolExecutor executor = null;
public void init() {
if (workQueueSize < 1) {
workQueueSize = 1000;
}
if (this.keepAliveTime < 1) {
this.keepAliveTime = 1000;
}
int coreSize = 0;
if (this.corePoolSize < 1) {
coreSize = Runtime.getRuntime().availableProcessors();
maxPoolSize = Math.round(((float) (coreSize * notifyRadio)) / 10);
corePoolSize = coreSize / 4;
if (corePoolSize < 1) {
corePoolSize = 1;
}
}
// NOTICE: corePoolSize不能大于maxPoolSize,否则会出错
if (maxPoolSize < corePoolSize) {
maxPoolSize = corePoolSize;
}
/**
* ThreadPoolExecutor就是依靠BlockingQueue的阻塞机制来维持线程池,当池子里的线程无事可干的时候就通过workQueue.take()阻塞住
*/
BlockingQueue<Runnable> notifyWorkQueue = new ArrayBlockingQueue<Runnable>(workQueueSize);
|
executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, notifyWorkQueue, new ThreadPoolExecutor.CallerRunsPolicy());
LOG.info("NotifyExecutor Info : CPU = " + coreSize +
" | corePoolSize = " + corePoolSize + " | maxPoolSize = " +
maxPoolSize + " | workQueueSize = " + workQueueSize);
}
public void destroy() {
executor.shutdownNow();
}
public void execute(Runnable command) {
executor.execute(command);
}
public void showExecutorInfo() {
LOG.info("NotifyExecutor Info : corePoolSize = " + corePoolSize +
" | maxPoolSize = " + maxPoolSize + " | workQueueSize = " +
workQueueSize + " | taskCount = " + executor.getTaskCount() +
" | activeCount = " + executor.getActiveCount() +
" | completedTaskCount = " + executor.getCompletedTaskCount());
}
public void setNotifyRadio(int notifyRadio) {
this.notifyRadio = notifyRadio;
}
public void setWorkQueueSize(int workQueueSize) {
this.workQueueSize = workQueueSize;
}
public void setKeepAliveTime(long keepAliveTime) {
this.keepAliveTime = keepAliveTime;
}
public void setCorePoolSize(int corePoolSize) {
this.corePoolSize = corePoolSize;
}
public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
}
|
repos\roncoo-pay-master\roncoo-pay-app-settlement\src\main\java\com\roncoo\pay\app\settlement\utils\SettThreadPoolExecutor.java
| 1
|
请完成以下Java代码
|
protected static void bulkDeleteHistoricTaskInstances(Collection<String> taskIds, CmmnEngineConfiguration cmmnEngineConfiguration) {
HistoricTaskService historicTaskService = cmmnEngineConfiguration.getTaskServiceConfiguration().getHistoricTaskService();
List<String> subTaskIds = historicTaskService.findHistoricTaskIdsByParentTaskIds(taskIds);
if (subTaskIds != null && !subTaskIds.isEmpty()) {
bulkDeleteHistoricTaskInstances(subTaskIds, cmmnEngineConfiguration);
}
cmmnEngineConfiguration.getVariableServiceConfiguration().getHistoricVariableService().bulkDeleteHistoricVariableInstancesByTaskIds(taskIds);
cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getHistoricIdentityLinkService().bulkDeleteHistoricIdentityLinksForTaskIds(taskIds);
historicTaskService.bulkDeleteHistoricTaskInstances(taskIds);
historicTaskService.bulkDeleteHistoricTaskLogEntriesForTaskIds(taskIds);
}
protected static Boolean getBoolean(Object booleanObject) {
if (booleanObject instanceof Boolean) {
return (Boolean) booleanObject;
}
if (booleanObject instanceof String) {
|
if ("true".equalsIgnoreCase((String) booleanObject)) {
return Boolean.TRUE;
}
if ("false".equalsIgnoreCase((String) booleanObject)) {
return Boolean.FALSE;
}
}
return null;
}
protected static void fireAssignmentEvents(TaskEntity taskEntity, CmmnEngineConfiguration cmmnEngineConfiguration) {
cmmnEngineConfiguration.getListenerNotificationHelper().executeTaskListeners(taskEntity, TaskListener.EVENTNAME_ASSIGNMENT);
FlowableEventDispatcher eventDispatcher = cmmnEngineConfiguration.getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableCmmnEventBuilder.createTaskAssignedEvent(taskEntity), cmmnEngineConfiguration.getEngineCfgKey());
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\task\TaskHelper.java
| 1
|
请完成以下Java代码
|
private static final class DateFieldValueExtractor implements FieldValueExtractor
{
private final String fieldName;
private final DocumentFieldWidgetType widgetType;
@Override
public String extractFieldValueToString(final Document document)
{
final Object fieldValue = document.getFieldView(fieldName).getValue();
if (fieldValue == null)
{
return null;
}
try
{
final java.util.Date date = TimeUtil.asDate(DateTimeConverters.fromObject(fieldValue, widgetType));
return DisplayType.getDateFormat(widgetType.getDisplayType())
.format(date);
}
catch (final Exception ex)
{
logger.warn("Failed formatting date field value '{}' ({}) using {}. Returning toString().", fieldValue, fieldValue.getClass(), this, ex);
return fieldValue.toString();
}
}
}
private static final class NumericFieldValueExtractor implements FieldValueExtractor
{
private final String fieldName;
private final String formatPattern;
private final int displayType;
private NumericFieldValueExtractor(final String fieldName, final DocumentFieldWidgetType widgetType, final String formatPattern)
{
this.fieldName = fieldName;
this.formatPattern = Check.isEmpty(formatPattern, true) ? null : formatPattern;
if (widgetType == DocumentFieldWidgetType.Integer)
{
displayType = DisplayType.Integer;
}
else if (widgetType == DocumentFieldWidgetType.Number)
{
displayType = DisplayType.Number;
}
else if (widgetType == DocumentFieldWidgetType.Amount)
{
displayType = DisplayType.Amount;
}
else if (widgetType == DocumentFieldWidgetType.Quantity)
{
displayType = DisplayType.Quantity;
}
else if (widgetType == DocumentFieldWidgetType.CostPrice)
{
displayType = DisplayType.CostPrice;
}
else
{
|
// shall not happen
displayType = DisplayType.Number;
}
}
@Override
public String getFieldName()
{
return fieldName;
}
@Override
public String extractFieldValueToString(final Document document)
{
final Object fieldValue = document.getFieldView(fieldName).getValue();
if (fieldValue == null)
{
return null;
}
try
{
return getDecimalFormat().format(fieldValue);
}
catch (final Exception ex)
{
logger.warn("Failed formatting date field value '{}' using {}. Returning toString().", fieldValue, this, ex);
return fieldValue.toString();
}
}
private DecimalFormat getDecimalFormat()
{
final Language language = Env.getLanguage(Env.getCtx());
return DisplayType.getNumberFormat(displayType, language, formatPattern);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\GenericDocumentSummaryValueProvider.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Collection<Foo> findAll() {
return myfoos.values();
}
@RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = { "application/json" })
@ResponseBody
public Foo findById(@PathVariable final long id) {
final Foo foo = myfoos.get(id);
if (foo == null) {
throw new ResourceNotFoundException();
}
return foo;
}
// API - write
@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) {
myfoos.put(id, foo);
return foo;
}
@RequestMapping(method = RequestMethod.PATCH, value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void updateFoo2(@PathVariable("id") final long id, @RequestBody final Foo foo) {
myfoos.put(id, foo);
}
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
|
@ResponseBody
public Foo createFoo(@RequestBody final Foo foo, HttpServletResponse response) {
myfoos.put(foo.getId(), foo);
response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentRequest()
.path("/" + foo.getId())
.toUriString());
return foo;
}
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void deleteById(@PathVariable final long id) {
myfoos.remove(id);
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-runtime\src\main\java\com\baeldung\sampleapp\web\controller\MyFooController.java
| 2
|
请完成以下Java代码
|
public void setAD_User_ID(final int AD_User_ID)
{
delegate.setAD_User_ID(AD_User_ID);
}
@Override
public String getBPartnerAddress()
{
return address;
}
@Override
public void setBPartnerAddress(String address)
{
this.address = address;
}
@Override
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentLocationAdapter.super.setRenderedAddress(from);
}
|
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public BPartnerLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new BPartnerLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_OLCand.class));
}
@Override
public I_C_OLCand getWrappedRecord()
{
return delegate;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\location\adapter\BPartnerLocationAdapter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserRpcServiceTest02 implements CommandLineRunner {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Resource
private UserRpcService userRpcService;
@Override
public void run(String... args) throws Exception {
// 获得用户
try {
// 发起调用
UserDTO user = userRpcService.get(null); // 故意传入空的编号,为了校验编号不通过
logger.info("[run][发起一次 Dubbo RPC 请求,获得用户为({})]", user);
} catch (Exception e) {
logger.error("[run][获得用户发生异常,信息为:[{}]", e.getMessage());
}
// 添加用户
try {
// 创建 UserAddDTO
UserAddDTO addDTO = new UserAddDTO();
addDTO.setName("yudaoyuanmayudaoyuanma"); // 故意把名字打的特别长,为了校验名字不通过
addDTO.setGender(null); // 不传递性别,为了校验性别不通过
// 发起调用
userRpcService.add(addDTO);
logger.info("[run][发起一次 Dubbo RPC 请求,添加用户为({})]", addDTO);
} catch (Exception e) {
logger.error("[run][添加用户发生异常,信息为:[{}]", e.getMessage());
}
}
}
@Component
public class UserRpcServiceTest03 implements CommandLineRunner {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Resource
private UserRpcService userRpcService;
|
@Override
public void run(String... args) {
// 添加用户
try {
// 创建 UserAddDTO
UserAddDTO addDTO = new UserAddDTO();
addDTO.setName("yudaoyuanma"); // 设置为 yudaoyuanma ,触发 ServiceException 异常
addDTO.setGender(1);
// 发起调用
userRpcService.add(addDTO);
logger.info("[run][发起一次 Dubbo RPC 请求,添加用户为({})]", addDTO);
} catch (Exception e) {
logger.error("[run][添加用户发生异常({}),信息为:[{}]", e.getClass().getSimpleName(), e.getMessage());
}
}
}
}
|
repos\SpringBoot-Labs-master\lab-30\lab-30-dubbo-xml-demo\user-rpc-service-consumer\src\main\java\cn\iocoder\springboot\lab30\rpc\ConsumerApplication.java
| 2
|
请完成以下Java代码
|
public int getReversalLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verworfene Menge.
@param ScrappedQty
Durch QA verworfene Menge
*/
public void setScrappedQty (BigDecimal ScrappedQty)
{
set_ValueNoCheck (COLUMNNAME_ScrappedQty, ScrappedQty);
}
/** Get Verworfene Menge.
@return Durch QA verworfene Menge
*/
public BigDecimal getScrappedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Zielmenge.
|
@param TargetQty
Zielmenge der Warenbewegung
*/
public void setTargetQty (BigDecimal TargetQty)
{
set_ValueNoCheck (COLUMNNAME_TargetQty, TargetQty);
}
/** Get Zielmenge.
@return Zielmenge der Warenbewegung
*/
public BigDecimal getTargetQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_M_InOutLine_Overview.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MainApplication {
private final BookstoreService bookstoreService;
public MainApplication(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
List<AuthorNameAge> authors = bookstoreService.fetchAuthorsNamesAndAges();
System.out.println("Number of authors:" + authors.size());
|
for (AuthorNameAge author : authors) {
System.out.println("Author name: " + author.getName()
+ " | Age: " + author.getAge());
}
System.out.println("============================================");
List<String> names = bookstoreService.fetchAuthorsNames();
System.out.println("Number of items:" + names.size());
System.out.println(names);
};
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoSpringProjectionAnnotatedNamedNativeQuery\src\main\java\com\bookstore\MainApplication.java
| 2
|
请完成以下Java代码
|
private void validateMember(Member member) throws ConstraintViolationException, ValidationException {
// Create a bean validator and check for issues.
Set<ConstraintViolation<Member>> violations = validator.validate(member);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(new HashSet<ConstraintViolation<?>>(violations));
}
// Check the uniqueness of the email address
if (emailAlreadyExists(member.getEmail())) {
throw new ValidationException("Unique Email Violation");
}
}
/**
* Creates a JAX-RS "Bad Request" response including a map of all violation fields, and their message. This can then be used
* by clients to show violations.
*
* @param violations A set of violations that needs to be reported
* @return JAX-RS response containing all violations
*/
private Response.ResponseBuilder createViolationResponse(Set<ConstraintViolation<?>> violations) {
log.fine("Validation completed. violations found: " + violations.size());
Map<String, String> responseObj = new HashMap<>();
for (ConstraintViolation<?> violation : violations) {
responseObj.put(violation.getPropertyPath().toString(), violation.getMessage());
}
return Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
|
}
/**
* Checks if a member with the same email address is already registered. This is the only way to easily capture the
* "@UniqueConstraint(columnNames = "email")" constraint from the Member class.
*
* @param email The email to check
* @return True if the email already exists, and false otherwise
*/
public boolean emailAlreadyExists(String email) {
Member member = null;
try {
member = repository.findByEmail(email);
} catch (NoResultException e) {
// ignore
}
return member != null;
}
}
|
repos\tutorials-master\persistence-modules\deltaspike\src\main\java\baeldung\rest\MemberResourceRESTService.java
| 1
|
请完成以下Java代码
|
public void setQRCode_Attribute_Config_ID (final int QRCode_Attribute_Config_ID)
{
if (QRCode_Attribute_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_QRCode_Attribute_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_QRCode_Attribute_Config_ID, QRCode_Attribute_Config_ID);
}
@Override
public int getQRCode_Attribute_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_QRCode_Attribute_Config_ID);
}
@Override
public I_QRCode_Configuration getQRCode_Configuration()
{
return get_ValueAsPO(COLUMNNAME_QRCode_Configuration_ID, I_QRCode_Configuration.class);
}
@Override
public void setQRCode_Configuration(final I_QRCode_Configuration QRCode_Configuration)
{
|
set_ValueFromPO(COLUMNNAME_QRCode_Configuration_ID, I_QRCode_Configuration.class, QRCode_Configuration);
}
@Override
public void setQRCode_Configuration_ID (final int QRCode_Configuration_ID)
{
if (QRCode_Configuration_ID < 1)
set_Value (COLUMNNAME_QRCode_Configuration_ID, null);
else
set_Value (COLUMNNAME_QRCode_Configuration_ID, QRCode_Configuration_ID);
}
@Override
public int getQRCode_Configuration_ID()
{
return get_ValueAsInt(COLUMNNAME_QRCode_Configuration_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_QRCode_Attribute_Config.java
| 1
|
请完成以下Java代码
|
/* package */boolean isRunDoItOutOfTransaction()
{
return runDoItOutOfTransaction;
}
/**
* @return <code>true</code> if at least a part of the process shall be executed out of transaction
*/
public boolean isRunOutOfTransaction()
{
return runPrepareOutOfTransaction || runDoItOutOfTransaction;
}
/**
* @return true if this process shall be executed on the same node where it was called.
* @see {@link ClientOnlyProcess}
*/
public boolean isClientOnly()
{
return clientOnly;
}
public boolean isParameterMandatory(final String parameterName, final boolean parameterTo)
{
return getParameterInfos(parameterName, parameterTo)
.stream()
.anyMatch(ProcessClassParamInfo::isMandatory);
}
public Collection<ProcessClassParamInfo> getParameterInfos()
{
return parameterInfos.values();
}
public List<ProcessClassParamInfo> getParameterInfos(final String parameterName, final boolean parameterTo)
{
return parameterInfos.get(ProcessClassParamInfo.createParameterUniqueKey(parameterName, parameterTo));
|
}
public List<ProcessClassParamInfo> getParameterInfos(final String parameterName)
{
final List<ProcessClassParamInfo> params = new ArrayList<>();
params.addAll(parameterInfos.get(ProcessClassParamInfo.createParameterUniqueKey(parameterName, false)));
params.addAll(parameterInfos.get(ProcessClassParamInfo.createParameterUniqueKey(parameterName, true)));
return params;
}
/**
* @return true if a current record needs to be selected when this process is called from gear/window.
* @see Process annotation
*/
public boolean isExistingCurrentRecordRequiredWhenCalledFromGear()
{
return existingCurrentRecordRequiredWhenCalledFromGear;
}
public boolean isAllowedForCurrentProfiles()
{
// No profiles restriction => allowed
if (onlyForProfiles == null || onlyForProfiles.length == 0)
{
return true;
}
// No application context => allowed (but warn)
final ApplicationContext context = SpringContextHolder.instance.getApplicationContext();
if (context == null)
{
logger.warn("No application context found to determine if {} is allowed for current profiles. Considering allowed", this);
return true;
}
return context.getEnvironment().acceptsProfiles(onlyForProfiles);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessClassInfo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@ApiModelProperty(example = "http://localhost:8182/repository/process-definitions/oneTaskProcess%3A1%3A4")
public String getProcessDefinitionUrl() {
return processDefinitionUrl;
}
public void setProcessDefinitionUrl(String processDefinitionUrl) {
this.processDefinitionUrl = processDefinitionUrl;
}
@ApiModelProperty(example = "3")
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@ApiModelProperty(example = "http://localhost:8182/history/historic-process-instances/3")
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
@ApiModelProperty(example = "4")
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@ApiModelProperty(example = "4")
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@ApiModelProperty(example = "null")
public String getCalledProcessInstanceId() {
return calledProcessInstanceId;
}
public void setCalledProcessInstanceId(String calledProcessInstanceId) {
this.calledProcessInstanceId = calledProcessInstanceId;
}
@ApiModelProperty(example = "fozzie")
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
|
@ApiModelProperty(example = "2013-04-17T10:17:43.902+0000")
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
@ApiModelProperty(example = "2013-04-18T14:06:32.715+0000")
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
@ApiModelProperty(example = "86400056")
public Long getDurationInMillis() {
return durationInMillis;
}
public void setDurationInMillis(Long durationInMillis) {
this.durationInMillis = durationInMillis;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricActivityInstanceResponse.java
| 2
|
请完成以下Java代码
|
private static void printBoard(Board board) {
StringBuilder topLines = new StringBuilder();
StringBuilder midLines = new StringBuilder();
for (int x = 0; x < board.getSize(); ++x) {
topLines.append("+--------");
midLines.append("| ");
}
topLines.append("+");
midLines.append("|");
for (int y = 0; y < board.getSize(); ++y) {
System.out.println(topLines);
System.out.println(midLines);
for (int x = 0; x < board.getSize(); ++x) {
Cell cell = new Cell(x, y);
System.out.print("|");
if (board.isEmpty(cell)) {
System.out.print(" ");
} else {
|
StringBuilder output = new StringBuilder(Integer.toString(board.getCell(cell)));
while (output.length() < 8) {
output.append(" ");
if (output.length() < 8) {
output.insert(0, " ");
}
}
System.out.print(output);
}
}
System.out.println("|");
System.out.println(midLines);
}
System.out.println(topLines);
System.out.println("Score: " + board.getScore());
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\play2048\Play2048.java
| 1
|
请完成以下Java代码
|
protected ListenableFuture<List<ReadTsKvQueryResult>> processFindAllAsync(TenantId tenantId, EntityId entityId, List<ReadTsKvQuery> queries) {
List<ListenableFuture<ReadTsKvQueryResult>> futures = queries
.stream()
.map(query -> findAllAsync(tenantId, entityId, query))
.collect(Collectors.toList());
return Futures.transform(Futures.allAsList(futures), new Function<>() {
@Nullable
@Override
public List<ReadTsKvQueryResult> apply(@Nullable List<ReadTsKvQueryResult> results) {
if (results == null || results.isEmpty()) {
return null;
}
return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
}
}, service);
}
|
protected long computeTtl(long ttl) {
if (systemTtl > 0) {
if (ttl == 0) {
ttl = systemTtl;
} else {
ttl = Math.min(systemTtl, ttl);
}
}
return ttl;
}
protected int getDataPointDays(TsKvEntry tsKvEntry, long ttl) {
return tsKvEntry.getDataPoints() * Math.max(1, (int) (ttl / SECONDS_IN_DAY));
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\AbstractSqlTimeseriesDao.java
| 1
|
请完成以下Java代码
|
public StatusEnum getStatus() {
return status;
}
public void setStatus(StatusEnum status) {
this.status = status;
}
public Order complete(Boolean complete) {
this.complete = complete;
return this;
}
/**
* Get complete
* @return complete
**/
@ApiModelProperty(value = "")
public Boolean getComplete() {
return complete;
}
public void setComplete(Boolean complete) {
this.complete = complete;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order order = (Order) o;
return Objects.equals(this.id, order.id) &&
Objects.equals(this.petId, order.petId) &&
Objects.equals(this.quantity, order.quantity) &&
Objects.equals(this.shipDate, order.shipDate) &&
Objects.equals(this.status, order.status) &&
Objects.equals(this.complete, order.complete);
}
@Override
public int hashCode() {
return Objects.hash(id, petId, quantity, shipDate, status, complete);
}
@Override
public String toString() {
|
StringBuilder sb = new StringBuilder();
sb.append("class Order {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" petId: ").append(toIndentedString(petId)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" complete: ").append(toIndentedString(complete)).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-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\Order.java
| 1
|
请完成以下Java代码
|
public Timestamp getCreated() {
return po.getCreated(); // getCreated
}
/**
* Get Updated
* @return updated
*/
public Timestamp getUpdated() {
return po.getUpdated(); // getUpdated
}
/**
* Get CreatedBy
* @return AD_User_ID
*/
public int getCreatedBy() {
return po.getCreatedBy(); // getCreateddBy
}
/**
* Get UpdatedBy
* @return AD_User_ID
*/
public int getUpdatedBy() {
return po.getUpdatedBy(); // getUpdatedBy
}
/**************************************************************************
* Update Value or create new record.
* To reload call load() - not updated
* @return true if saved
*/
public boolean save() {
return po.save(); // save
}
/**
* Update Value or create new record.
* To reload call load() - not updated
* @param trxName transaction
* @return true if saved
*/
public boolean save(String trxName) {
return po.save(trxName); // save
}
/**
* Is there a Change to be saved?
* @return true if record changed
*/
public boolean is_Changed() {
return po.is_Changed(); // is_Change
}
/**
* Create Single/Multi Key Where Clause
* @param withValues if true uses actual values otherwise ?
* @return where clause
*/
public String get_WhereClause(boolean withValues) {
return po.get_WhereClause(withValues); // getWhereClause
}
/**************************************************************************
* Delete Current Record
|
* @param force delete also processed records
* @return true if deleted
*/
public boolean delete(boolean force) {
return po.delete(force); // delete
}
/**
* Delete Current Record
* @param force delete also processed records
* @param trxName transaction
*/
public boolean delete(boolean force, String trxName) {
return po.delete(force, trxName); // delete
}
/**************************************************************************
* Lock it.
* @return true if locked
*/
public boolean lock() {
return po.lock(); // lock
}
/**
* UnLock it
* @return true if unlocked (false only if unlock fails)
*/
public boolean unlock(String trxName) {
return po.unlock(trxName); // unlock
}
/**
* Set Trx
* @param trxName transaction
*/
public void set_TrxName(String trxName) {
po.set_TrxName(trxName); // setTrx
}
/**
* Get Trx
* @return transaction
*/
public String get_TrxName() {
return po.get_TrxName(); // getTrx
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\wrapper\AbstractPOWrapper.java
| 1
|
请完成以下Java代码
|
public Currency getByCurrencyCode(@NonNull final CurrencyCode currencyCode)
{
Adempiere.assertUnitTestMode();
return getOrCreateByCurrencyCode(currencyCode);
}
public Currency getOrCreateByCurrencyCode(@NonNull final CurrencyCode currencyCode)
{
Adempiere.assertUnitTestMode();
return getCurrenciesMap()
.getByCurrencyCodeIfExists(currencyCode)
.orElseGet(() -> createCurrency(currencyCode));
}
public static CurrencyId createCurrencyId(@NonNull final CurrencyCode currencyCode)
{
Adempiere.assertUnitTestMode();
return createCurrency(currencyCode).getId();
}
public static Currency createCurrency(@NonNull final CurrencyCode currencyCode)
{
Adempiere.assertUnitTestMode();
return prepareCurrency()
.currencyCode(currencyCode)
.build();
}
public static Currency createCurrency(
@NonNull final CurrencyCode currencyCode,
@NonNull final CurrencyPrecision precision)
{
Adempiere.assertUnitTestMode();
return prepareCurrency()
.currencyCode(currencyCode)
.precision(precision)
.build();
}
@Builder(builderMethodName = "prepareCurrency", builderClassName = "CurrencyBuilder")
private static Currency createCurrency(
@NonNull final CurrencyCode currencyCode,
@Nullable final CurrencyPrecision precision,
|
@Nullable final CurrencyId currencyId)
{
Adempiere.assertUnitTestMode();
final CurrencyPrecision precisionToUse = precision != null ? precision : CurrencyPrecision.TWO;
final I_C_Currency record = newInstanceOutOfTrx(I_C_Currency.class);
record.setISO_Code(currencyCode.toThreeLetterCode());
record.setCurSymbol(currencyCode.toThreeLetterCode());
record.setIsEuro(currencyCode.isEuro());
record.setStdPrecision(precisionToUse.toInt());
record.setCostingPrecision(precisionToUse.toInt() + 2);
if (currencyId != null)
{
record.setC_Currency_ID(currencyId.getRepoId());
}
else if (CurrencyCode.EUR.equals(currencyCode))
{
record.setC_Currency_ID(CurrencyId.EUR.getRepoId());
}
saveRecord(record);
POJOWrapper.enableStrictValues(record);
return toCurrency(record);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\impl\PlainCurrencyDAO.java
| 1
|
请完成以下Java代码
|
public DocumentIdsSelection getDocumentIdsToInvalidate(final TableRecordReferenceSet recordRefs)
{
return DocumentIdsSelection.EMPTY;
}
@Override
public void invalidateAll()
{
headerPropertiesHolder.setValue(null);
rowsHolder.setRows(viewDataService.retrieveRows(soTrx, filter));
}
public ViewHeaderProperties getHeaderProperties()
{
return headerPropertiesHolder.computeIfNull(this::computeHeaderProperties);
|
}
private ViewHeaderProperties computeHeaderProperties()
{
return ViewHeaderProperties.builder()
.group(ViewHeaderPropertiesGroup.builder()
.entry(ViewHeaderProperty.builder()
.caption(TranslatableStrings.adElementOrMessage("InvoiceOpenAmt"))
.value(TranslatableStrings.amount(viewDataService.getInvoiceLineOpenAmount(invoiceAndLineId)))
.build())
.build())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoice\match_inout_costs\InOutCostsViewData.java
| 1
|
请完成以下Java代码
|
public void resetModelInterceptor(@NonNull final I_AD_Column column)
{
final String tableName = adTableDAO.retrieveTableName(column.getAD_Table_ID());
valRuleAutoApplierService.unregisterForTableName(tableName);
// createAndRegisterForQuery might add it again
engine.removeModelChange(tableName, autoApplyValRuleInterceptor);
tabCalloutFactory.unregisterTabCalloutForTable(tableName, AD_Column_AutoApplyValRuleTabCallout.class);
final IQueryBuilder<I_AD_Column> queryBuilder = createQueryBuilder()
.addEqualsFilter(I_AD_Column.COLUMNNAME_AD_Table_ID, column.getAD_Table_ID());
createAndRegisterForQuery(engine, queryBuilder.create());
}
private void createAndRegisterForQuery(
@NonNull final IModelValidationEngine engine,
@NonNull final IQuery<I_AD_Column> query)
{
final HashSet<String> tableNamesWithRegisteredColumn = new HashSet<>();
final ImmutableSet<AdColumnId> allColumnIds = query.idsAsSet(AdColumnId::ofRepoId);
final Collection<MinimalColumnInfo> allColumns = adTableDAO.getMinimalColumnInfosByIds(allColumnIds);
final ImmutableListMultimap<AdTableId, MinimalColumnInfo> tableId2columns = Multimaps.index(allColumns, MinimalColumnInfo::getAdTableId);
for (final AdTableId adTableId : tableId2columns.keySet())
{
final String tableName = adTableDAO.retrieveTableName(adTableId);
final Collection<MinimalColumnInfo> columns = tableId2columns.get(adTableId);
|
final ValRuleAutoApplier valRuleAutoApplier = ValRuleAutoApplier.builder()
.adTableDAO(adTableDAO)
.adReferenceService(adReferenceService)
.tableName(tableName)
.columns(columns)
.build();
valRuleAutoApplierService.registerApplier(valRuleAutoApplier);
tableNamesWithRegisteredColumn.add(tableName);
}
tableNamesWithRegisteredColumn
.forEach(tableNameWithRegisteredColum -> {
engine.addModelChange(tableNameWithRegisteredColum, autoApplyValRuleInterceptor);
tabCalloutFactory.registerTabCalloutForTable(tableNameWithRegisteredColum, AD_Column_AutoApplyValRuleTabCallout.class);
});
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\column\autoapplyvalrule\interceptor\AD_Column_AutoApplyValRuleConfig.java
| 1
|
请完成以下Java代码
|
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionCategory() {
return processDefinitionCategory;
}
public String getProcessDefinitionName() {
return processDefinitionName;
}
public Integer getProcessDefinitionVersion() {
return processDefinitionVersion;
}
public String getActivityId() {
return activityId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessInstanceIds() {
return null;
}
public String getBusinessKey() {
return businessKey;
}
public String getExecutionId() {
return executionId;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public String getSubProcessInstanceId() {
return subProcessInstanceId;
}
public boolean isExcludeSubprocesses() {
return excludeSubprocesses;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(SuspensionState suspensionState) {
this.suspensionState = suspensionState;
}
public List<EventSubscriptionQueryValue> getEventSubscriptions() {
return eventSubscriptions;
}
public boolean isIncludeChildExecutionsWithBusinessKeyQuery() {
return includeChildExecutionsWithBusinessKeyQuery;
}
public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) {
this.eventSubscriptions = eventSubscriptions;
}
public boolean isActive() {
return isActive;
}
|
public String getInvolvedUser() {
return involvedUser;
}
public void setInvolvedUser(String involvedUser) {
this.involvedUser = involvedUser;
}
public Set<String> getProcessDefinitionIds() {
return processDefinitionIds;
}
public Set<String> getProcessDefinitionKeys() {
return processDefinitionKeys;
}
public String getParentId() {
return parentId;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public void setName(String name) {
this.name = name;
}
public void setNameLike(String nameLike) {
this.nameLike = nameLike;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) {
this.nameLikeIgnoreCase = nameLikeIgnoreCase;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ExecutionQueryImpl.java
| 1
|
请完成以下Java代码
|
public List<EventDefinition> findEventDefinitionsByQueryCriteria(EventDefinitionQueryImpl eventQuery) {
return dataManager.findEventDefinitionsByQueryCriteria(eventQuery);
}
@Override
public long findEventDefinitionCountByQueryCriteria(EventDefinitionQueryImpl eventQuery) {
return dataManager.findEventDefinitionCountByQueryCriteria(eventQuery);
}
@Override
public EventDefinitionEntity findEventDefinitionByDeploymentAndKey(String deploymentId, String eventDefinitionKey) {
return dataManager.findEventDefinitionByDeploymentAndKey(deploymentId, eventDefinitionKey);
}
@Override
public EventDefinitionEntity findEventDefinitionByDeploymentAndKeyAndTenantId(String deploymentId, String eventDefinitionKey, String tenantId) {
return dataManager.findEventDefinitionByDeploymentAndKeyAndTenantId(deploymentId, eventDefinitionKey, tenantId);
}
@Override
public EventDefinitionEntity findLatestEventDefinitionByKeyAndTenantId(String eventDefinitionKey, String tenantId) {
if (tenantId == null || EventRegistryEngineConfiguration.NO_TENANT_ID.equals(tenantId)) {
return dataManager.findLatestEventDefinitionByKey(eventDefinitionKey);
} else {
return dataManager.findLatestEventDefinitionByKeyAndTenantId(eventDefinitionKey, tenantId);
}
}
@Override
public EventDefinitionEntity findEventDefinitionByKeyAndVersionAndTenantId(String eventDefinitionKey, Integer eventVersion, String tenantId) {
if (tenantId == null || EventRegistryEngineConfiguration.NO_TENANT_ID.equals(tenantId)) {
return dataManager.findEventDefinitionByKeyAndVersion(eventDefinitionKey, eventVersion);
} else {
return dataManager.findEventDefinitionByKeyAndVersionAndTenantId(eventDefinitionKey, eventVersion, tenantId);
}
}
|
@Override
public List<EventDefinition> findEventDefinitionsByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findEventDefinitionsByNativeQuery(parameterMap);
}
@Override
public long findEventDefinitionCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findEventDefinitionCountByNativeQuery(parameterMap);
}
@Override
public void updateEventDefinitionTenantIdForDeployment(String deploymentId, String newTenantId) {
dataManager.updateEventDefinitionTenantIdForDeployment(deploymentId, newTenantId);
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\EventDefinitionEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
public Builder setProcessed(final boolean processed)
{
this.processed = processed;
return this;
}
private boolean isProcessed()
{
if (processed == null)
{
// NOTE: don't take the "Processed" field if any, because in frontend we will end up with a lot of grayed out completed sales orders, for example.
// return DisplayType.toBoolean(values.getOrDefault("Processed", false));
return false;
}
else
{
return processed.booleanValue();
}
}
public Builder putFieldValue(final String fieldName, @Nullable final Object jsonValue)
{
if (jsonValue == null || JSONNullValue.isNull(jsonValue))
{
values.remove(fieldName);
}
else
{
values.put(fieldName, jsonValue);
}
return this;
}
private Map<String, Object> getValues()
{
return values;
}
public LookupValue getFieldValueAsLookupValue(final String fieldName)
{
return LookupValue.cast(values.get(fieldName));
}
public Builder addIncludedRow(final IViewRow includedRow)
{
|
if (includedRows == null)
{
includedRows = new ArrayList<>();
}
includedRows.add(includedRow);
return this;
}
private List<IViewRow> buildIncludedRows()
{
if (includedRows == null || includedRows.isEmpty())
{
return ImmutableList.of();
}
return ImmutableList.copyOf(includedRows);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRow.java
| 1
|
请完成以下Java代码
|
public class Document {
private int id;
private String title;
private String text;
private Date modificationTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
|
return text;
}
public void setText(String text) {
this.text = text;
}
public Date getModificationTime() {
return modificationTime;
}
public void setModificationTime(Date modificationTime) {
this.modificationTime = modificationTime;
}
}
|
repos\tutorials-master\mapstruct\src\main\java\com\baeldung\unmappedproperties\entity\Document.java
| 1
|
请完成以下Java代码
|
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public int getRetries() {
return retries;
}
public void setRetries(int retries) {
this.retries = retries;
}
public int getMaxIterations() {
return maxIterations;
}
public void setMaxIterations(int maxIterations) {
this.maxIterations = maxIterations;
}
public String getRepeat() {
return repeat;
}
public void setRepeat(String repeat) {
this.repeat = repeat;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dueDate == null) ? 0 : dueDate.hashCode());
result = prime * result + ((endDate == null) ? 0 : endDate.hashCode());
result = prime * result + ((exceptionMessage == null) ? 0 : exceptionMessage.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
|
result = prime * result + maxIterations;
result = prime * result + ((repeat == null) ? 0 : repeat.hashCode());
result = prime * result + retries;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
TimerPayload other = (TimerPayload) obj;
if (dueDate == null) {
if (other.dueDate != null) return false;
} else if (!dueDate.equals(other.dueDate)) return false;
if (endDate == null) {
if (other.endDate != null) return false;
} else if (!endDate.equals(other.endDate)) return false;
if (exceptionMessage == null) {
if (other.exceptionMessage != null) return false;
} else if (!exceptionMessage.equals(other.exceptionMessage)) return false;
if (id == null) {
if (other.id != null) return false;
} else if (!id.equals(other.id)) return false;
if (maxIterations != other.maxIterations) return false;
if (repeat == null) {
if (other.repeat != null) return false;
} else if (!repeat.equals(other.repeat)) return false;
if (retries != other.retries) return false;
return true;
}
}
|
repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\TimerPayload.java
| 1
|
请完成以下Java代码
|
public final class AdMessageKey
{
@JsonCreator
public static AdMessageKey of(@NonNull final String value)
{
return new AdMessageKey(value);
}
@Nullable
public static AdMessageKey ofNullable(@Nullable final String value)
{
return value != null && Check.isNotBlank(value) ? of(value) : null;
}
private final String value;
private AdMessageKey(final String value)
{
Check.assumeNotEmpty(value, "value is not empty");
this.value = value;
}
|
@Override
public String toString()
{
return toAD_Message();
}
@JsonValue
public String toAD_Message()
{
return value;
}
public String toAD_MessageWithMarkers()
{
return "@" + toAD_Message() + "@";
}
public boolean startsWith(final String prefix) {return value.startsWith(prefix);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\AdMessageKey.java
| 1
|
请完成以下Java代码
|
public String getJobDefinitionId() {
return jobDefinitionId;
}
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
|
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getExternalTaskId() {
return externalTaskId;
}
public void setExternalTaskId(String externalTaskId) {
this.externalTaskId = externalTaskId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContextEntry.java
| 1
|
请完成以下Java代码
|
public void setIsInclude (boolean IsInclude)
{
set_Value (COLUMNNAME_IsInclude, Boolean.valueOf(IsInclude));
}
/** Get Included.
@return Defines whether this content / template is included into another one
*/
public boolean isInclude ()
{
Object oo = get_Value(COLUMNNAME_IsInclude);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Printed.
@param IsPrinted
Indicates if this document / line is printed
*/
public void setIsPrinted (boolean IsPrinted)
{
set_Value (COLUMNNAME_IsPrinted, Boolean.valueOf(IsPrinted));
}
/** Get Printed.
@return Indicates if this document / line is printed
*/
public boolean isPrinted ()
{
Object oo = get_Value(COLUMNNAME_IsPrinted);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
|
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_PayrollConcept.java
| 1
|
请完成以下Java代码
|
public void generateNewDocument() {
try {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("XMLTutorials");
Element tutorialElement = root.addElement("tutorial").addAttribute("tutId", "01");
tutorialElement.addAttribute("type", "xml");
tutorialElement.addElement("title").addText("XML with Dom4J");
tutorialElement.addElement("description").addText("XML handling with Dom4J");
tutorialElement.addElement("date").addText("14/06/2016");
tutorialElement.addElement("author").addText("Dom4J tech writer");
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_dom4j_new.xml")), format);
|
writer.write(document);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
|
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\Dom4JParser.java
| 1
|
请完成以下Java代码
|
public boolean isAllowInfiniteCapacity()
{
return allowInfiniteCapacity;
}
@Override
public void setAllowInfiniteCapacity(final boolean allowInfiniteCapacity)
{
this.allowInfiniteCapacity = allowInfiniteCapacity;
}
@Override
public boolean isAllowAnyPartner()
{
return allowAnyPartner;
}
@Override
public void setAllowAnyPartner(final boolean allowAnyPartner)
{
|
this.allowAnyPartner = allowAnyPartner;
}
@Override
public int getM_Product_Packaging_ID()
{
return packagingProductId;
}
@Override
public void setM_Product_Packaging_ID(final int packagingProductId)
{
this.packagingProductId = packagingProductId > 0 ? packagingProductId : -1;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductQuery.java
| 1
|
请完成以下Java代码
|
public void onReactivate(@NonNull final I_PP_Product_BOM productBOMRecord)
{
final ProductBOMId productBOMId = ProductBOMId.ofRepoId(productBOMRecord.getPP_Product_BOM_ID());
if (isBOMInUse(productBOMId))
{
throw new AdempiereException("Product BOM is already in use (linked to a manufacturing order or candidate). It cannot be reactivated!")
.appendParametersToMessage()
.setParameter("productBOMId", productBOMId);
}
}
private boolean isBOMInUse(@NonNull final ProductBOMId productBOMId)
{
return !EmptyUtil.isEmpty(ppOrderCandidateDAO.getByProductBOMId(productBOMId))
|| !EmptyUtil.isEmpty(ppOrderDAO.getByProductBOMId(productBOMId));
}
private void updateBOMOnMatchingOrderCandidates(
@NonNull final ProductBOMId previousBOMVersionID,
|
@NonNull final I_PP_Product_BOM productBOMRecord)
{
ppOrderCandidateDAO.getByProductBOMId(previousBOMVersionID)
.stream()
.filter(ppOrderCandidate -> PPOrderCandidateService.canAssignBOMVersion(ppOrderCandidate, productBOMRecord))
.peek(ppOrderCandidate -> ppOrderCandidate.setPP_Product_BOM_ID(productBOMRecord.getPP_Product_BOM_ID()))
.forEach(ppOrderCandidateDAO::save);
}
private boolean shouldUpdateExistingPPOrderCandidates(@NonNull final I_PP_Product_BOM currentVersion, @NonNull final I_PP_Product_BOM oldVersion)
{
final AttributeSetInstanceId orderLineCandidateASIId = AttributeSetInstanceId.ofRepoIdOrNull(currentVersion.getM_AttributeSetInstance_ID());
final AttributeSetInstanceId productBOMLineASIId = AttributeSetInstanceId.ofRepoIdOrNull(oldVersion.getM_AttributeSetInstance_ID());
return asiBL.nullSafeASIEquals(orderLineCandidateASIId, productBOMLineASIId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\model\interceptor\PP_Product_BOM.java
| 1
|
请完成以下Java代码
|
public void restoreConstraints()
{
final Thread callingThread = Thread.currentThread();
try (final CloseableReentrantLock lock = thread2TrxConstraintLock.open())
{
final Deque<ITrxConstraints> stack = thread2TrxConstraint.get(callingThread);
if (stack == null)
{
// There are no constraints for the calling thread.
// In other words, getConstraints() hasn't been called yet.
// Consequently there is nothing to restore.
return;
}
Check.assume(!stack.isEmpty(), "Stack for thread " + callingThread + " is not empty");
|
if (stack.size() <= 1)
{
// there is only the current constraint instance, but no saved instance.
// Consequently there is nothing to restore.
return;
}
stack.pop();
}
}
@Override
public boolean isDisabled(ITrxConstraints constraints)
{
return constraints instanceof TrxConstraintsDisabled;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\TrxConstraintsBL.java
| 1
|
请完成以下Java代码
|
private void loadUIWindowHeaderNotice()
{
final LoginContext ctx = getCtx();
final ClientId clientId = ctx.getClientId();
final OrgId orgId = ctx.getOrgId();
final String windowHeaderNoticeText = sysConfigBL.getValue(SYSCONFIG_UI_WindowHeader_Notice_Text, clientId.getRepoId(), orgId.getRepoId());
ctx.setProperty(Env.CTXNAME_UI_WindowHeader_Notice_Text, windowHeaderNoticeText);
// FRESH-352: also allow setting the status message's foreground and background color.
final String windowHeaderBackgroundColor = sysConfigBL.getValue(SYSCONFIG_UI_WindowHeader_Notice_BG_Color, clientId.getRepoId(), orgId.getRepoId());
ctx.setProperty(Env.CTXNAME_UI_WindowHeader_Notice_BG_COLOR, windowHeaderBackgroundColor);
final String windowHeaderForegroundColor = sysConfigBL.getValue(SYSCONFIG_UI_WindowHeader_Notice_FG_Color, clientId.getRepoId(), orgId.getRepoId());
ctx.setProperty(Env.CTXNAME_UI_WindowHeader_Notice_FG_COLOR, windowHeaderForegroundColor);
}
public void setRemoteAddr(final String remoteAddr)
{
getCtx().setRemoteAddr(remoteAddr);
}
// RemoteAddr
public void setRemoteHost(final String remoteHost)
|
{
getCtx().setRemoteHost(remoteHost);
}
// RemoteHost
public void setWebSessionId(final String webSessionId)
{
getCtx().setWebSessionId(webSessionId);
}
public boolean isAllowLoginDateOverride()
{
return getCtx().isAllowLoginDateOverride();
}
} // Login
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Login.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getRootScopeId() {
return rootScopeId;
}
public String getRootScopeType() {
return rootScopeType;
}
public String getLinkType() {
return linkType;
}
public String getHierarchyType() {
return hierarchyType;
}
// This method is needed because we have a different way of querying list and single objects via MyBatis.
// Querying lists wraps the object in a ListQueryParameterObject
public InternalEntityLinkQueryImpl<E> getParameter() {
return this;
}
@Override
public boolean isRetained(E entity, Object param) {
return isRetained(entity, (InternalEntityLinkQueryImpl<?>) param);
}
@Override
public boolean isRetained(Collection<E> databaseEntities, Collection<CachedEntity> cachedEntities, E entity, Object param) {
return isRetained(entity, (InternalEntityLinkQueryImpl<?>) param);
}
public boolean isRetained(E entity, InternalEntityLinkQueryImpl<?> param) {
if (param.scopeId != null && !param.scopeId.equals(entity.getScopeId())) {
return false;
}
if (param.scopeIds != null && !param.scopeIds.contains(entity.getScopeId())) {
return false;
}
if (param.scopeDefinitionId != null && !param.scopeDefinitionId.equals(entity.getScopeDefinitionId())) {
return false;
}
if (param.scopeType != null && !param.scopeType.equals(entity.getScopeType())) {
return false;
}
if (param.referenceScopeId != null && !param.referenceScopeId.equals(entity.getReferenceScopeId())) {
return false;
}
if (param.referenceScopeDefinitionId != null && !param.referenceScopeDefinitionId.equals(entity.getReferenceScopeDefinitionId())) {
return false;
}
|
if (param.referenceScopeType != null && !param.referenceScopeType.equals(entity.getReferenceScopeType())) {
return false;
}
if (param.rootScopeId != null && !param.rootScopeId.equals(entity.getRootScopeId())) {
return false;
}
if (param.rootScopeType != null && !param.rootScopeType.equals(entity.getRootScopeType())) {
return false;
}
if (param.linkType != null && !param.linkType.equals(entity.getLinkType())) {
return false;
}
if (param.hierarchyType != null && !param.hierarchyType.equals(entity.getHierarchyType())) {
return false;
}
return true;
}
}
|
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\InternalEntityLinkQueryImpl.java
| 2
|
请完成以下Java代码
|
public void parseRootElement(Element rootElement, List<ProcessDefinitionEntity> processDefinitions) {
}
@Override
public void parseIntermediateTimerEventDefinition(Element timerEventDefinition, ActivityImpl timerActivity) {
addStartEventListener(timerActivity);
addEndEventListener(timerActivity);
}
@Override
public void parseReceiveTask(Element receiveTaskElement, ScopeImpl scope, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
}
@Override
public void parseIntermediateSignalCatchEventDefinition(Element signalEventDefinition, ActivityImpl signalActivity) {
addStartEventListener(signalActivity);
addEndEventListener(signalActivity);
}
@Override
public void parseBoundarySignalEventDefinition(Element signalEventDefinition, boolean interrupting, ActivityImpl signalActivity) {
addStartEventListener(signalActivity);
addEndEventListener(signalActivity);
}
@Override
public void parseEventBasedGateway(Element eventBasedGwElement, ScopeImpl scope, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
}
@Override
public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
}
@Override
public void parseCompensateEventDefinition(Element compensateEventDefinition, ActivityImpl compensationActivity) {
}
@Override
public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
}
@Override
public void parseIntermediateCatchEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
}
@Override
public void parseBoundaryEvent(Element boundaryEventElement, ScopeImpl scopeElement, ActivityImpl nestedActivity) {
}
@Override
|
public void parseIntermediateMessageCatchEventDefinition(Element messageEventDefinition, ActivityImpl nestedActivity) {
}
@Override
public void parseBoundaryMessageEventDefinition(Element element, boolean interrupting, ActivityImpl messageActivity) {
}
@Override
public void parseBoundaryEscalationEventDefinition(Element escalationEventDefinition, boolean interrupting, ActivityImpl boundaryEventActivity) {
}
@Override
public void parseBoundaryConditionalEventDefinition(Element element, boolean interrupting, ActivityImpl conditionalActivity) {
}
@Override
public void parseIntermediateConditionalEventDefinition(Element conditionalEventDefinition, ActivityImpl conditionalActivity) {
}
@Override
public void parseConditionalStartEventForEventSubprocess(Element element, ActivityImpl conditionalActivity, boolean interrupting) {
}
@Override
public void parseIoMapping(Element extensionElements, ActivityImpl activity, IoMapping inputOutput) {
}
}
|
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\event\CdiEventSupportBpmnParseListener.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Optional<IAttributeSetInstanceAware> getAttributeSetInstanceAware()
{
final Object referencedObj = getReferencedObject();
if (referencedObj == null)
{
return Optional.empty();
}
final IAttributeSetInstanceAwareFactoryService attributeSetInstanceAwareFactoryService = Services.get(IAttributeSetInstanceAwareFactoryService.class);
final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(referencedObj);
return Optional.ofNullable(asiAware);
}
@Override
public Quantity getQuantity()
{
final BigDecimal ctxQty = getQty();
|
if (ctxQty == null)
{
return null;
}
final UomId ctxUomId = getUomId();
if (ctxUomId == null)
{
return null;
}
return Quantitys.of(ctxQty, ctxUomId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PricingContext.java
| 2
|
请完成以下Java代码
|
public IQueryOrderByBuilder<T> addColumnAscending(@NonNull final String columnName)
{
final Direction direction = Direction.Ascending;
final Nulls nulls = getNulls(direction);
return addColumn(columnName, direction, nulls);
}
@Override
public IQueryOrderByBuilder<T> addColumnDescending(@NonNull final String columnName)
{
final Direction direction = Direction.Descending;
final Nulls nulls = getNulls(direction);
return addColumn(columnName, direction, nulls);
}
@Override
public IQueryOrderByBuilder<T> addColumn(
@NonNull final String columnName,
@NonNull final Direction direction,
@NonNull final Nulls nulls)
{
final QueryOrderByItem orderByItem = new QueryOrderByItem(columnName, direction, nulls);
orderBys.add(orderByItem);
return this;
}
@Override
public IQueryOrderByBuilder<T> addColumn(@NonNull final ModelColumn<T, ?> column, final Direction direction, final Nulls nulls)
{
final String columnName = column.getColumnName();
return addColumn(columnName, direction, nulls);
}
|
private Nulls getNulls(final Direction direction)
{
// NOTE: keeping backward compatibility
// i.e. postgresql 9.1. specifications:
// "By default, null values sort as if larger than any non-null value;
// that is, NULLS FIRST is the default for DESC order, and NULLS LAST otherwise."
//
// see https://www.postgresql.org/docs/9.5/queries-order.html
if (direction == Direction.Descending)
{
return Nulls.First;
}
else
{
return Nulls.Last;
}
}
@Override
public IQueryOrderBy createQueryOrderBy()
{
final QueryOrderBy orderBy = new QueryOrderBy(orderBys);
return orderBy;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryOrderByBuilder.java
| 1
|
请完成以下Java代码
|
public Model getModel(String modelId) {
return commandExecutor.execute(new GetModelCmd(modelId));
}
@Override
public byte[] getModelEditorSource(String modelId) {
return commandExecutor.execute(new GetModelEditorSourceCmd(modelId));
}
@Override
public byte[] getModelEditorSourceExtra(String modelId) {
return commandExecutor.execute(new GetModelEditorSourceExtraCmd(modelId));
}
@Override
public void addCandidateStarterUser(String processDefinitionId, String userId) {
commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null));
}
@Override
public void addCandidateStarterGroup(String processDefinitionId, String groupId) {
commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId));
}
@Override
public void deleteCandidateStarterGroup(String processDefinitionId, String groupId) {
commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId));
}
|
@Override
public void deleteCandidateStarterUser(String processDefinitionId, String userId) {
commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null));
}
@Override
public List<IdentityLink> getIdentityLinksForProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetIdentityLinksForProcessDefinitionCmd(processDefinitionId));
}
@Override
public List<ValidationError> validateProcess(BpmnModel bpmnModel) {
return commandExecutor.execute(new ValidateBpmnModelCmd(bpmnModel));
}
@Override
public List<DmnDecision> getDecisionsForProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetDecisionsForProcessDefinitionCmd(processDefinitionId));
}
@Override
public List<FormDefinition> getFormDefinitionsForProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetFormDefinitionsForProcessDefinitionCmd(processDefinitionId));
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\RepositoryServiceImpl.java
| 1
|
请完成以下Java代码
|
protected boolean isStopOnFailedRun()
{
return false;
}
private void restartExecutorsIfTerminated()
{
if (plannerExecutorService == null || plannerExecutorService.isTerminated())
{
plannerExecutorService = createPlannerThreadExecutor();
}
if (queueProcessorExecutorService == null || queueProcessorExecutorService.isTerminated())
{
queueProcessorExecutorService = createQueueProcessorThreadExecutor();
}
}
private static void shutdownExecutor(@NonNull final ExecutorService executor)
{
logger.info("shutdown - Shutdown started for executor={}", executor);
executor.shutdown();
int retryCount = 5;
boolean terminated = false;
while (!terminated && retryCount > 0)
{
logger.info("shutdown - waiting for executor to be terminated; retries left={}; executor={}", retryCount, executor);
try
{
terminated = executor.awaitTermination(5 * 1000, TimeUnit.MICROSECONDS);
}
catch (final InterruptedException e)
{
logger.warn("Failed shutting down executor for " + executor + ". Retry " + retryCount + " more times.");
terminated = false;
}
retryCount--;
}
executor.shutdownNow();
logger.info("Shutdown finished for executor: {}", executor);
}
|
@NonNull
private static ThreadPoolExecutor createPlannerThreadExecutor()
{
final CustomizableThreadFactory threadFactory = CustomizableThreadFactory.builder()
.setThreadNamePrefix("QueueProcessorPlanner")
.setDaemon(true)
.build();
return new ThreadPoolExecutor(
1, // corePoolSize
1, // maximumPoolSize
1000, // keepAliveTime
TimeUnit.MILLISECONDS, // timeUnit
new SynchronousQueue<>(), // workQueue
threadFactory, // threadFactory
new ThreadPoolExecutor.AbortPolicy());
}
@NonNull
private static ThreadPoolExecutor createQueueProcessorThreadExecutor()
{
final ThreadFactory threadFactory = CustomizableThreadFactory.builder()
.setThreadNamePrefix("QueueProcessor")
.setDaemon(true)
.build();
return new ThreadPoolExecutor(
1, // corePoolSize
100, // maximumPoolSize
1000, // keepAliveTime
TimeUnit.MILLISECONDS, // timeUnit
// SynchronousQueue has *no* capacity. Therefore, each new submitted task will directly cause a new thread to be started,
// which is exactly what we want here.
// Thank you, http://stackoverflow.com/questions/10186397/threadpoolexecutor-without-a-queue !!!
new SynchronousQueue<>(), // workQueue
threadFactory, // threadFactory
new ThreadPoolExecutor.AbortPolicy() // RejectedExecutionHandler
);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\planner\AsyncProcessorPlanner.java
| 1
|
请完成以下Java代码
|
public String getAmtInWords(String amount) throws Exception {
assert(amount!=null);
amount = amount.replaceAll(" ", "").replaceAll("\u00A0", "");
amount = amount.replaceAll("\\"+thousandseparator, "");
int pos = amount.lastIndexOf(wholeseparator);
String amountWhole;
String cents=null;
if(pos>=0)
{
amountWhole=amount.substring(0,pos);
cents=amount.substring(pos+1);
}
else
{
amountWhole=amount;
}
BigInteger num = new BigInteger(amountWhole);
StringBuilder ret=new StringBuilder();
if(num.compareTo(BigInteger.valueOf(0))<0)
{
num=num.negate();
ret.append("mínusz ");
}
boolean needDivisor=true;
if(num.compareTo(BigInteger.valueOf(2000))<0)
{
needDivisor=false;
}
List<Integer> pieces=new ArrayList<Integer>();
if(BigInteger.valueOf(0).equals(num))
{
return numbers[0];
}
while(num.compareTo(BigInteger.valueOf(0))>0)
{
BigInteger[] divAndMod=num.divideAndRemainder(BigInteger.valueOf(1000));
int mod=divAndMod[1].intValue();
num=divAndMod[0];
pieces.add(mod);
}
Collections.reverse(pieces);
boolean firstPiece=true;
for(int i=0;i<pieces.size();++i) {
int piece=pieces.get(i);
int weight=pieces.size()-i-1;
if(piece!=0||firstPiece)
{
if(!firstPiece&&needDivisor)
{
ret.append("-");
}
firstPiece=false;
ret.append(getAmtInWordsTo1000(piece));
if(majorNames.length>weight)
{
ret.append(majorNames[weight]);
}else
{
throw new NumberFormatException("number too big for converting amount to word"+amount);
}
}
}
if (cents!=null) {
ret.append(" egész ");
ret.append(getAmtInWords(cents));
ret.append(" század");
}
|
return ret.toString();
}
String[] numbers = new String[] { "nulla", "egy", "kettő", "három", "négy",
"öt", "hat", "hét", "nyolc", "kilenc" };
String[] tens_solo = new String[] { null, "tíz", "húsz", "harminc", "negyven",
"ötven", "hatvan", "hetven", "nyolcvan", "kilencven" };
String[] tens_connected = new String[] { null, "tizen", "huszon",
"harminc", "negyven", "ötven", "hatvan", "hetven", "nyolcvan",
"kilencven" };
String[] majorNames = { "", "ezer", "millió", "billió", "trillió",
"kvadrillió", "kvintillió" };
public String getAmtInWordsTo1000(int amount) {
StringBuilder ret = new StringBuilder();
int hundred = amount / 100;
int ten = (amount - (amount / 100)*100) / 10;
int one = (amount - (amount / 10)*10);
if (hundred != 0) {
if(hundred!=0)
{
ret.append(numbers[hundred]);
}
ret.append("száz");
}
if (ten != 0) {
if (one != 0) {
ret.append(tens_connected[ten]);
} else {
ret.append(tens_solo[ten]);
}
}
if (one != 0||(hundred==0&&ten==0)) {
ret.append(numbers[one]);
}
return ret.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\AmtInWords_HU.java
| 1
|
请完成以下Java代码
|
private IAllocationRequest createAllocationRequest(final I_M_ReceiptSchedule rs)
{
// Get Qty
final BigDecimal qty = getEffectiveQtyToReceive(rs);
if (qty.signum() <= 0)
{
// nothing to do
return null;
}
final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(rs.getAD_Client_ID(), rs.getAD_Org_ID());
final IMutableHUContext huContextInitial = Services.get(IHUContextFactory.class).createMutableHUContextForProcessing(getCtx(), clientAndOrgId);
final I_M_Product product = productDAO.getById(rs.getM_Product_ID());
final ClearanceStatus clearanceStatus = ClearanceStatus.ofNullableCode(product.getHUClearanceStatus());
final ClearanceStatusInfo clearanceStatusInfo;
if (clearanceStatus != null)
{
final String language = partnerOrgBL.getOrgLanguageOrLoggedInUserLanguage(clientAndOrgId.getOrgId());
clearanceStatusInfo = ClearanceStatusInfo.builder()
.clearanceStatus(clearanceStatus)
.clearanceNote(msgBL.getMsg(language, MESSAGE_ClearanceStatusInfo_Receipt))
.clearanceDate(InstantAndOrgId.ofInstant(SystemTime.asInstant(), clientAndOrgId.getOrgId()))
.build();
|
}
else
{
clearanceStatusInfo = null;
}
return AllocationUtils.builder()
.setHUContext(huContextInitial)
.setDateAsToday()
.setProduct(product)
.setQuantity(new Quantity(qty, loadOutOfTrx(rs.getC_UOM_ID(), I_C_UOM.class)))
.setFromReferencedModel(rs)
.setForceQtyAllocation(true)
.setClearanceStatusInfo(clearanceStatusInfo)
.create();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_ReceiveCUs.java
| 1
|
请完成以下Java代码
|
private void actionOK()
{
if (fCreateNew.isSelected())
{
// Get Warehouse Info
KeyNamePair pp = (KeyNamePair)fWarehouse.getSelectedItem();
if (pp != null)
loadWarehouseInfo(pp.getKey());
// Check mandatory values
String mandatoryFields = "";
if (m_M_Warehouse_ID == null)
{
mandatoryFields += lWarehouse.getText() + " - ";
}
if (fValue.getText().length()==0)
mandatoryFields += lValue.getText() + " - ";
if (fX.getText().length()==0)
mandatoryFields += lX.getText() + " - ";
if (fY.getText().length()==0)
mandatoryFields += lY.getText() + " - ";
if (fZ.getText().length()==0)
mandatoryFields += lZ.getText() + " - ";
if (mandatoryFields.length() != 0)
{
ADialog.error(m_WindowNo, this, "FillMandatory", mandatoryFields.substring(0, mandatoryFields.length()-3));
return;
}
final I_M_Locator locator = warehousesRepo.getOrCreateLocatorByCoordinates(m_M_Warehouse_ID,
fValue.getText(),
fX.getText(),
fY.getText(),
fZ.getText());
m_M_Locator_ID = locator.getM_Locator_ID();
final MLocator locatorPO = LegacyAdapters.convertToPO(locator);
fLocator.addItem(locatorPO);
fLocator.setSelectedItem(locatorPO);
} // createNew
//
log.info("M_Locator_ID=" + m_M_Locator_ID);
} // actionOK
|
/**
* Get Selected value
*
* @return value as Integer
*/
public Integer getValue()
{
MLocator l = getSelectedLocator();
if (l != null && l.getM_Locator_ID() != 0)
return new Integer(l.getM_Locator_ID());
return null;
} // getValue
/**
* Get result
*
* @return true if changed
*/
public boolean isChanged()
{
if (m_change)
{
MLocator l = getSelectedLocator();
if (l != null)
return l.getM_Locator_ID() == m_M_Locator_ID;
}
return m_change;
} // getChange
} // VLocatorDialog
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocatorDialog.java
| 1
|
请完成以下Java代码
|
public class Users implements Streamable<User> {
private final Streamable<User> userStreamable;
public Users(Streamable<User> userStreamable) {
this.userStreamable = userStreamable;
}
@Override
public Iterator<User> iterator() {
return userStreamable.iterator();
}
public Map<Long, User> getUserIdToUserMap() {
return stream().collect(Collectors.toMap(User::getId, Function.identity()));
|
}
public List<User> getAllUsersWithShortNames(int maxNameLength) {
return stream()
.filter(s -> s.getFirstName().length() <= maxNameLength)
.collect(Collectors.toList());
}
public Map<Character, List<User>> groupUsersAlphabetically() {
return stream().collect(Collectors.groupingBy(s -> getFristCharacter(s.getFirstName())));
}
private Character getFristCharacter(final String string) {
return string.substring(0, 1).toUpperCase().charAt(0);
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-query-4\src\main\java\com\baeldung\spring\data\jpa\querymap\Users.java
| 1
|
请完成以下Java代码
|
public void handleTransportError(WebSocketSession session, Throwable throwable) throws Exception {
logger.error("error occured at sender " + session, throwable);
}
/**
* 给所有的用户发送消息
*/
public void sendMessagesToUsers(TextMessage message) {
for (WebSocketSession user : sessions) {
try {
// isOpen()在线就发送
if (user.isOpen()) {
user.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
|
}
}
/**
* 发送消息给指定的用户
*/
private void sendMessageToUser(WebSocketSession user, TextMessage message) {
try {
// 在线就发送
if (user.isOpen()) {
user.sendMessage(message);
}
} catch (IOException e) {
logger.error("发送消息给指定的用户出错", e);
}
}
}
|
repos\SpringBootBucket-master\springboot-websocket\src\main\java\com\xncoding\jwt\handler\SocketHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Integer getPayModeCode() {
return payModeCode;
}
public void setPayModeCode(Integer payModeCode) {
this.payModeCode = payModeCode;
}
public String getExpressNo() {
return expressNo;
}
public void setExpressNo(String expressNo) {
this.expressNo = expressNo;
}
public String getBuyerId() {
return buyerId;
}
public void setBuyerId(String buyerId) {
this.buyerId = buyerId;
}
public String getSellerId() {
return sellerId;
}
public void setSellerId(String sellerId) {
this.sellerId = sellerId;
}
|
@Override
public String toString() {
return "OrderQueryReq{" +
"id='" + id + '\'' +
", buyerId='" + buyerId + '\'' +
", buyerName='" + buyerName + '\'' +
", buyerPhone='" + buyerPhone + '\'' +
", buyerMail='" + buyerMail + '\'' +
", sellerId='" + sellerId + '\'' +
", sellerCompanyName='" + sellerCompanyName + '\'' +
", sellerPhone='" + sellerPhone + '\'' +
", sellerMail='" + sellerMail + '\'' +
", orderStateCode=" + orderStateCode +
", placeOrderStartTime='" + placeOrderStartTime + '\'' +
", placeOrderEndTime='" + placeOrderEndTime + '\'' +
", recipientName='" + recipientName + '\'' +
", recipientPhone='" + recipientPhone + '\'' +
", recipientLocation='" + recipientLocation + '\'' +
", payModeCode=" + payModeCode +
", expressNo='" + expressNo + '\'' +
", page=" + page +
", numPerPage=" + numPerPage +
", currentPage=" + currentPage +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\order\OrderQueryReq.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class CityWebFluxController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping(value = "/{id}")
public Mono<City> findCityById(@PathVariable("id") Long id) {
String key = "city_" + id;
ValueOperations<String, City> operations = redisTemplate.opsForValue();
boolean hasKey = redisTemplate.hasKey(key);
City city = operations.get(key);
if (!hasKey) {
return Mono.create(monoSink -> monoSink.success(null));
}
return Mono.create(monoSink -> monoSink.success(city));
}
@PostMapping()
public Mono<City> saveCity(@RequestBody City city) {
|
String key = "city_" + city.getId();
ValueOperations<String, City> operations = redisTemplate.opsForValue();
operations.set(key, city, 60, TimeUnit.SECONDS);
return Mono.create(monoSink -> monoSink.success(city));
}
@DeleteMapping(value = "/{id}")
public Mono<Long> deleteCity(@PathVariable("id") Long id) {
String key = "city_" + id;
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
redisTemplate.delete(key);
}
return Mono.create(monoSink -> monoSink.success(id));
}
}
|
repos\springboot-learning-example-master\springboot-webflux-6-redis\src\main\java\org\spring\springboot\webflux\controller\CityWebFluxController.java
| 2
|
请完成以下Java代码
|
public int hash(String str, int groupSize, int maxValue) {
final int[] codes = this.toAsciiCodes(str);
return IntStream.range(0, str.length())
.filter(i -> i % groupSize == 0)
.mapToObj(i -> extract(codes, i, groupSize))
.map(block -> concatenate(block))
.reduce(0, (a, b) -> (a + b) % maxValue);
}
/**
* Returns a new array of given length whose elements are take from
* the original one starting from the offset.
*
* If the original array has not enough elements, the returning array will contain
* element from the offset till the end of the original array.
*
* @param numbers original array. Assume it is not null.
* @param offset index of the element to start from. Assume it is less than the size of the array
* @param length max size of the resulting array
* @return
*/
public int[] extract(int[] numbers, int offset, int length) {
final int defect = numbers.length - (offset + length);
final int s = defect < 0 ? length + defect : length;
int[] result = new int[s];
for (int index = 0; index < s; index++) {
result[index] = numbers[index + offset];
}
return result;
}
/**
|
* Concatenate the numbers into a single number as if they were strings.
* Assume that the procedure does not suffer from the overflow.
* @param numbers integers to concatenate
* @return
*/
public int concatenate(int[] numbers) {
final String merged = IntStream.of(numbers)
.mapToObj(number -> "" + number)
.collect(Collectors.joining());
return Integer.parseInt(merged, 10);
}
/**
* Convert the string into its characters' ASCII codes.
* @param str input string
* @return
*/
private int[] toAsciiCodes(String str) {
return str.chars()
.toArray();
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-3\src\main\java\com\baeldung\folding\FoldingHash.java
| 1
|
请完成以下Java代码
|
public Double getTotalOrderPrice() {
double sum = 0D;
List<OrderProduct> orderProducts = getOrderProducts();
for (OrderProduct op : orderProducts) {
sum += op.getTotalPrice();
}
return sum;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDate getDateCreated() {
return dateCreated;
}
public void setDateCreated(LocalDate dateCreated) {
this.dateCreated = dateCreated;
}
|
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<OrderProduct> getOrderProducts() {
return orderProducts;
}
public void setOrderProducts(List<OrderProduct> orderProducts) {
this.orderProducts = orderProducts;
}
@Transient
public int getNumberOfProducts() {
return this.orderProducts.size();
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\model\Order.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
application:
name: demo-consumer-application
cloud:
# Spring Cloud Stream 配置项,对应 BindingServiceProperties 类
stream:
# Binder 配置项,对应 BinderProperties Map
binders:
rabbit001:
type: rabbit # 设置 Binder 的类型
environment: # 设置 Binder 的环境配置
# 如果是 RabbitMQ 类型的时候,则对应的是 RabbitProperties 类
spring:
rabbitmq:
host: 127.0.0.1 # RabbitMQ 服务的地址
port: 5672 # RabbitMQ 服务的端口
username: guest # RabbitMQ 服务的账号
password: guest # RabbitMQ 服务的密码
# Binding 配置项,对应 BindingProperties Map
bindings:
demo01-input:
destination: DEMO-TOPIC-01 # 目的地。这里使用 RabbitMQ Exchange
content-type: application/json # 内容格式。这里使用 JSON
group: demo01-consumer-group-DEMO-TOPIC-01 # 消费者分组
|
binder: rabbit001 # 设置使用的 Binder 名字
# RabbitMQ 自定义 Binding 配置项,对应 RabbitBindingProperties Map
rabbit:
bindings:
demo01-input:
# RabbitMQ Consumer 配置项,对应 RabbitConsumerProperties 类
consumer:
acknowledge-mode: MANUAL # 消费消息的确认模式,默认为 AUTO 自动确认
server:
port: ${random.int[10000,19999]} # 随机端口,方便启动多个消费者
|
repos\SpringBoot-Labs-master\labx-10-spring-cloud-stream-rabbitmq\labx-10-sc-stream-rabbitmq-consumer-ack\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public DirectoryStream<Path> newDirectoryStream(Path dir, Filter<? super Path> filter) throws IOException {
throw new NotDirectoryException(NestedPath.cast(dir).toString());
}
@Override
public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException {
throw new ReadOnlyFileSystemException();
}
@Override
public void delete(Path path) throws IOException {
throw new ReadOnlyFileSystemException();
}
@Override
public void copy(Path source, Path target, CopyOption... options) throws IOException {
throw new ReadOnlyFileSystemException();
}
@Override
public void move(Path source, Path target, CopyOption... options) throws IOException {
throw new ReadOnlyFileSystemException();
}
@Override
public boolean isSameFile(Path path, Path path2) throws IOException {
return path.equals(path2);
}
@Override
public boolean isHidden(Path path) throws IOException {
return false;
}
@Override
public FileStore getFileStore(Path path) throws IOException {
NestedPath nestedPath = NestedPath.cast(path);
nestedPath.assertExists();
return new NestedFileStore(nestedPath.getFileSystem());
}
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException {
Path jarPath = getJarPath(path);
jarPath.getFileSystem().provider().checkAccess(jarPath, modes);
}
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
|
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().getFileAttributeView(jarPath, type, options);
}
@Override
public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options)
throws IOException {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().readAttributes(jarPath, type, options);
}
@Override
public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().readAttributes(jarPath, attributes, options);
}
protected Path getJarPath(Path path) {
return NestedPath.cast(path).getJarPath();
}
@Override
public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException {
throw new ReadOnlyFileSystemException();
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileSystemProvider.java
| 1
|
请完成以下Java代码
|
public Set<String> keySet() {
return variableScope.getVariables().keySet();
}
@Override
public int size() {
return variableScope.getVariables().size();
}
@Override
public Collection<Object> values() {
return variableScope.getVariables().values();
}
@Override
public void putAll(Map<? extends String, ? extends Object> toMerge) {
throw new UnsupportedOperationException();
}
@Override
public Object remove(Object key) {
if (UNSTORED_KEYS.contains(key)) {
return null;
}
|
return defaultBindings.remove(key);
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public boolean containsValue(Object value) {
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty() {
throw new UnsupportedOperationException();
}
public void addUnstoredKey(String unstoredKey) {
UNSTORED_KEYS.add(unstoredKey);
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\scripting\ScriptBindings.java
| 1
|
请完成以下Java代码
|
public ShipperMappingConfigList getByShipperId(@NonNull final ShipperId shipperId)
{
return getList().subsetOf(shipperId);
}
private ShipperMappingConfigList getList()
{
//noinspection DataFlowIssue
return cache.getOrLoad(0, this::retrieveList);
}
private ShipperMappingConfigList retrieveList()
{
return ShipperMappingConfigList.ofCollection(queryBL.createQueryBuilder(I_M_Shipper_Mapping_Config.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(ShipperMappingConfigRepository::fromRecord)
.collect(Collectors.toList()));
}
private static ShipperMappingConfig fromRecord(@NonNull final I_M_Shipper_Mapping_Config record)
|
{
return ShipperMappingConfig.builder()
.id(ShipperMappingConfigId.ofRepoId(record.getM_Shipper_Mapping_Config_ID()))
.shipperId(ShipperId.ofRepoId(record.getM_Shipper_ID()))
.seqNo(SeqNo.ofInt(record.getSeqNo()))
.carrierProductId(CarrierProductId.ofRepoIdOrNull(record.getCarrier_Product_ID()))
.attributeType(AttributeType.ofCode(record.getMappingAttributeType()))
.attributeKey(record.getMappingAttributeKey())
.attributeValue(AttributeValue.ofCode(record.getMappingAttributeValue()))
.groupKey(record.getMappingGroupKey())
.mappingRule(MappingRule.ofNullableCode(record.getMappingRule()))
.mappingRuleValue(record.getMappingRuleValue())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\mapping\ShipperMappingConfigRepository.java
| 1
|
请完成以下Java代码
|
public List<HistoricExternalTaskLogDto> queryHistoricExternalTaskLogs(HistoricExternalTaskLogQueryDto queryDto, Integer firstResult, Integer maxResults) {
queryDto.setObjectMapper(objectMapper);
HistoricExternalTaskLogQuery query = queryDto.toQuery(processEngine);
List<HistoricExternalTaskLog> matchingHistoricExternalTaskLogs = QueryUtil.list(query, firstResult, maxResults);
List<HistoricExternalTaskLogDto> results = new ArrayList<HistoricExternalTaskLogDto>();
for (HistoricExternalTaskLog historicExternalTaskLog : matchingHistoricExternalTaskLogs) {
HistoricExternalTaskLogDto result = HistoricExternalTaskLogDto.fromHistoricExternalTaskLog(historicExternalTaskLog);
results.add(result);
}
return results;
}
@Override
public CountResultDto getHistoricExternalTaskLogsCount(UriInfo uriInfo) {
HistoricExternalTaskLogQueryDto queryDto = new HistoricExternalTaskLogQueryDto(objectMapper, uriInfo.getQueryParameters());
|
return queryHistoricExternalTaskLogsCount(queryDto);
}
@Override
public CountResultDto queryHistoricExternalTaskLogsCount(HistoricExternalTaskLogQueryDto queryDto) {
queryDto.setObjectMapper(objectMapper);
HistoricExternalTaskLogQuery query = queryDto.toQuery(processEngine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricExternalTaskLogRestServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AsyncBatchNotifyRequest
{
@JsonProperty("clientId")
@NonNull
ClientId clientId;
@JsonProperty("asyncBatchId")
@NonNull
Integer asyncBatchId;
@JsonProperty("noOfProcessedWPs")
@NonNull
Integer noOfProcessedWPs;
@JsonProperty("noOfErrorWPs")
@NonNull
Integer noOfErrorWPs;
@JsonProperty("noOfEnqueuedWPs")
|
@NonNull
Integer noOfEnqueuedWPs;
@JsonCreator
@Builder
public AsyncBatchNotifyRequest(
@JsonProperty("clientId") @NonNull final ClientId clientId,
@JsonProperty("asyncBatchId") @NonNull final Integer asyncBatchId,
@JsonProperty("noOfProcessedWPs") @NonNull final Integer noOfProcessedWPs,
@JsonProperty("noOfErrorWPs") @NonNull final Integer noOfErrorWPs,
@JsonProperty("noOfEnqueuedWPs") @NonNull final Integer noOfEnqueuedWPs)
{
this.clientId = clientId;
this.asyncBatchId = asyncBatchId;
this.noOfProcessedWPs = noOfProcessedWPs;
this.noOfErrorWPs = noOfErrorWPs;
this.noOfEnqueuedWPs = noOfEnqueuedWPs;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\eventbus\AsyncBatchNotifyRequest.java
| 2
|
请完成以下Java代码
|
private void updatePaymentByIndex(final int paymentIndex, @NonNull final UnaryOperator<POSPayment> updater)
{
final POSPayment payment = paymentIndex >= 0 ? payments.get(paymentIndex) : null;
final POSPayment paymentChanged = updater.apply(payment);
if (paymentIndex >= 0)
{
payments.set(paymentIndex, paymentChanged);
}
else
{
payments.add(paymentChanged);
}
updateTotals();
}
private int getPaymentIndexById(final @NonNull POSPaymentId posPaymentId)
{
for (int i = 0; i < payments.size(); i++)
{
if (POSPaymentId.equals(payments.get(i).getLocalId(), posPaymentId))
{
return i;
}
}
throw new AdempiereException("No payment found for " + posPaymentId + " in " + payments);
}
private OptionalInt getPaymentIndexByExternalId(final @NonNull POSPaymentExternalId externalId)
{
for (int i = 0; i < payments.size(); i++)
{
if (POSPaymentExternalId.equals(payments.get(i).getExternalId(), externalId))
{
return OptionalInt.of(i);
}
}
return OptionalInt.empty();
}
|
public void removePaymentsIf(@NonNull final Predicate<POSPayment> predicate)
{
updateAllPayments(payment -> {
// skip payments marked as DELETED
if (payment.isDeleted())
{
return payment;
}
if (!predicate.test(payment))
{
return payment;
}
if (payment.isAllowDeleteFromDB())
{
payment.assertAllowDelete();
return null;
}
else
{
return payment.changingStatusToDeleted();
}
});
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrder.java
| 1
|
请完成以下Java代码
|
public CacheInvalidateMultiRequest createRequestOrNull(
@NonNull final ICacheSourceModel model,
@NonNull final ModelCacheInvalidationTiming timing)
{
final String tableName = model.getTableName();
final HashSet<CacheInvalidateRequest> requests = getRequestFactoriesByTableName(tableName, timing)
.stream()
.map(requestFactory -> requestFactory.createRequestsFromModel(model, timing))
.filter(Objects::nonNull)
.flatMap(List::stream)
.filter(Objects::nonNull)
.collect(Collectors.toCollection(HashSet::new));
//
final CacheInvalidateRequest request = createChildRecordInvalidateUsingRootRecordReference(model);
if (request != null)
{
requests.add(request);
}
//
if (requests.isEmpty())
{
return null;
}
return CacheInvalidateMultiRequest.of(requests);
|
}
private CacheInvalidateRequest createChildRecordInvalidateUsingRootRecordReference(final ICacheSourceModel model)
{
final TableRecordReference rootRecordReference = model.getRootRecordReferenceOrNull();
if (rootRecordReference == null)
{
return null;
}
final String modelTableName = model.getTableName();
final int modelRecordId = model.getRecordId();
return CacheInvalidateRequest.builder()
.rootRecord(rootRecordReference.getTableName(), rootRecordReference.getRecord_ID())
.childRecord(modelTableName, modelRecordId)
.build();
}
private Set<ModelCacheInvalidateRequestFactory> getRequestFactoriesByTableName(@NonNull final String tableName, @NonNull final ModelCacheInvalidationTiming timing)
{
final Set<ModelCacheInvalidateRequestFactory> factories = factoryGroups.stream()
.flatMap(factoryGroup -> factoryGroup.getFactoriesByTableName(tableName, timing).stream())
.collect(ImmutableSet.toImmutableSet());
return factories != null && !factories.isEmpty() ? factories : DEFAULT_REQUEST_FACTORIES;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\ModelCacheInvalidationService.java
| 1
|
请完成以下Java代码
|
public static IncotermsId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new IncotermsId(repoId) : null;
}
public static Optional<IncotermsId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
@JsonCreator
public static IncotermsId ofObject(@NonNull final Object object)
{
return RepoIdAwares.ofObject(object, IncotermsId.class, IncotermsId::ofRepoId);
}
public static int toRepoId(@Nullable final IncotermsId incotermsId)
{
return toRepoIdOr(incotermsId, -1);
}
public static int toRepoIdOr(@Nullable final IncotermsId incotermsId, final int defaultValue)
|
{
return incotermsId != null ? incotermsId.getRepoId() : defaultValue;
}
private IncotermsId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_Incoterms_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
public static boolean equals(@Nullable final IncotermsId o1, @Nullable final IncotermsId o2)
{
return Objects.equals(o1, o2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\incoterms\IncotermsId.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CreateBOMProductsRouteBuilder extends RouteBuilder
{
@Override
public void configure()
{
from(direct(MF_UPSERT_BOM_V2_CAMEL_URI))
.routeId(MF_UPSERT_BOM_V2_CAMEL_URI)
.streamCache("true")
.process(exchange -> {
final Object request = exchange.getIn().getBody();
if (!(request instanceof BOMUpsertCamelRequest))
{
throw new RuntimeCamelException("The route " + MF_UPSERT_BOM_V2_CAMEL_URI + " requires the body to be instanceof BOMUpsertCamelRequest V2."
+ " However, it is " + (request == null ? "null" : request.getClass().getName()));
}
final BOMUpsertCamelRequest bomUpsertCamelRequest = (BOMUpsertCamelRequest)request;
|
exchange.getIn().setHeader(HEADER_ORG_CODE, bomUpsertCamelRequest.getOrgCode());
final JsonBOMCreateRequest jsonBOMCreateRequest = bomUpsertCamelRequest.getJsonBOMCreateRequest();
exchange.getIn().setBody(jsonBOMCreateRequest);
})
.marshal(CamelRouteHelper.setupJacksonDataFormatFor(getContext(), JsonBOMCreateRequest.class))
.removeHeaders("CamelHttp*")
.setHeader(Exchange.HTTP_METHOD, constant(HttpMethods.PUT))
.toD("{{metasfresh.upsert-bom-v2.api.uri}}/${header." + HEADER_ORG_CODE + "}")
.to(direct(UNPACK_V2_API_RESPONSE));
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\to_mf\v2\CreateBOMProductsRouteBuilder.java
| 2
|
请完成以下Java代码
|
public int getHC_Forum_Datenaustausch_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_HC_Forum_Datenaustausch_Config_ID);
}
/**
* ImportedBPartnerLanguage AD_Reference_ID=327
* Reference name: AD_Language System
*/
public static final int IMPORTEDBPARTNERLANGUAGE_AD_Reference_ID=327;
@Override
public void setImportedBPartnerLanguage (final @Nullable java.lang.String ImportedBPartnerLanguage)
{
set_Value (COLUMNNAME_ImportedBPartnerLanguage, ImportedBPartnerLanguage);
}
@Override
public java.lang.String getImportedBPartnerLanguage()
{
return get_ValueAsString(COLUMNNAME_ImportedBPartnerLanguage);
}
@Override
public org.compiere.model.I_C_BP_Group getImportedMunicipalityBP_Group()
{
return get_ValueAsPO(COLUMNNAME_ImportedMunicipalityBP_Group_ID, org.compiere.model.I_C_BP_Group.class);
}
@Override
public void setImportedMunicipalityBP_Group(final org.compiere.model.I_C_BP_Group ImportedMunicipalityBP_Group)
{
set_ValueFromPO(COLUMNNAME_ImportedMunicipalityBP_Group_ID, org.compiere.model.I_C_BP_Group.class, ImportedMunicipalityBP_Group);
}
@Override
public void setImportedMunicipalityBP_Group_ID (final int ImportedMunicipalityBP_Group_ID)
{
if (ImportedMunicipalityBP_Group_ID < 1)
set_Value (COLUMNNAME_ImportedMunicipalityBP_Group_ID, null);
else
set_Value (COLUMNNAME_ImportedMunicipalityBP_Group_ID, ImportedMunicipalityBP_Group_ID);
}
@Override
public int getImportedMunicipalityBP_Group_ID()
{
return get_ValueAsInt(COLUMNNAME_ImportedMunicipalityBP_Group_ID);
}
@Override
public org.compiere.model.I_C_BP_Group getImportedPartientBP_Group()
{
return get_ValueAsPO(COLUMNNAME_ImportedPartientBP_Group_ID, org.compiere.model.I_C_BP_Group.class);
}
@Override
public void setImportedPartientBP_Group(final org.compiere.model.I_C_BP_Group ImportedPartientBP_Group)
{
|
set_ValueFromPO(COLUMNNAME_ImportedPartientBP_Group_ID, org.compiere.model.I_C_BP_Group.class, ImportedPartientBP_Group);
}
@Override
public void setImportedPartientBP_Group_ID (final int ImportedPartientBP_Group_ID)
{
if (ImportedPartientBP_Group_ID < 1)
set_Value (COLUMNNAME_ImportedPartientBP_Group_ID, null);
else
set_Value (COLUMNNAME_ImportedPartientBP_Group_ID, ImportedPartientBP_Group_ID);
}
@Override
public int getImportedPartientBP_Group_ID()
{
return get_ValueAsInt(COLUMNNAME_ImportedPartientBP_Group_ID);
}
@Override
public void setStoreDirectory (final @Nullable java.lang.String StoreDirectory)
{
set_Value (COLUMNNAME_StoreDirectory, StoreDirectory);
}
@Override
public java.lang.String getStoreDirectory()
{
return get_ValueAsString(COLUMNNAME_StoreDirectory);
}
@Override
public void setVia_EAN (final java.lang.String Via_EAN)
{
set_Value (COLUMNNAME_Via_EAN, Via_EAN);
}
@Override
public java.lang.String getVia_EAN()
{
return get_ValueAsString(COLUMNNAME_Via_EAN);
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java-gen\de\metas\vertical\healthcare\forum_datenaustausch_ch\commons\model\X_HC_Forum_Datenaustausch_Config.java
| 1
|
请完成以下Java代码
|
public Message getRawEvent() {
return message;
}
@Override
public String getBody() {
return convertEventToString();
}
@Override
public Map<String, Object> getHeaders() {
if (headers == null) {
headers = retrieveHeaders();
}
return headers;
}
@SuppressWarnings("unchecked")
protected Map<String, Object> retrieveHeaders() {
try {
Map<String, Object> headers = new HashMap<>();
Enumeration<String> headerNames = message.getPropertyNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
headers.put(headerName, message.getObjectProperty(headerName));
}
return headers;
} catch (JMSException e) {
throw new FlowableException("Could not get header information", e);
}
}
protected String convertEventToString() {
if (message instanceof TextMessage) {
|
try {
return ((TextMessage) message).getText();
} catch (JMSException e) {
throw new FlowableException("Could not get body information");
}
} else {
return message.toString();
}
}
@Override
public String toString() {
return "JmsMessageInboundEvent{" +
"message=" + message +
", headers=" + headers +
'}';
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\jms\JmsMessageInboundEvent.java
| 1
|
请完成以下Java代码
|
public java.sql.Timestamp getDunningDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DunningDate);
}
/** Set Benutze abw. Adresse.
@param IsUseBPartnerAddress Benutze abw. Adresse */
@Override
public void setIsUseBPartnerAddress (boolean IsUseBPartnerAddress)
{
set_Value (COLUMNNAME_IsUseBPartnerAddress, Boolean.valueOf(IsUseBPartnerAddress));
}
/** Get Benutze abw. Adresse.
@return Benutze abw. Adresse */
@Override
public boolean isUseBPartnerAddress ()
{
Object oo = get_Value(COLUMNNAME_IsUseBPartnerAddress);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Massenaustritt.
@param IsWriteOff Massenaustritt */
@Override
public void setIsWriteOff (boolean IsWriteOff)
{
throw new IllegalArgumentException ("IsWriteOff is virtual column"); }
/** Get Massenaustritt.
@return Massenaustritt */
@Override
public boolean isWriteOff ()
{
Object oo = get_Value(COLUMNNAME_IsWriteOff);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** 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;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_DunningDoc.java
| 1
|
请完成以下Java代码
|
public Authentication convert(HttpServletRequest request) {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header == null) {
return null;
}
String[] parts = header.split("\\s");
if (!parts[0].equalsIgnoreCase("Basic")) {
return null;
}
if (parts.length != 2) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST);
}
byte[] decodedCredentials;
try {
decodedCredentials = Base64.getDecoder().decode(parts[1].getBytes(StandardCharsets.UTF_8));
}
catch (IllegalArgumentException ex) {
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST), ex);
}
|
String credentialsString = new String(decodedCredentials, StandardCharsets.UTF_8);
String[] credentials = credentialsString.split(":", 2);
if (credentials.length != 2 || !StringUtils.hasText(credentials[0]) || !StringUtils.hasText(credentials[1])) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST);
}
String clientID;
String clientSecret;
try {
clientID = URLDecoder.decode(credentials[0], StandardCharsets.UTF_8.name());
clientSecret = URLDecoder.decode(credentials[1], StandardCharsets.UTF_8.name());
}
catch (Exception ex) {
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST), ex);
}
return new OAuth2ClientAuthenticationToken(clientID, ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
clientSecret, OAuth2EndpointUtils.getParametersIfMatchesAuthorizationCodeGrantRequest(request));
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\web\authentication\ClientSecretBasicAuthenticationConverter.java
| 1
|
请完成以下Java代码
|
private I_M_Product getProductNotNull(@NonNull final String productSearchKey)
{
final I_M_Product product = searchKey2Product.computeIfAbsent(productSearchKey, this::loadProduct);
if (product == null)
{
throw new AdempiereException("No product could be found for the target search key!")
.appendParametersToMessage()
.setParameter("ProductSearchKey", productSearchKey);
}
return product;
}
private I_M_Product loadProduct(@NonNull final String productSearchKey)
{
|
return productRepo.retrieveProductByValue(productSearchKey);
}
private OrgId retrieveOrgId(@NonNull final String orgCode)
{
final OrgQuery query = OrgQuery.builder()
.orgValue(orgCode)
.failIfNotExists(true)
.build();
return orgDAO.retrieveOrgIdBy(query).orElseThrow(() -> new AdempiereException("No AD_Org was found for the given search key!")
.appendParametersToMessage()
.setParameter("OrgSearchKey", orgCode));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\receipt\CustomerReturnRestService.java
| 1
|
请完成以下Java代码
|
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionName() {
return processDefinitionName;
}
public int getProcessDefinitionVersion() {
return processDefinitionVersion;
}
public Integer getHistoryTimeToLive() {
return historyTimeToLive;
}
public Long getFinishedProcessInstanceCount() {
return finishedProcessInstanceCount;
}
public Long getCleanableProcessInstanceCount() {
return cleanableProcessInstanceCount;
}
public String getTenantId() {
return tenantId;
}
|
protected CleanableHistoricProcessInstanceReport createNewReportQuery(ProcessEngine engine) {
return engine.getHistoryService().createCleanableHistoricProcessInstanceReport();
}
public static List<CleanableHistoricProcessInstanceReportResultDto> convert(List<CleanableHistoricProcessInstanceReportResult> reportResult) {
List<CleanableHistoricProcessInstanceReportResultDto> dtos = new ArrayList<CleanableHistoricProcessInstanceReportResultDto>();
for (CleanableHistoricProcessInstanceReportResult current : reportResult) {
CleanableHistoricProcessInstanceReportResultDto dto = new CleanableHistoricProcessInstanceReportResultDto();
dto.setProcessDefinitionId(current.getProcessDefinitionId());
dto.setProcessDefinitionKey(current.getProcessDefinitionKey());
dto.setProcessDefinitionName(current.getProcessDefinitionName());
dto.setProcessDefinitionVersion(current.getProcessDefinitionVersion());
dto.setHistoryTimeToLive(current.getHistoryTimeToLive());
dto.setFinishedProcessInstanceCount(current.getFinishedProcessInstanceCount());
dto.setCleanableProcessInstanceCount(current.getCleanableProcessInstanceCount());
dto.setTenantId(current.getTenantId());
dtos.add(dto);
}
return dtos;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricProcessInstanceReportResultDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String firstname;
@Column
private String surname;
@Column
private int age;
Person() {
}
public Person(final String firstname, final String surname) {
this.firstname = firstname;
this.surname = surname;
}
public Person(final String firstname, final String surname, final int age) {
this(firstname, surname);
this.age = age;
}
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
|
public String getFirstname() {
return firstname;
}
public void setFirstname(final String firstname) {
this.firstname = firstname;
}
public String getSurname() {
return surname;
}
public void setSurname(final String surname) {
this.surname = surname;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
}
|
repos\tutorials-master\persistence-modules\querydsl\src\main\java\com\baeldung\entity\Person.java
| 2
|
请完成以下Java代码
|
private void checkInput(@Valid @RequestBody RegisterParam registerParam, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
throw new InvalidRequestException(bindingResult);
}
if (userRepository.findByUsername(registerParam.getUsername()).isPresent()) {
bindingResult.rejectValue("username", "DUPLICATED", "duplicated username");
}
if (userRepository.findByEmail(registerParam.getEmail()).isPresent()) {
bindingResult.rejectValue("email", "DUPLICATED", "duplicated email");
}
if (bindingResult.hasErrors()) {
throw new InvalidRequestException(bindingResult);
}
}
@RequestMapping(path = "/users/login", method = POST)
public ResponseEntity userLogin(@Valid @RequestBody LoginParam loginParam, BindingResult bindingResult) {
Optional<User> optional = userRepository.findByEmail(loginParam.getEmail());
if (optional.isPresent() && encryptService.check(loginParam.getPassword(), optional.get().getPassword())) {
UserData userData = userQueryService.findById(optional.get().getId()).get();
return ResponseEntity.ok(userResponse(new UserWithToken(userData, jwtService.toToken(optional.get()))));
} else {
bindingResult.rejectValue("password", "INVALID", "invalid email or password");
throw new InvalidRequestException(bindingResult);
}
}
private Map<String, Object> userResponse(UserWithToken userWithToken) {
|
return new HashMap<String, Object>() {{
put("user", userWithToken);
}};
}
}
@Getter
@JsonRootName("user")
@NoArgsConstructor
class LoginParam {
@NotBlank(message = "can't be empty")
@Email(message = "should be an email")
private String email;
@NotBlank(message = "can't be empty")
private String password;
}
@Getter
@JsonRootName("user")
@NoArgsConstructor
class RegisterParam {
@NotBlank(message = "can't be empty")
@Email(message = "should be an email")
private String email;
@NotBlank(message = "can't be empty")
private String username;
@NotBlank(message = "can't be empty")
private String password;
}
|
repos\spring-boot-realworld-example-app-master (1)\src\main\java\io\spring\api\UsersApi.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.open-in-view=false
logging.level.ROOT=INFO
logging.level.org.
|
hibernate.engine.transaction.internal.TransactionImpl=DEBUG
logging.level.org.springframework.orm.jpa=DEBUG
logging.level.org.springframework.transaction=DEBUG
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootTransactionPropagation\HibernateSpringBootTransactionMandatoryAndRollback\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public boolean isParallelMultiple() {
return parallelMultipleAttribute.getValue(this);
}
public void setParallelMultiple(boolean parallelMultiple) {
parallelMultipleAttribute.setValue(this, parallelMultiple);
}
public Collection<DataOutput> getDataOutputs() {
return dataOutputCollection.get(this);
}
public Collection<DataOutputAssociation> getDataOutputAssociations() {
return dataOutputAssociationCollection.get(this);
}
|
public OutputSet getOutputSet() {
return outputSetChild.getChild(this);
}
public void setOutputSet(OutputSet outputSet) {
outputSetChild.setChild(this, outputSet);
}
public Collection<EventDefinition> getEventDefinitions() {
return eventDefinitionCollection.get(this);
}
public Collection<EventDefinition> getEventDefinitionRefs() {
return eventDefinitionRefCollection.getReferenceTargetElements(this);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CatchEventImpl.java
| 1
|
请完成以下Java代码
|
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Number of Inventory counts.
@param NoInventoryCount
Frequency of inventory counts per year
*/
public void setNoInventoryCount (int NoInventoryCount)
{
set_Value (COLUMNNAME_NoInventoryCount, Integer.valueOf(NoInventoryCount));
}
/** Get Number of Inventory counts.
@return Frequency of inventory counts per year
*/
public int getNoInventoryCount ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NoInventoryCount);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Number of Product counts.
@param NoProductCount
Frequency of product counts per year
*/
public void setNoProductCount (int NoProductCount)
{
set_Value (COLUMNNAME_NoProductCount, Integer.valueOf(NoProductCount));
}
/** Get Number of Product counts.
@return Frequency of product counts per year
*/
public int getNoProductCount ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NoProductCount);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Number of runs.
@param NumberOfRuns
Frequency of processing Perpetual Inventory
|
*/
public void setNumberOfRuns (int NumberOfRuns)
{
set_Value (COLUMNNAME_NumberOfRuns, Integer.valueOf(NumberOfRuns));
}
/** Get Number of runs.
@return Frequency of processing Perpetual Inventory
*/
public int getNumberOfRuns ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NumberOfRuns);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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_PerpetualInv.java
| 1
|
请完成以下Java代码
|
public int getWindowNo()
{
return getDocument().getWindowNo();
}
@Override
public boolean isRecordCopyingMode()
{
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isRecordCopyingModeIncludingDetails()
{
// TODO Auto-generated method stub
return false;
}
@Override
public ICalloutExecutor getCurrentCalloutExecutor()
{
return getDocument().getFieldCalloutExecutor();
}
@Override
public void fireDataStatusEEvent(@NonNull final String captionAD_Message, final String message, final boolean isError)
{
final IDocumentChangesCollector changesCollector = Execution.getCurrentDocumentChangesCollectorOrNull();
if (NullDocumentChangesCollector.isNull(changesCollector))
{
logger.warn("Got WARNING on field {} but there is no changes collector to dispatch"
+ "\n captionAD_Message={}"
+ "\n message={}"
+ "\n isError={}",
documentField, captionAD_Message, message, isError);
}
else
{
changesCollector.collectFieldWarning(documentField, DocumentFieldWarning.builder()
.caption(Services.get(IMsgBL.class).translatable(captionAD_Message))
.message(message)
.error(isError)
.build());
}
}
@Override
public void fireDataStatusEEvent(final ValueNamePair errorLog)
{
final boolean isError = true;
fireDataStatusEEvent(errorLog.getValue(), errorLog.getName(), isError);
}
@Override
public void putContext(final String name, final boolean value)
{
getDocument().setDynAttribute(name, value);
}
@Override
public void putContext(final String name, final java.util.Date value)
{
getDocument().setDynAttribute(name, value);
}
@Override
|
public void putContext(final String name, final int value)
{
getDocument().setDynAttribute(name, value);
}
@Override
public boolean getContextAsBoolean(final String name)
{
final Object valueObj = getDocument().getDynAttribute(name);
return DisplayType.toBoolean(valueObj);
}
@Override
public int getContextAsInt(final String name)
{
final Object valueObj = getDocument().getDynAttribute(name);
if (valueObj == null)
{
return -1;
}
else if (valueObj instanceof Number)
{
return ((Number)valueObj).intValue();
}
else
{
return Integer.parseInt(valueObj.toString());
}
}
@Override
public ICalloutRecord getCalloutRecord()
{
return getDocument().asCalloutRecord();
}
@Override
public boolean isLookupValuesContainingId(@NonNull final RepoIdAware id)
{
return documentField.getLookupValueById(id) != null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentFieldAsCalloutField.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected DecisionDefinitionEntity loadDecisionDefinition(String decisionDefinitionId) {
ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration();
DeploymentCache deploymentCache = configuration.getDeploymentCache();
DecisionDefinitionEntity decisionDefinition = deploymentCache.findDecisionDefinitionFromCache(decisionDefinitionId);
if (decisionDefinition == null) {
CommandContext commandContext = Context.getCommandContext();
DecisionDefinitionManager decisionDefinitionManager = commandContext.getDecisionDefinitionManager();
decisionDefinition = decisionDefinitionManager.findDecisionDefinitionById(decisionDefinitionId);
if (decisionDefinition != null) {
decisionDefinition = deploymentCache.resolveDecisionDefinition(decisionDefinition);
}
}
return decisionDefinition;
}
public String getPreviousDecisionDefinitionId() {
ensurePreviousDecisionDefinitionIdInitialized();
return previousDecisionDefinitionId;
}
public void setPreviousDecisionDefinitionId(String previousDecisionDefinitionId) {
this.previousDecisionDefinitionId = previousDecisionDefinitionId;
}
protected void resetPreviousDecisionDefinitionId() {
previousDecisionDefinitionId = null;
ensurePreviousDecisionDefinitionIdInitialized();
}
protected void ensurePreviousDecisionDefinitionIdInitialized() {
if (previousDecisionDefinitionId == null && !firstVersion) {
previousDecisionDefinitionId = Context
.getCommandContext()
.getDecisionDefinitionManager()
.findPreviousDecisionDefinitionId(key, version, tenantId);
if (previousDecisionDefinitionId == null) {
firstVersion = true;
}
}
}
@Override
public Integer getHistoryTimeToLive() {
return historyTimeToLive;
}
public void setHistoryTimeToLive(Integer historyTimeToLive) {
this.historyTimeToLive = historyTimeToLive;
|
}
@Override
public String getVersionTag() {
return versionTag;
}
public void setVersionTag(String versionTag) {
this.versionTag = versionTag;
}
@Override
public String toString() {
return "DecisionDefinitionEntity{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", category='" + category + '\'' +
", key='" + key + '\'' +
", version=" + version +
", versionTag=" + versionTag +
", decisionRequirementsDefinitionId='" + decisionRequirementsDefinitionId + '\'' +
", decisionRequirementsDefinitionKey='" + decisionRequirementsDefinitionKey + '\'' +
", deploymentId='" + deploymentId + '\'' +
", tenantId='" + tenantId + '\'' +
", historyTimeToLive=" + historyTimeToLive +
'}';
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionDefinitionEntity.java
| 2
|
请完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
|
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
|
repos\tutorials-master\web-modules\jakarta-ee\src\main\java\com\baeldung\eclipse\krazo\User.java
| 1
|
请完成以下Java代码
|
public T execute(CommandContext commandContext) {
if (taskId == null) {
throw new FlowableIllegalArgumentException("taskId is null");
}
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
TaskEntity task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(taskId);
if (task == null) {
throw new FlowableObjectNotFoundException("Cannot find task with id " + taskId, Task.class);
}
if (task.isDeleted()) {
throw new FlowableException(task + " is already deleted");
}
if (task.isSuspended()) {
throw new FlowableException(getSuspendedTaskExceptionPrefix() + " a suspended " + task);
}
|
return execute(commandContext, task);
}
/**
* Subclasses must implement in this method their normal command logic. The provided task is ensured to be active.
*/
protected abstract T execute(CommandContext commandContext, TaskEntity task);
/**
* Subclasses can override this method to provide a customized exception message that will be thrown when the task is suspended.
*/
protected String getSuspendedTaskExceptionPrefix() {
return "Cannot execute operation for";
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\NeedsActiveTaskCmd.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public final void setImportMetadata(AnnotationMetadata importMetadata) {
Map<String, Object> annotationAttributes = importMetadata
.getAnnotationAttributes(EnableGlobalMethodSecurity.class.getName());
this.enableMethodSecurity = AnnotationAttributes.fromMap(annotationAttributes);
}
@Autowired(required = false)
public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcessor) {
this.objectPostProcessor = objectPostProcessor;
}
@Autowired(required = false)
public void setMethodSecurityExpressionHandler(List<MethodSecurityExpressionHandler> handlers) {
if (handlers.size() != 1) {
logger.debug("Not autowiring MethodSecurityExpressionHandler since size != 1. Got " + handlers);
return;
}
this.expressionHandler = handlers.get(0);
}
@Autowired(required = false)
void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.context = beanFactory;
}
private AuthenticationConfiguration getAuthenticationConfiguration() {
return this.context.getBean(AuthenticationConfiguration.class);
}
private boolean prePostEnabled() {
return enableMethodSecurity().getBoolean("prePostEnabled");
}
private boolean securedEnabled() {
return enableMethodSecurity().getBoolean("securedEnabled");
}
|
private boolean jsr250Enabled() {
return enableMethodSecurity().getBoolean("jsr250Enabled");
}
private boolean isAspectJ() {
return enableMethodSecurity().getEnum("mode") == AdviceMode.ASPECTJ;
}
private AnnotationAttributes enableMethodSecurity() {
if (this.enableMethodSecurity == null) {
// if it is null look at this instance (i.e. a subclass was used)
EnableGlobalMethodSecurity methodSecurityAnnotation = AnnotationUtils.findAnnotation(getClass(),
EnableGlobalMethodSecurity.class);
Assert.notNull(methodSecurityAnnotation, () -> EnableGlobalMethodSecurity.class.getName() + " is required");
Map<String, Object> methodSecurityAttrs = AnnotationUtils.getAnnotationAttributes(methodSecurityAnnotation);
this.enableMethodSecurity = AnnotationAttributes.fromMap(methodSecurityAttrs);
}
return this.enableMethodSecurity;
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\GlobalMethodSecurityConfiguration.java
| 2
|
请完成以下Java代码
|
public T deserialize(String topic, byte[] data) {
return deserialize(topic, null, data);
}
@Override
public T deserialize(String topic, @Nullable Headers headers, byte[] data) {
return this.parser.apply(data == null ? null : new String(data, this.charset), headers);
}
@Override
public T deserialize(String topic, Headers headers, ByteBuffer data) {
String value = deserialize(data);
return this.parser.apply(value, headers);
}
private @Nullable String deserialize(@Nullable ByteBuffer data) {
if (data == null) {
return null;
}
if (data.hasArray()) {
return new String(data.array(), data.position() + data.arrayOffset(), data.remaining(), this.charset);
}
return new String(Utils.toArray(data), this.charset);
}
/**
|
* Set a charset to use when converting byte[] to {@link String}. Default UTF-8.
* @param charset the charset.
*/
public void setCharset(Charset charset) {
Assert.notNull(charset, "'charset' cannot be null");
this.charset = charset;
}
/**
* Get the configured charset.
* @return the charset.
*/
public Charset getCharset() {
return this.charset;
}
/**
* Get the configured parser function.
* @return the function.
*/
public BiFunction<String, Headers, T> getParser() {
return this.parser;
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\ParseStringDeserializer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected void validateIdentityLinkArguments(String family, String identityId) {
if (family == null || (!RestUrls.SEGMENT_IDENTITYLINKS_FAMILY_GROUPS.equals(family) && !RestUrls.SEGMENT_IDENTITYLINKS_FAMILY_USERS.equals(family))) {
throw new FlowableIllegalArgumentException("Identity link family should be 'users' or 'groups'.");
}
if (identityId == null) {
throw new FlowableIllegalArgumentException("IdentityId is required.");
}
}
protected IdentityLink getIdentityLink(String family, String identityId, String processDefinitionId) {
boolean isUser = family.equals(RestUrls.SEGMENT_IDENTITYLINKS_FAMILY_USERS);
// Perhaps it would be better to offer getting a single identitylink
// from
// the API
List<IdentityLink> allLinks = repositoryService.getIdentityLinksForProcessDefinition(processDefinitionId);
|
for (IdentityLink link : allLinks) {
boolean rightIdentity = false;
if (isUser) {
rightIdentity = identityId.equals(link.getUserId());
} else {
rightIdentity = identityId.equals(link.getGroupId());
}
if (rightIdentity && link.getType().equals(IdentityLinkType.CANDIDATE)) {
return link;
}
}
throw new FlowableObjectNotFoundException("Could not find the requested identity link.", IdentityLink.class);
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ProcessDefinitionIdentityLinkResource.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class AcquireExternalWorkerJobRequest {
@ApiModelProperty(value = "Acquire jobs with the given topic", example = "order", required = true)
protected String topic;
@ApiModelProperty(
value = "The acquired jobs will be locked with this lock duration. ISO-8601 duration format PnDTnHnMn.nS with days considered to be exactly 24 hours.",
example = "PT10M", dataType = "string", required = true)
protected Duration lockDuration;
@ApiModelProperty(value = "The number of tasks that should be acquired. Default is 1.", example = "1")
protected int numberOfTasks = 1;
@ApiModelProperty(value = "The number of retries if an optimistic lock exception occurs during acquiring. Default is 5", example = "10")
protected int numberOfRetries = 5;
@ApiModelProperty(value = "The id of the external worker that would be used for locking the job", example = "orderWorker1", required = true)
protected String workerId;
@ApiModelProperty(value = "Only acquire jobs with the given scope type", example = "cmmn")
protected String scopeType;
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public Duration getLockDuration() {
return lockDuration;
}
public void setLockDuration(Duration lockDuration) {
this.lockDuration = lockDuration;
}
public int getNumberOfTasks() {
return numberOfTasks;
}
public void setNumberOfTasks(int numberOfTasks) {
this.numberOfTasks = numberOfTasks;
}
public int getNumberOfRetries() {
return numberOfRetries;
|
}
public void setNumberOfRetries(int numberOfRetries) {
this.numberOfRetries = numberOfRetries;
}
public String getWorkerId() {
return workerId;
}
public void setWorkerId(String workerId) {
this.workerId = workerId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
}
|
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\acquire\AcquireExternalWorkerJobRequest.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Book {
@Id
private String name;
private String author;
// Default constructor for JPA deserialization
public Book() {
}
public Book(String name, String author) {
this.name = name;
this.author = author;
}
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-crud\src\main\java\com\baeldung\entitydtodifferences\entity\Book.java
| 2
|
请完成以下Java代码
|
private boolean checkIpAddress(List<String> expectedList, List<String> serverList) {
if (expectedList != null && expectedList.size() > 0) {
if (serverList != null && serverList.size() > 0) {
for (String expected : expectedList) {
if (serverList.contains(expected.trim())) {
return true;
}
}
}
return false;
} else {
return true;
}
}
/**
* <p>项目名称: true-license-demo </p>
* <p>文件名称: CustomLicenseManager.java </p>
|
* <p>方法描述: 校验当前服务器硬件(主板、CPU 等)序列号是否在可允许范围内 </p>
* <p>创建时间: 2020/10/10 13:18 </p>
*
* @param expectedSerial expectedSerial
* @param serverSerial serverSerial
* @return boolean
* @author 方瑞冬
* @version 1.0
*/
private boolean checkSerial(String expectedSerial, String serverSerial) {
if (StringUtils.hasText(expectedSerial)) {
if (StringUtils.hasText(serverSerial)) {
return expectedSerial.equals(serverSerial);
}
return false;
} else {
return true;
}
}
}
|
repos\springboot-demo-master\SoftwareLicense\src\main\java\com\et\license\license\CustomLicenseManager.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Author> getAuthors() {
return authors;
}
|
public void setAuthors(List<Author> authors) {
this.authors = authors;
}
public String[] getTags() {
return tags;
}
public void setTags(String... tags) {
this.tags = tags;
}
@Override
public String toString() {
return "Article{" + "id='" + id + '\'' + ", title='" + title + '\'' + ", authors=" + authors + ", tags=" + Arrays.toString(tags) + '}';
}
}
|
repos\tutorials-master\persistence-modules\spring-data-elasticsearch\src\main\java\com\baeldung\spring\data\es\model\Article.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CodeGenController {
private final CodeGenService codeGenService;
/**
* 列表
*
* @param request 参数集
* @return 数据库表
*/
@GetMapping("/table")
public R listTables(TableRequest request) {
return R.success(codeGenService.listTables(request));
}
/**
|
* 生成代码
*/
@SneakyThrows
@PostMapping("")
public void generatorCode(@RequestBody GenConfig genConfig, HttpServletResponse response) {
byte[] data = codeGenService.generatorCode(genConfig);
response.reset();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", genConfig.getTableName()));
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
}
}
|
repos\spring-boot-demo-master\demo-codegen\src\main\java\com\xkcoding\codegen\controller\CodeGenController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class POSOrderLine
{
@NonNull String externalId;
@NonNull ProductId productId;
@NonNull String productName;
@Nullable String scannedBarcode;
@NonNull TaxCategoryId taxCategoryId;
@NonNull TaxId taxId;
@NonNull Quantity qty;
@Nullable Quantity catchWeight;
@NonNull Money price;
@NonNull Money amount;
@NonNull Money taxAmt;
@Builder(toBuilder = true)
private POSOrderLine(
@NonNull final String externalId,
@NonNull final ProductId productId,
@NonNull final String productName,
@Nullable final String scannedBarcode,
@NonNull final TaxCategoryId taxCategoryId,
@NonNull final TaxId taxId,
@NonNull final Quantity qty,
@Nullable final Quantity catchWeight,
@NonNull final Money price,
@NonNull final Money amount,
@NonNull Money taxAmt)
{
Money.assertSameCurrency(price, amount, taxAmt);
|
this.externalId = externalId;
this.productId = productId;
this.productName = productName;
this.scannedBarcode = StringUtils.trimBlankToNull(scannedBarcode);
this.taxCategoryId = taxCategoryId;
this.taxId = taxId;
this.qty = qty;
this.catchWeight = catchWeight;
this.price = price;
this.amount = amount;
this.taxAmt = taxAmt;
}
public Money getLineTotalAmt(final boolean isTaxIncluded)
{
return isTaxIncluded ? amount : amount.add(taxAmt);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrderLine.java
| 2
|
请完成以下Java代码
|
public boolean hasVariables() {
return false;
}
public boolean hasVariablesLocal() {
return false;
}
public boolean hasVariable(String variableName) {
return false;
}
public boolean hasVariableLocal(String variableName) {
return false;
}
public void removeVariable(String variableName) {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
public void removeVariableLocal(String variableName) {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
public void removeVariables() {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
public void removeVariablesLocal() {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
public void removeVariables(Collection<String> variableNames) {
|
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
public void removeVariablesLocal(Collection<String> variableNames) {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
public Map<String, CoreVariableInstance> getVariableInstances() {
return Collections.emptyMap();
}
public CoreVariableInstance getVariableInstance(String name) {
return null;
}
public Map<String, CoreVariableInstance> getVariableInstancesLocal() {
return Collections.emptyMap();
}
public CoreVariableInstance getVariableInstanceLocal(String name) {
return null;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\el\StartProcessVariableScope.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Person {
@Id
private int id;
private String firstName;
private String lastName;
@OneToOne(mappedBy = "person")
private Address address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
|
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\mapsid\Person.java
| 2
|
请完成以下Java代码
|
public class BearerTokenServerAccessDeniedHandler implements ServerAccessDeniedHandler {
private static final Collection<String> WELL_KNOWN_SCOPE_ATTRIBUTE_NAMES = Arrays.asList("scope", "scp");
private String realmName;
@Override
public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) {
Map<String, String> parameters = new LinkedHashMap<>();
if (this.realmName != null) {
parameters.put("realm", this.realmName);
}
// @formatter:off
return exchange.getPrincipal()
.filter(AbstractOAuth2TokenAuthenticationToken.class::isInstance)
.map((token) -> errorMessageParameters(parameters))
.switchIfEmpty(Mono.just(parameters))
.flatMap((params) -> respond(exchange, params));
// @formatter:on
}
/**
* Set the default realm name to use in the bearer token error response
* @param realmName
*/
public final void setRealmName(String realmName) {
this.realmName = realmName;
}
private static Map<String, String> errorMessageParameters(Map<String, String> parameters) {
parameters.put("error", BearerTokenErrorCodes.INSUFFICIENT_SCOPE);
parameters.put("error_description",
"The request requires higher privileges than provided by the access token.");
parameters.put("error_uri", "https://tools.ietf.org/html/rfc6750#section-3.1");
return parameters;
}
private static Mono<Void> respond(ServerWebExchange exchange, Map<String, String> parameters) {
String wwwAuthenticate = computeWWWAuthenticateHeaderValue(parameters);
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
exchange.getResponse().getHeaders().set(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate);
|
return exchange.getResponse().setComplete();
}
private static String computeWWWAuthenticateHeaderValue(Map<String, String> parameters) {
StringBuilder wwwAuthenticate = new StringBuilder();
wwwAuthenticate.append("Bearer");
if (!parameters.isEmpty()) {
wwwAuthenticate.append(" ");
int i = 0;
for (Map.Entry<String, String> entry : parameters.entrySet()) {
wwwAuthenticate.append(entry.getKey()).append("=\"").append(entry.getValue()).append("\"");
if (i != parameters.size() - 1) {
wwwAuthenticate.append(", ");
}
i++;
}
}
return wwwAuthenticate.toString();
}
}
|
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\web\access\server\BearerTokenServerAccessDeniedHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isAllowTrailingComma() {
return this.allowTrailingComma;
}
public void setAllowTrailingComma(boolean allowTrailingComma) {
this.allowTrailingComma = allowTrailingComma;
}
public boolean isAllowComments() {
return this.allowComments;
}
public void setAllowComments(boolean allowComments) {
this.allowComments = allowComments;
}
/**
* Enum representing strategies for JSON property naming. The values correspond to
|
* {@link kotlinx.serialization.json.JsonNamingStrategy} implementations that cannot
* be directly referenced.
*/
public enum JsonNamingStrategy {
/**
* Snake case strategy.
*/
SNAKE_CASE,
/**
* Kebab case strategy.
*/
KEBAB_CASE
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-kotlinx-serialization-json\src\main\java\org\springframework\boot\kotlinx\serialization\json\autoconfigure\KotlinxSerializationJsonProperties.java
| 2
|
请完成以下Java代码
|
public static void main(String[] args) {
// Seed for HMAC-SHA1 - 20 bytes
String seed = "3132333435363738393031323334353637383930";
// Seed for HMAC-SHA256 - 32 bytes
String seed32 = "3132333435363738393031323334353637383930" +
"313233343536373839303132";
// Seed for HMAC-SHA512 - 64 bytes
String seed64 = "3132333435363738393031323334353637383930" +
"3132333435363738393031323334353637383930" +
"3132333435363738393031323334353637383930" +
"31323334";
long T0 = 0;
long X = 30;
long[] testTime = {59L, 1111111109L, 1111111111L,
1234567890L, 2000000000L, 20000000000L};
String steps = "0";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
logger.info(
"+---------------+-----------------------+" +
"------------------+--------+--------+");
logger.info(
"| Time(sec) | Time (UTC format) " +
"| Value of T(Hex) | TOTP | Mode |");
logger.info(
"+---------------+-----------------------+" +
"------------------+--------+--------+");
for (int i = 0; i < testTime.length; i++) {
long T = (testTime[i] - T0) / X;
steps = Long.toHexString(T).toUpperCase();
while (steps.length() < 16) steps = "0" + steps;
String fmtTime = String.format("%1$-11s", testTime[i]);
String utcTime = df.format(new Date(testTime[i] * 1000));
|
logger.info("| " + fmtTime + " | " + utcTime +
" | " + steps + " |");
logger.info(generateTOTP(seed, steps, "8",
"HmacSHA1") + "| SHA1 |");
logger.info("| " + fmtTime + " | " + utcTime +
" | " + steps + " |");
logger.info(generateTOTP(seed32, steps, "8",
"HmacSHA256") + "| SHA256 |");
logger.info("| " + fmtTime + " | " + utcTime +
" | " + steps + " |");
logger.info(generateTOTP(seed64, steps, "8",
"HmacSHA512") + "| SHA512 |");
logger.info(
"+---------------+-----------------------+" +
"------------------+--------+--------+");
}
} catch (final Exception e) {
logger.info("Error : " + e);
}
}
}
|
repos\springboot-demo-master\MFA\src\main\java\com\et\mfa\domain\TOTP.java
| 1
|
请完成以下Java代码
|
/* package */void setColumnName(final String columnName)
{
this.columnName = columnName;
}
/**
* Get Info Name
*
* @return Info Name
*/
public String getInfoName()
{
return infoName;
} // getInfoName
public Operator getOperator()
{
return operator;
}
/**
* Get Info Operator
*
* @return info Operator
*/
public String getInfoOperator()
{
return operator == null ? null : operator.getCaption();
} // getInfoOperator
/**
* Get Display with optional To
*
* @return info display
*/
public String getInfoDisplayAll()
|
{
if (infoDisplayTo == null)
{
return infoDisplay;
}
StringBuilder sb = new StringBuilder(infoDisplay);
sb.append(" - ").append(infoDisplayTo);
return sb.toString();
} // getInfoDisplay
public Object getCode()
{
return code;
}
public String getInfoDisplay()
{
return infoDisplay;
}
public Object getCodeTo()
{
return codeTo;
}
public String getInfoDisplayTo()
{
return infoDisplayTo;
}
} // Restriction
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MQuery.java
| 1
|
请完成以下Java代码
|
protected String doIt() throws Exception
{
final IExternalSystemChildConfigId externalSystemChildConfigId = getExternalSystemChildConfigId();
addLog("Calling with params: externalSystemChildConfigId: {}", externalSystemChildConfigId);
final Iterator<I_S_ExternalReference> externalRefIterator = getSelectedExternalReferenceRecords();
while (externalRefIterator.hasNext())
{
final TableRecordReference externalReferenceRecordRef = TableRecordReference.of(externalRefIterator.next());
getExportExternalReferenceToExternalSystem().exportToExternalSystem(externalSystemChildConfigId, externalReferenceRecordRef, getPinstanceId());
}
return JavaProcess.MSG_OK;
}
|
@NonNull
private Iterator<I_S_ExternalReference> getSelectedExternalReferenceRecords()
{
final IQueryBuilder<I_S_ExternalReference> externalReferenceQuery = retrieveSelectedRecordsQueryBuilder(I_S_ExternalReference.class);
return externalReferenceQuery
.create()
.iterate(I_S_ExternalReference.class);
}
protected abstract ExternalSystemType getExternalSystemType();
protected abstract IExternalSystemChildConfigId getExternalSystemChildConfigId();
protected abstract String getExternalSystemParam();
protected abstract ExportToExternalSystemService getExportExternalReferenceToExternalSystem();
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\export\externalreference\S_ExternalReference_SyncTo_ExternalSystem.java
| 1
|
请完成以下Java代码
|
public void validateUOM(final I_M_ProductPrice productPrice)
{
if (productPrice.getM_Product_ID() <= 0)
{
return; // nothing to do yet
}
final UomId uomId = UomId.ofRepoId(productPrice.getC_UOM_ID());
if (uomDAO.isUOMForTUs(uomId))
{
validateTuUom(productPrice);
productPrice.setIsHUPrice(true);
}
else
{
productPrice.setIsHUPrice(false);
validatePriceUOM(productPrice);
}
}
private void validateTuUom(@NonNull final I_M_ProductPrice productPrice)
{
final HUPIItemProductId packingMaterialPriceId = HUPIItemProductId.ofRepoIdOrNull(productPrice.getM_HU_PI_Item_Product_ID());
if (packingMaterialPriceId == null)
{
final I_C_UOM priceUom = uomDAO.getById(productPrice.getC_UOM_ID());
throw new AdempiereException(MSG_ERR_M_PRODUCT_PRICE_MISSING_PACKING_ITEM, priceUom.getName())
.markAsUserValidationError();
}
final I_M_HU_PI_Item_Product packingMaterial = huPIItemProductBL.getRecordById(packingMaterialPriceId);
if (huCapacityBL.isInfiniteCapacity(packingMaterial))
{
final Object errorParameter = CoalesceUtil.coalesceNotNull(packingMaterial.getName(), packingMaterial.getM_HU_PI_Item_Product_ID());
throw new AdempiereException(MSG_ERR_M_PRODUCT_PRICE_PACKING_ITEM_INFINITE_CAPACITY, errorParameter)
|
.markAsUserValidationError();
}
}
private void validatePriceUOM(@NonNull final I_M_ProductPrice productPrice)
{
final UomId productPriceUOMId = UomId.ofRepoId(productPrice.getC_UOM_ID());
final UOMConversionsMap uomConversionsMap = uomConversionDAO.getProductConversions(ProductId.ofRepoId(productPrice.getM_Product_ID()));
final UomId productUomId = productBL.getStockUOMId(productPrice.getM_Product_ID());
uomConversionsMap.getRateIfExists(productUomId, productPriceUOMId)
.orElseThrow(() -> new AdempiereException(MSG_ERR_M_PRODUCT_PRICE_NO_UOM_CONVERSION)
.markAsUserValidationError());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_ProductPrice.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.