instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public InOutLineId getInOutLineId() {return inoutAndLineId.getInOutLineId();}
public void addCostAmountInvoiced(@NonNull final Money amtToAdd)
{
this.costAmountInvoiced = this.costAmountInvoiced.add(amtToAdd);
this.isInvoiced = this.costAmount.isEqualByComparingTo(this.costAmountInvoiced);
}
public Money getCostAmountToInvoice()
{
return costAmount.subtract(costAmountInvoiced);
}
public Money getCostAmountForQty(final Quantity qty, CurrencyPrecision precision)
{
|
if (qty.equalsIgnoreSource(this.qty))
{
return costAmount;
}
else if (qty.isZero())
{
return costAmount.toZero();
}
else
{
final Money price = costAmount.divide(this.qty.toBigDecimal(), CurrencyPrecision.ofInt(12));
return price.multiply(qty.toBigDecimal()).round(precision);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\inout\InOutCost.java
| 1
|
请完成以下Java代码
|
public I_M_Locator getEmptiesLocator(@NonNull final I_M_Warehouse warehouse)
{
final WarehouseId emptiesWarehouseId = getEmptiesWarehouse(warehouse);
return InterfaceWrapperHelper.create(Services.get(IWarehouseBL.class).getOrCreateDefaultLocator(emptiesWarehouseId), I_M_Locator.class);
}
@Override
public EmptiesMovementProducer newEmptiesMovementProducer()
{
return EmptiesMovementProducer.newInstance();
}
@Override
public void generateMovementFromEmptiesInout(@NonNull final I_M_InOut emptiesInOut)
{
//
// Fetch shipment/receipt lines and convert them to packing material line candidates.
final List<HUPackingMaterialDocumentLineCandidate> lines = Services.get(IInOutDAO.class).retrieveLines(emptiesInOut, I_M_InOutLine.class)
.stream()
.map(line -> HUPackingMaterialDocumentLineCandidate.of(
loadOutOfTrx(line.getM_Locator_ID(), I_M_Locator.class),
loadOutOfTrx(line.getM_Product_ID(), I_M_Product.class),
line.getMovementQty().intValueExact()))
.collect(GuavaCollectors.toImmutableList());
//
// Generate the empties movement
newEmptiesMovementProducer()
.setEmptiesMovementDirection(emptiesInOut.isSOTrx() ? EmptiesMovementDirection.ToEmptiesWarehouse : EmptiesMovementDirection.FromEmptiesWarehouse)
.setReferencedInOutId(emptiesInOut.getM_InOut_ID())
.addCandidates(lines)
.createMovements();
}
@Override
public boolean isEmptiesInOut(@NonNull final I_M_InOut inout)
{
final I_C_DocType docType = loadOutOfTrx(inout.getC_DocType_ID(), I_C_DocType.class);
|
if (docType == null || docType.getC_DocType_ID() <= 0)
{
return false;
}
final String docSubType = docType.getDocSubType();
return X_C_DocType.DOCSUBTYPE_Leergutanlieferung.equals(docSubType)
|| X_C_DocType.DOCSUBTYPE_Leergutausgabe.equals(docSubType);
}
@Override
public IReturnsInOutProducer newReturnsInOutProducer(final Properties ctx)
{
return new EmptiesInOutProducer(ctx);
}
@Override
@Nullable
public I_M_InOut createDraftEmptiesInOutFromReceiptSchedule(@NonNull final I_M_ReceiptSchedule receiptSchedule, @NonNull final String movementType)
{
//
// Create a draft "empties inout" without any line;
// Lines will be created manually by the user.
return newReturnsInOutProducer(getCtx())
.setMovementType(movementType)
.setMovementDate(SystemTime.asDayTimestamp())
.setC_BPartner(receiptScheduleBL.getC_BPartner_Effective(receiptSchedule))
.setC_BPartner_Location(receiptScheduleBL.getC_BPartner_Location_Effective(receiptSchedule))
.setM_Warehouse(receiptScheduleBL.getM_Warehouse_Effective(receiptSchedule))
.setC_Order(receiptSchedule.getC_Order())
//
.dontComplete()
.create();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\empties\impl\HUEmptiesService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class SecurityLogProperties {
private static final String DEFAULT_SECURITY_LOG_LEVEL = "config";
private String file;
private String level = DEFAULT_SECURITY_LOG_LEVEL;
public String getFile() {
return this.file;
}
public void setFile(String file) {
this.file = file;
}
public String getLevel() {
return this.level;
}
public void setLevel(String level) {
this.level = level;
}
}
public static class SecurityManagerProperties {
private String className;
public String getClassName() {
return this.className;
}
|
public void setClassName(String className) {
this.className = className;
}
}
public static class SecurityPostProcessorProperties {
private String className;
public String getClassName() {
return this.className;
}
public void setClassName(String className) {
this.className = className;
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\SecurityProperties.java
| 2
|
请完成以下Java代码
|
public DmnDiDiagram getCurrentDiDiagram() {
return currentDiDiagram;
}
public void setCurrentDiDiagram(DmnDiDiagram currentDiDiagram) {
this.currentDiDiagram = currentDiDiagram;
}
public DmnDiShape getCurrentDiShape() {
return currentDiShape;
}
public void setCurrentDiShape(DmnDiShape currentDiShape) {
this.currentDiShape = currentDiShape;
}
public DiEdge getCurrentDiEdge() {
return currentDiEdge;
}
|
public void setCurrentDiEdge(DiEdge currentDiEdge) {
this.currentDiEdge = currentDiEdge;
}
public List<DmnDiDiagram> getDiDiagrams() {
return diDiagrams;
}
public List<DmnDiShape> getDiShapes(String diagramId) {
return diShapes.get(diagramId);
}
public List<DmnDiEdge> getDiEdges(String diagramId) {
return diEdges.get(diagramId);
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-xml-converter\src\main\java\org\flowable\dmn\xml\converter\ConversionHelper.java
| 1
|
请完成以下Java代码
|
public List<Task> getSubTasks(String parentTaskId) {
return commandExecutor.execute(new GetSubTasksCmd(parentTaskId));
}
@Override
public VariableInstance getVariableInstance(String taskId, String variableName) {
return commandExecutor.execute(new GetTaskVariableInstanceCmd(taskId, variableName, false));
}
@Override
public VariableInstance getVariableInstanceLocal(String taskId, String variableName) {
return commandExecutor.execute(new GetTaskVariableInstanceCmd(taskId, variableName, true));
}
@Override
public Map<String, VariableInstance> getVariableInstances(String taskId) {
return commandExecutor.execute(new GetTaskVariableInstancesCmd(taskId, null, false));
}
@Override
public Map<String, VariableInstance> getVariableInstances(String taskId, Collection<String> variableNames) {
return commandExecutor.execute(new GetTaskVariableInstancesCmd(taskId, variableNames, false));
}
@Override
public Map<String, VariableInstance> getVariableInstancesLocal(String taskId) {
return commandExecutor.execute(new GetTaskVariableInstancesCmd(taskId, null, true));
}
@Override
public Map<String, VariableInstance> getVariableInstancesLocal(String taskId, Collection<String> variableNames) {
return commandExecutor.execute(new GetTaskVariableInstancesCmd(taskId, variableNames, true));
}
@Override
public Map<String, DataObject> getDataObjects(String taskId) {
return commandExecutor.execute(new GetTaskDataObjectsCmd(taskId, null));
}
@Override
public Map<String, DataObject> getDataObjects(String taskId, String locale, boolean withLocalizationFallback) {
return commandExecutor.execute(new GetTaskDataObjectsCmd(taskId, null, locale, withLocalizationFallback));
}
@Override
public Map<String, DataObject> getDataObjects(String taskId, Collection<String> dataObjectNames) {
return commandExecutor.execute(new GetTaskDataObjectsCmd(taskId, dataObjectNames));
}
@Override
|
public Map<String, DataObject> getDataObjects(
String taskId,
Collection<String> dataObjectNames,
String locale,
boolean withLocalizationFallback
) {
return commandExecutor.execute(
new GetTaskDataObjectsCmd(taskId, dataObjectNames, locale, withLocalizationFallback)
);
}
@Override
public DataObject getDataObject(String taskId, String dataObject) {
return commandExecutor.execute(new GetTaskDataObjectCmd(taskId, dataObject));
}
@Override
public DataObject getDataObject(
String taskId,
String dataObjectName,
String locale,
boolean withLocalizationFallback
) {
return commandExecutor.execute(
new GetTaskDataObjectCmd(taskId, dataObjectName, locale, withLocalizationFallback)
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TaskServiceImpl.java
| 1
|
请完成以下Java代码
|
public <T> T execute(HttpHost target, org.apache.http.HttpRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context)
throws IOException, ClientProtocolException {
try (CloseableHttpClient httpClient = clientBuilder.build()) {
return httpClient.execute(target, request, responseHandler, context);
}
}
protected class ApacheHttpComponentsExecutableHttpRequest implements ExecutableHttpRequest {
protected final HttpRequestBase request;
public ApacheHttpComponentsExecutableHttpRequest(HttpRequestBase request) {
this.request = request;
}
@Override
public HttpResponse call() {
try (CloseableHttpClient httpClient = clientBuilder.build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
return toFlowableHttpResponse(response);
}
} catch (ClientProtocolException ex) {
throw new FlowableException("HTTP exception occurred", ex);
} catch (IOException ex) {
throw new FlowableException("IO exception occurred", ex);
}
}
}
/**
* A HttpDelete alternative that extends {@link HttpEntityEnclosingRequestBase} to allow DELETE with a request body
|
*
* @author ikaakkola
*/
protected static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public HttpDeleteWithBody(URI uri) {
super();
setURI(uri);
}
@Override
public String getMethod() {
return "DELETE";
}
}
}
|
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\impl\apache\ApacheHttpComponentsFlowableHttpClient.java
| 1
|
请完成以下Java代码
|
public void setScript (java.lang.String Script)
{
set_Value (COLUMNNAME_Script, Script);
}
/** Get Skript.
@return Dynamic Java Language Script to calculate result
*/
@Override
public java.lang.String getScript ()
{
return (java.lang.String)get_Value(COLUMNNAME_Script);
}
/** Set Reihenfolge.
@param SeqNo
Method of ordering records; lowest number comes first
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start No.
@param StartNo
Starting number/position
|
*/
@Override
public void setStartNo (int StartNo)
{
set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo));
}
/** Get Start No.
@return Starting number/position
*/
@Override
public int getStartNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StartNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ImpFormat_Row.java
| 1
|
请完成以下Java代码
|
public boolean isValueChanged(final Object model, final String columnName)
{
final Document document = DocumentInterfaceWrapper.getDocument(model);
if (document == null)
{
return false;
}
final IDocumentFieldView field = document.getFieldViewOrNull(columnName);
if (field == null)
{
return false;
}
return field.hasChangesToSave();
}
@Override
public boolean isValueChanged(final Object model, final Set<String> columnNames)
{
if (columnNames == null || columnNames.isEmpty())
{
return false;
}
final Document document = DocumentInterfaceWrapper.getDocument(model);
if (document == null)
{
return false;
}
for (final String columnName : columnNames)
{
final IDocumentFieldView field = document.getFieldViewOrNull(columnName);
if (field == null)
{
continue;
}
if (field.hasChangesToSave())
{
return true;
}
}
return false;
}
@Override
public boolean isNull(final Object model, final String columnName)
{
final Document document = DocumentInterfaceWrapper.getDocument(model);
final IDocumentFieldView field = document.getFieldViewOrNull(columnName);
if(field == null)
{
return true;
}
final Object value = field.getValue();
return value == null;
}
@Override
public <T> T getDynAttribute(final @NonNull Object model, final String attributeName)
{
return DocumentInterfaceWrapper.getDocument(model).getDynAttribute(attributeName);
}
|
@Override
public Object setDynAttribute(final Object model, final String attributeName, final Object value)
{
return DocumentInterfaceWrapper.getDocument(model).setDynAttribute(attributeName, value);
}
@Override
public <T extends PO> T getPO(final Object model, final boolean strict)
{
if (strict)
{
return null;
}
final Document document = DocumentInterfaceWrapper.getDocument(model);
if (document == null)
{
throw new AdempiereException("Cannot extract " + Document.class + " from " + model);
}
final String tableName = document.getEntityDescriptor().getTableName();
final boolean checkCache = false;
@SuppressWarnings("unchecked")
final T po = (T)TableModelLoader.instance.getPO(document.getCtx(), tableName, document.getDocumentIdAsInt(), checkCache, ITrx.TRXNAME_ThreadInherited);
return po;
}
@Override
public Evaluatee getEvaluatee(final Object model)
{
return DocumentInterfaceWrapper.getDocument(model).asEvaluatee();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentInterfaceWrapperHelper.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToMany
@JoinTable(name = "r_user_group", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "group_id"))
private List<Group> groups = new ArrayList<>();
@WhereJoinTable(clause = "role='MODERATOR'")
@ManyToMany
@JoinTable(name = "r_user_group", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "group_id"))
private List<Group> moderatorGroups = new ArrayList<>();
public User(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
|
public List<Group> getGroups() {
return groups;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
public void setModeratorGroups(List<Group> moderatorGroups) {
this.moderatorGroups = moderatorGroups;
}
public List<Group> getModeratorGroups() {
return moderatorGroups;
}
@Override
public String toString() {
return "User [name=" + name + "]";
}
}
|
repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\wherejointable\User.java
| 2
|
请完成以下Java代码
|
public class DefaultTransactionIdSuffixStrategy implements TransactionIdSuffixStrategy {
private final AtomicInteger transactionIdSuffix = new AtomicInteger();
private final Map<String, BlockingQueue<String>> suffixCache = new ConcurrentHashMap<>();
private final int maxCache;
/**
* Construct a transaction id suffix strategy with the provided size of the cache.
* @param maxCache the maximum size of the cache.
*/
public DefaultTransactionIdSuffixStrategy(int maxCache) {
Assert.isTrue(maxCache >= 0, "'maxCache' must be greater than or equal to 0");
this.maxCache = maxCache;
}
/**
* Acquire the suffix for the transactional producer from the cache or generate a new one
* if caching is disabled.
* @param txIdPrefix the transaction id prefix.
* @return the suffix.
* @throws NoProducerAvailableException if caching is enabled and no suffixes are available.
*/
@Override
public String acquireSuffix(@Nullable String txIdPrefix) {
Assert.notNull(txIdPrefix, "'txIdPrefix' must not be null");
BlockingQueue<String> cache = getSuffixCache(txIdPrefix);
if (cache == null) {
return String.valueOf(this.transactionIdSuffix.getAndIncrement());
}
String suffix = cache.poll();
if (suffix == null) {
throw new NoProducerAvailableException("No available transaction producer", txIdPrefix);
}
return suffix;
}
@Override
public void releaseSuffix(@Nullable String txIdPrefix, @Nullable String suffix) {
|
Assert.notNull(txIdPrefix, "'txIdPrefix' must not be null");
Assert.notNull(suffix, "'suffix' must not be null");
if (this.maxCache <= 0) {
return;
}
BlockingQueue<String> queue = getSuffixCache(txIdPrefix);
if (queue != null && !queue.contains(suffix)) {
queue.add(suffix);
}
}
@Nullable
private BlockingQueue<String> getSuffixCache(String txIdPrefix) {
if (this.maxCache <= 0) {
return null;
}
return this.suffixCache.computeIfAbsent(txIdPrefix, txId -> {
BlockingQueue<String> queue = new LinkedBlockingQueue<>();
for (int suffix = 0; suffix < this.maxCache; suffix++) {
queue.add(String.valueOf(this.transactionIdSuffix.getAndIncrement()));
}
return queue;
});
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\DefaultTransactionIdSuffixStrategy.java
| 1
|
请完成以下Java代码
|
public String getVariableName() {
return variableName;
}
public void setVariableName(String variableName) {
this.variableName = variableName;
}
public Expression getVariableExpression() {
return variableExpression;
}
public void setVariableExpression(Expression variableExpression) {
this.variableExpression = variableExpression;
}
|
public Expression getDefaultExpression() {
return defaultExpression;
}
public void setDefaultExpression(Expression defaultExpression) {
this.defaultExpression = defaultExpression;
}
public boolean isWritable() {
return isWritable;
}
public void setWritable(boolean isWritable) {
this.isWritable = isWritable;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\handler\FormPropertyHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
brave.Tracer braveTracer(Tracing tracing) {
return tracing.tracer();
}
@Bean
@ConditionalOnMissingBean
CurrentTraceContext braveCurrentTraceContext(List<CurrentTraceContext.ScopeDecorator> scopeDecorators,
List<CurrentTraceContextCustomizer> currentTraceContextCustomizers) {
ThreadLocalCurrentTraceContext.Builder builder = ThreadLocalCurrentTraceContext.newBuilder();
scopeDecorators.forEach(builder::addScopeDecorator);
for (CurrentTraceContextCustomizer currentTraceContextCustomizer : currentTraceContextCustomizers) {
currentTraceContextCustomizer.customize(builder);
}
return builder.build();
}
@Bean
@ConditionalOnMissingBean
Sampler braveSampler() {
return Sampler.create(this.tracingProperties.getSampling().getProbability());
}
@Bean
@ConditionalOnMissingBean(io.micrometer.tracing.Tracer.class)
BraveTracer braveTracerBridge(brave.Tracer tracer, CurrentTraceContext currentTraceContext) {
return new BraveTracer(tracer, new BraveCurrentTraceContext(currentTraceContext),
new BraveBaggageManager(this.tracingProperties.getBaggage().getTagFields(),
this.tracingProperties.getBaggage().getRemoteFields()));
}
|
@Bean
@ConditionalOnMissingBean
BravePropagator bravePropagator(Tracing tracing) {
return new BravePropagator(tracing);
}
@Bean
@ConditionalOnMissingBean(SpanCustomizer.class)
CurrentSpanCustomizer currentSpanCustomizer(Tracing tracing) {
return CurrentSpanCustomizer.create(tracing);
}
@Bean
@ConditionalOnMissingBean(io.micrometer.tracing.SpanCustomizer.class)
BraveSpanCustomizer braveSpanCustomizer(SpanCustomizer spanCustomizer) {
return new BraveSpanCustomizer(spanCustomizer);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-brave\src\main\java\org\springframework\boot\micrometer\tracing\brave\autoconfigure\BraveAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs)
throws IOException {
NestedPath nestedPath = NestedPath.cast(path);
return new NestedByteChannel(nestedPath.getJarPath(), nestedPath.getNestedEntryName());
}
@Override
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 String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Pet photoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls;
return this;
}
public Pet addPhotoUrlsItem(String photoUrlsItem) {
this.photoUrls.add(photoUrlsItem);
return this;
}
/**
* Get photoUrls
* @return photoUrls
**/
@ApiModelProperty(required = true, value = "")
public List<String> getPhotoUrls() {
return photoUrls;
}
public void setPhotoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls;
}
public Pet tags(List<Tag> tags) {
this.tags = tags;
return this;
}
public Pet addTagsItem(Tag tagsItem) {
if (this.tags == null) {
this.tags = new ArrayList<Tag>();
}
this.tags.add(tagsItem);
return this;
}
/**
* Get tags
* @return tags
**/
@ApiModelProperty(value = "")
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public Pet status(StatusEnum status) {
this.status = status;
return this;
}
/**
* pet status in the store
* @return status
**/
|
@ApiModelProperty(value = "pet status in the store")
public StatusEnum getStatus() {
return status;
}
public void setStatus(StatusEnum status) {
this.status = status;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pet pet = (Pet) o;
return Objects.equals(this.id, pet.id) &&
Objects.equals(this.category, pet.category) &&
Objects.equals(this.name, pet.name) &&
Objects.equals(this.photoUrls, pet.photoUrls) &&
Objects.equals(this.tags, pet.tags) &&
Objects.equals(this.status, pet.status);
}
@Override
public int hashCode() {
return Objects.hash(id, category, name, photoUrls, tags, status);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Pet {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" category: ").append(toIndentedString(category)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n");
sb.append(" tags: ").append(toIndentedString(tags)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\Pet.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public CommonResult updatePublishStatus(@RequestParam("ids") List<Long> ids,
@RequestParam("publishStatus") Integer publishStatus) {
int count = productService.updatePublishStatus(ids, publishStatus);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("批量推荐商品")
@RequestMapping(value = "/update/recommendStatus", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateRecommendStatus(@RequestParam("ids") List<Long> ids,
@RequestParam("recommendStatus") Integer recommendStatus) {
int count = productService.updateRecommendStatus(ids, recommendStatus);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("批量设为新品")
@RequestMapping(value = "/update/newStatus", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateNewStatus(@RequestParam("ids") List<Long> ids,
|
@RequestParam("newStatus") Integer newStatus) {
int count = productService.updateNewStatus(ids, newStatus);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("批量修改删除状态")
@RequestMapping(value = "/update/deleteStatus", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateDeleteStatus(@RequestParam("ids") List<Long> ids,
@RequestParam("deleteStatus") Integer deleteStatus) {
int count = productService.updateDeleteStatus(ids, deleteStatus);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\PmsProductController.java
| 2
|
请完成以下Java代码
|
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Ranking.
@param Ranking
Relative Rank Number
|
*/
@Override
public void setRanking (int Ranking)
{
set_Value (COLUMNNAME_Ranking, Integer.valueOf(Ranking));
}
/** Get Ranking.
@return Relative Rank Number
*/
@Override
public int getRanking ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ranking);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponse.java
| 1
|
请完成以下Java代码
|
public Date calculateRemovalTime(HistoricBatchEntity historicBatch) {
String batchOperation = historicBatch.getType();
if (batchOperation != null) {
Integer historyTimeToLive = getTTLByBatchOperation(batchOperation);
if (historyTimeToLive != null) {
if (isBatchRunning(historicBatch)) {
Date startTime = historicBatch.getStartTime();
return determineRemovalTime(startTime, historyTimeToLive);
} else if (isBatchEnded(historicBatch)) {
Date endTime = historicBatch.getEndTime();
return determineRemovalTime(endTime, historyTimeToLive);
}
}
}
return null;
}
protected boolean isBatchRunning(HistoricBatchEntity historicBatch) {
return historicBatch.getEndTime() == null;
}
protected boolean isBatchEnded(HistoricBatchEntity historicBatch) {
return historicBatch.getEndTime() != null;
}
protected Integer getTTLByBatchOperation(String batchOperation) {
return Context.getCommandContext()
.getProcessEngineConfiguration()
.getParsedBatchOperationsForHistoryCleanup()
.get(batchOperation);
|
}
protected boolean isProcessInstanceRunning(HistoricProcessInstanceEventEntity historicProcessInstance) {
return historicProcessInstance.getEndTime() == null;
}
protected boolean isProcessInstanceEnded(HistoricProcessInstanceEventEntity historicProcessInstance) {
return historicProcessInstance.getEndTime() != null;
}
public static Date determineRemovalTime(Date initTime, Integer timeToLive) {
Calendar removalTime = Calendar.getInstance();
removalTime.setTime(initTime);
removalTime.add(Calendar.DATE, timeToLive);
return removalTime.getTime();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\DefaultHistoryRemovalTimeProvider.java
| 1
|
请完成以下Java代码
|
public void deleteCalculatedField(TenantId tenantId, CalculatedFieldId calculatedFieldId) {
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
validateId(calculatedFieldId, id -> INCORRECT_CALCULATED_FIELD_ID + id);
deleteEntity(tenantId, calculatedFieldId, false);
}
@Override
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
CalculatedField calculatedField = calculatedFieldDao.findById(tenantId, id.getId());
if (calculatedField == null) {
if (force) {
return;
} else {
throw new IncorrectParameterException("Unable to delete non-existent calculated field.");
}
}
deleteCalculatedField(tenantId, calculatedField);
}
private void deleteCalculatedField(TenantId tenantId, CalculatedField calculatedField) {
log.trace("Executing deleteCalculatedField, tenantId [{}], calculatedFieldId [{}]", tenantId, calculatedField.getId());
calculatedFieldDao.removeById(tenantId, calculatedField.getUuidId());
eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entityId(calculatedField.getId()).entity(calculatedField).build());
}
@Override
public int deleteAllCalculatedFieldsByEntityId(TenantId tenantId, EntityId entityId) {
log.trace("Executing deleteAllCalculatedFieldsByEntityId, tenantId [{}], entityId [{}]", tenantId, entityId);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
validateId(entityId.getId(), id -> INCORRECT_ENTITY_ID + id);
List<CalculatedField> calculatedFields = calculatedFieldDao.removeAllByEntityId(tenantId, entityId);
return calculatedFields.size();
|
}
@Override
public boolean referencedInAnyCalculatedField(TenantId tenantId, EntityId referencedEntityId) {
return calculatedFieldDao.findAllByTenantId(tenantId).stream()
.filter(calculatedField -> !referencedEntityId.equals(calculatedField.getEntityId()))
.map(CalculatedField::getConfiguration)
.map(CalculatedFieldConfiguration::getReferencedEntities)
.anyMatch(referencedEntities -> referencedEntities.contains(referencedEntityId));
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findById(tenantId, new CalculatedFieldId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(calculatedFieldDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.CALCULATED_FIELD;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\cf\BaseCalculatedFieldService.java
| 1
|
请完成以下Java代码
|
public void setPolicy(ReferrerPolicy policy) {
Assert.notNull(policy, "policy can not be null");
this.policy = policy;
}
/**
* @see org.springframework.security.web.header.HeaderWriter#writeHeaders(HttpServletRequest,
* HttpServletResponse)
*/
@Override
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
if (!response.containsHeader(REFERRER_POLICY_HEADER)) {
response.setHeader(REFERRER_POLICY_HEADER, this.policy.getPolicy());
}
}
public enum ReferrerPolicy {
NO_REFERRER("no-referrer"),
NO_REFERRER_WHEN_DOWNGRADE("no-referrer-when-downgrade"),
SAME_ORIGIN("same-origin"),
ORIGIN("origin"),
STRICT_ORIGIN("strict-origin"),
ORIGIN_WHEN_CROSS_ORIGIN("origin-when-cross-origin"),
STRICT_ORIGIN_WHEN_CROSS_ORIGIN("strict-origin-when-cross-origin"),
UNSAFE_URL("unsafe-url");
private static final Map<String, ReferrerPolicy> REFERRER_POLICIES;
static {
Map<String, ReferrerPolicy> referrerPolicies = new HashMap<>();
|
for (ReferrerPolicy referrerPolicy : values()) {
referrerPolicies.put(referrerPolicy.getPolicy(), referrerPolicy);
}
REFERRER_POLICIES = Collections.unmodifiableMap(referrerPolicies);
}
private final String policy;
ReferrerPolicy(String policy) {
this.policy = policy;
}
public String getPolicy() {
return this.policy;
}
public static @Nullable ReferrerPolicy get(String referrerPolicy) {
return REFERRER_POLICIES.get(referrerPolicy);
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\ReferrerPolicyHeaderWriter.java
| 1
|
请完成以下Java代码
|
public EndpointServlet withInitParameter(String name, String value) {
Assert.hasText(name, "'name' must not be empty");
return withInitParameters(Collections.singletonMap(name, value));
}
public EndpointServlet withInitParameters(Map<String, String> initParameters) {
Assert.notNull(initParameters, "'initParameters' must not be null");
boolean hasEmptyName = initParameters.keySet().stream().anyMatch((name) -> !StringUtils.hasText(name));
Assert.isTrue(!hasEmptyName, "'initParameters' must not contain empty names");
Map<String, String> mergedInitParameters = new LinkedHashMap<>(this.initParameters);
mergedInitParameters.putAll(initParameters);
return new EndpointServlet(this.servlet, mergedInitParameters, this.loadOnStartup);
}
/**
* Sets the {@code loadOnStartup} priority that will be set on Servlet registration.
* The default value for {@code loadOnStartup} is {@code -1}.
* @param loadOnStartup the initialization priority of the Servlet
* @return a new instance of {@link EndpointServlet} with the provided
* {@code loadOnStartup} value set
* @since 2.2.0
* @see Dynamic#setLoadOnStartup(int)
*/
public EndpointServlet withLoadOnStartup(int loadOnStartup) {
|
return new EndpointServlet(this.servlet, this.initParameters, loadOnStartup);
}
Servlet getServlet() {
return this.servlet;
}
Map<String, String> getInitParameters() {
return this.initParameters;
}
int getLoadOnStartup() {
return this.loadOnStartup;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\EndpointServlet.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void exportUser(HttpServletResponse response) {
List<UserExcel> list = new ArrayList<>();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
String fileName = URLEncoder.encode("用户数据模板", StandardCharsets.UTF_8);
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
FastExcel.write(response.getOutputStream(), UserExcel.class).sheet("用户数据表").doWrite(list);
}
/**
* 第三方注册用户
*/
@PostMapping("/register-guest")
@ApiOperationSupport(order = 15)
@Operation(summary = "第三方注册用户", description = "传入user")
public R registerGuest(User user, Long oauthId) {
return R.status(userService.registerGuest(user, oauthId));
}
/**
* 用户解锁
|
*/
@PostMapping("/unlock")
@ApiOperationSupport(order = 16)
@Operation(summary = "账号解锁")
@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
public R unlock(String userIds) {
if (StringUtil.isBlank(userIds)) {
return R.fail("请至少选择一个用户");
}
List<User> userList = userService.list(Wrappers.<User>lambdaQuery().in(User::getId, Func.toLongList(userIds)));
userList.forEach(user -> bladeRedis.del(CacheNames.tenantKey(user.getTenantId(), CacheNames.USER_FAIL_KEY, user.getAccount())));
return R.success("操作成功");
}
}
|
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\UserController.java
| 2
|
请完成以下Java代码
|
public boolean isCancelled() {
return mainFuture.isCancelled();
}
@Override
public boolean isDone() {
return mainFuture.isDone();
}
@Override
public TbResultSet get() throws InterruptedException, ExecutionException {
return mainFuture.get();
}
@Override
public TbResultSet get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return mainFuture.get(timeout, unit);
}
@Override
public void addListener(Runnable listener, Executor executor) {
mainFuture.addListener(listener, executor);
}
|
private TbResultSet getSafe() {
try {
return mainFuture.get();
} catch (InterruptedException | ExecutionException e) {
throw new IllegalStateException(e);
}
}
private TbResultSet getSafe(long timeout, TimeUnit unit) throws TimeoutException {
try {
return mainFuture.get(timeout, unit);
} catch (InterruptedException | ExecutionException e) {
throw new IllegalStateException(e);
}
}
}
|
repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\nosql\TbResultSetFuture.java
| 1
|
请完成以下Java代码
|
public void setPaymentTermId(@Nullable final PaymentTermId paymentTermId)
{
this.paymentTermId = paymentTermId;
}
@Override
public PaymentTermId getPaymentTermId()
{
return paymentTermId;
}
public void setPaymentRule(@Nullable final String paymentRule)
{
this.paymentRule = paymentRule;
}
@Override
public String getPaymentRule()
{
return paymentRule;
}
@Override
public String getExternalId()
{
return externalId;
}
@Override
public int getC_Async_Batch_ID()
{
return C_Async_Batch_ID;
}
public void setC_Async_Batch_ID(final int C_Async_Batch_ID)
{
this.C_Async_Batch_ID = C_Async_Batch_ID;
}
|
public String setExternalId(String externalId)
{
return this.externalId = externalId;
}
@Override
public int getC_Incoterms_ID()
{
return C_Incoterms_ID;
}
public void setC_Incoterms_ID(final int C_Incoterms_ID)
{
this.C_Incoterms_ID = C_Incoterms_ID;
}
@Override
public String getIncotermLocation()
{
return incotermLocation;
}
public void setIncotermLocation(final String incotermLocation)
{
this.incotermLocation = incotermLocation;
}
@Override
public InputDataSourceId getAD_InputDataSource_ID() { return inputDataSourceId;}
public void setAD_InputDataSource_ID(final InputDataSourceId inputDataSourceId){this.inputDataSourceId = inputDataSourceId;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceHeaderImpl.java
| 1
|
请完成以下Java代码
|
public Integer getCollectCouont() {
return collectCouont;
}
public void setCollectCouont(Integer collectCouont) {
this.collectCouont = collectCouont;
}
public Integer getReadCount() {
return readCount;
}
public void setReadCount(Integer readCount) {
this.readCount = readCount;
}
public String getPics() {
return pics;
}
public void setPics(String pics) {
this.pics = pics;
}
public String getMemberIcon() {
return memberIcon;
}
public void setMemberIcon(String memberIcon) {
this.memberIcon = memberIcon;
}
public Integer getReplayCount() {
return replayCount;
}
public void setReplayCount(Integer replayCount) {
this.replayCount = replayCount;
}
public String getContent() {
|
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", productId=").append(productId);
sb.append(", memberNickName=").append(memberNickName);
sb.append(", productName=").append(productName);
sb.append(", star=").append(star);
sb.append(", memberIp=").append(memberIp);
sb.append(", createTime=").append(createTime);
sb.append(", showStatus=").append(showStatus);
sb.append(", productAttribute=").append(productAttribute);
sb.append(", collectCouont=").append(collectCouont);
sb.append(", readCount=").append(readCount);
sb.append(", pics=").append(pics);
sb.append(", memberIcon=").append(memberIcon);
sb.append(", replayCount=").append(replayCount);
sb.append(", content=").append(content);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsComment.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void onSuccess(TbQueueMsgMetadata metadata) {
}
@Override
public void onFailure(Throwable t) {
log.error("Failed to send state message: {}", stateId, t);
}
});
callback.onSuccess();
}
@Override
protected void doRemove(CalculatedFieldEntityCtxId stateId, TbCallback callback) {
doPersist(stateId, null, callback);
}
private void putStateId(TbQueueMsgHeaders headers, CalculatedFieldEntityCtxId stateId) {
headers.put("tenantId", uuidToBytes(stateId.tenantId().getId()));
headers.put("cfId", uuidToBytes(stateId.cfId().getId()));
headers.put("entityId", uuidToBytes(stateId.entityId().getId()));
|
headers.put("entityType", stringToBytes(stateId.entityId().getEntityType().name()));
}
private CalculatedFieldEntityCtxId getStateId(TbQueueMsgHeaders headers) {
TenantId tenantId = TenantId.fromUUID(bytesToUuid(headers.get("tenantId")));
CalculatedFieldId cfId = new CalculatedFieldId(bytesToUuid(headers.get("cfId")));
EntityId entityId = EntityIdFactory.getByTypeAndUuid(bytesToString(headers.get("entityType")), bytesToUuid(headers.get("entityId")));
return new CalculatedFieldEntityCtxId(tenantId, cfId, entityId);
}
@Override
public void stop() {
super.stop();
stateProducer.stop();
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\cf\ctx\state\KafkaCalculatedFieldStateService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Job multiStepJob() {
// return jobBuilderFactory.get("multiStepJob")
// .start(step1())
// .next(step2())
// .next(step3())
// .build();
return jobBuilderFactory.get("multiStepJob2")
.start(step1())
.on(ExitStatus.COMPLETED.getExitCode()).to(step2())
.from(step2())
.on(ExitStatus.COMPLETED.getExitCode()).to(step3())
.from(step3()).end()
.build();
}
private Step step1() {
return stepBuilderFactory.get("step1")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("执行步骤一操作。。。");
return RepeatStatus.FINISHED;
}).build();
}
|
private Step step2() {
return stepBuilderFactory.get("step2")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("执行步骤二操作。。。");
return RepeatStatus.FINISHED;
}).build();
}
private Step step3() {
return stepBuilderFactory.get("step3")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("执行步骤三操作。。。");
return RepeatStatus.FINISHED;
}).build();
}
}
|
repos\SpringAll-master\67.spring-batch-start\src\main\java\cc\mrbird\batch\job\MultiStepJobDemo.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getElementId() {
return elementId;
}
public void setElementId(String elementId) {
this.elementId = elementId;
}
public String getElementName() {
return elementName;
}
public void setElementName(String elementName) {
this.elementName = elementName;
}
public Integer getRetries() {
return retries;
}
public void setRetries(Integer retries) {
this.retries = retries;
}
public String getExceptionMessage() {
return exceptionMessage;
}
|
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
}
public String getLockOwner() {
return lockOwner;
}
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
}
public Date getLockExpirationTime() {
return lockExpirationTime;
}
public void setLockExpirationTime(Date lockExpirationTime) {
this.lockExpirationTime = lockExpirationTime;
}
}
|
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\query\ExternalWorkerJobResponse.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Class<?> getObjectType() {
return AuthorizationManagerBeforeMethodInterceptor.class;
}
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
public void setExpressionHandler(MethodSecurityExpressionHandler expressionHandler) {
this.manager.setExpressionHandler(expressionHandler);
}
public void setObservationRegistry(ObservationRegistry registry) {
this.observationRegistry = registry;
}
}
public static final class PostAuthorizeAuthorizationMethodInterceptor
implements FactoryBean<AuthorizationManagerAfterMethodInterceptor> {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private ObservationRegistry observationRegistry = ObservationRegistry.NOOP;
private final PostAuthorizeAuthorizationManager manager = new PostAuthorizeAuthorizationManager();
@Override
public AuthorizationManagerAfterMethodInterceptor getObject() {
AuthorizationManager<MethodInvocationResult> manager = this.manager;
if (!this.observationRegistry.isNoop()) {
manager = new ObservationAuthorizationManager<>(this.observationRegistry, this.manager);
}
AuthorizationManagerAfterMethodInterceptor interceptor = AuthorizationManagerAfterMethodInterceptor
.postAuthorize(manager);
interceptor.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
return interceptor;
}
@Override
public Class<?> getObjectType() {
return AuthorizationManagerAfterMethodInterceptor.class;
}
|
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
public void setExpressionHandler(MethodSecurityExpressionHandler expressionHandler) {
this.manager.setExpressionHandler(expressionHandler);
}
public void setObservationRegistry(ObservationRegistry registry) {
this.observationRegistry = registry;
}
}
static class SecurityContextHolderStrategyFactory implements FactoryBean<SecurityContextHolderStrategy> {
@Override
public SecurityContextHolderStrategy getObject() throws Exception {
return SecurityContextHolder.getContextHolderStrategy();
}
@Override
public Class<?> getObjectType() {
return SecurityContextHolderStrategy.class;
}
}
static class ObservationRegistryFactory implements FactoryBean<ObservationRegistry> {
@Override
public ObservationRegistry getObject() throws Exception {
return ObservationRegistry.NOOP;
}
@Override
public Class<?> getObjectType() {
return ObservationRegistry.class;
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\MethodSecurityBeanDefinitionParser.java
| 2
|
请完成以下Java代码
|
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Integer getPtype() {
return ptype;
}
public void setPtype(Integer ptype) {
this.ptype = ptype;
}
public String getPval() {
return pval;
}
public void setPval(String pval) {
this.pval = pval;
}
|
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
}
|
repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\entity\Perm.java
| 1
|
请完成以下Java代码
|
public int getMaxImpression ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MaxImpression);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
/** Set Start Count Impression.
@param StartImpression
For rotation we need a start count
*/
public void setStartImpression (int StartImpression)
{
set_Value (COLUMNNAME_StartImpression, Integer.valueOf(StartImpression));
}
/** Get Start Count Impression.
@return For rotation we need a start count
*/
public int getStartImpression ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StartImpression);
if (ii == null)
return 0;
return ii.intValue();
|
}
/** Set Target Frame.
@param Target_Frame
Which target should be used if user clicks?
*/
public void setTarget_Frame (String Target_Frame)
{
set_Value (COLUMNNAME_Target_Frame, Target_Frame);
}
/** Get Target Frame.
@return Which target should be used if user clicks?
*/
public String getTarget_Frame ()
{
return (String)get_Value(COLUMNNAME_Target_Frame);
}
/** Set Target URL.
@param TargetURL
URL for the Target
*/
public void setTargetURL (String TargetURL)
{
set_Value (COLUMNNAME_TargetURL, TargetURL);
}
/** Get Target URL.
@return URL for the Target
*/
public String getTargetURL ()
{
return (String)get_Value(COLUMNNAME_TargetURL);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Ad.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void loadShiroFilterChain(ShiroFilterFactoryBean shiroFilterFactoryBean) {
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/", "securityFilter");
filterChainDefinitionMap.put("/index", "securityFilter");
filterChainDefinitionMap.put("/callback", "callbackFilter");
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/**", "anon");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
}
/**
* shiroFilter
* @param securityManager
* @param config
* @return
*/
@Bean("shiroFilter")
public ShiroFilterFactoryBean factory(DefaultWebSecurityManager securityManager, Config config) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 必须设置 SecurityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
//shiroFilterFactoryBean.setUnauthorizedUrl("/403");
// 添加casFilter到shiroFilter中
loadShiroFilterChain(shiroFilterFactoryBean);
Map<String, Filter> filters = new HashMap<>(4);
//cas 资源认证拦截器
SecurityFilter securityFilter = new SecurityFilter();
securityFilter.setConfig(config);
securityFilter.setClients(clientName);
filters.put("securityFilter", securityFilter);
//cas 认证后回调拦截器
CallbackFilter callbackFilter = new CallbackFilter();
callbackFilter.setConfig(config);
callbackFilter.setDefaultUrl(projectUrl);
filters.put("callbackFilter", callbackFilter);
// 注销 拦截器
LogoutFilter logoutFilter = new LogoutFilter();
logoutFilter.setConfig(config);
logoutFilter.setCentralLogout(true);
logoutFilter.setLocalLogout(true);
//添加logout后 跳转到指定url url的匹配规则 默认为 /.*;
logoutFilter.setLogoutUrlPattern(".*");
logoutFilter.setDefaultUrl(projectUrl + "/callback?client_name=" + clientName);
filters.put("logout", logoutFilter);
shiroFilterFactoryBean.setFilters(filters);
return shiroFilterFactoryBean;
}
@Bean
public SessionDAO sessionDAO() {
return new MemorySessionDAO();
}
|
/**
* 自定义cookie名称
* @return
*/
@Bean
public SimpleCookie sessionIdCookie() {
SimpleCookie cookie = new SimpleCookie("sid");
cookie.setMaxAge(-1);
cookie.setPath("/");
cookie.setHttpOnly(false);
return cookie;
}
@Bean
public DefaultWebSessionManager sessionManager(SimpleCookie sessionIdCookie, SessionDAO sessionDAO) {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setSessionIdCookie(sessionIdCookie);
sessionManager.setSessionIdCookieEnabled(true);
//30分钟
sessionManager.setGlobalSessionTimeout(180000);
sessionManager.setSessionDAO(sessionDAO);
sessionManager.setDeleteInvalidSessions(true);
sessionManager.setSessionValidationSchedulerEnabled(true);
return sessionManager;
}
}
|
repos\spring-boot-quick-master\quick-shiro-cas\src\main\java\com\shiro\config\ShiroConfig.java
| 2
|
请完成以下Java代码
|
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Distribution List.
@param M_DistributionList_ID
Distribution Lists allow to distribute products to a selected list of partners
*/
public void setM_DistributionList_ID (int M_DistributionList_ID)
{
if (M_DistributionList_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DistributionList_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DistributionList_ID, Integer.valueOf(M_DistributionList_ID));
}
/** Get Distribution List.
@return Distribution Lists allow to distribute products to a selected list of partners
*/
public int getM_DistributionList_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionList_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
|
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Total Ratio.
@param RatioTotal
Total of relative weight in a distribution
*/
public void setRatioTotal (BigDecimal RatioTotal)
{
set_Value (COLUMNNAME_RatioTotal, RatioTotal);
}
/** Get Total Ratio.
@return Total of relative weight in a distribution
*/
public BigDecimal getRatioTotal ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RatioTotal);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionList.java
| 1
|
请完成以下Java代码
|
public final class Cache implements TreeCache {
private final Map<String,Tree> primary;
private final Map<String,Tree> secondary;
/**
* Constructor.
* Use a {@link WeakHashMap} as secondary map.
* @param size maximum primary cache size
*/
public Cache(int size) {
this(size, new WeakHashMap<String,Tree>());
}
/**
* Constructor.
* If the least recently used entry is removed from the primary cache, it is added to
* the secondary map.
* @param size maximum primary cache size
* @param secondary the secondary map (may be <code>null</code>)
*/
@SuppressWarnings("serial")
public Cache(final int size, Map<String,Tree> secondary) {
this.primary = Collections.synchronizedMap(new LinkedHashMap<String,Tree>(16, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Entry<String,Tree> eldest) {
if (size() > size) {
if (Cache.this.secondary != null) { // move to secondary cache
Cache.this.secondary.put(eldest.getKey(), eldest.getValue());
}
return true;
}
return false;
}
});
|
this.secondary = secondary == null ? null : Collections.synchronizedMap(secondary);
}
public Tree get(String expression) {
if (secondary == null) {
return primary.get(expression);
} else {
Tree tree = primary.get(expression);
if (tree == null) {
tree = secondary.get(expression);
}
return tree;
}
}
public void put(String expression, Tree tree) {
primary.put(expression, tree);
}
}
|
repos\camunda-bpm-platform-master\juel\src\main\java\org\camunda\bpm\impl\juel\Cache.java
| 1
|
请完成以下Java代码
|
public static List<String> processPatterns(List<String> patterns, TbMsg tbMsg) {
if (CollectionsUtil.isEmpty(patterns)) {
return Collections.emptyList();
}
return patterns.stream().map(p -> processPattern(p, tbMsg)).toList();
}
public static String processPattern(String pattern, TbMsg tbMsg) {
try {
String result = processPattern(pattern, tbMsg.getMetaData());
JsonNode json = JacksonUtil.toJsonNode(tbMsg.getData());
result = result.replace(ALL_DATA_TEMPLATE, JacksonUtil.toString(json));
if (json.isObject()) {
Matcher matcher = DATA_PATTERN.matcher(result);
while (matcher.find()) {
String group = matcher.group(2);
String[] keys = group.split("\\.");
JsonNode jsonNode = json;
for (String key : keys) {
if (StringUtils.isNotEmpty(key) && jsonNode != null) {
jsonNode = jsonNode.get(key);
} else {
jsonNode = null;
break;
}
}
if (jsonNode != null && jsonNode.isValueNode()) {
result = result.replace(formatDataVarTemplate(group), jsonNode.asText());
}
}
}
return result;
} catch (Exception e) {
throw new RuntimeException("Failed to process pattern!", e);
}
}
|
private static String processPattern(String pattern, TbMsgMetaData metaData) {
String replacement = metaData.isEmpty() ? "{}" : JacksonUtil.toString(metaData.getData());
pattern = pattern.replace(ALL_METADATA_TEMPLATE, replacement);
return processTemplate(pattern, metaData.values());
}
public static String processTemplate(String template, Map<String, String> data) {
String result = template;
for (Map.Entry<String, String> kv : data.entrySet()) {
result = processVar(result, kv.getKey(), kv.getValue());
}
return result;
}
private static String processVar(String pattern, String key, String val) {
return pattern.replace(formatMetadataVarTemplate(key), val);
}
static String formatDataVarTemplate(String key) {
return "$[" + key + "]";
}
static String formatMetadataVarTemplate(String key) {
return "${" + key + "}";
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-api\src\main\java\org\thingsboard\rule\engine\api\util\TbNodeUtils.java
| 1
|
请完成以下Java代码
|
public LocalDate getDocumentDate()
{
return TimeUtil.asLocalDate(getDateReport());
}
/**
* Get Process Message
* @return clear text error message
*/
@Override
public String getProcessMsg()
{
return m_processMsg;
} // getProcessMsg
/**
* Get Document Owner (Responsible)
* @return AD_User_ID
*/
@Override
public int getDoc_User_ID()
{
if (m_AD_User_ID != 0)
return m_AD_User_ID;
if (getC_BPartner_ID() != 0)
{
final List<I_AD_User> users = Services.get(IBPartnerDAO.class).retrieveContacts(getCtx(), getC_BPartner_ID(), ITrx.TRXNAME_None);
if (!users.isEmpty())
{
m_AD_User_ID = users.get(0).getAD_User_ID();
return m_AD_User_ID;
|
}
}
return getCreatedBy();
} // getDoc_User_ID
/**
* Get Document Currency
* @return C_Currency_ID
*/
@Override
public int getC_Currency_ID()
{
final I_M_PriceList pl = Services.get(IPriceListDAO.class).getById(getM_PriceList_ID());
return pl.getC_Currency_ID();
} // getC_Currency_ID
/**
* Document Status is Complete or Closed
* @return true if CO, CL or RE
*/
public boolean isComplete()
{
String ds = getDocStatus();
return DOCSTATUS_Completed.equals(ds)
|| DOCSTATUS_Closed.equals(ds)
|| DOCSTATUS_Reversed.equals(ds);
} // isComplete
} // MTimeExpense
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MTimeExpense.java
| 1
|
请完成以下Java代码
|
public List<DataAssociation> getDataOutputAssociations() {
return dataOutputAssociations;
}
public void setDataOutputAssociations(List<DataAssociation> dataOutputAssociations) {
this.dataOutputAssociations = dataOutputAssociations;
}
public List<MapExceptionEntry> getMapExceptions() {
return mapExceptions;
}
public void setMapExceptions(List<MapExceptionEntry> mapExceptions) {
this.mapExceptions = mapExceptions;
}
public void setValues(Activity otherActivity) {
super.setValues(otherActivity);
setFailedJobRetryTimeCycleValue(otherActivity.getFailedJobRetryTimeCycleValue());
setDefaultFlow(otherActivity.getDefaultFlow());
setForCompensation(otherActivity.isForCompensation());
if (otherActivity.getLoopCharacteristics() != null) {
setLoopCharacteristics(otherActivity.getLoopCharacteristics().clone());
}
if (otherActivity.getIoSpecification() != null) {
setIoSpecification(otherActivity.getIoSpecification().clone());
}
|
dataInputAssociations = new ArrayList<DataAssociation>();
if (otherActivity.getDataInputAssociations() != null && !otherActivity.getDataInputAssociations().isEmpty()) {
for (DataAssociation association : otherActivity.getDataInputAssociations()) {
dataInputAssociations.add(association.clone());
}
}
dataOutputAssociations = new ArrayList<DataAssociation>();
if (otherActivity.getDataOutputAssociations() != null && !otherActivity.getDataOutputAssociations().isEmpty()) {
for (DataAssociation association : otherActivity.getDataOutputAssociations()) {
dataOutputAssociations.add(association.clone());
}
}
boundaryEvents.clear();
for (BoundaryEvent event : otherActivity.getBoundaryEvents()) {
boundaryEvents.add(event);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Activity.java
| 1
|
请完成以下Java代码
|
public Object getTransientVariableLocal(String variableName) {
throw new UnsupportedOperationException();
}
@Override
public Map<String, Object> getTransientVariablesLocal() {
throw new UnsupportedOperationException();
}
@Override
public Object getTransientVariable(String variableName) {
throw new UnsupportedOperationException();
}
@Override
public Map<String, Object> getTransientVariables() {
throw new UnsupportedOperationException();
}
@Override
public void removeTransientVariableLocal(String variableName) {
throw new UnsupportedOperationException();
}
|
@Override
public void removeTransientVariablesLocal() {
throw new UnsupportedOperationException();
}
@Override
public void removeTransientVariable(String variableName) {
throw new UnsupportedOperationException();
}
@Override
public void removeTransientVariables() {
throw new UnsupportedOperationException();
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\ExecutionImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ApplicationRunner init() {
return args -> {
System.out.println("\n\n Fetch authors read-only entities:");
System.out.println("-----------------------------------------------------------------------------");
bookstoreService.fetchAuthorAsReadOnlyEntities();
System.out.println("\n\n Fetch authors as array of objects");
System.out.println("-----------------------------------------------------------------------------");
bookstoreService.fetchAuthorAsArrayOfObject();
System.out.println("\n\n Fetch authors as array of objects by specifying columns");
System.out.println("-----------------------------------------------------------------------------");
bookstoreService.fetchAuthorAsArrayOfObjectColumns();
System.out.println("\n\n Fetch authors as array of objects via native query");
System.out.println("-----------------------------------------------------------------------------");
bookstoreService.fetchAuthorAsArrayOfObjectNative();
System.out.println("\n\n Fetch authors as array of objects via query builder mechanism");
System.out.println("-----------------------------------------------------------------------------");
bookstoreService.fetchAuthorAsArrayOfObjectQueryBuilderMechanism();
System.out.println("\n\n Fetch authors as Spring projection (DTO):");
|
System.out.println("-----------------------------------------------------------------------------");
bookstoreService.fetchAuthorAsDtoClass();
System.out.println("\n\n Fetch authors as Spring projection (DTO) by specifying columns:");
System.out.println("-----------------------------------------------------------------------------");
bookstoreService.fetchAuthorAsDtoClassColumns();
System.out.println("\n\n Fetch authors as Spring projection (DTO) and native query:");
System.out.println("-----------------------------------------------------------------------------");
bookstoreService.fetchAuthorAsDtoClassNative();
System.out.println("\n\n Fetch authors as Spring projection (DTO) via query builder mechanism:");
System.out.println("-----------------------------------------------------------------------------");
bookstoreService.fetchAuthorByGenreAsDtoClassQueryBuilderMechanism();
};
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinDtoAllFields\src\main\java\com\bookstore\MainApplication.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
protected Optional<Integer> getDistributedSystemId() {
return Optional.ofNullable(this.distributedSystemId)
.filter(id -> id > -1);
}
protected Logger getLogger() {
return this.logger;
}
private int validateDistributedSystemId(int distributedSystemId) {
Assert.isTrue(distributedSystemId >= -1 && distributedSystemId < 256,
String.format("Distributed System ID [%d] must be between -1 and 255", distributedSystemId));
return distributedSystemId;
}
@Bean
ClientCacheConfigurer clientCacheDistributedSystemIdConfigurer() {
return (beanName, clientCacheFactoryBean) -> getDistributedSystemId().ifPresent(distributedSystemId -> {
Logger logger = getLogger();
if (logger.isWarnEnabled()) {
|
logger.warn("Distributed System Id [{}] was set on the ClientCache instance, which will not have any effect",
distributedSystemId);
}
});
}
@Bean
PeerCacheConfigurer peerCacheDistributedSystemIdConfigurer() {
return (beanName, cacheFactoryBean) ->
getDistributedSystemId().ifPresent(id -> cacheFactoryBean.getProperties()
.setProperty(GEMFIRE_DISTRIBUTED_SYSTEM_ID_PROPERTY,
String.valueOf(validateDistributedSystemId(id))));
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\DistributedSystemIdConfiguration.java
| 2
|
请完成以下Java代码
|
public void setLogLevel(@Nullable String loggerName, @Nullable LogLevel level) {
throw new UnsupportedOperationException("Unable to set log level");
}
/**
* Returns a collection of the current configuration for all a {@link LoggingSystem}'s
* loggers.
* @return the current configurations
* @since 1.5.0
*/
public List<LoggerConfiguration> getLoggerConfigurations() {
throw new UnsupportedOperationException("Unable to get logger configurations");
}
/**
* Returns the current configuration for a {@link LoggingSystem}'s logger.
* @param loggerName the name of the logger
* @return the current configuration
* @since 1.5.0
*/
public @Nullable LoggerConfiguration getLoggerConfiguration(String loggerName) {
throw new UnsupportedOperationException("Unable to get logger configuration");
}
/**
* Detect and return the logging system in use. Supports Logback and Java Logging.
* @param classLoader the classloader
* @return the logging system
*/
public static LoggingSystem get(ClassLoader classLoader) {
String loggingSystemClassName = System.getProperty(SYSTEM_PROPERTY);
if (StringUtils.hasLength(loggingSystemClassName)) {
if (NONE.equals(loggingSystemClassName)) {
return new NoOpLoggingSystem();
}
return get(classLoader, loggingSystemClassName);
}
LoggingSystem loggingSystem = SYSTEM_FACTORY.getLoggingSystem(classLoader);
Assert.state(loggingSystem != null, "No suitable logging system located");
return loggingSystem;
}
private static LoggingSystem get(ClassLoader classLoader, String loggingSystemClassName) {
|
try {
Class<?> systemClass = ClassUtils.forName(loggingSystemClassName, classLoader);
Constructor<?> constructor = systemClass.getDeclaredConstructor(ClassLoader.class);
constructor.setAccessible(true);
return (LoggingSystem) constructor.newInstance(classLoader);
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
/**
* {@link LoggingSystem} that does nothing.
*/
static class NoOpLoggingSystem extends LoggingSystem {
@Override
public void beforeInitialize() {
}
@Override
public void setLogLevel(@Nullable String loggerName, @Nullable LogLevel level) {
}
@Override
public List<LoggerConfiguration> getLoggerConfigurations() {
return Collections.emptyList();
}
@Override
public @Nullable LoggerConfiguration getLoggerConfiguration(String loggerName) {
return null;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\LoggingSystem.java
| 1
|
请完成以下Java代码
|
public void onMaxRetransmissionAttemptsReached() {
pendingServerUnsubscribes.computeIfPresent(variableHeader.messageId(), (__, pendingUnsubscription) -> {
var message = "Unable to deliver unsubscribe message due to max retransmission attempts (%s) being reached for client '%s' on topic '%s' (message ID: %d)"
.formatted(clientConfig.getRetransmissionConfig().maxAttempts(), clientConfig.getClientId(), topic, variableHeader.messageId());
pendingUnsubscription.getFuture().tryFailure(new MaxRetransmissionsReachedException(message));
return null;
});
}
}).build();
this.pendingServerUnsubscribes.put(variableHeader.messageId(), pendingUnsubscription);
pendingUnsubscription.startRetransmissionTimer(this.eventLoop.next(), this::sendAndFlushPacket);
this.sendAndFlushPacket(message);
} else {
promise.setSuccess(null);
}
}
private class MqttChannelInitializer extends ChannelInitializer<SocketChannel> {
private final Promise<MqttConnectResult> connectFuture;
private final String host;
private final int port;
private final SslContext sslContext;
public MqttChannelInitializer(Promise<MqttConnectResult> connectFuture, String host, int port, SslContext sslContext) {
this.connectFuture = connectFuture;
|
this.host = host;
this.port = port;
this.sslContext = sslContext;
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
if (sslContext != null) {
ch.pipeline().addLast(sslContext.newHandler(ch.alloc(), host, port));
}
ch.pipeline().addLast("mqttDecoder", new MqttDecoder(clientConfig.getMaxBytesInMessage()));
ch.pipeline().addLast("mqttEncoder", MqttEncoder.INSTANCE);
ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(MqttClientImpl.this.clientConfig.getTimeoutSeconds(), MqttClientImpl.this.clientConfig.getTimeoutSeconds(), 0));
ch.pipeline().addLast("mqttPingHandler", new MqttPingHandler(MqttClientImpl.this.clientConfig.getTimeoutSeconds()));
ch.pipeline().addLast("mqttHandler", new MqttChannelHandler(MqttClientImpl.this, connectFuture));
}
}
}
|
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttClientImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Store getKeystore() {
return this.keystore;
}
public Store getTruststore() {
return this.truststore;
}
/**
* Store properties.
*/
public static class Store {
/**
* Type of the store to create, e.g. JKS.
*/
private @Nullable String type;
/**
* Provider for the store.
*/
private @Nullable String provider;
/**
* Location of the resource containing the store content.
*/
private @Nullable String location;
/**
* Password used to access the store.
*/
private @Nullable String password;
public @Nullable String getType() {
return this.type;
}
public void setType(@Nullable String type) {
this.type = type;
}
public @Nullable String getProvider() {
return this.provider;
|
}
public void setProvider(@Nullable String provider) {
this.provider = provider;
}
public @Nullable String getLocation() {
return this.location;
}
public void setLocation(@Nullable String location) {
this.location = location;
}
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\JksSslBundleProperties.java
| 2
|
请完成以下Spring Boot application配置
|
spring:
thymeleaf:
cache: true
web:
resources:
cache:
period: PT10H
chain:
cache: true
mvc:
static-path-pattern: /static/**
datasource:
hikari:
maximum-pool-size: 500
jpa:
show-sql: false
hibernate:
ddl-auto: none # we use liquibase
generate_statist
|
ics: false
logging.level:
org.jooq.tools.LoggerListener: DEBUG
org.springframework.security: WARN
org.springframework.security.web: WARN
ROOT: INFO
gt: INFO
|
repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\resources\application-loadtest.yml
| 2
|
请完成以下Java代码
|
public static ProcessEngineInfo retry(String resourceUrl) {
try {
return initProcessEngineFromResource(new URL(resourceUrl));
} catch (MalformedURLException e) {
throw new ProcessEngineException("invalid url: "+resourceUrl, e);
}
}
/** provides access to process engine to application clients in a
* managed server environment.
*/
public static Map<String, ProcessEngine> getProcessEngines() {
return processEngines;
}
/** closes all process engines. This method should be called when the server shuts down. */
public synchronized static void destroy() {
if (isInitialized) {
Map<String, ProcessEngine> engines = new HashMap<String, ProcessEngine>(processEngines);
processEngines = new HashMap<String, ProcessEngine>();
for (String processEngineName: engines.keySet()) {
ProcessEngine processEngine = engines.get(processEngineName);
try {
processEngine.close();
|
}
catch (Exception e) {
LOG.exceptionWhileClosingProcessEngine(processEngineName==null ? "the default process engine" : "process engine "+processEngineName, e);
}
}
processEngineInfosByName.clear();
processEngineInfosByResourceUrl.clear();
processEngineInfos.clear();
isInitialized = false;
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\ProcessEngines.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static final class CheckConnectionForErrorCustomizer implements WebServiceTemplateCustomizer {
private final boolean checkConnectionForError;
private CheckConnectionForErrorCustomizer(boolean checkConnectionForError) {
this.checkConnectionForError = checkConnectionForError;
}
@Override
public void customize(WebServiceTemplate webServiceTemplate) {
webServiceTemplate.setCheckConnectionForError(this.checkConnectionForError);
}
}
/**
* {@link WebServiceTemplateCustomizer} to set
* {@link WebServiceTemplate#setFaultMessageResolver(FaultMessageResolver)
|
* faultMessageResolver}.
*/
private static final class FaultMessageResolverCustomizer implements WebServiceTemplateCustomizer {
private final FaultMessageResolver faultMessageResolver;
private FaultMessageResolverCustomizer(FaultMessageResolver faultMessageResolver) {
this.faultMessageResolver = faultMessageResolver;
}
@Override
public void customize(WebServiceTemplate webServiceTemplate) {
webServiceTemplate.setFaultMessageResolver(this.faultMessageResolver);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-webservices\src\main\java\org\springframework\boot\webservices\client\WebServiceTemplateBuilder.java
| 2
|
请完成以下Java代码
|
private static long getBufferAddress(MappedByteBuffer shm) {
try {
Class<?> cls = shm.getClass();
Method maddr = cls.getMethod("address");
maddr.setAccessible(true);
Long addr = (Long) maddr.invoke(shm);
if ( addr == null ) {
throw new RuntimeException("Unable to retrieve buffer's address");
}
return addr;
}
catch( NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
throw new RuntimeException(ex);
}
}
|
private static MappedByteBuffer createSharedMemory(String path, long size) {
try (FileChannel fc = (FileChannel)Files.newByteChannel(new File(path).toPath(),
EnumSet.of(
StandardOpenOption.CREATE,
StandardOpenOption.SPARSE,
StandardOpenOption.WRITE,
StandardOpenOption.READ))) {
return fc.map(FileChannel.MapMode.READ_WRITE, 0, size);
}
catch( IOException ioe) {
throw new RuntimeException(ioe);
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-sun\src\main\java\com\baeldung\sharedmem\ProducerApp.java
| 1
|
请完成以下Java代码
|
public class LwM2MClientSwOtaInfo extends LwM2MClientOtaInfo<LwM2MSoftwareUpdateStrategy, SoftwareUpdateState, SoftwareUpdateResult> {
public LwM2MClientSwOtaInfo(String endpoint, String baseUrl, LwM2MSoftwareUpdateStrategy strategy) {
super(endpoint, baseUrl, strategy);
}
@JsonIgnore
@Override
public OtaPackageType getType() {
return OtaPackageType.SOFTWARE;
}
public void update(SoftwareUpdateResult result) {
this.result = result;
|
if (result.getCode() >= NOT_ENOUGH_STORAGE.getCode()) {
failedPackageId = getPackageId(targetName, targetVersion);
}
switch (result) {
case INITIAL:
break;
case SUCCESSFULLY_INSTALLED:
retryAttempts = 0;
break;
default:
break;
}
}
}
|
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\ota\software\LwM2MClientSwOtaInfo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable String getCron() {
return this.cron;
}
public void setCron(@Nullable String cron) {
this.cron = cron;
}
}
public static class Management {
/**
* Whether Spring Integration components should perform logging in the main
* message flow. When disabled, such logging will be skipped without checking the
* logging level. When enabled, such logging is controlled as normal by the
* logging system's log level configuration.
*/
private boolean defaultLoggingEnabled = true;
/**
* List of simple patterns to match against the names of Spring Integration
* components. When matched, observation instrumentation will be performed for the
|
* component. Please refer to the javadoc of the smartMatch method of Spring
* Integration's PatternMatchUtils for details of the pattern syntax.
*/
private List<String> observationPatterns = new ArrayList<>();
public boolean isDefaultLoggingEnabled() {
return this.defaultLoggingEnabled;
}
public void setDefaultLoggingEnabled(boolean defaultLoggingEnabled) {
this.defaultLoggingEnabled = defaultLoggingEnabled;
}
public List<String> getObservationPatterns() {
return this.observationPatterns;
}
public void setObservationPatterns(List<String> observationPatterns) {
this.observationPatterns = observationPatterns;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-integration\src\main\java\org\springframework\boot\integration\autoconfigure\IntegrationProperties.java
| 2
|
请完成以下Java代码
|
public PrivilegeMappingEntity create() {
return new PrivilegeMappingEntityImpl();
}
@Override
public Class<? extends PrivilegeMappingEntity> getManagedEntityClass() {
return PrivilegeMappingEntityImpl.class;
}
@Override
public void deleteByPrivilegeId(String privilegeId) {
getDbSqlSession().delete("deleteByPrivilegeId", privilegeId, getManagedEntityClass());
}
@Override
public void deleteByPrivilegeIdAndUserId(String privilegeId, String userId) {
Map<String, String> params = new HashMap<>();
params.put("privilegeId", privilegeId);
|
params.put("userId", userId);
getDbSqlSession().delete("deleteByPrivilegeIdAndUserId", params, getManagedEntityClass());
}
@Override
public void deleteByPrivilegeIdAndGroupId(String privilegeId, String groupId) {
Map<String, String> params = new HashMap<>();
params.put("privilegeId", privilegeId);
params.put("groupId", groupId);
getDbSqlSession().delete("deleteByPrivilegeIdAndGroupId", params, getManagedEntityClass());
}
@Override
@SuppressWarnings("unchecked")
public List<PrivilegeMapping> getPrivilegeMappingsByPrivilegeId(String privilegeId) {
return (List<PrivilegeMapping>) getDbSqlSession().selectList("selectPrivilegeMappingsByPrivilegeId", privilegeId);
}
}
|
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\data\impl\MybatisPrivilegeMappingDataManager.java
| 1
|
请完成以下Spring Boot application配置
|
spring.application.name=sample (test)
spring.application.group=sample-group
#logging.include-application-name=false
#logging.include-application-group=false
service.name=Phil
spring.security.user.name=user
spring.security.user.password=password
# logging.file.name=/tmp/logs/app.log
# logging.level.org.springframework.security=DEBUG
management.endpoints.web.exposure.include=*
management.endpoint.shutdown.enabled=true
server.tomcat.basedir=target/tomcat
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.pattern=%h %t "%r" %s %b
#spring.jackson.serialization.INDENT_OUTPUT=true
spring.jmx.enabled=true
management.httpexchanges.recording.include=request-headers,response-headers,principal,remote-address,session-id
management.endpoint.health.show-details=always
management.endpoint.health.group.ready.include=db,diskSpace
management.endpoint.health.group.live.include=e
|
xample,hello,db
management.endpoint.health.group.live.show-details=never
management.endpoint.health.group.comp.include=compositeHello/spring/a,compositeHello/spring/c
management.endpoint.health.group.comp.show-details=always
management.endpoints.migrate-legacy-ids=true
management.endpoints.jackson.isolated-json-mapper=true
spring.jackson.mapper.require-setters-for-getters=true
|
repos\spring-boot-4.0.1\smoke-test\spring-boot-smoke-test-actuator\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public int getOrg_ID()
{
return get_ValueAsInt(COLUMNNAME_Org_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setUserElementString1 (final @Nullable java.lang.String UserElementString1)
{
set_Value (COLUMNNAME_UserElementString1, UserElementString1);
}
@Override
public java.lang.String getUserElementString1()
{
return get_ValueAsString(COLUMNNAME_UserElementString1);
}
@Override
public void setUserElementString2 (final @Nullable java.lang.String UserElementString2)
{
set_Value (COLUMNNAME_UserElementString2, UserElementString2);
}
@Override
public java.lang.String getUserElementString2()
{
return get_ValueAsString(COLUMNNAME_UserElementString2);
}
@Override
public void setUserElementString3 (final @Nullable java.lang.String UserElementString3)
{
set_Value (COLUMNNAME_UserElementString3, UserElementString3);
}
@Override
public java.lang.String getUserElementString3()
{
return get_ValueAsString(COLUMNNAME_UserElementString3);
}
@Override
public void setUserElementString4 (final @Nullable java.lang.String UserElementString4)
{
set_Value (COLUMNNAME_UserElementString4, UserElementString4);
}
@Override
public java.lang.String getUserElementString4()
{
|
return get_ValueAsString(COLUMNNAME_UserElementString4);
}
@Override
public void setUserElementString5 (final @Nullable java.lang.String UserElementString5)
{
set_Value (COLUMNNAME_UserElementString5, UserElementString5);
}
@Override
public java.lang.String getUserElementString5()
{
return get_ValueAsString(COLUMNNAME_UserElementString5);
}
@Override
public void setUserElementString6 (final @Nullable java.lang.String UserElementString6)
{
set_Value (COLUMNNAME_UserElementString6, UserElementString6);
}
@Override
public java.lang.String getUserElementString6()
{
return get_ValueAsString(COLUMNNAME_UserElementString6);
}
@Override
public void setUserElementString7 (final @Nullable java.lang.String UserElementString7)
{
set_Value (COLUMNNAME_UserElementString7, UserElementString7);
}
@Override
public java.lang.String getUserElementString7()
{
return get_ValueAsString(COLUMNNAME_UserElementString7);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema_Element.java
| 1
|
请完成以下Java代码
|
protected void executeOperations(final CommandContext commandContext) {
while (!commandContext.getAgenda().isEmpty()) {
Runnable runnable = commandContext.getAgenda().getNextOperation();
executeOperation(runnable);
}
}
public void executeOperation(Runnable runnable) {
if (runnable instanceof AbstractOperation) {
AbstractOperation operation = (AbstractOperation) runnable;
// Execute the operation if the operation has no execution (i.e. it's an operation not working on a process instance)
// or the operation has an execution and it is not ended
if (operation.getExecution() == null || !operation.getExecution().isEnded()) {
if (logger.isDebugEnabled()) {
logger.debug("Executing operation {} ", operation.getClass());
}
runnable.run();
|
}
} else {
runnable.run();
}
}
@Override
public CommandInterceptor getNext() {
return null;
}
@Override
public void setNext(CommandInterceptor next) {
throw new UnsupportedOperationException("CommandInvoker must be the last interceptor in the chain");
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandInvoker.java
| 1
|
请完成以下Java代码
|
public int getC_CompensationGroup_Schema_ID()
{
return get_ValueAsInt(COLUMNNAME_C_CompensationGroup_Schema_ID);
}
@Override
public void setC_CompensationGroup_SchemaLine_ID (final int C_CompensationGroup_SchemaLine_ID)
{
if (C_CompensationGroup_SchemaLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_SchemaLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_SchemaLine_ID, C_CompensationGroup_SchemaLine_ID);
}
@Override
public int getC_CompensationGroup_SchemaLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_CompensationGroup_SchemaLine_ID);
}
@Override
public void setC_Flatrate_Conditions_ID (final int C_Flatrate_Conditions_ID)
{
if (C_Flatrate_Conditions_ID < 1)
set_Value (COLUMNNAME_C_Flatrate_Conditions_ID, null);
else
set_Value (COLUMNNAME_C_Flatrate_Conditions_ID, C_Flatrate_Conditions_ID);
}
@Override
public int getC_Flatrate_Conditions_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Flatrate_Conditions_ID);
}
@Override
public void setCompleteOrderDiscount (final @Nullable BigDecimal CompleteOrderDiscount)
{
set_Value (COLUMNNAME_CompleteOrderDiscount, CompleteOrderDiscount);
}
@Override
public BigDecimal getCompleteOrderDiscount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CompleteOrderDiscount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
|
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
/**
* Type AD_Reference_ID=540836
* Reference name: C_CompensationGroup_SchemaLine_Type
*/
public static final int TYPE_AD_Reference_ID=540836;
/** Revenue = R */
public static final String TYPE_Revenue = "R";
/** Flatrate = F */
public static final String TYPE_Flatrate = "F";
@Override
public void setType (final @Nullable java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\order\model\X_C_CompensationGroup_SchemaLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class TaskQueryProperty implements QueryProperty {
private static final long serialVersionUID = 1L;
private static final Map<String, TaskQueryProperty> properties = new HashMap<>();
public static final TaskQueryProperty TASK_ID = new TaskQueryProperty("RES.ID_");
public static final TaskQueryProperty NAME = new TaskQueryProperty("RES.NAME_");
public static final TaskQueryProperty DESCRIPTION = new TaskQueryProperty("RES.DESCRIPTION_");
public static final TaskQueryProperty PRIORITY = new TaskQueryProperty("RES.PRIORITY_");
public static final TaskQueryProperty ASSIGNEE = new TaskQueryProperty("RES.ASSIGNEE_");
public static final TaskQueryProperty OWNER = new TaskQueryProperty("RES.OWNER_");
public static final TaskQueryProperty CREATE_TIME = new TaskQueryProperty("RES.CREATE_TIME_");
public static final TaskQueryProperty PROCESS_INSTANCE_ID = new TaskQueryProperty("RES.PROC_INST_ID_");
public static final TaskQueryProperty EXECUTION_ID = new TaskQueryProperty("RES.EXECUTION_ID_");
public static final TaskQueryProperty PROCESS_DEFINITION_ID = new TaskQueryProperty("RES.PROC_DEF_ID_");
public static final TaskQueryProperty DUE_DATE = new TaskQueryProperty("RES.DUE_DATE_");
public static final TaskQueryProperty TENANT_ID = new TaskQueryProperty("RES.TENANT_ID_");
public static final TaskQueryProperty TASK_DEFINITION_KEY = new TaskQueryProperty("RES.TASK_DEF_KEY_");
public static final TaskQueryProperty CATEGORY = new TaskQueryProperty("RES.CATEGORY_");
|
private String name;
public TaskQueryProperty(String name) {
this.name = name;
properties.put(name, this);
}
@Override
public String getName() {
return name;
}
public static TaskQueryProperty findByName(String propertyName) {
return properties.get(propertyName);
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\TaskQueryProperty.java
| 2
|
请完成以下Java代码
|
private URL getURL(final Integer AD_Image_ID)
{
if (AD_Image_ID == null || AD_Image_ID.intValue() <= 0)
return null;
return MImage.getURLOrNull(AD_Image_ID);
} // getURL
/*************************************************************************/
/**
* Action Listener - Open Dialog
* @param e event
*/
@Override
public void actionPerformed (ActionEvent e)
{
// Show Dialog
MFColor cc = ColorEditor.showDialog(SwingUtils.getFrame(this), color);
if (cc == null)
{
log.info( "VColor.actionPerformed - no color");
return;
}
setBackgroundColor(cc); // set Button
repaint();
// Update Values
m_mTab.setValue("ColorType", cc.getType().getCode());
if (cc.isFlat())
{
setColor (cc.getFlatColor(), true);
}
else if (cc.isGradient())
{
setColor (cc.getGradientUpperColor(), true);
setColor (cc.getGradientLowerColor(), false);
m_mTab.setValue("RepeatDistance", new BigDecimal(cc.getGradientRepeatDistance()));
m_mTab.setValue("StartPoint", String.valueOf(cc.getGradientStartPoint()));
}
else if (cc.isLine())
{
setColor (cc.getLineBackColor(), true);
setColor (cc.getLineColor(), false);
m_mTab.getValue("LineWidth");
m_mTab.getValue("LineDistance");
}
else if (cc.isTexture())
{
setColor (cc.getTextureTaintColor(), true);
// URL url = cc.getTextureURL();
// m_mTab.setValue("AD_Image_ID");
m_mTab.setValue("ImageAlpha", new BigDecimal(cc.getTextureCompositeAlpha()));
}
color = cc;
|
} // actionPerformed
/**
* Set Color in Tab
* @param c Color
* @param primary true if primary false if secondary
*/
private void setColor (Color c, boolean primary)
{
String add = primary ? "" : "_1";
m_mTab.setValue("Red" + add, new BigDecimal(c.getRed()));
m_mTab.setValue("Green" + add, new BigDecimal(c.getGreen()));
m_mTab.setValue("Blue" + add, new BigDecimal(c.getBlue()));
} // setColor
// metas: Ticket#2011062310000013
@Override
public boolean isAutoCommit()
{
return false;
}
} // VColor
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VColor.java
| 1
|
请完成以下Java代码
|
public ExternalSystemExportAudit createESExportAudit(@NonNull final CreateExportAuditRequest request)
{
final I_ExternalSystem_ExportAudit record = InterfaceWrapperHelper.newInstance(I_ExternalSystem_ExportAudit.class);
record.setRecord_ID(request.getTableRecordReference().getRecord_ID());
record.setAD_Table_ID(request.getTableRecordReference().getAD_Table_ID());
record.setExportTime(TimeUtil.asTimestamp(request.getExportTime()));
record.setExportUser_ID(request.getExportUserId().getRepoId());
record.setExportRole_ID(request.getExportRoleId().getRepoId());
record.setExportParameters(request.getExportParameters());
if (request.getPInstanceId() != null)
{
record.setAD_PInstance_ID(request.getPInstanceId().getRepoId());
}
record.setExternalSystem_ID(request.getExternalSystemType() != null
? externalSystemRepository.getByType(request.getExternalSystemType()).getId().getRepoId()
: -1);
InterfaceWrapperHelper.saveRecord(record);
return recordToModel(record);
}
@NonNull
|
private ExternalSystemExportAudit recordToModel(@NonNull final I_ExternalSystem_ExportAudit exportAudit)
{
final ExternalSystemId externalSystemId = ExternalSystemId.ofRepoIdOrNull(exportAudit.getExternalSystem_ID());
final ExternalSystemType externalSystemType = externalSystemId == null ? null : externalSystemRepository.getById(externalSystemId).getType();
return ExternalSystemExportAudit.builder()
.externalSystemExportAuditId(ExternalSystemExportAuditId.ofRepoId(exportAudit.getExternalSystem_ExportAudit_ID()))
.pInstanceId(PInstanceId.ofRepoIdOrNull(exportAudit.getAD_PInstance_ID()))
.exportRoleId(RoleId.ofRepoId(exportAudit.getExportRole_ID()))
.exportUserId(UserId.ofRepoId(exportAudit.getExportUser_ID()))
.tableRecordReference(TableRecordReference.of(exportAudit.getAD_Table_ID(), exportAudit.getRecord_ID()))
.exportTime(TimeUtil.asInstant(exportAudit.getExportTime()))
.exportParameters(exportAudit.getExportParameters())
.externalSystemType(externalSystemType)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\audit\ExternalSystemExportAuditRepo.java
| 1
|
请完成以下Java代码
|
private void validateSourceHUs(@NonNull final List<HuId> sourceHUIds)
{
for (final HuId sourceHuId : sourceHUIds)
{
if (!handlingUnitsBL.isHUHierarchyCleared(sourceHuId))
{
throw new AdempiereException("Non 'Cleared' HUs cannot be picked!")
.appendParametersToMessage()
.setParameter("M_HU_ID", sourceHuId);
}
}
}
private void assertNotAggregatingCUsToDiffOrders()
{
final OrderId pickingForOrderId = OrderId.ofRepoIdOrNull(shipmentSchedule.getC_Order_ID());
if (pickingForOrderId == null)
{
throw new AdempiereException("When isForbidAggCUsForDifferentOrders='Y' the pickingForOrderId must be known!")
.appendParametersToMessage()
.setParameter("ShipmentScheduleId", shipmentSchedule.getM_ShipmentSchedule_ID());
}
final I_M_HU hu = handlingUnitsDAO.getById(packToHuId);
final boolean isLoadingUnit = handlingUnitsBL.isLoadingUnit(hu);
if (isLoadingUnit)
|
{
throw new AdempiereException("packToHuId cannot be an LU, as picking to unknown TU is not allowed when isForbidAggCUsForDifferentOrders='Y'");
}
final ImmutableMap<HuId, ImmutableSet<OrderId>> huId2OpenPickingOrderIds = pickingCandidateService
.getOpenPickingOrderIdsByHuId(ImmutableSet.of(packToHuId));
final boolean thereAreOpenPickingOrdersForHU = CollectionUtils.isNotEmpty(huId2OpenPickingOrderIds.get(packToHuId));
final boolean noneOfThePickingOrdersMatchesTheCurrentOrder = !huId2OpenPickingOrderIds.get(packToHuId).contains(pickingForOrderId);
if (thereAreOpenPickingOrdersForHU && noneOfThePickingOrdersMatchesTheCurrentOrder)
{
throw new AdempiereException("Cannot pick to an HU with an open picking candidate pointing to a different order!")
.appendParametersToMessage()
.setParameter("shipmentScheduleId", shipmentSchedule.getM_ShipmentSchedule_ID())
.setParameter("huId", packToHuId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\AddQtyToHUCommand.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class LogAspect {
@Pointcut("execution(public * com.xncoding.aop.controller.*.*(..))")
public void webLog(){}
@Before("webLog()")
public void deBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
System.out.println("URL : " + request.getRequestURL().toString());
System.out.println("HTTP_METHOD : " + request.getMethod());
System.out.println("IP : " + request.getRemoteAddr());
System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
System.out.println("方法的返回值 : " + ret);
}
//后置异常通知
@AfterThrowing("webLog()")
public void throwss(JoinPoint jp){
|
System.out.println("方法异常时执行.....");
}
//后置最终通知,final增强,不管是抛出异常或者正常退出都会执行
@After("webLog()")
public void after(JoinPoint jp){
System.out.println("方法最后执行.....");
}
//环绕通知,环绕增强,相当于MethodInterceptor
@Around("webLog()")
public Object arround(ProceedingJoinPoint pjp) {
System.out.println("方法环绕start.....");
try {
Object o = pjp.proceed();
System.out.println("方法环绕proceed,结果是 :" + o);
return o;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
}
|
repos\SpringBootBucket-master\springboot-aop\src\main\java\com\xncoding\aop\aspect\LogAspect.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Person {
@Id @GeneratedValue private Long id;
@TenantId private String tenant;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
|
}
public void setName(String name) {
this.name = name;
}
public String getTenant() {
return tenant;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}
@Override
public String toString() {
return "Person{" + "id=" + id + ", name='" + name + '\'' + '}';
}
}
|
repos\spring-data-examples-main\jpa\multitenant\partition\src\main\java\example\springdata\jpa\hibernatemultitenant\partition\Person.java
| 2
|
请完成以下Java代码
|
public class PersonDTOWithCustomDeserializer {
private List<KeyValuePair> person;
public PersonDTOWithCustomDeserializer() {
}
public List<KeyValuePair> getPerson() {
return person;
}
public void setPerson(List<KeyValuePair> person) {
this.person = person;
}
public static class KeyValuePair {
private String key;
@JsonDeserialize(using = ValueDeserializer.class)
private Object value;
public KeyValuePair() {
}
public KeyValuePair(String key, Object value) {
this.key = key;
this.value = value;
}
public String getKey() {
|
return key;
}
public void setKey(String key) {
this.key = key;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
}
|
repos\tutorials-master\jackson-modules\jackson-conversions-3\src\main\java\com\baeldung\jackson\specifictype\dtos\PersonDTOWithCustomDeserializer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int getPort() {
if (this.port == 0) {
this.port = SocketUtils.findAvailableTcpPort();
}
return this.port;
}
/**
* Sets the maximum message size allowed to be received by the server. If not set ({@code null}) then it will
* default to {@link GrpcUtil#DEFAULT_MAX_MESSAGE_SIZE gRPC's default}. If set to {@code -1} then it will use the
* highest possible limit (not recommended).
*
* @param maxInboundMessageSize The new maximum size allowed for incoming messages. {@code -1} for max possible.
* Null to use the gRPC's default.
*
* @see ServerBuilder#maxInboundMessageSize(int)
*/
public void setMaxInboundMessageSize(final DataSize maxInboundMessageSize) {
if (maxInboundMessageSize == null || maxInboundMessageSize.toBytes() >= 0) {
this.maxInboundMessageSize = maxInboundMessageSize;
} else if (maxInboundMessageSize.toBytes() == -1) {
this.maxInboundMessageSize = DataSize.ofBytes(Integer.MAX_VALUE);
} else {
throw new IllegalArgumentException("Unsupported maxInboundMessageSize: " + maxInboundMessageSize);
}
}
/**
|
* Sets the maximum metadata size allowed to be received by the server. If not set ({@code null}) then it will
* default to {@link GrpcUtil#DEFAULT_MAX_HEADER_LIST_SIZE gRPC's default}. If set to {@code -1} then it will use
* the highest possible limit (not recommended).
*
* @param maxInboundMetadataSize The new maximum size allowed for incoming metadata. {@code -1} for max possible.
* Null to use the gRPC's default.
*
* @see ServerBuilder#maxInboundMetadataSize(int)
*/
public void setMaxInboundMetadataSize(final DataSize maxInboundMetadataSize) {
if (maxInboundMetadataSize == null || maxInboundMetadataSize.toBytes() >= 0) {
this.maxInboundMetadataSize = maxInboundMetadataSize;
} else if (maxInboundMetadataSize.toBytes() == -1) {
this.maxInboundMetadataSize = DataSize.ofBytes(Integer.MAX_VALUE);
} else {
throw new IllegalArgumentException("Unsupported maxInboundMetadataSize: " + maxInboundMetadataSize);
}
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\config\GrpcServerProperties.java
| 2
|
请完成以下Java代码
|
public long getCompleteScope() {
return completeScope;
}
public long getOpenIncidents() {
return openIncidents;
}
public long getResolvedIncidents() {
return resolvedIncidents;
}
public long getDeletedIncidents() {
return deletedIncidents;
}
public static HistoricActivityStatisticsDto fromHistoricActivityStatistics(HistoricActivityStatistics statistics) {
HistoricActivityStatisticsDto result = new HistoricActivityStatisticsDto();
|
result.id = statistics.getId();
result.instances = statistics.getInstances();
result.canceled = statistics.getCanceled();
result.finished = statistics.getFinished();
result.completeScope = statistics.getCompleteScope();
result.openIncidents = statistics.getOpenIncidents();
result.resolvedIncidents = statistics.getResolvedIncidents();
result.deletedIncidents = statistics.getDeletedIncidents();
return result;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricActivityStatisticsDto.java
| 1
|
请完成以下Java代码
|
public void deleteModel(String modelId) {
commandExecutor.execute(new DeleteModelCmd(modelId));
}
@Override
public void addModelEditorSource(String modelId, byte[] bytes) {
commandExecutor.execute(new AddEditorSourceForModelCmd(modelId, bytes));
}
@Override
public void addModelEditorSourceExtra(String modelId, byte[] bytes) {
commandExecutor.execute(new AddEditorSourceExtraForModelCmd(modelId, bytes));
}
@Override
public ModelQuery createModelQuery() {
return new ModelQueryImpl(commandExecutor);
}
@Override
public NativeModelQuery createNativeModelQuery() {
return new NativeModelQueryImpl(commandExecutor);
}
@Override
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代码
|
public void notifyModelStaled()
{
modelRef = new SoftReference<>(null);
}
/**
* Checks if underlying (and cached) model is still valid in given context. In case is no longer valid, it will be set to <code>null</code>.
*/
private void checkModelStaled(final IContextAware context)
{
final Object model = modelRef.get();
if (model == null)
{
return;
}
final String modelTrxName = InterfaceWrapperHelper.getTrxName(model);
if (!Services.get(ITrxManager.class).isSameTrxName(modelTrxName, context.getTrxName()))
{
modelRef = new SoftReference<>(null);
}
// TODO: why the ctx is not validated, like org.adempiere.ad.dao.cache.impl.TableRecordCacheLocal.getValue(Class<RT>) does?
}
@Deprecated
@Override
public Object getModel()
{
return getModel(PlainContextAware.newWithThreadInheritedTrx());
}
/**
* Deprecated: pls use appropriate DAO/Repository for loading models
* e.g. ModelDAO.getById({@link TableRecordReference#getIdAssumingTableName(String, IntFunction)})
*/
@Deprecated
@Override
public <T> T getModel(final Class<T> modelClass)
{
return getModel(PlainContextAware.newWithThreadInheritedTrx(), modelClass);
|
}
@NonNull
public <T> T getModelNonNull(@NonNull final Class<T> modelClass)
{
return getModelNonNull(PlainContextAware.newWithThreadInheritedTrx(), modelClass);
}
public static <T> List<T> getModels(
@NonNull final Collection<? extends ITableRecordReference> references,
@NonNull final Class<T> modelClass)
{
return references
.stream()
.map(ref -> ref.getModel(modelClass))
.collect(ImmutableList.toImmutableList());
}
public boolean isOfType(@NonNull final Class<?> modelClass)
{
final String modelTableName = InterfaceWrapperHelper.getTableNameOrNull(modelClass);
return modelTableName != null && modelTableName.equals(getTableName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\lang\impl\TableRecordReference.java
| 1
|
请完成以下Java代码
|
public static String missingProperty(String propertyName) {
return "The " + propertyName + " property need to be set!";
}
@SuppressWarnings("deprecation")
public static HashFunction forName(String name) {
switch (name) {
case "murmur3_32":
return Hashing.murmur3_32();
case "murmur3_128":
return Hashing.murmur3_128();
case "crc32":
return Hashing.crc32();
case "md5":
return Hashing.md5();
default:
throw new IllegalArgumentException("Can't find hash function with name " + name);
}
}
public static String constructBaseUrl(HttpServletRequest request) {
return String.format("%s://%s:%d",
getScheme(request),
getDomainName(request),
getPort(request));
}
public static String getScheme(HttpServletRequest request){
String scheme = request.getScheme();
String forwardedProto = request.getHeader("x-forwarded-proto");
if (forwardedProto != null) {
scheme = forwardedProto;
}
return scheme;
}
public static String getDomainName(HttpServletRequest request){
return request.getServerName();
}
public static String getDomainNameAndPort(HttpServletRequest request){
String domainName = getDomainName(request);
String scheme = getScheme(request);
int port = MiscUtils.getPort(request);
if (needsPort(scheme, port)) {
domainName += ":" + port;
|
}
return domainName;
}
private static boolean needsPort(String scheme, int port) {
boolean isHttpDefault = "http".equals(scheme.toLowerCase()) && port == 80;
boolean isHttpsDefault = "https".equals(scheme.toLowerCase()) && port == 443;
return !isHttpDefault && !isHttpsDefault;
}
public static int getPort(HttpServletRequest request){
String forwardedProto = request.getHeader("x-forwarded-proto");
int serverPort = request.getServerPort();
if (request.getHeader("x-forwarded-port") != null) {
try {
serverPort = request.getIntHeader("x-forwarded-port");
} catch (NumberFormatException e) {
}
} else if (forwardedProto != null) {
switch (forwardedProto) {
case "http":
serverPort = 80;
break;
case "https":
serverPort = 443;
break;
}
}
return serverPort;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\utils\MiscUtils.java
| 1
|
请完成以下Java代码
|
class PurchaseRowLookups
{
public static final PurchaseRowLookups newInstance()
{
return new PurchaseRowLookups();
}
private final IProductDAO productsRepo = Services.get(IProductDAO.class);
private final IProductBL productBL = Services.get(IProductBL.class);
private final IBPartnerDAO bpartnersRepo = Services.get(IBPartnerDAO.class);
private PurchaseRowLookups()
{
}
public LookupValue createProductLookupValue(final ProductId productId)
{
final String productValue = null;
final String productName = null;
return createProductLookupValue(productId, productValue, productName);
}
public LookupValue createProductLookupValue(
@Nullable final ProductId productId,
@Nullable final String productValue,
@Nullable final String productName)
{
if (productId == null)
{
return null;
}
final I_M_Product product = productsRepo.getById(productId);
if (product == null)
{
return IntegerLookupValue.unknown(productId.getRepoId());
}
final String productValueEffective = !Check.isEmpty(productValue, true) ? productValue.trim() : product.getValue();
final String productNameEffective = !Check.isEmpty(productName, true) ? productName.trim() : product.getName();
final String displayName = productValueEffective + "_" + productNameEffective;
return IntegerLookupValue.of(product.getM_Product_ID(), displayName);
}
public LookupValue createASILookupValue(final AttributeSetInstanceId attributeSetInstanceId)
{
if (attributeSetInstanceId == null)
{
return null;
}
final I_M_AttributeSetInstance asi = loadOutOfTrx(attributeSetInstanceId.getRepoId(), I_M_AttributeSetInstance.class);
if (asi == null)
{
return null;
}
String description = asi.getDescription();
if (Check.isEmpty(description, true))
{
description = "<" + attributeSetInstanceId.getRepoId() + ">";
}
return IntegerLookupValue.of(attributeSetInstanceId.getRepoId(), description);
}
public LookupValue createBPartnerLookupValue(final BPartnerId bpartnerId)
{
if (bpartnerId == null)
{
return null;
}
|
final I_C_BPartner bpartner = bpartnersRepo.getById(bpartnerId);
if (bpartner == null)
{
return null;
}
final String displayName = bpartner.getValue() + "_" + bpartner.getName();
return IntegerLookupValue.of(bpartner.getC_BPartner_ID(), displayName);
}
public String createUOMLookupValueForProductId(final ProductId productId)
{
if (productId == null)
{
return null;
}
final I_C_UOM uom = productBL.getStockUOM(productId);
if (uom == null)
{
return null;
}
return createUOMLookupValue(uom);
}
public String createUOMLookupValue(final I_C_UOM uom)
{
return translate(uom, I_C_UOM.class).getUOMSymbol();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseRowLookups.java
| 1
|
请完成以下Java代码
|
public class CustomerBulkResponse {
private BulkActionType bulkActionType;
private List<Customer> customers;
private BulkStatus status;
public CustomerBulkResponse() {
}
public CustomerBulkResponse(List<Customer> customers, BulkActionType bulkActionType, BulkStatus status) {
this.customers = customers;
this.bulkActionType = bulkActionType;
this.status = status;
}
public BulkActionType getBulkType() {
return bulkActionType;
}
|
public void setBulkType(BulkActionType bulkActionType) {
this.bulkActionType = bulkActionType;
}
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
public BulkStatus getStatus() {
return status;
}
public void setStatus(BulkStatus status) {
this.status = status;
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\bulkandbatchapi\response\CustomerBulkResponse.java
| 1
|
请完成以下Java代码
|
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
if (session.isOpen()) {
session.close();
}
sessions.remove(session);
logger.info(String.format("Session %s closed because of %s", session.getId(), status.getReason()));
}
@Override
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
|
请完成以下Java代码
|
public class TextAnnotationImpl extends ArtifactImpl implements TextAnnotation {
protected static Attribute<String> textFormatAttribute;
protected static ChildElement<Text> textChild;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder
.defineType(TextAnnotation.class, BPMN_ELEMENT_TEXT_ANNOTATION).namespaceUri(BPMN20_NS)
.extendsType(Artifact.class)
.instanceProvider(new ModelTypeInstanceProvider<TextAnnotation>() {
public TextAnnotation newInstance(ModelTypeInstanceContext context) {
return new TextAnnotationImpl(context);
}
});
textFormatAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_TEXT_FORMAT)
.defaultValue("text/plain")
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
textChild = sequenceBuilder.element(Text.class)
.build();
|
typeBuilder.build();
}
public TextAnnotationImpl(ModelTypeInstanceContext context) {
super(context);
}
public String getTextFormat() {
return textFormatAttribute.getValue(this);
}
public void setTextFormat(String textFormat) {
textFormatAttribute.setValue(this, textFormat);
}
public Text getText() {
return textChild.getChild(this);
}
public void setText(Text text) {
textChild.setChild(this, text);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\TextAnnotationImpl.java
| 1
|
请完成以下Java代码
|
public class BPartnerGlobalIDImportTableSqlUpdater
{
private static final transient Logger logger = LogManager.getLogger(BPartnerGlobalIDImportTableSqlUpdater.class);
public void updateBPartnerGlobalIDImortTable(@NonNull final ImportRecordsSelection selection)
{
dbUpdateCbPartnerIdsFromGlobalID(selection);
dbUpdateErrorMessages(selection);
}
private void dbUpdateCbPartnerIdsFromGlobalID(final ImportRecordsSelection selection)
{
StringBuilder sql;
int no;
sql = new StringBuilder("UPDATE " + I_I_BPartner_GlobalID.Table_Name + " i ")
.append("SET C_BPartner_ID=(SELECT C_BPartner_ID FROM C_BPartner p ")
.append("WHERE i." + I_I_BPartner_GlobalID.COLUMNNAME_GlobalId)
.append("=p." + I_C_BPartner.COLUMNNAME_GlobalId)
.append(" AND p.AD_Client_ID=i.AD_Client_ID ")
.append(" AND p.IsActive='Y') ")
|
.append("WHERE C_BPartner_ID IS NULL AND " + I_I_BPartner_GlobalID.COLUMNNAME_GlobalId + " IS NOT NULL")
.append(" AND " + COLUMNNAME_I_IsImported + "='N'")
.append(selection.toSqlWhereClause("i"));
no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
logger.info("Found BPartner={}", no);
}
private void dbUpdateErrorMessages(final ImportRecordsSelection selection)
{
StringBuilder sql;
int no;
sql = new StringBuilder("UPDATE " + I_I_BPartner_GlobalID.Table_Name)
.append(" SET " + COLUMNNAME_I_IsImported + "='N', " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||'ERR=Partner is mandatory, ' ")
.append("WHERE " + I_I_BPartner_GlobalID.COLUMNNAME_C_BPartner_ID + " IS NULL ")
.append("AND " + COLUMNNAME_I_IsImported + "<>'Y'")
.append(selection.toSqlWhereClause());
no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
logger.info("Value is mandatory={}", no);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\globalid\impexp\BPartnerGlobalIDImportTableSqlUpdater.java
| 1
|
请完成以下Java代码
|
private void fireListener(
@NonNull final OnError onError,
@NonNull final TrxEventTiming timingInfo,
@NonNull final ITrx trx,
@Nullable final RegisterListenerRequest listener)
{
// shouldn't be necessary but in fact i just had an NPE at this place
if (listener == null || !listener.isActive())
{
return;
}
// Execute the listener method
try
{
listener.getHandlingMethod().onTransactionEvent(trx);
}
catch (final Exception ex)
{
handleException(onError, timingInfo, listener, ex);
}
finally
{
if (listener.isInvokeMethodJustOnce())
{
listener.deactivate();
}
}
}
private void handleException(
@NonNull final OnError onError,
|
@NonNull final TrxEventTiming timingInfo,
@NonNull final RegisterListenerRequest listener,
@NonNull final Exception ex)
{
if (onError == OnError.LogAndSkip)
{
logger.warn("Error while invoking {} using {}. Error was discarded.", timingInfo, listener, ex);
}
else // if (onError == OnError.ThrowException)
{
throw AdempiereException.wrapIfNeeded(ex)
.setParameter("listener", listener)
.setParameter(timingInfo)
.appendParametersToMessage();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\TrxListenerManager.java
| 1
|
请完成以下Java代码
|
public final class GlobalEventBus {
public static final String GLOBAL_EVENT_BUS_EXPRESSION = "T(com.baeldung.beanpostprocessor.GlobalEventBus).getEventBus()";
private static final String IDENTIFIER = "global-event-bus";
private static final GlobalEventBus GLOBAL_EVENT_BUS = new GlobalEventBus();
private final EventBus eventBus = new AsyncEventBus(IDENTIFIER, Executors.newCachedThreadPool());
private GlobalEventBus() {
}
public static GlobalEventBus getInstance() {
return GlobalEventBus.GLOBAL_EVENT_BUS;
|
}
public static EventBus getEventBus() {
return GlobalEventBus.GLOBAL_EVENT_BUS.eventBus;
}
public static void subscribe(Object obj) {
getEventBus().register(obj);
}
public static void unsubscribe(Object obj) {
getEventBus().unregister(obj);
}
public static void post(Object event) {
getEventBus().post(event);
}
}
|
repos\tutorials-master\spring-core-4\src\main\java\com\baeldung\beanpostprocessor\GlobalEventBus.java
| 1
|
请完成以下Java代码
|
public void setDate(final ZonedDateTime date)
{
this.date = date;
}
@Override
public ZonedDateTime getDate()
{
return date;
}
@Override
public boolean isAllowAnyProduct()
{
return allowAnyProduct;
}
@Override
public void setAllowAnyProduct(final boolean allowAnyProduct)
{
this.allowAnyProduct = allowAnyProduct;
}
@Override
public String getHU_UnitType()
{
return huUnitType;
}
@Override
public void setHU_UnitType(final String huUnitType)
{
this.huUnitType = huUnitType;
}
@Override
public boolean isAllowVirtualPI()
{
return allowVirtualPI;
}
@Override
public void setAllowVirtualPI(final boolean allowVirtualPI)
{
this.allowVirtualPI = allowVirtualPI;
}
@Override
public void setOneConfigurationPerPI(final boolean oneConfigurationPerPI)
{
this.oneConfigurationPerPI = oneConfigurationPerPI;
}
@Override
public boolean isOneConfigurationPerPI()
{
return oneConfigurationPerPI;
}
@Override
public boolean isAllowDifferentCapacities()
{
return allowDifferentCapacities;
}
@Override
public void setAllowDifferentCapacities(final boolean allowDifferentCapacities)
{
this.allowDifferentCapacities = allowDifferentCapacities;
}
@Override
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 java.lang.String getProducts()
{
return get_ValueAsString(COLUMNNAME_Products);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU getVHU()
{
return get_ValueAsPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setVHU(final de.metas.handlingunits.model.I_M_HU VHU)
|
{
set_ValueFromPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class, VHU);
}
@Override
public void setVHU_ID (final int VHU_ID)
{
if (VHU_ID < 1)
set_Value (COLUMNNAME_VHU_ID, null);
else
set_Value (COLUMNNAME_VHU_ID, VHU_ID);
}
@Override
public int getVHU_ID()
{
return get_ValueAsInt(COLUMNNAME_VHU_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Assignment.java
| 1
|
请完成以下Java代码
|
public Integer getLuckeyCount() {
return luckeyCount;
}
public void setLuckeyCount(Integer luckeyCount) {
this.luckeyCount = luckeyCount;
}
public Integer getHistoryIntegration() {
return historyIntegration;
}
public void setHistoryIntegration(Integer historyIntegration) {
this.historyIntegration = historyIntegration;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", memberLevelId=").append(memberLevelId);
sb.append(", username=").append(username);
sb.append(", password=").append(password);
sb.append(", nickname=").append(nickname);
sb.append(", phone=").append(phone);
sb.append(", status=").append(status);
sb.append(", createTime=").append(createTime);
|
sb.append(", icon=").append(icon);
sb.append(", gender=").append(gender);
sb.append(", birthday=").append(birthday);
sb.append(", city=").append(city);
sb.append(", job=").append(job);
sb.append(", personalizedSignature=").append(personalizedSignature);
sb.append(", sourceType=").append(sourceType);
sb.append(", integration=").append(integration);
sb.append(", growth=").append(growth);
sb.append(", luckeyCount=").append(luckeyCount);
sb.append(", historyIntegration=").append(historyIntegration);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMember.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String email;
private String password;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable( name = "user_roles",
joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
private Collection<Role> roles;
public User(String firstName, String lastName, String email, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
}
public User(String firstName, String lastName, String email, String password, Collection<Role> roles) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.roles = roles;
}
public Long getId() {
return id;
}
public void setId(Long 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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Collection<Role> getRoles() {
return roles;
}
public void setRoles(Collection<Role> roles) {
this.roles = roles;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +
", roles=" + roles +
'}';
}
}
|
repos\Spring-Boot-Advanced-Projects-main\Springboot-Registration-Page\src\main\java\aspera\registration\model\User.java
| 2
|
请完成以下Java代码
|
public void setExternal_Request (final String External_Request)
{
set_Value (COLUMNNAME_External_Request, External_Request);
}
@Override
public String getExternal_Request()
{
return get_ValueAsString(COLUMNNAME_External_Request);
}
@Override
public I_ExternalSystem_Config getExternalSystem_Config()
{
return get_ValueAsPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class);
}
@Override
public void setExternalSystem_Config(final I_ExternalSystem_Config ExternalSystem_Config)
{
set_ValueFromPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class, ExternalSystem_Config);
}
@Override
public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID)
{
if (ExternalSystem_Config_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_Config_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID);
}
@Override
public int getExternalSystem_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
}
@Override
public void setExternalSystem_RuntimeParameter_ID (final int ExternalSystem_RuntimeParameter_ID)
{
if (ExternalSystem_RuntimeParameter_ID < 1)
|
set_ValueNoCheck (COLUMNNAME_ExternalSystem_RuntimeParameter_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_RuntimeParameter_ID, ExternalSystem_RuntimeParameter_ID);
}
@Override
public int getExternalSystem_RuntimeParameter_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_RuntimeParameter_ID);
}
@Override
public void setName (final String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final @Nullable String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_RuntimeParameter.java
| 1
|
请完成以下Java代码
|
public void close() {
super.close();
second.close();
}
@Override
public void flush() {
super.flush();
second.flush();
}
@Override
public void write(byte[] buf, int off, int len) {
super.write(buf, off, len);
second.write(buf, off, len);
}
@Override
public void write(int b) {
|
super.write(b);
second.write(b);
}
@Override
public void write(byte[] b) throws IOException {
super.write(b);
second.write(b);
}
@Override
public boolean checkError() {
return super.checkError() && second.checkError();
}
}
|
repos\tutorials-master\core-java-modules\core-java-io-apis-3\src\main\java\com\baeldung\outputtofile\DualPrintStream.java
| 1
|
请完成以下Java代码
|
public void updateReversedQtys(final I_M_InOut inout)
{
final I_M_InOut reversal = inout.getReversal();
// shall never happen
if (reversal == null)
{
return;
}
final List<I_M_InOutLine> reversalLines = inoutDao.retrieveLines(reversal, I_M_InOutLine.class);
for (final I_M_InOutLine reversalLine : reversalLines)
{
final BigDecimal qtyTuReversed = reversalLine.getQtyEnteredTU().negate();
reversalLine.setQtyTU_Override(qtyTuReversed);
reversalLine.setQtyEnteredTU(qtyTuReversed);
InterfaceWrapperHelper.save(reversalLine);
}
}
@DocValidate(timings = { ModelValidator.TIMING_BEFORE_COMPLETE })
public void generateHUsForCustomerReturn(final I_M_InOut customerReturn)
{
if (!returnsServiceFacade.isCustomerReturn(customerReturn))
{
return; // do nothing if the inout is not a customer return
}
if (inOutBL.isReversal(customerReturn))
{
return; // nothing to do
}
if (returnsServiceFacade.isEmptiesReturn(customerReturn))
{
return; // no HUs to generate if the whole InOut is about HUs
}
final List<I_M_HU> assignedHUs = inOutDAO.retrieveHandlingUnits(customerReturn);
if (assignedHUs.isEmpty())
{
throw new AdempiereException("No HUs to return assigned");
}
// make sure all assigned HUs are active
handlingUnitsBL.setHUStatus(assignedHUs, X_M_HU.HUSTATUS_Active);
}
@DocValidate(timings = ModelValidator.TIMING_AFTER_REVERSECORRECT)
public void reverseReturn(final de.metas.handlingunits.model.I_M_InOut returnInOut)
{
if (!returnsServiceFacade.isVendorReturn(returnInOut))
{
return; // nothing to do
}
final String snapshotId = returnInOut.getSnapshot_UUID();
if (Check.isEmpty(snapshotId, true))
{
throw new HUException("@NotFound@ @Snapshot_UUID@ (" + returnInOut + ")");
|
}
final List<I_M_HU> hus = huAssignmentDAO.retrieveTopLevelHUsForModel(returnInOut);
if (hus.isEmpty())
{
// nothing to do.
return;
}
final IContextAware context = InterfaceWrapperHelper.getContextAware(returnInOut);
snapshotDAO.restoreHUs()
.setContext(context)
.setSnapshotId(snapshotId)
.setDateTrx(returnInOut.getMovementDate())
.setReferencedModel(returnInOut)
.addModels(hus)
.restoreFromSnapshot();
}
@DocValidate(timings = { ModelValidator.TIMING_BEFORE_COMPLETE })
public void validateAttributesOnShipmentCompletion(final I_M_InOut shipment)
{
if (!shipment.isSOTrx())
{
// nothing to do
return;
}
huInOutBL.validateMandatoryOnShipmentAttributes(shipment);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_InOut.java
| 1
|
请完成以下Java代码
|
public class M_HU_UpdateHUAgeAttributeProcess extends JavaProcess
{
private final IAttributeStorageFactoryService attributeStorageFactoryService = Services.get(IAttributeStorageFactoryService.class);
private final IAttributeStorageFactory attributeStorageFactory = attributeStorageFactoryService.createHUAttributeStorageFactory();
private final HUWithAgeRepository huWithAgeRepository = Adempiere.getBean(HUWithAgeRepository.class);
private final AgeAttributesService ageAttributesService = Adempiere.getBean(AgeAttributesService.class);
@Override
@RunOutOfTrx
protected String doIt()
{
streamHUs().forEach(this::updateAgeAttribute);
return MSG_OK;
}
private Stream<I_M_HU> streamHUs()
{
return huWithAgeRepository.getAllWhereProductionDateIsNotEmptyAndStatusActive();
}
|
private void updateAgeAttribute(final I_M_HU hu)
{
final IAttributeStorage storage = attributeStorageFactory.getAttributeStorage(hu);
storage.setSaveOnChange(true);
final LocalDateTime productionDate = storage.getValueAsLocalDateTime(HUAttributeConstants.ATTR_ProductionDate);
final Age age = ageAttributesService.getAgeValues().computeAgeInMonths(productionDate);
updateAgeAttribute(storage, age);
}
public static void updateAgeAttribute(IAttributeStorage storage, Age age)
{
Age ageOffset = Age.ZERO;
if (storage.hasAttribute(HUAttributeConstants.ATTR_AgeOffset))
{
ageOffset = Age.ofAgeInMonths(storage.getValueAsInt(HUAttributeConstants.ATTR_AgeOffset));
}
final Age ageWithOffset = age.add(ageOffset);
storage.setValue(HUAttributeConstants.ATTR_Age, ageWithOffset.toStringValue());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\age\process\M_HU_UpdateHUAgeAttributeProcess.java
| 1
|
请完成以下Java代码
|
public static ExternalSystemType ofLegacyCodeOrNull(@NonNull final String code)
{
return LEGACY_CODES.inverse().get(code);
}
@Override
public String toString() {return getValue();}
@JsonValue
public String toJson() {return getValue();}
public boolean isAlberta() {return Alberta.equals(this);}
public boolean isRabbitMQ() {return RabbitMQ.equals(this);}
public boolean isWOO() {return WOO.equals(this);}
public boolean isGRSSignum() {return GRSSignum.equals(this);}
public boolean isLeichUndMehl() {return LeichUndMehl.equals(this);}
|
public boolean isPrintClient() {return PrintClient.equals(this);}
public boolean isProCareManagement() {return ProCareManagement.equals(this);}
public boolean isShopware6() {return Shopware6.equals(this);}
public boolean isOther() {return Other.equals(this);}
public boolean isGithub() {return Github.equals(this);}
public boolean isEverhour() {return Everhour.equals(this);}
public boolean isScriptedExportConversion() {return ScriptedExportConversion.equals(this);}
public boolean isScriptedImportConversion() {return ScriptedImportConversion.equals(this);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\externalsystem\ExternalSystemType.java
| 1
|
请完成以下Java代码
|
public void drawIcon(
final int imageX,
final int imageY,
final int iconPadding,
final ProcessDiagramSVGGraphics2D svgGenerator
) {
Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG);
gTag.setAttributeNS(null, "transform", "translate(" + (imageX - 6) + "," + (imageY - 3) + ")");
Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG);
pathTag.setAttributeNS(null, "d", this.getDValue());
pathTag.setAttributeNS(null, "style", this.getStyleValue());
pathTag.setAttributeNS(null, "fill", this.getFillValue());
pathTag.setAttributeNS(null, "stroke", this.getStrokeValue());
gTag.appendChild(pathTag);
svgGenerator.getExtendDOMGroupManager().addElement(gTag);
}
@Override
public String getAnchorValue() {
return null;
}
@Override
public String getStyleValue() {
|
return "fill:none;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10";
}
@Override
public Integer getWidth() {
return 17;
}
@Override
public Integer getHeight() {
return 22;
}
@Override
public String getStrokeWidth() {
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\ErrorIconType.java
| 1
|
请完成以下Java代码
|
public WebuiRelatedProcessDescriptor toWebuiRelatedProcessDescriptor(final ViewAsPreconditionsContext viewContext)
{
final IView view = viewContext.getView();
final DocumentIdsSelection selectedDocumentIds = viewContext.getSelectedRowIds();
return WebuiRelatedProcessDescriptor.builder()
.processId(ViewProcessInstancesRepository.buildProcessId(view.getViewId(), actionId))
.processCaption(caption)
.processDescription(description)
//
.displayPlace(DisplayPlace.ViewQuickActions)
.defaultQuickAction(defaultAction)
//
.preconditionsResolutionSupplier(() -> checkPreconditions(view, selectedDocumentIds))
//
.build();
}
private ProcessPreconditionsResolution checkPreconditions(final IView view, final DocumentIdsSelection selectedDocumentIds)
{
try
{
return getPreconditionsInstance().matches(view, selectedDocumentIds);
}
catch (final InstantiationException | IllegalAccessException ex)
{
throw AdempiereException.wrapIfNeeded(ex);
}
}
private Precondition getPreconditionsInstance() throws InstantiationException, IllegalAccessException
{
if (preconditionSharedInstance != null)
{
return preconditionSharedInstance;
}
return preconditionClass.newInstance();
}
@NonNull public Method getViewActionMethod()
{
return viewActionMethod;
}
|
public ProcessInstanceResult.ResultAction convertReturnType(final Object returnValue)
{
return viewActionReturnTypeConverter.convert(returnValue);
}
@NonNull public Object[] extractMethodArguments(final IView view, final Document processParameters, final DocumentIdsSelection selectedDocumentIds)
{
return viewActionParamDescriptors.stream()
.map(paramDesc -> paramDesc.extractArgument(view, processParameters, selectedDocumentIds))
.toArray();
}
@FunctionalInterface
public interface ViewActionMethodReturnTypeConverter
{
ProcessInstanceResult.ResultAction convert(Object returnValue);
}
@FunctionalInterface
public interface ViewActionMethodArgumentExtractor
{
Object extractArgument(IView view, Document processParameters, DocumentIdsSelection selectedDocumentIds);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\view\ViewActionDescriptor.java
| 1
|
请完成以下Java代码
|
public class FactorAuthorizationDecision implements AuthorizationResult {
private final List<RequiredFactorError> factorErrors;
/**
* Creates a new instance.
* @param factorErrors the {@link RequiredFactorError}. If empty, {@link #isGranted()}
* returns true. Cannot be null or contain empty values.
*/
public FactorAuthorizationDecision(List<RequiredFactorError> factorErrors) {
Assert.notNull(factorErrors, "factorErrors cannot be null");
Assert.noNullElements(factorErrors, "factorErrors must not contain null elements");
this.factorErrors = Collections.unmodifiableList(factorErrors);
}
/**
* The specified {@link RequiredFactorError}s
* @return the errors. Cannot be null or contain null values.
|
*/
public List<RequiredFactorError> getFactorErrors() {
return this.factorErrors;
}
/**
* Returns {@code getFactorErrors().isEmpty()}.
* @return
*/
@Override
public boolean isGranted() {
return this.factorErrors.isEmpty();
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\FactorAuthorizationDecision.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getType() {
return type;
}
@Override
public String getTaskId() {
return taskId;
}
@Override
public Date getTimeStamp() {
return timeStamp;
}
@Override
public String getUserId() {
return userId;
}
@Override
public String getData() {
return data;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getScopeId() {
return scopeId;
}
@Override
|
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void create() {
// add is not supported by default
throw new RuntimeException("Operation is not supported");
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\BaseHistoricTaskLogEntryBuilderImpl.java
| 2
|
请完成以下Java代码
|
Attributes getEntryAttributes(JarEntry entry) throws IOException {
Manifest manifest = supply();
if (manifest == null) {
return null;
}
Attributes attributes = manifest.getEntries().get(entry.getName());
return cloneAttributes(attributes);
}
private Attributes cloneAttributes(Attributes attributes) {
return (attributes != null) ? (Attributes) attributes.clone() : null;
}
private Manifest supply() throws IOException {
Object supplied = this.supplied;
if (supplied == null) {
|
supplied = this.supplier.getManifest();
this.supplied = (supplied != null) ? supplied : NONE;
}
return (supplied != NONE) ? (Manifest) supplied : null;
}
/**
* Interface used to supply the actual manifest.
*/
@FunctionalInterface
interface ManifestSupplier {
Manifest getManifest() throws IOException;
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\UrlJarManifest.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static HUManagerProfile fromRecord(
@NonNull final I_MobileUI_HUManager record,
@NonNull final ImmutableListMultimap<HUManagerProfileId, AttributeId> displayedAttributeIdsInOrderByProfileId,
@NonNull final Map<HUManagerProfileId, HUManagerProfileLayoutSectionList> layoutSectionsByProfileId)
{
final HUManagerProfileId profileId = HUManagerProfileId.ofRepoId(record.getMobileUI_HUManager_ID());
return HUManagerProfile.builder()
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.displayedAttributeIdsInOrder(displayedAttributeIdsInOrderByProfileId.get(profileId))
.layoutSections(layoutSectionsByProfileId.getOrDefault(profileId, HUManagerProfileLayoutSectionList.DEFAULT))
.build();
}
@NonNull
private Map<HUManagerProfileId, HUManagerProfileLayoutSectionList> retrieveLayoutSectionsInOrder()
{
return queryBL.createQueryBuilder(I_MobileUI_HUManager_LayoutSection.class)
.addOnlyActiveRecordsFilter()
.orderBy(I_MobileUI_HUManager_LayoutSection.COLUMNNAME_MobileUI_HUManager_ID)
.orderBy(I_MobileUI_HUManager_LayoutSection.COLUMNNAME_SeqNo)
|
.orderBy(I_MobileUI_HUManager_LayoutSection.COLUMNNAME_MobileUI_HUManager_LayoutSection_ID)
.create()
.stream()
.collect(Collectors.groupingBy(
record -> HUManagerProfileId.ofRepoId(record.getMobileUI_HUManager_ID()),
Collectors.mapping(
HUManagerProfileRepository::fromRecord,
HUManagerProfileLayoutSectionList.collectOrDefault()
)
));
}
private static @NotNull HUManagerProfileLayoutSection fromRecord(final I_MobileUI_HUManager_LayoutSection record)
{
return HUManagerProfileLayoutSection.ofCode(record.getLayoutSection());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\mobileui\config\HUManagerProfileRepository.java
| 2
|
请完成以下Java代码
|
public java.lang.String getPaymentRule ()
{
return (java.lang.String)get_Value(COLUMNNAME_PaymentRule);
}
/** 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;
}
|
/**
* Status AD_Reference_ID=541011
* Reference name: C_Payment_Reservation_Status
*/
public static final int STATUS_AD_Reference_ID=541011;
/** WAITING_PAYER_APPROVAL = W */
public static final String STATUS_WAITING_PAYER_APPROVAL = "W";
/** APPROVED = A */
public static final String STATUS_APPROVED = "A";
/** VOIDED = V */
public static final String STATUS_VOIDED = "V";
/** COMPLETED = C */
public static final String STATUS_COMPLETED = "C";
/** Set Status.
@param Status Status */
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status */
@Override
public java.lang.String getStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Payment_Reservation.java
| 1
|
请完成以下Java代码
|
private static @NotNull JsonCountStatus computeCountStatus(final ImmutableList<JsonInventoryJobLine> lines)
{
return JsonCountStatus.combine(lines, JsonInventoryJobLine::getCountStatus)
.orElse(JsonCountStatus.COUNTED); // consider counted when there are no lines (shall not happen)
}
private static @NonNull JsonCountStatus computeCountStatus(final InventoryLine line)
{
return JsonCountStatus.combine(line.getInventoryLineHUs(), JsonInventoryJobMapper::computeCountStatus)
.orElse(JsonCountStatus.COUNTED);
}
private static JsonCountStatus computeCountStatus(final InventoryLineHU lineHU)
{
return JsonCountStatus.ofIsCountedFlag(lineHU.isCounted());
}
public List<JsonInventoryLineHU> toJsonInventoryLineHUs(@NonNull final InventoryLine line)
{
return line.getInventoryLineHUs()
.stream()
.filter(lineHU -> lineHU.getId() != null)
.map(lineHU -> toJson(lineHU, line))
.collect(ImmutableList.toImmutableList());
}
public JsonInventoryLineHU toJson(final InventoryLineHU lineHU, InventoryLine line)
{
final ProductInfo product = products.getById(line.getProductId());
final HuId huId = lineHU.getHuId();
final String productName = product.getProductName().translate(adLanguage);
final String huDisplayName = huId != null ? handlingUnits.getDisplayName(huId) : null;
return JsonInventoryLineHU.builder()
.id(lineHU.getIdNotNull())
.caption(CoalesceUtil.firstNotBlank(huDisplayName, productName))
.productId(product.getProductId())
.productNo(product.getProductNo())
.productName(productName)
.locatorId(line.getLocatorId().getRepoId())
|
.locatorName(warehouses.getLocatorName(line.getLocatorId()))
.huId(huId)
.huDisplayName(huDisplayName)
.uom(lineHU.getUOMSymbol())
.qtyBooked(lineHU.getQtyBook().toBigDecimal())
.qtyCount(lineHU.getQtyCount().toBigDecimal())
.countStatus(computeCountStatus(lineHU))
.attributes(loadAllDetails ? JsonAttribute.of(asis.getById(lineHU.getAsiId()), adLanguage) : null)
.build();
}
public JsonInventoryLineHU toJson(final InventoryLine line, final InventoryLineHUId lineHUId)
{
final InventoryLineHU lineHU = line.getInventoryLineHUById(lineHUId);
return toJson(lineHU, line);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\mappers\JsonInventoryJobMapper.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getDeliverTo() {
return deliverTo;
}
/**
* Sets the value of the deliverTo property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDeliverTo(String value) {
this.deliverTo = value;
}
/**
* Gets the value of the productionDescription property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProductionDescription() {
return productionDescription;
}
/**
* Sets the value of the productionDescription property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProductionDescription(String value) {
this.productionDescription = value;
}
/**
* Gets the value of the kanbanCardNumberRange1Start property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKanbanCardNumberRange1Start() {
return kanbanCardNumberRange1Start;
}
/**
* Sets the value of the kanbanCardNumberRange1Start property.
*
* @param value
|
* allowed object is
* {@link String }
*
*/
public void setKanbanCardNumberRange1Start(String value) {
this.kanbanCardNumberRange1Start = value;
}
/**
* Gets the value of the kanbanCardNumberRange1End property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKanbanCardNumberRange1End() {
return kanbanCardNumberRange1End;
}
/**
* Sets the value of the kanbanCardNumberRange1End property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKanbanCardNumberRange1End(String value) {
this.kanbanCardNumberRange1End = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PackagingIdentificationType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class AppDeploymentResourceDataResource {
@Autowired
protected AppRepositoryService appRepositoryService;
@Autowired(required=false)
protected AppRestApiInterceptor restApiInterceptor;
@ApiOperation(value = "Get an app deployment resource content", tags = {"App Deployments" }, nickname = "getAppDeploymentResource",
notes = "The response body will contain the binary resource-content for the requested resource. The response content-type will be the same as the type returned in the resources mimeType property. Also, a content-disposition header is set, allowing browsers to download the file instead of displaying it.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates both app deployment and resource have been found and the resource data has been returned."),
@ApiResponse(code = 404, message = "Indicates the requested app deployment was not found or there is no resource with the given id present in the app deployment. The status-description contains additional information.") })
@GetMapping(value = "/app-repository/deployments/{deploymentId}/resourcedata/{resourceName}")
@ResponseBody
public byte[] getAppDeploymentResource(@ApiParam(name = "deploymentId") @PathVariable("deploymentId") String deploymentId,
@ApiParam(name = "resourceName") @PathVariable("resourceName") String resourceName,
HttpServletResponse response) {
if (deploymentId == null) {
throw new FlowableIllegalArgumentException("No deployment id provided");
}
if (resourceName == null) {
throw new FlowableIllegalArgumentException("No resource name provided");
}
// Check if deployment exists
|
AppDeployment deployment = appRepositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
if (deployment == null) {
throw new FlowableObjectNotFoundException("Could not find an app deployment with id '" + deploymentId);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessDeploymentById(deployment);
}
List<String> resourceList = appRepositoryService.getDeploymentResourceNames(deploymentId);
if (resourceList.contains(resourceName)) {
response.setContentType("application/json");
try (final InputStream resourceStream = appRepositoryService.getResourceAsStream(deploymentId, resourceName)) {
return IOUtils.toByteArray(resourceStream);
} catch (Exception e) {
throw new FlowableException("Error converting resource stream", e);
}
} else {
// Resource not found in deployment
throw new FlowableObjectNotFoundException("Could not find a resource with name '" + resourceName + "' in deployment '" + deploymentId);
}
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine-rest\src\main\java\org\flowable\app\rest\service\api\repository\AppDeploymentResourceDataResource.java
| 2
|
请完成以下Java代码
|
abstract class PaymentsView_Allocate_Template extends PaymentsViewBasedProcess
{
private final MoneyService moneyService = SpringContextHolder.instance.getBean(MoneyService.class);
private final InvoiceProcessingServiceCompanyService invoiceProcessingServiceCompanyService = SpringContextHolder.instance.getBean(InvoiceProcessingServiceCompanyService.class);
private final IPaymentAllocationBL paymentAllocationBL = Services.get(IPaymentAllocationBL.class);
@Override
protected final String doIt()
{
newPaymentsViewAllocateCommand()
.run();
// NOTE: the payment and invoice rows will be automatically invalidated (via a cache reset),
// when the payment allocation is processed
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
// FIXME: until https://github.com/metasfresh/me03/issues/3388 is fixed,
// as a workaround we have to invalidate the whole views
invalidatePaymentsAndInvoicesViews();
}
protected final PaymentsViewAllocateCommand newPaymentsViewAllocateCommand()
{
final PaymentsViewAllocateCommandBuilder builder = PaymentsViewAllocateCommand.builder()
.moneyService(moneyService)
|
.invoiceProcessingServiceCompanyService(invoiceProcessingServiceCompanyService)
//
.paymentRows(getPaymentRowsSelectedForAllocation())
.invoiceRows(getInvoiceRowsSelectedForAllocation())
.allowPurchaseSalesInvoiceCompensation(paymentAllocationBL.isPurchaseSalesInvoiceCompensationAllowed());
customizePaymentsViewAllocateCommandBuilder(builder);
return builder.build();
}
protected void customizePaymentsViewAllocateCommandBuilder(@NonNull final PaymentsViewAllocateCommandBuilder builder)
{
// nothing on this level
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentsView_Allocate_Template.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public SimpleCookie rememberMeCookie() {
SimpleCookie cookie = new SimpleCookie("rememberMe");
cookie.setMaxAge(86400);
return cookie;
}
public CookieRememberMeManager rememberMeManager() {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
cookieRememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag=="));
return cookieRememberMeManager;
}
@Bean
@DependsOn({"lifecycleBeanPostProcessor"})
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
|
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
return redisManager;
}
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
return redisCacheManager;
}
}
|
repos\SpringAll-master\14.Spring-Boot-Shiro-Redis\src\main\java\com\springboot\config\ShiroConfig.java
| 2
|
请完成以下Java代码
|
public ErrorInfo handleBadMessageConversion(HttpMessageConversionException e, HttpServletRequest request) {
if (sendFullErrorException) {
if (logger.isDebugEnabled()) {
logger.debug("Invalid message conversion. Message: {}, Request: {} {}", e.getMessage(), request.getMethod(), request.getRequestURI());
}
return new ErrorInfo("Bad request", e);
} else {
String errorIdentifier = UUID.randomUUID().toString();
logger.warn("Invalid Message conversion exception. Error ID: {}. Message: {}, Request: {} {}", errorIdentifier, e.getMessage(), request.getMethod(), request.getRequestURI());
ErrorInfo errorInfo = new ErrorInfo("Bad request", null);
errorInfo.setException("Invalid HTTP message. Error ID: " + errorIdentifier);
return errorInfo;
}
}
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler(FlowableTaskAlreadyClaimedException.class)
@ResponseBody
public ErrorInfo handleTaskAlreadyClaimed(FlowableTaskAlreadyClaimedException e, HttpServletRequest request) {
if (logger.isDebugEnabled()) {
logger.debug("Task was already claimed. Message: {}, Request: {} {}", e.getMessage(), request.getMethod(), request.getRequestURI());
}
return new ErrorInfo("Task was already claimed", e);
}
// Fall back
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 500
@ExceptionHandler(Exception.class)
@ResponseBody
public ErrorInfo handleOtherException(Exception e, HttpServletRequest request) {
if (sendFullErrorException) {
logger.error("Unhandled exception. Request: {} {}", request.getMethod(), request.getRequestURI(), e);
|
return new ErrorInfo("Internal server error", e);
} else {
String errorIdentifier = UUID.randomUUID().toString();
logger.error("Unhandled exception. Error ID: {}. Request: {} {}", errorIdentifier, request.getMethod(), request.getRequestURI(), e);
ErrorInfo errorInfo = new ErrorInfo("Internal server error", e);
errorInfo.setException("Error with ID: " + errorIdentifier);
return errorInfo;
}
}
public boolean isSendFullErrorException() {
return sendFullErrorException;
}
public void setSendFullErrorException(boolean sendFullErrorException) {
this.sendFullErrorException = sendFullErrorException;
}
}
|
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\exception\BaseExceptionHandlerAdvice.java
| 1
|
请完成以下Java代码
|
public class ReviewQtyPickedCommand
{
private final ITrxManager trxManager = Services.get(ITrxManager.class);
private final PickingCandidateRepository pickingCandidateRepository;
private PickingCandidateId pickingCandidateId;
private BigDecimal qtyReviewed;
@Builder
private ReviewQtyPickedCommand(
@NonNull final PickingCandidateRepository pickingCandidateRepository,
@NonNull PickingCandidateId pickingCandidateId,
@NonNull BigDecimal qtyReviewed)
{
this.pickingCandidateRepository = pickingCandidateRepository;
this.pickingCandidateId = pickingCandidateId;
this.qtyReviewed = qtyReviewed;
|
}
public PickingCandidate perform()
{
return trxManager.callInThreadInheritedTrx(this::performInTrx);
}
private PickingCandidate performInTrx()
{
final PickingCandidate pickingCandidate = pickingCandidateRepository.getById(pickingCandidateId);
pickingCandidate.assertDraft();
pickingCandidate.reviewPicking(qtyReviewed);
pickingCandidateRepository.save(pickingCandidate);
return pickingCandidate;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\ReviewQtyPickedCommand.java
| 1
|
请完成以下Java代码
|
public List<HistoricIdentityLinkEntity> findHistoricIdentityLinksByTaskId(String taskId) {
return historicIdentityLinkDataManager.findHistoricIdentityLinksByTaskId(taskId);
}
@Override
public List<HistoricIdentityLinkEntity> findHistoricIdentityLinksByProcessInstanceId(String processInstanceId) {
return historicIdentityLinkDataManager.findHistoricIdentityLinksByProcessInstanceId(processInstanceId);
}
@Override
public void deleteHistoricIdentityLinksByTaskId(String taskId) {
List<HistoricIdentityLinkEntity> identityLinks = findHistoricIdentityLinksByTaskId(taskId);
for (HistoricIdentityLinkEntity identityLink : identityLinks) {
delete(identityLink);
}
}
|
@Override
public void deleteHistoricIdentityLinksByProcInstance(final String processInstanceId) {
List<HistoricIdentityLinkEntity> identityLinks =
historicIdentityLinkDataManager.findHistoricIdentityLinksByProcessInstanceId(processInstanceId);
for (HistoricIdentityLinkEntity identityLink : identityLinks) {
delete(identityLink);
}
}
public HistoricIdentityLinkDataManager getHistoricIdentityLinkDataManager() {
return historicIdentityLinkDataManager;
}
public void setHistoricIdentityLinkDataManager(HistoricIdentityLinkDataManager historicIdentityLinkDataManager) {
this.historicIdentityLinkDataManager = historicIdentityLinkDataManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricIdentityLinkEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
public void setName (java.lang.String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/**
* QuoteType AD_Reference_ID=314
* Reference name: C_RfQ QuoteType
*/
public static final int QUOTETYPE_AD_Reference_ID=314;
/** Quote Total only = T */
public static final String QUOTETYPE_QuoteTotalOnly = "T";
/** Quote Selected Lines = S */
public static final String QUOTETYPE_QuoteSelectedLines = "S";
/** Quote All Lines = A */
public static final String QUOTETYPE_QuoteAllLines = "A";
/** Set RfQ Type.
@param QuoteType
Request for Quotation Type
*/
@Override
public void setQuoteType (java.lang.String QuoteType)
{
set_ValueNoCheck (COLUMNNAME_QuoteType, QuoteType);
}
/** Get RfQ Type.
@return Request for Quotation Type
*/
@Override
public java.lang.String getQuoteType ()
{
return (java.lang.String)get_Value(COLUMNNAME_QuoteType);
}
@Override
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep)
{
set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep);
|
}
/** Set Aussendienst.
@param SalesRep_ID Aussendienst */
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Aussendienst.
@return Aussendienst */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_RV_C_RfQ_UnAnswered.java
| 1
|
请完成以下Java代码
|
public BigDecimal addToBase(@NonNull final BigDecimal base, final int precision)
{
return addToBase(base, precision, RoundingMode.HALF_UP);
}
public BigDecimal addToBase(@NonNull final BigDecimal base, final int precision, final RoundingMode roundingMode)
{
Check.assumeGreaterOrEqualToZero(precision, "precision");
if (base.signum() == 0)
{
return BigDecimal.ZERO;
}
else if (isZero())
{
return base.setScale(precision, roundingMode);
}
else
{
// make sure the base we work with does not have more digits than we expect from the given precision.
final BigDecimal baseToUse = base.setScale(precision, roundingMode);
//noinspection BigDecimalMethodWithoutRoundingCalled
return baseToUse
.setScale(precision + 2)
.divide(ONE_HUNDRED_VALUE, RoundingMode.UNNECESSARY) // no rounding needed because we raised the current precision by 2
.multiply(ONE_HUNDRED_VALUE.add(value))
.setScale(precision, RoundingMode.HALF_UP);
}
}
/**
* Example: {@code Percent.of(TEN).subtractFromBase(new BigDecimal("100"), 0)} equals to 90
*/
public BigDecimal subtractFromBase(@NonNull final BigDecimal base, final int precision)
{
return subtractFromBase(base, precision, RoundingMode.HALF_UP);
}
public BigDecimal subtractFromBase(@NonNull final BigDecimal base, final int precision, @NonNull final RoundingMode roundingMode)
{
Check.assumeGreaterOrEqualToZero(precision, "precision");
if (base.signum() == 0)
{
return BigDecimal.ZERO;
}
else if (isZero())
{
return base.setScale(precision, roundingMode);
}
else if (isOneHundred())
{
return BigDecimal.ZERO;
|
}
else
{
// make sure the base we work with does not have more digits than we expect from the given precision.
final BigDecimal baseToUse = base.setScale(precision, roundingMode);
//noinspection BigDecimalMethodWithoutRoundingCalled
return baseToUse
.setScale(precision + 2)
.divide(ONE_HUNDRED_VALUE, RoundingMode.UNNECESSARY) // no rounding needed because we raised the current precision by 2
.multiply(ONE_HUNDRED_VALUE.subtract(value))
.setScale(precision, roundingMode);
}
}
/**
* Round to the nearest {@code .5%} percent value.
*/
public Percent roundToHalf(@NonNull final RoundingMode roundingMode)
{
@SuppressWarnings("BigDecimalMethodWithoutRoundingCalled") final BigDecimal newPercentValue = toBigDecimal()
.multiply(TWO_VALUE)
.setScale(0, roundingMode)
.divide(TWO_VALUE)
.setScale(1, roundingMode); // AFAIU not needed, but who knows..
return Percent.of(newPercentValue);
}
@Override
public int compareTo(final Percent other) {return this.value.compareTo(other.value);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\lang\Percent.java
| 1
|
请完成以下Java代码
|
public class ShellExecutorContext implements ExecutorContext {
private Boolean waitFlag;
private final Boolean cleanEnvBoolan;
private final Boolean redirectErrorFlag;
private final String directoryStr;
private final String resultVariableStr;
private final String errorCodeVariableStr;
private List<String> argList;
public ShellExecutorContext(
Boolean waitFlag,
Boolean cleanEnvBoolean,
Boolean redirectErrorFlag,
String directoryStr,
String resultVariableStr,
String errorCodeVariableStr,
List<String> argList
) {
this.waitFlag = waitFlag;
this.cleanEnvBoolan = cleanEnvBoolean;
this.redirectErrorFlag = redirectErrorFlag;
this.directoryStr = directoryStr;
this.resultVariableStr = resultVariableStr;
this.errorCodeVariableStr = errorCodeVariableStr;
this.argList = argList;
}
public Boolean getWaitFlag() {
return waitFlag;
}
public void setWaitFlag(Boolean waitFlag) {
this.waitFlag = waitFlag;
}
public Boolean getCleanEnvBoolan() {
return cleanEnvBoolan;
}
public Boolean getRedirectErrorFlag() {
return redirectErrorFlag;
}
|
public String getDirectoryStr() {
return directoryStr;
}
public String getResultVariableStr() {
return resultVariableStr;
}
public String getErrorCodeVariableStr() {
return errorCodeVariableStr;
}
public List<String> getArgList() {
return argList;
}
public void setArgList(List<String> argList) {
this.argList = argList;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\ShellExecutorContext.java
| 1
|
请完成以下Java代码
|
public String getCd() {
return cd;
}
/**
* Sets the value of the cd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCd(String value) {
this.cd = value;
}
/**
* Gets the value of the fmly property.
*
* @return
* possible object is
* {@link BankTransactionCodeStructure6 }
*
|
*/
public BankTransactionCodeStructure6 getFmly() {
return fmly;
}
/**
* Sets the value of the fmly property.
*
* @param value
* allowed object is
* {@link BankTransactionCodeStructure6 }
*
*/
public void setFmly(BankTransactionCodeStructure6 value) {
this.fmly = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\BankTransactionCodeStructure5.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.