instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
private void createJsonStock(@NonNull final Exchange exchange)
{
final ExportStockRouteContext exportStockRouteContext = exchange.getProperty(ROUTE_PROPERTY_EXPORT_STOCK_CONTEXT, ExportStockRouteContext.class);
final BigDecimal stockBD = exportStockRouteContext.getJsonAvailableForSales()
.getStock()
.setScale(0, RoundingMode.CEILING);
final JsonStock jsonStock = JsonStock.builder()
.stock(stockBD.intValueExact())
.build();
exchange.getIn().setBody(jsonStock);
}
private void buildAndAttachRouteContext(@NonNull final Exchange exchange)
{
final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class);
if (request.getAdPInstanceId() != null)
{
exchange.getIn().setHeader(HEADER_PINSTANCE_ID, request.getAdPInstanceId().getValue());
processLogger.logMessage("Shopware6:ExportStock process started!" + Instant.now(), request.getAdPInstanceId().getValue());
}
final String clientId = request.getParameters().get(ExternalSystemConstants.PARAM_CLIENT_ID);
final String clientSecret = request.getParameters().get(ExternalSystemConstants.PARAM_CLIENT_SECRET);
final String basePath = request.getParameters().get(ExternalSystemConstants.PARAM_BASE_PATH);
final PInstanceLogger pInstanceLogger = PInstanceLogger.builder()
.processLogger(processLogger)
.pInstanceId(request.getAdPInstanceId())
.build();
final ShopwareClient shopwareClient = ShopwareClient.of(clientId, clientSecret, basePath, pInstanceLogger);
final JsonAvailableForSales jsonAvailableForSales = getJsonAvailableForSales(request);
final ExportStockRouteContext exportStockRouteContext = ExportStockRouteContext.builder()
|
.shopwareClient(shopwareClient)
.jsonAvailableForSales(jsonAvailableForSales)
.build();
exchange.setProperty(ROUTE_PROPERTY_EXPORT_STOCK_CONTEXT, exportStockRouteContext);
}
@NonNull
private JsonAvailableForSales getJsonAvailableForSales(@NonNull final JsonExternalSystemRequest request)
{
try
{
return objectMapper.readValue(request.getParameters().get(ExternalSystemConstants.PARAM_JSON_AVAILABLE_FOR_SALES), JsonAvailableForSales.class);
}
catch (final IOException e)
{
throw new RuntimeException("Unable to deserialize JsonAvailableStock", e);
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\stock\ExportStockRouteBuilder.java
| 2
|
请完成以下Java代码
|
public String toString()
{
final BigDecimal price = pricingResult == null ? null : pricingResult.getPriceStd();
return "QualityInvoiceLine ["
+ "product=" + (product == null ? null : product.getName())
+ ", productName=" + productName
+ ", percentage=" + percentage
+ ", qty=" + qty
+ ", uom=" + (uom == null ? null : uom.getUOMSymbol())
+ ", price=" + price
+ ", displayed=" + displayed
+ ", description=" + description
+ ", ppOrder=" + ppOrder
+ ", handlingUnitsInfo=" + handlingUnitsInfo
+ "]";
}
@Override
public IQualityInvoiceLineGroup getGroup()
{
return qualityInvoiceLineGroup;
}
/* package */ void setGroup(final IQualityInvoiceLineGroup qualityInvoiceLineGroup)
{
Check.errorIf(this.qualityInvoiceLineGroup != null,
"This instance {} was already added to qualityInvoiceLineGroup {}; can't be added to {}",
this, this.qualityInvoiceLineGroup, qualityInvoiceLineGroup);
this.qualityInvoiceLineGroup = qualityInvoiceLineGroup;
}
@Override
public I_M_Product getM_Product()
{
return product;
}
@Override
public ProductId getProductId()
{
final I_M_Product product = getM_Product();
return product != null ? ProductId.ofRepoId(product.getM_Product_ID()) : null;
}
public void setM_Product(final I_M_Product product)
{
this.product = product;
}
@Override
public String getProductName()
{
return productName;
}
public void setProductName(final String productName)
{
this.productName = productName;
}
@Override
public BigDecimal getPercentage()
{
return percentage;
}
public void setPercentage(final BigDecimal percentage)
{
this.percentage = percentage;
}
@Override
public Quantity getQty()
{
|
return Quantity.of(qty, uom);
}
public void setQty(@NonNull final Quantity qty)
{
this.qty = qty.toBigDecimal();
this.uom = qty.getUOM();
}
@Override
public IPricingResult getPrice()
{
return pricingResult;
}
public void setPrice(final IPricingResult price)
{
pricingResult = price;
}
@Override
public boolean isDisplayed()
{
return displayed;
}
public void setDisplayed(final boolean displayed)
{
this.displayed = displayed;
}
@Override
public String getDescription()
{
return description;
}
public void setDescription(final String description)
{
this.description = description;
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfo()
{
return handlingUnitsInfo;
}
public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo)
{
this.handlingUnitsInfo = handlingUnitsInfo;
}
@Override
public I_PP_Order getPP_Order()
{
return ppOrder;
}
public void setPP_Order(I_PP_Order ppOrder)
{
this.ppOrder = ppOrder;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\invoicing\impl\QualityInvoiceLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getURL() {
return url;
}
/**
* Sets the value of the url property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setURL(String value) {
this.url = value;
}
/**
* A URL to the logo of the issuer of the document.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLogoURL() {
return logoURL;
}
/**
* Sets the value of the logoURL property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLogoURL(String value) {
this.logoURL = value;
}
/**
* A certain layout id.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLayoutID() {
return layoutID;
}
/**
* Sets the value of the layoutID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLayoutID(String value) {
this.layoutID = value;
}
|
/**
* Indicates whether an amount of 0 shall be shown or not.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isSuppressZero() {
return suppressZero;
}
/**
* Sets the value of the suppressZero property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setSuppressZero(Boolean value) {
this.suppressZero = value;
}
/**
* Gets the value of the presentationDetailsExtension property.
*
* @return
* possible object is
* {@link PresentationDetailsExtensionType }
*
*/
public PresentationDetailsExtensionType getPresentationDetailsExtension() {
return presentationDetailsExtension;
}
/**
* Sets the value of the presentationDetailsExtension property.
*
* @param value
* allowed object is
* {@link PresentationDetailsExtensionType }
*
*/
public void setPresentationDetailsExtension(PresentationDetailsExtensionType value) {
this.presentationDetailsExtension = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PresentationDetailsType.java
| 2
|
请完成以下Java代码
|
public BigDecimal getQtyOnHand()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyRequiered (final @Nullable BigDecimal QtyRequiered)
{
set_ValueNoCheck (COLUMNNAME_QtyRequiered, QtyRequiered);
}
@Override
public BigDecimal getQtyRequiered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyRequiered);
|
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyReserved (final @Nullable BigDecimal QtyReserved)
{
set_ValueNoCheck (COLUMNNAME_QtyReserved, QtyReserved);
}
@Override
public BigDecimal getQtyReserved()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_RV_PP_Order_BOMLine.java
| 1
|
请完成以下Java代码
|
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DmnTypeDefinition getTypeDefinition() {
return typeDefinition;
}
|
public void setTypeDefinition(DmnTypeDefinition typeDefinition) {
this.typeDefinition = typeDefinition;
}
@Override
public String toString() {
return "DmnVariableImpl{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", typeDefinition=" + typeDefinition +
'}';
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnVariableImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("modify_request_body", r -> r.path("/post")
.filters(f -> f.modifyRequestBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE,
(exchange, s) -> Mono.just(new Hello(s.toUpperCase())))).uri("https://httpbin.org"))
.build();
}
@Bean
public RouteLocator responseRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route("modify_response_body", r -> r.path("/put/**")
.filters(f -> f.modifyResponseBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE,
(exchange, s) -> Mono.just(new Hello("New Body")))).uri("https://httpbin.org"))
.build();
}
static class Hello {
|
String message;
public Hello() { }
public Hello(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway-2\src\main\java\com\baeldung\springcloudgateway\webfilters\config\ModifyBodyRouteConfig.java
| 2
|
请完成以下Java代码
|
private String buildStringRepresentation()
{
final StringBuilder sb = new StringBuilder();
sb.append(accountConceptualName != null ? accountConceptualName.getAsString() : "-");
sb.append("#").append(tableName);
sb.append("#").append(Math.max(recordId, 0));
if (lineId > 0)
{
sb.append("#").append(lineId);
}
if (subLineId > 0)
{
sb.append("#").append(subLineId);
}
return sb.toString();
}
public Optional<InvoiceId> getInvoiceId()
{
return I_C_Invoice.Table_Name.equals(tableName)
? InvoiceId.optionalOfRepoId(recordId)
: Optional.empty();
}
public Optional<PaymentId> getPaymentId()
{
|
return I_C_Payment.Table_Name.equals(tableName)
? PaymentId.optionalOfRepoId(recordId)
: Optional.empty();
}
public Optional<BankStatementId> getBankStatementId()
{
return I_C_BankStatement.Table_Name.equals(tableName)
? BankStatementId.optionalOfRepoId(recordId)
: Optional.empty();
}
public Optional<BankStatementLineId> getBankStatementLineId()
{
return I_C_BankStatement.Table_Name.equals(tableName)
? BankStatementLineId.optionalOfRepoId(lineId)
: Optional.empty();
}
public Optional<BankStatementLineRefId> getBankStatementLineRefId()
{
return I_C_BankStatement.Table_Name.equals(tableName)
? BankStatementLineRefId.optionalOfRepoId(subLineId)
: Optional.empty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\open_items\FAOpenItemKey.java
| 1
|
请完成以下Java代码
|
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!getClass().equals(obj.getClass()))
{
return false;
}
final EffectiveValuesEvaluatee other = (EffectiveValuesEvaluatee)obj;
return values.equals(other.values);
}
@Override
public String get_ValueAsString(final String variableName)
{
return values.get(variableName);
}
|
@Override
public boolean has_Variable(final String variableName)
{
return values.containsKey(variableName);
}
@Override
public String get_ValueOldAsString(final String variableName)
{
// TODO Auto-generated method stub
return null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\CachedStringExpression.java
| 1
|
请完成以下Java代码
|
private void putToQueue(TopicPartitionInfo tpi, TbMsg newMsg, TbQueueCallback callbackWrapper) {
ToRuleEngineMsg toQueueMsg = ToRuleEngineMsg.newBuilder()
.setTenantIdMSB(tenantId.getId().getMostSignificantBits())
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits())
.setTbMsgProto(TbMsg.toProto(newMsg))
.build();
clusterService.pushMsgToRuleEngine(tpi, newMsg.getId(), toQueueMsg, callbackWrapper);
}
private boolean contains(Set<String> relationTypes, String type) {
if (relationTypes == null) {
return true;
}
for (String relationType : relationTypes) {
if (relationType.equalsIgnoreCase(type)) {
return true;
}
}
return false;
}
|
private void pushMsgToNode(RuleNodeCtx nodeCtx, TbMsg msg, String fromRelationType) {
if (nodeCtx != null) {
var tbCtx = new DefaultTbContext(systemContext, ruleChainName, nodeCtx);
nodeCtx.getSelfActor().tell(new RuleChainToRuleNodeMsg(tbCtx, msg, fromRelationType));
} else {
log.error("[{}][{}] RuleNodeCtx is empty", entityId, ruleChainName);
msg.getCallback().onFailure(new RuleEngineException("Rule Node CTX is empty"));
}
}
@Override
protected RuleNodeException getInactiveException() {
RuleNode firstRuleNode = firstNode != null ? firstNode.getSelf() : null;
return new RuleNodeException("Rule Chain is not active! Failed to initialize.", ruleChainName, firstRuleNode);
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\RuleChainActorMessageProcessor.java
| 1
|
请完成以下Java代码
|
protected final Context getContext() {
return this.context;
}
/**
* Internal class used to supply the aggregate and cache the value.
*
* @param <T> the aggregate type
*/
protected static class AggregateSupplier<T> {
private final Supplier<T> supplier;
private @Nullable T supplied;
public AggregateSupplier(Supplier<T> supplier) {
|
this.supplier = supplier;
}
public T get() {
if (this.supplied == null) {
this.supplied = this.supplier.get();
}
return this.supplied;
}
public boolean wasSupplied() {
return this.supplied != null;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\bind\AggregateBinder.java
| 1
|
请完成以下Java代码
|
public final JComponent getComponent()
{
return findPanel;
}
@Override
public boolean isExpanded()
{
return expanded;
}
@Override
public void setExpanded(final boolean expanded)
{
if (this.expanded == expanded)
{
return;
}
this.expanded = expanded;
findPanel.setVisible(expanded);
findPanel.setEnabled(expanded);
_pcs.firePropertyChange(PROPERTY_Expanded, !expanded, expanded);
}
@Override
public boolean isFocusable()
{
return findPanel.isFocusable();
}
@Override
public void requestFocus()
{
findPanel.requestFocus();
}
|
@Override
public boolean requestFocusInWindow()
{
return findPanel.requestFocusInWindow();
}
private final synchronized PropertyChangeSupport getPropertyChangeSupport()
{
if (_pcs == null)
{
_pcs = new PropertyChangeSupport(this);
}
return _pcs;
}
@Override
public void runOnExpandedStateChange(final Runnable runnable)
{
Check.assumeNotNull(runnable, "runnable not null");
getPropertyChangeSupport().addPropertyChangeListener(PROPERTY_Expanded, new PropertyChangeListener()
{
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
runnable.run();
}
});
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelContainer_EmbeddedPanel.java
| 1
|
请完成以下Java代码
|
public boolean isNewDunningDoc(I_C_Dunning_Candidate candidate)
{
Result finalResult = null;
for (IDunningAggregator agg : dunningAggregators)
{
final Result result = agg.isNewDunningDoc(candidate);
if (result == Result.I_FUCKING_DONT_CARE)
{
continue;
}
if (result == null)
{
finalResult = result;
}
if (!Util.same(result, finalResult))
{
throw new DunningException("Confusing verdict for aggregators: " + dunningAggregators);
}
}
if (finalResult == null)
{
finalResult = defaultDunningAggregator.isNewDunningDoc(candidate);
}
return toBoolean(finalResult);
}
public boolean isNewDunningDocLine(I_C_Dunning_Candidate candidate)
{
if (dunningAggregators.isEmpty())
{
throw new DunningException("No child " + IDunningAggregator.class + " registered");
}
Result finalResult = null;
for (IDunningAggregator agg : dunningAggregators)
{
final Result result = agg.isNewDunningDocLine(candidate);
if (result == Result.I_FUCKING_DONT_CARE)
{
|
continue;
}
if (result == null)
{
finalResult = result;
}
if (!Util.same(result, finalResult))
{
throw new DunningException("Confusing verdict for aggregators: " + dunningAggregators);
}
}
if (finalResult == null)
{
finalResult = defaultDunningAggregator.isNewDunningDocLine(candidate);
}
return toBoolean(finalResult);
}
private static final boolean toBoolean(final Result result)
{
if (result == Result.YES)
{
return true;
}
else if (result == Result.NO)
{
return false;
}
else
{
throw new IllegalArgumentException("Result shall be YES or NO: " + result);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\CompositeDunningAggregator.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_OrderLine_ID (final int C_OrderLine_ID)
{
if (C_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, C_OrderLine_ID);
}
@Override
public int getC_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID);
}
@Override
public org.compiere.model.I_M_InOut getM_InOut()
{
return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class);
}
@Override
public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut)
{
set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut);
}
|
@Override
public void setM_InOut_ID (final int M_InOut_ID)
{
if (M_InOut_ID < 1)
set_Value (COLUMNNAME_M_InOut_ID, null);
else
set_Value (COLUMNNAME_M_InOut_ID, M_InOut_ID);
}
@Override
public int getM_InOut_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOut_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_M_InOut_Overdelivery_C_OrderLine_v.java
| 1
|
请完成以下Java代码
|
public class Item {
private UUID id;
private String title;
private List<Person> authors = new ArrayList<>();
private float price;
public Item(){}
public Item(String title, Author author) {
this.id = UUID.randomUUID();
this.title = title;
this.authors.add(author);
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
|
public void setTitle(String title) {
this.title = title;
}
public List<Person> getAuthors() {
return authors;
}
public void setAuthors(List<Person> authors) {
this.authors = authors;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
|
repos\tutorials-master\video-tutorials\jackson-annotations-video\src\main\java\com\baeldung\jacksonannotation\deserialization\jsondeserialize\Item.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Thread getAsyncJobAcquisitionThread() {
return asyncJobAcquisitionThread;
}
public void setAsyncJobAcquisitionThread(Thread asyncJobAcquisitionThread) {
this.asyncJobAcquisitionThread = asyncJobAcquisitionThread;
}
public Thread getResetExpiredJobThread() {
return resetExpiredJobThread;
}
public void setResetExpiredJobThread(Thread resetExpiredJobThread) {
this.resetExpiredJobThread = resetExpiredJobThread;
}
public boolean isUnlockOwnedJobs() {
return configuration.isUnlockOwnedJobs();
}
|
public void setUnlockOwnedJobs(boolean unlockOwnedJobs) {
configuration.setUnlockOwnedJobs(unlockOwnedJobs);
}
@Override
public AsyncTaskExecutor getTaskExecutor() {
return taskExecutor;
}
@Override
public void setTaskExecutor(AsyncTaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\DefaultAsyncJobExecutor.java
| 2
|
请完成以下Java代码
|
public class ResourceDocumentSource implements DocumentSource {
/**
* The default file extensions, ".graphql" and ".gql".
*/
public static final List<String> FILE_EXTENSIONS = Arrays.asList(".graphql", ".gql");
private final List<Resource> locations;
private final List<String> extensions;
/**
* Default constructor that sets the location to {@code "classpath:graphql/"}
* and the extensions to ".graphql" and ".gql".
*/
public ResourceDocumentSource() {
this(Collections.singletonList(new ClassPathResource("graphql/")), FILE_EXTENSIONS);
}
/**
* Constructor with a single location and the default file extensions.
* @param location the resource location
* @since 2.0.0
*/
public ResourceDocumentSource(Resource location) {
this(Collections.singletonList(location), FILE_EXTENSIONS);
}
/**
* Constructor with given locations and extensions.
* @param locations the resource locations
* @param extensions the file extensions for document sources
*/
public ResourceDocumentSource(List<Resource> locations, List<String> extensions) {
this.locations = Collections.unmodifiableList(new ArrayList<>(locations));
this.extensions = Collections.unmodifiableList(new ArrayList<>(extensions));
}
/**
* Return a read-only list with the configured locations where to check for
* documents.
*/
public List<Resource> getLocations() {
return this.locations;
}
/**
* Return a read-only list with the file extensions to try when checking
* for documents by name.
*/
public List<String> getExtensions() {
return this.extensions;
}
|
@Override
public Mono<String> getDocument(String name) {
return Flux.fromIterable(this.locations)
.flatMapIterable((location) -> getCandidateResources(name, location))
.filter(Resource::exists)
.next()
.map(this::resourceToString)
.switchIfEmpty(Mono.fromRunnable(() -> {
throw new IllegalStateException(
"Failed to find document, name='" + name + "', under location(s)=" +
this.locations.stream().map(Resource::toString).toList());
}))
.subscribeOn(Schedulers.boundedElastic());
}
private List<Resource> getCandidateResources(String name, Resource location) {
return this.extensions.stream()
.map((ext) -> {
try {
return location.createRelative(name + ext);
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
})
.collect(Collectors.toList());
}
private String resourceToString(Resource resource) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
FileCopyUtils.copy(resource.getInputStream(), outputStream);
return outputStream.toString(StandardCharsets.UTF_8);
}
catch (IOException ex) {
throw new IllegalArgumentException(
"Found resource: " + resource.getDescription() + " but failed to read it", ex);
}
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\support\ResourceDocumentSource.java
| 1
|
请完成以下Java代码
|
public void setOrg(OrgLawType value) {
this.org = value;
}
/**
* Gets the value of the treatment property.
*
* @return
* possible object is
* {@link TreatmentType }
*
*/
public TreatmentType getTreatment() {
return treatment;
}
/**
* Sets the value of the treatment property.
*
* @param value
* allowed object is
* {@link TreatmentType }
*
*/
public void setTreatment(TreatmentType value) {
this.treatment = value;
}
/**
* Gets the value of the services property.
*
* @return
* possible object is
* {@link ServicesType }
*
*/
public ServicesType getServices() {
return services;
}
/**
* Sets the value of the services property.
*
* @param value
* allowed object is
* {@link ServicesType }
*
*/
public void setServices(ServicesType value) {
this.services = value;
}
/**
* Gets the value of the documents property.
*
* @return
* possible object is
* {@link DocumentsType }
*
*/
public DocumentsType getDocuments() {
return documents;
}
/**
* Sets the value of the documents property.
*
* @param value
* allowed object is
* {@link DocumentsType }
*
*/
public void setDocuments(DocumentsType value) {
this.documents = value;
}
/**
* Gets the value of the roleTitle property.
*
* @return
* possible object is
* {@link String }
*
|
*/
public String getRoleTitle() {
return roleTitle;
}
/**
* Sets the value of the roleTitle property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRoleTitle(String value) {
this.roleTitle = value;
}
/**
* Gets the value of the role property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRole() {
return role;
}
/**
* Sets the value of the role property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRole(String value) {
this.role = value;
}
/**
* Gets the value of the place property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPlace() {
return place;
}
/**
* Sets the value of the place property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPlace(String value) {
this.place = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\BodyType.java
| 1
|
请完成以下Java代码
|
private String computeDefaultValue_Line(final I_AD_Table table, final I_AD_Column column)
{
if (table.isView()) {return null;}
if (!Check.isBlank(column.getColumnSQL())) {return null;}
final String columnName = column.getColumnName();
final String tableName = table.getTableName();
final ImmutableSet<String> parentColumnNames = adTableDAO.retrieveColumnsForTable(table)
.stream()
.filter(c -> c.getAD_Column_ID() != column.getAD_Column_ID())
.filter(I_AD_Column::isParent)
.map(I_AD_Column::getColumnName)
.collect(ImmutableSet.toImmutableSet());
if (parentColumnNames.isEmpty()) {return null;}
final StringBuilder sqlWhereClause = new StringBuilder();
|
parentColumnNames.forEach(parentColumnName -> {
if (sqlWhereClause.length() > 0)
{
sqlWhereClause.append(" AND ");
}
sqlWhereClause.append("t.").append(parentColumnName).append("=@").append(parentColumnName).append("@");
});
return "@SQL="
+ "SELECT CEILING(COALESCE(MAX(t." + columnName + "), 0) / 10) * 10 + 10"
+ " FROM " + tableName + " t"
+ " WHERE " + sqlWhereClause;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\column\callout\AD_Column.java
| 1
|
请完成以下Java代码
|
public class ConnectCoreLogger extends ConnectLogger {
public void closingResponse(CloseableConnectorResponse response) {
logDebug("001", "Closing closeable connector response '{}'", response);
}
public void successfullyClosedResponse(CloseableConnectorResponse response) {
logDebug("002", "Successfully closed closeable connector response '{}'", response);
}
public ConnectorException exceptionWhileClosingResponse(Exception cause) {
return new ConnectorException(exceptionMessage("003", "Unable to close response"), cause);
}
public void connectorProviderDiscovered(ConnectorProvider provider, String connectorId, Connector connectorInstance) {
if (isInfoEnabled()) {
|
logInfo("004", "Discovered provider for connector id '{}' and class '{}': '{}'",
connectorId, connectorInstance.getClass().getName(), provider.getClass().getName());
}
}
public ConnectorException multipleConnectorProvidersFound(String connectorId) {
return new ConnectorException(exceptionMessage("005", "Multiple providers found for connector '{}'", connectorId));
}
public void connectorConfiguratorDiscovered(ConnectorConfigurator configurator) {
if (isInfoEnabled()) {
logInfo("006", "Discovered configurator for connector class '{}': '{}'",
configurator.getConnectorClass().getName(), configurator.getClass().getName());
}
}
}
|
repos\camunda-bpm-platform-master\connect\core\src\main\java\org\camunda\connect\impl\ConnectCoreLogger.java
| 1
|
请完成以下Java代码
|
public void setM_Shipper(final org.compiere.model.I_M_Shipper M_Shipper)
{
set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper);
}
@Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
}
@Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setM_WarehouseSource_ID (final int M_WarehouseSource_ID)
{
if (M_WarehouseSource_ID < 1)
set_Value (COLUMNNAME_M_WarehouseSource_ID, null);
else
set_Value (COLUMNNAME_M_WarehouseSource_ID, M_WarehouseSource_ID);
}
@Override
public int getM_WarehouseSource_ID()
{
return get_ValueAsInt(COLUMNNAME_M_WarehouseSource_ID);
}
@Override
public void setPercent (final BigDecimal Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
@Override
public BigDecimal getPercent()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Percent);
return bd != null ? bd : BigDecimal.ZERO;
|
}
@Override
public void setPriorityNo (final int PriorityNo)
{
set_Value (COLUMNNAME_PriorityNo, PriorityNo);
}
@Override
public int getPriorityNo()
{
return get_ValueAsInt(COLUMNNAME_PriorityNo);
}
@Override
public void setTransfertTime (final @Nullable BigDecimal TransfertTime)
{
set_Value (COLUMNNAME_TransfertTime, TransfertTime);
}
@Override
public BigDecimal getTransfertTime()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TransfertTime);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_NetworkDistributionLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public long getPingInterval() {
return this.pingInterval;
}
public void setPingInterval(long pingInterval) {
this.pingInterval = pingInterval;
}
public boolean isPrSingleHopEnabled() {
return this.prSingleHopEnabled;
}
public void setPrSingleHopEnabled(boolean prSingleHopEnabled) {
this.prSingleHopEnabled = prSingleHopEnabled;
}
public int getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
public boolean isReadyForEvents() {
return this.readyForEvents;
}
public void setReadyForEvents(boolean readyForEvents) {
this.readyForEvents = readyForEvents;
}
public int getRetryAttempts() {
return this.retryAttempts;
}
public void setRetryAttempts(int retryAttempts) {
this.retryAttempts = retryAttempts;
}
public String getServerGroup() {
return this.serverGroup;
}
public void setServerGroup(String serverGroup) {
this.serverGroup = serverGroup;
}
public String[] getServers() {
return this.servers;
}
public void setServers(String[] servers) {
this.servers = servers;
}
|
public int getSocketBufferSize() {
return this.socketBufferSize;
}
public void setSocketBufferSize(int socketBufferSize) {
this.socketBufferSize = socketBufferSize;
}
public int getStatisticInterval() {
return this.statisticInterval;
}
public void setStatisticInterval(int statisticInterval) {
this.statisticInterval = statisticInterval;
}
public int getSubscriptionAckInterval() {
return this.subscriptionAckInterval;
}
public void setSubscriptionAckInterval(int subscriptionAckInterval) {
this.subscriptionAckInterval = subscriptionAckInterval;
}
public boolean isSubscriptionEnabled() {
return this.subscriptionEnabled;
}
public void setSubscriptionEnabled(boolean subscriptionEnabled) {
this.subscriptionEnabled = subscriptionEnabled;
}
public int getSubscriptionMessageTrackingTimeout() {
return this.subscriptionMessageTrackingTimeout;
}
public void setSubscriptionMessageTrackingTimeout(int subscriptionMessageTrackingTimeout) {
this.subscriptionMessageTrackingTimeout = subscriptionMessageTrackingTimeout;
}
public int getSubscriptionRedundancy() {
return this.subscriptionRedundancy;
}
public void setSubscriptionRedundancy(int subscriptionRedundancy) {
this.subscriptionRedundancy = subscriptionRedundancy;
}
public boolean isThreadLocalConnections() {
return this.threadLocalConnections;
}
public void setThreadLocalConnections(boolean threadLocalConnections) {
this.threadLocalConnections = threadLocalConnections;
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\PoolProperties.java
| 2
|
请完成以下Java代码
|
public class PriorityJobScheduler {
private ExecutorService priorityJobPoolExecutor;
private ExecutorService priorityJobScheduler =
Executors.newSingleThreadExecutor();
private PriorityBlockingQueue<Job> priorityQueue;
public PriorityJobScheduler(Integer poolSize, Integer queueSize) {
priorityJobPoolExecutor = Executors.newFixedThreadPool(poolSize);
priorityQueue = new PriorityBlockingQueue<Job>(queueSize,
Comparator.comparing(Job::getJobPriority));
priorityJobScheduler.execute(()->{
while (true) {
try {
priorityJobPoolExecutor.execute(priorityQueue.take());
} catch (InterruptedException e) {
// exception needs special handling
break;
}
}
});
}
public void scheduleJob(Job job) {
priorityQueue.add(job);
}
public int getQueuedTaskCount() {
|
return priorityQueue.size();
}
protected void close(ExecutorService scheduler) {
scheduler.shutdown();
try {
if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
scheduler.shutdownNow();
}
} catch (InterruptedException e) {
scheduler.shutdownNow();
}
}
public void closeScheduler() {
close(priorityJobPoolExecutor);
close(priorityJobScheduler);
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-2\src\main\java\com\baeldung\concurrent\prioritytaskexecution\PriorityJobScheduler.java
| 1
|
请完成以下Java代码
|
public static void merge() {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike2 = new Product("E-Bike", "A bike with a battery");
eBike2.getTags().add("sport");
productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProduct);
//Prior to Java 8:
if(productsByName.containsKey("E-Bike")) {
productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2);
} else {
productsByName.put("E-Bike", eBike2);
}
}
public static void compute() {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike2 = new Product("E-Bike", "A bike with a battery");
|
productsByName.compute("E-Bike", (k,v) -> {
if(v != null) {
return v.addTagsOfOtherProduct(eBike2);
} else {
return eBike2;
}
});
//Prior to Java 8:
if(productsByName.containsKey("E-Bike")) {
productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2);
} else {
productsByName.put("E-Bike", eBike2);
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\hashmapguide\Product.java
| 1
|
请完成以下Java代码
|
private boolean hasSelector(OperationParameter parameter) {
return parameter.getAnnotation(Selector.class) != null;
}
private String dashName(OperationParameter parameter) {
return "-" + parameter.getName();
}
private boolean getBlocking(OperationMethod method) {
return !REACTIVE_STREAMS_PRESENT || !Publisher.class.isAssignableFrom(method.getMethod().getReturnType());
}
@Override
public String getId() {
return this.id;
}
@Override
public boolean isBlocking() {
|
return this.blocking;
}
@Override
public WebOperationRequestPredicate getRequestPredicate() {
return this.requestPredicate;
}
@Override
protected void appendFields(ToStringCreator creator) {
creator.append("id", this.id)
.append("blocking", this.blocking)
.append("requestPredicate", this.requestPredicate);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\annotation\DiscoveredWebOperation.java
| 1
|
请完成以下Java代码
|
protected void createDocumentLine(final IPackingMaterialDocumentLine pmLine)
{
final OrderLinePackingMaterialDocumentLine orderLinePMLine = toImpl(pmLine);
final I_C_OrderLine pmOrderLine = orderLinePMLine.getC_OrderLine();
// qtyOrdered is in the product's UOM whereas QtyEntered is in the order line's UOM. They don't have to be the same.
// pmOrderLine.setQtyEntered(pmOrderLine.getQtyOrdered());
final boolean ordereWasInactive = !pmOrderLine.isActive();
pmOrderLine.setIsActive(true);
if (ordereWasInactive)
{
// while the order line was inactive e.g. the order's datePromised might have been changed
orderLineBL.setOrder(pmOrderLine, order);
}
orderLineBL.updatePrices(OrderLinePriceUpdateRequest.builder()
.orderLine(pmOrderLine)
.resultUOM(ResultUOM.CONTEXT_UOM)
.updatePriceEnteredAndDiscountOnlyIfNotAlreadySet(true)
.updateLineNetAmt(true)
.build());
InterfaceWrapperHelper.save(pmOrderLine);
|
}
@Override
protected void linkSourceToDocumentLine(final IPackingMaterialDocumentLineSource source,
final IPackingMaterialDocumentLine pmLine)
{
final OrderLinePackingMaterialDocumentLineSource orderLineSource = toImpl(source);
final OrderLinePackingMaterialDocumentLine orderLinePMLine = toImpl(pmLine);
final I_C_OrderLine regularOrderLine = orderLineSource.getC_OrderLine();
Check.assume(regularOrderLine.getC_OrderLine_ID() > 0, "Regular order line shall be already saved: {}", regularOrderLine);
final I_C_OrderLine pmOrderLine;
if (orderLinePMLine == null)
{
pmOrderLine = null;
}
else
{
pmOrderLine = orderLinePMLine.getC_OrderLine();
}
regularOrderLine.setC_PackingMaterial_OrderLine(pmOrderLine);
InterfaceWrapperHelper.save(regularOrderLine);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\order\api\impl\OrderPackingMaterialDocumentLinesBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Deployment deploy(String bpmnFileUrl) {
Deployment deploy = createDeployment().addClasspathResource(bpmnFileUrl).deploy();
return deploy;
}
@Override
public Deployment deploy(String url, String pngUrl) {
Deployment deploy = createDeployment().addClasspathResource(url).addClasspathResource(pngUrl).deploy();
return deploy;
}
@Override
public Deployment deploy(String name, String tenantId, String category, ZipInputStream zipInputStream) {
return createDeployment().addZipInputStream(zipInputStream)
.name(name).category(category).tenantId(tenantId).deploy();
}
@Override
public Deployment deployBpmnAndDrl(String url, String drlUrl) {
Deployment deploy = createDeployment().addClasspathResource(url).addClasspathResource(drlUrl).deploy();
return deploy;
}
@Override
public Deployment deploy(String url, String name, String category) {
Deployment deploy = createDeployment().addClasspathResource(url).name(name).category(category).deploy();
return deploy;
}
@Override
public Deployment deploy(String url, String pngUrl, String name, String category) {
Deployment deploy = createDeployment().addClasspathResource(url).addClasspathResource(pngUrl)
.name(name).category(category).deploy();
return deploy;
}
@Override
public boolean exist(String processDefinitionKey) {
ProcessDefinitionQuery processDefinitionQuery
= createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey);
long count = processDefinitionQuery.count();
return count > 0 ? true : false;
}
@Override
public Deployment deploy(String name, String tenantId, String category, InputStream in) {
return createDeployment().addInputStream(name + BPMN_FILE_SUFFIX, in)
.name(name)
.tenantId(tenantId)
.category(category)
|
.deploy();
}
@Override
public ProcessDefinition queryByProcessDefinitionKey(String processDefinitionKey) {
ProcessDefinition processDefinition
= createProcessDefinitionQuery()
.processDefinitionKey(processDefinitionKey)
.active().singleResult();
return processDefinition;
}
@Override
public Deployment deployName(String deploymentName) {
List<Deployment> list = repositoryService
.createDeploymentQuery()
.deploymentName(deploymentName).list();
Assert.notNull(list, "list must not be null");
return list.get(0);
}
@Override
public void addCandidateStarterUser(String processDefinitionKey, String userId) {
repositoryService.addCandidateStarterUser(processDefinitionKey, userId);
}
}
|
repos\spring-boot-quick-master\quick-flowable\src\main\java\com\quick\flowable\service\handler\ProcessHandler.java
| 2
|
请完成以下Java代码
|
public static ByteArrayFileStream createByteArrayFileStream(FileInputStream fileInputStream) throws IOException
{
FileChannel channel = fileInputStream.getChannel();
long size = channel.size();
int bufferSize = (int) Math.min(1048576, size);
ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);
if (channel.read(byteBuffer) == size)
{
channel.close();
channel = null;
}
byteBuffer.flip();
byte[] bytes = byteBuffer.array();
return new ByteArrayFileStream(bytes, bufferSize, channel);
}
@Override
public boolean hasMore()
{
return offset < bufferSize || fileChannel != null;
}
/**
* 确保buffer数组余有size个字节
* @param size
*/
@Override
protected void ensureAvailableBytes(int size)
{
if (offset + size > bufferSize)
{
try
{
int availableBytes = (int) (fileChannel.size() - fileChannel.position());
ByteBuffer byteBuffer = ByteBuffer.allocate(Math.min(availableBytes, offset));
int readBytes = fileChannel.read(byteBuffer);
|
if (readBytes == availableBytes)
{
fileChannel.close();
fileChannel = null;
}
assert readBytes > 0 : "已到达文件尾部!";
byteBuffer.flip();
byte[] bytes = byteBuffer.array();
System.arraycopy(this.bytes, offset, this.bytes, offset - readBytes, bufferSize - offset);
System.arraycopy(bytes, 0, this.bytes, bufferSize - readBytes, readBytes);
offset -= readBytes;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
}
@Override
public void close()
{
super.close();
try
{
if (fileChannel == null) return;
fileChannel.close();
}
catch (IOException e)
{
Predefine.logger.warning(TextUtility.exceptionToString(e));
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\io\ByteArrayFileStream.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
@Override
public Object getValue(ValueFields valueFields) {
return valueFields.getBytes();
}
@Override
public void setValue(Object value, ValueFields valueFields) {
if (value == null) {
valueFields.setBytes(null);
|
return;
}
byte[] bytes = (byte[]) value;
lengthVerifier.verifyLength(bytes.length, valueFields, this);
valueFields.setBytes((byte[]) value);
}
@Override
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return byte[].class.isAssignableFrom(value.getClass());
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\ByteArrayType.java
| 2
|
请完成以下Java代码
|
public String getViewId()
{
return viewId;
}
@Override
@Deprecated
public String toString()
{
return toJson();
}
@JsonValue
public String toJson()
{
return viewId;
}
public String getPart(final int index)
{
return parts.get(index);
}
public int getPartAsInt(final int index)
{
try
{
final String partStr = getPart(index);
return Integer.parseInt(partStr);
}
catch (final Exception ex)
{
throw new AdempiereException("Cannot extract part with index " + index + " as integer from " + this, ex);
}
}
/**
* @return just the viewId part (without the leading WindowId, without other parts etc)
*/
public String getViewIdPart()
{
|
return parts.get(1);
}
/**
* @return other parts (those which come after viewId part)
*/
@JsonIgnore // IMPORTANT: for some reason, without this annotation the json deserialization does not work even if we have toJson() method annotated with @JsonValue
public ImmutableList<String> getOtherParts()
{
return parts.size() > 2 ? parts.subList(2, parts.size()) : ImmutableList.of();
}
public ViewId withWindowId(@NonNull final WindowId newWindowId)
{
if (windowId.equals(newWindowId))
{
return this;
}
final ImmutableList<String> newParts = ImmutableList.<String>builder()
.add(newWindowId.toJson())
.addAll(parts.subList(1, parts.size()))
.build();
final String newViewId = JOINER.join(newParts);
return new ViewId(newViewId, newParts, newWindowId);
}
public void assertWindowId(@NonNull final WindowId expectedWindowId)
{
if (!windowId.equals(expectedWindowId))
{
throw new AdempiereException("" + this + " does not have expected windowId: " + expectedWindowId);
}
}
public static boolean equals(@Nullable final ViewId id1, @Nullable final ViewId id2)
{
return Objects.equals(id1, id2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewId.java
| 1
|
请完成以下Java代码
|
public String getTableName()
{
return gridTab.getTableName();
}
@Override
public <T> T getSelectedModel(final Class<T> modelClass)
{
return gridTab.getModel(modelClass);
}
@Override
public <T> List<T> getSelectedModels(final Class<T> modelClass)
{
// backward compatibility
return streamSelectedModels(modelClass)
.collect(ImmutableList.toImmutableList());
}
@NonNull
@Override
public <T> Stream<T> streamSelectedModels(@NonNull final Class<T> modelClass)
{
|
return Stream.of(getSelectedModel(modelClass));
}
@Override
public int getSingleSelectedRecordId()
{
return gridTab.getRecord_ID();
}
@Override
public SelectionSize getSelectionSize()
{
// backward compatibility
return SelectionSize.ofSize(1);
}
@Override
public <T> IQueryFilter<T> getQueryFilter(@NonNull Class<T> recordClass)
{
return gridTab.createCurrentRecordsQueryFilter(recordClass);
}
}
} // GridTab
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTab.java
| 1
|
请完成以下Java代码
|
public String uploadFile(String content, String fileExtension) {
byte[] buff = content.getBytes(Charset.forName("UTF-8"));
ByteArrayInputStream stream = new ByteArrayInputStream(buff);
StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null);
return getResAccessUrl(storePath);
}
// 封装图片完整URL地址
private String getResAccessUrl(StorePath storePath) {
String fileUrl = FastDFSConstants.HTTP_PRODOCOL + "://" + FastDFSConstants.RES_HOST + "/" + storePath.getFullPath();
return fileUrl;
}
/**
* 删除文件
* @param fileUrl 文件访问地址
* @return
*/
public void deleteFile(String fileUrl) {
if (StringUtils.isEmpty(fileUrl)) {
return;
}
|
try {
StorePath storePath = StorePath.praseFromUrl(fileUrl);
storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
} catch (FdfsUnsupportStorePathException e) {
log.warn(e.getMessage());
}
}
// 除了FastDFSClientWrapper类中用到的api,客户端提供的api还有很多,可根据自身的业务需求,将其它接口也添加到工具类中即可。
// 上传文件,并添加文件元数据
//StorePath uploadFile(InputStream inputStream, long fileSize, String fileExtName, Set<MateData> metaDataSet);
// 获取文件元数据
//Set<MateData> getMetadata(String groupName, String path);
// 上传图片并同时生成一个缩略图
//StorePath uploadImageAndCrtThumbImage(InputStream inputStream, long fileSize, String fileExtName, Set<MateData> metaDataSet);
// 。。。
}
|
repos\springboot-demo-master\fastdfs\src\main\java\com\et\fastdfs\util\FastDFSClientWrapper.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setOrderStateTimeList(List<OrderStateTimeEntity> orderStateTimeList) {
this.orderStateTimeList = orderStateTimeList;
}
public PayModeEnum getPayModeEnum() {
return payModeEnum;
}
public void setPayModeEnum(PayModeEnum payModeEnum) {
this.payModeEnum = payModeEnum;
}
public String getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(String totalPrice) {
this.totalPrice = totalPrice;
}
public ReceiptEntity getReceiptEntity() {
return receiptEntity;
}
public void setReceiptEntity(ReceiptEntity receiptEntity) {
this.receiptEntity = receiptEntity;
}
public LocationEntity getLocationEntity() {
return locationEntity;
}
public void setLocationEntity(LocationEntity locationEntity) {
this.locationEntity = locationEntity;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
|
}
public String getExpressNo() {
return expressNo;
}
public void setExpressNo(String expressNo) {
this.expressNo = expressNo;
}
public UserEntity getBuyer() {
return buyer;
}
public void setBuyer(UserEntity buyer) {
this.buyer = buyer;
}
@Override
public String toString() {
return "OrdersEntity{" +
"id='" + id + '\'' +
", buyer=" + buyer +
", company=" + company +
", productOrderList=" + productOrderList +
", orderStateEnum=" + orderStateEnum +
", orderStateTimeList=" + orderStateTimeList +
", payModeEnum=" + payModeEnum +
", totalPrice='" + totalPrice + '\'' +
", receiptEntity=" + receiptEntity +
", locationEntity=" + locationEntity +
", remark='" + remark + '\'' +
", expressNo='" + expressNo + '\'' +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\order\OrdersEntity.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private String updateTo(final IParams params)
{
String toTmp = "";
if (!params.hasParameter(I_C_BPartner.COLUMNNAME_C_BPartner_ID))
{
throw new IllegalArgumentException("Process instance doesn't contain a business partner as parameter");
}
// find the C_BPartner_ID parameter
final int bpartnerId = params.getParameterAsInt(I_C_BPartner.COLUMNNAME_C_BPartner_ID, -1);
if (bpartnerId <= 0)
{
logger.info("Process parameter " + I_C_BPartner.COLUMNNAME_C_BPartner_ID + " didn't contain a value");
}
else
{
final int userId = MBPartner.getDefaultContactId(bpartnerId);
if (userId > 0)
{
final I_AD_User contanct = Services.get(IUserDAO.class).retrieveUserOrNull(Env.getCtx(), userId);
if (contanct.getEMail() == null || "".equals(contanct.getEMail()))
{
logger.info("Default contact " + contanct + " doesn't have an email address");
}
else
{
toTmp = contanct.getEMail();
}
}
}
return toTmp;
}
/**
* @param defaultValue
* ignored
* @return the title of the process
*/
@Override
public String getAttachmentPrefix(final String defaultValue)
{
return attachmentPrefix;
}
/**
* @return <code>null</code>
*/
@Override
public MADBoilerPlate getDefaultTextPreset()
{
return DEFAULT_TEXT_PRESET;
}
/**
* @return the title of the process
*/
@Override
|
public String getExportFilePrefix()
{
return exportFilePrefix;
}
@Override
public I_AD_User getFrom()
{
return from;
}
/**
* @return <code>null</code>
*/
@Override
public String getMessage()
{
return MESSAGE;
}
/**
* @return the title of the process
*/
@Override
public String getSubject()
{
return subject;
}
/**
* @return the title of the process
*/
@Override
public String getTitle()
{
return title;
}
@Override
public String getTo()
{
return to;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\report\email\service\impl\BPartnerEmailParams.java
| 2
|
请完成以下Java代码
|
public static void removeBpmnOverrideContext() {
bpmnOverrideContextThreadLocal.remove();
}
protected static ObjectNode getProcessDefinitionInfoNode(String processDefinitionId) {
Map<String, ObjectNode> bpmnOverrideMap = getBpmnOverrideContext();
if (!bpmnOverrideMap.containsKey(processDefinitionId)) {
ProcessDefinitionInfoCacheObject cacheObject = getProcessEngineConfiguration()
.getDeploymentManager()
.getProcessDefinitionInfoCache()
.get(processDefinitionId);
addBpmnOverrideElement(processDefinitionId, cacheObject.getInfoNode());
}
return getBpmnOverrideContext().get(processDefinitionId);
}
protected static Map<String, ObjectNode> getBpmnOverrideContext() {
Map<String, ObjectNode> bpmnOverrideMap = bpmnOverrideContextThreadLocal.get();
if (bpmnOverrideMap == null) {
bpmnOverrideMap = new HashMap<String, ObjectNode>();
}
return bpmnOverrideMap;
}
protected static void addBpmnOverrideElement(String id, ObjectNode infoNode) {
Map<String, ObjectNode> bpmnOverrideMap = bpmnOverrideContextThreadLocal.get();
|
if (bpmnOverrideMap == null) {
bpmnOverrideMap = new HashMap<String, ObjectNode>();
bpmnOverrideContextThreadLocal.set(bpmnOverrideMap);
}
bpmnOverrideMap.put(id, infoNode);
}
public static class ResourceBundleControl extends ResourceBundle.Control {
@Override
public List<Locale> getCandidateLocales(String baseName, Locale locale) {
return super.getCandidateLocales(baseName, locale);
}
}
public static ProcessDefinitionHelper getProcessDefinitionHelper() {
return processDefinitionHelperThreadLocal.get();
}
public static void setProcessDefinitionHelper(ProcessDefinitionHelper processDefinitionHelper) {
processDefinitionHelperThreadLocal.set(processDefinitionHelper);
}
public static void removeProcessDefinitionHelper() {
processDefinitionHelperThreadLocal.remove();
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\context\Context.java
| 1
|
请完成以下Java代码
|
public SequenceFlow newInstance(ModelTypeInstanceContext instanceContext) {
return new SequenceFlowImpl(instanceContext);
}
});
sourceRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_SOURCE_REF)
.required()
.idAttributeReference(FlowNode.class)
.build();
targetRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_TARGET_REF)
.required()
.idAttributeReference(FlowNode.class)
.build();
isImmediateAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_IS_IMMEDIATE)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
conditionExpressionCollection = sequenceBuilder.element(ConditionExpression.class)
.build();
typeBuilder.build();
}
public SequenceFlowImpl(ModelTypeInstanceContext context) {
super(context);
}
@Override
public SequenceFlowBuilder builder() {
return new SequenceFlowBuilder((BpmnModelInstance) modelInstance, this);
}
public FlowNode getSource() {
return sourceRefAttribute.getReferenceTargetElement(this);
}
public void setSource(FlowNode source) {
|
sourceRefAttribute.setReferenceTargetElement(this, source);
}
public FlowNode getTarget() {
return targetRefAttribute.getReferenceTargetElement(this);
}
public void setTarget(FlowNode target) {
targetRefAttribute.setReferenceTargetElement(this, target);
}
public boolean isImmediate() {
return isImmediateAttribute.getValue(this);
}
public void setImmediate(boolean isImmediate) {
isImmediateAttribute.setValue(this, isImmediate);
}
public ConditionExpression getConditionExpression() {
return conditionExpressionCollection.getChild(this);
}
public void setConditionExpression(ConditionExpression conditionExpression) {
conditionExpressionCollection.setChild(this, conditionExpression);
}
public void removeConditionExpression() {
conditionExpressionCollection.removeChild(this);
}
public BpmnEdge getDiagramElement() {
return (BpmnEdge) super.getDiagramElement();
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\SequenceFlowImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public CommonResult delete(@RequestParam("ids") List<Long> ids) {
int count = homeBrandService.delete(ids);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("批量修改推荐品牌状态")
@RequestMapping(value = "/update/recommendStatus", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateRecommendStatus(@RequestParam("ids") List<Long> ids, @RequestParam Integer recommendStatus) {
int count = homeBrandService.updateRecommendStatus(ids, recommendStatus);
if (count > 0) {
return CommonResult.success(count);
|
}
return CommonResult.failed();
}
@ApiOperation("分页查询推荐品牌")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<SmsHomeBrand>> list(@RequestParam(value = "brandName", required = false) String brandName,
@RequestParam(value = "recommendStatus", required = false) Integer recommendStatus,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
List<SmsHomeBrand> homeBrandList = homeBrandService.list(brandName, recommendStatus, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(homeBrandList));
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\SmsHomeBrandController.java
| 2
|
请完成以下Java代码
|
public void setDateAcct (java.sql.Timestamp DateAcct)
{
throw new IllegalArgumentException ("DateAcct is virtual column"); }
/** Get Buchungsdatum.
@return Accounting Date
*/
@Override
public java.sql.Timestamp getDateAcct ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DateAcct);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
@Override
public org.compiere.model.I_Fact_Acct getFact_Acct() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Fact_Acct_ID, org.compiere.model.I_Fact_Acct.class);
}
@Override
public void setFact_Acct(org.compiere.model.I_Fact_Acct Fact_Acct)
{
set_ValueFromPO(COLUMNNAME_Fact_Acct_ID, org.compiere.model.I_Fact_Acct.class, Fact_Acct);
}
/** Set Accounting Fact.
@param Fact_Acct_ID Accounting Fact */
|
@Override
public void setFact_Acct_ID (int Fact_Acct_ID)
{
if (Fact_Acct_ID < 1)
set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID));
}
/** Get Accounting Fact.
@return Accounting Fact */
@Override
public int getFact_Acct_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Zeile Nr..
@param Line
Unique line for this document
*/
@Override
public void setLine (int Line)
{
set_Value (COLUMNNAME_Line, Integer.valueOf(Line));
}
/** Get Zeile Nr..
@return Unique line for this document
*/
@Override
public int getLine ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line);
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_C_TaxDeclarationAcct.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public abstract class PathBasedTemplateAvailabilityProvider implements TemplateAvailabilityProvider {
private final String className;
private final Class<TemplateAvailabilityProperties> propertiesClass;
private final String propertyPrefix;
@SuppressWarnings("unchecked")
public PathBasedTemplateAvailabilityProvider(String className,
Class<? extends TemplateAvailabilityProperties> propertiesClass, String propertyPrefix) {
this.className = className;
this.propertiesClass = (Class<TemplateAvailabilityProperties>) propertiesClass;
this.propertyPrefix = propertyPrefix;
}
@Override
public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader,
ResourceLoader resourceLoader) {
if (ClassUtils.isPresent(this.className, classLoader)) {
Binder binder = Binder.get(environment);
TemplateAvailabilityProperties properties = binder.bindOrCreate(this.propertyPrefix, this.propertiesClass);
return isTemplateAvailable(view, resourceLoader, properties);
}
return false;
}
private boolean isTemplateAvailable(String view, ResourceLoader resourceLoader,
TemplateAvailabilityProperties properties) {
String location = properties.getPrefix() + view + properties.getSuffix();
for (String path : properties.getLoaderPath()) {
if (resourceLoader.getResource(path + location).exists()) {
return true;
}
}
return false;
}
protected abstract static class TemplateAvailabilityProperties {
|
private String prefix;
private String suffix;
protected TemplateAvailabilityProperties(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
protected abstract List<String> getLoaderPath();
public String getPrefix() {
return this.prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getSuffix() {
return this.suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\template\PathBasedTemplateAvailabilityProvider.java
| 2
|
请完成以下Java代码
|
public class StandardServices implements IAddOn
{
@Override
public void beforeConnection()
{
// Services related to inOut
Services.registerService(IReplenishForFutureQty.class, new ReplenishForFutureQty());
// Services related to invoice
Services.registerService(IInvoiceBL.class, new InvoiceBL());
Services.registerService(IInvoiceDAO.class, new InvoiceDAO());
//
// misc services
Services.registerService(IOrderBL.class, new OrderBL());
|
Services.registerService(IParameterBL.class, new ParameterBL());
Services.registerService(ICalendarDAO.class, new CalendarDAO());
Services.registerService(IPOService.class, new POService());
Services.registerService(IPriceListDAO.class, new PriceListDAO());
Services.registerService(ISweepTableBL.class, new SweepTableBL());
Services.registerService(IAppDictionaryBL.class, new AppDictionaryBL());
Services.registerService(ITableColumnPathBL.class, new TableColumnPathBL());
// us316: Printer Routing Service
// NOTE: we need to register this service here because we need it before any database connection
Services.registerService(IPrinterRoutingBL.class, new PrinterRoutingBL());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\addon\standard\StandardServices.java
| 1
|
请完成以下Java代码
|
public void setTargetWeight (final BigDecimal TargetWeight)
{
set_Value (COLUMNNAME_TargetWeight, TargetWeight);
}
@Override
public BigDecimal getTargetWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TargetWeight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTolerance_Perc (final BigDecimal Tolerance_Perc)
{
set_Value (COLUMNNAME_Tolerance_Perc, Tolerance_Perc);
}
@Override
public BigDecimal getTolerance_Perc()
{
|
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Tolerance_Perc);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWeightChecksRequired (final int WeightChecksRequired)
{
set_Value (COLUMNNAME_WeightChecksRequired, WeightChecksRequired);
}
@Override
public int getWeightChecksRequired()
{
return get_ValueAsInt(COLUMNNAME_WeightChecksRequired);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Weighting_Run.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Employee implements Serializable {
@Id
@Column(name = "employee_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long employeeId;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(
name = "Employee_Project",
joinColumns = { @JoinColumn(name = "employee_id") },
inverseJoinColumns = { @JoinColumn(name = "project_id") }
)
Set<Project> projects = new HashSet<Project>();
public Employee() {
super();
}
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Employee(String firstName, String lastName, Set<Project> projects) {
this.firstName = firstName;
this.lastName = lastName;
this.projects = projects;
}
|
public Long getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Long employeeId) {
this.employeeId = employeeId;
}
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 Set<Project> getProjects() {
return projects;
}
public void setProjects(Set<Project> projects) {
this.projects = projects;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\manytomany\model\Employee.java
| 2
|
请完成以下Java代码
|
public Stream<ImpDataLine> streamDataLines(final Resource resource)
{
final AtomicInteger nextLineNo = new AtomicInteger(1);
return streamSourceLines(resource)
.skip(skipFirstNRows)
.map(lineStr -> createImpDataLine(lineStr, nextLineNo));
}
private Stream<String> streamSourceLines(final Resource resource)
{
final byte[] data = toByteArray(resource);
try
{
if (multiline)
{
return FileImportReader.readMultiLines(data, charset).stream();
}
else
{
return FileImportReader.readRegularLines(data, charset).stream();
}
}
catch (final IOException ex)
{
throw new AdempiereException("Failed reading resource: " + resource, ex);
}
}
private static byte[] toByteArray(final Resource resource)
{
try
{
|
return Util.readBytes(resource.getInputStream());
}
catch (final IOException ex)
{
throw new AdempiereException("Failed reading resource: " + resource, ex);
}
}
private ImpDataLine createImpDataLine(final String lineStr, final AtomicInteger nextLineNo)
{
try
{
return ImpDataLine.builder()
.fileLineNo(nextLineNo.getAndIncrement())
.lineStr(lineStr)
.cells(lineParser.parseDataCells(lineStr))
.build();
}
catch (final Exception ex)
{
return ImpDataLine.builder()
.fileLineNo(nextLineNo.getAndIncrement())
.lineStr(lineStr)
.parseError(ErrorMessage.of(ex))
.build();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\parser\ImpDataParser.java
| 1
|
请完成以下Java代码
|
public class ClaimTaskCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected String taskId;
protected String userId;
public ClaimTaskCmd(String taskId, String userId) {
this.taskId = taskId;
this.userId = userId;
}
public Void execute(CommandContext commandContext) {
ensureNotNull("taskId", taskId);
TaskManager taskManager = commandContext.getTaskManager();
TaskEntity task = taskManager.findTaskById(taskId);
ensureNotNull("Cannot find task with id " + taskId, "task", task);
checkClaimTask(task, commandContext);
if (userId != null) {
if (task.getAssignee() != null) {
if (!task.getAssignee().equals(userId)) {
// When the task is already claimed by another user, throw exception. Otherwise, ignore
// this, post-conditions of method already met.
throw new TaskAlreadyClaimedException(task.getId(), task.getAssignee());
}
|
} else {
task.setAssignee(userId);
}
} else {
// Task should be assigned to no one
task.setAssignee(null);
}
task.triggerUpdateEvent();
task.logUserOperation(UserOperationLogEntry.OPERATION_TYPE_CLAIM);
return null;
}
protected void checkClaimTask(TaskEntity task, CommandContext commandContext) {
for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkTaskWork(task);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ClaimTaskCmd.java
| 1
|
请完成以下Java代码
|
public Object eval(ScriptContext ctx) throws ScriptException {
return evaluateExpression(valueExpression, ctx);
}
}
/**
* ValueMapper that uses the ScriptContext to get variable values or value expressions.
*
*/
private class ScriptContextVariableMapper extends VariableMapper {
private ScriptContext scriptContext;
ScriptContextVariableMapper(ScriptContext scriptCtx) {
this.scriptContext = scriptCtx;
}
@Override
public ValueExpression resolveVariable(String variableName) {
int scope = scriptContext.getAttributesScope(variableName);
if (scope != -1) {
Object value = scriptContext.getAttribute(variableName, scope);
if (value instanceof ValueExpression) {
// Just return the existing ValueExpression
return (ValueExpression) value;
} else {
// Create a new ValueExpression based on the variable value
return expressionFactory.createValueExpression(value, Object.class);
}
}
return null;
}
@Override
public ValueExpression setVariable(String name, ValueExpression value) {
ValueExpression previousValue = resolveVariable(name);
scriptContext.setAttribute(name, value, ScriptContext.ENGINE_SCOPE);
return previousValue;
}
}
/**
* FunctionMapper that uses the ScriptContext to resolve functions in EL.
*
|
*/
private class ScriptContextFunctionMapper extends FunctionMapper {
private ScriptContext scriptContext;
ScriptContextFunctionMapper(ScriptContext ctx) {
this.scriptContext = ctx;
}
private String getFullFunctionName(String prefix, String localName) {
return prefix + ":" + localName;
}
@Override
public Method resolveFunction(String prefix, String localName) {
String functionName = getFullFunctionName(prefix, localName);
int scope = scriptContext.getAttributesScope(functionName);
if (scope != -1) {
// Methods are added as variables in the ScriptScope
Object attributeValue = scriptContext.getAttribute(functionName);
return (attributeValue instanceof Method) ? (Method) attributeValue : null;
} else {
return null;
}
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\JuelScriptEngine.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setMobileUI_HUManager_ID (final int MobileUI_HUManager_ID)
{
if (MobileUI_HUManager_ID < 1)
set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_ID, MobileUI_HUManager_ID);
}
@Override
public int getMobileUI_HUManager_ID()
|
{
return get_ValueAsInt(COLUMNNAME_MobileUI_HUManager_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_HUManager.java
| 1
|
请完成以下Java代码
|
public void setUseSuspenseBalancing (boolean UseSuspenseBalancing)
{
set_Value (COLUMNNAME_UseSuspenseBalancing, Boolean.valueOf(UseSuspenseBalancing));
}
/** Get doppelte Buchführung.
@return Verwendet doppelte Buchführung über Zwischenkonto bei manuellen Buchungen.
*/
@Override
public boolean isUseSuspenseBalancing ()
{
Object oo = get_Value(COLUMNNAME_UseSuspenseBalancing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set CpD-Fehlerkonto verwenden.
@param UseSuspenseError CpD-Fehlerkonto verwenden */
@Override
public void setUseSuspenseError (boolean UseSuspenseError)
{
set_Value (COLUMNNAME_UseSuspenseError, Boolean.valueOf(UseSuspenseError));
|
}
/** Get CpD-Fehlerkonto verwenden.
@return CpD-Fehlerkonto verwenden */
@Override
public boolean isUseSuspenseError ()
{
Object oo = get_Value(COLUMNNAME_UseSuspenseError);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema_GL.java
| 1
|
请完成以下Java代码
|
public T execute(CommandContext commandContext) {
if (taskId == null) {
throw new ActivitiIllegalArgumentException("taskId is null");
}
TaskEntity task = commandContext.getTaskEntityManager().findById(taskId);
if (task == null) {
throw new ActivitiObjectNotFoundException("Cannot find task with id " + taskId, Task.class);
}
if (task.isSuspended()) {
throw new ActivitiException(getSuspendedTaskException());
}
|
return execute(commandContext, task);
}
/**
* Subclasses must implement in this method their normal command logic. The provided task is ensured to be active.
*/
protected abstract T execute(CommandContext commandContext, TaskEntity task);
/**
* Subclasses can override this method to provide a customized exception message that will be thrown when the task is suspended.
*/
protected String getSuspendedTaskException() {
return "Cannot execute operation: task is suspended";
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\NeedsActiveTaskCmd.java
| 1
|
请完成以下Java代码
|
public boolean isEmpty() {return queuesById.isEmpty();}
public Set<PickingSlotId> getPickingSlotIds() {return queuesById.keySet();}
public OptionalInt getCountHUs(@NonNull final PickingSlotId pickingSlotId)
{
final PickingSlotQueueSummary queue = queuesById.get(pickingSlotId);
return queue != null ? OptionalInt.of(queue.getCountHUs()) : OptionalInt.empty();
}
public OptionalInt getCountHUs(@NonNull final Set<PickingSlotId> pickingSlotIds)
{
if (pickingSlotIds.isEmpty())
{
return OptionalInt.of(0);
}
|
int countHUs = 0;
for (final PickingSlotId pickingSlotId : pickingSlotIds)
{
final PickingSlotQueueSummary queue = queuesById.get(pickingSlotId);
if (queue == null)
{
return OptionalInt.empty();
}
countHUs += queue.getCountHUs();
}
return OptionalInt.of(countHUs);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\PickingSlotQueuesSummary.java
| 1
|
请完成以下Java代码
|
public class PreparedStatementInClause {
public static ResultSet populateParamsWithStringBuilder(Connection connection, List<Integer> ids) throws SQLException {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < ids.size(); i++) {
stringBuilder.append("?,");
}
String placeHolders = stringBuilder.deleteCharAt(stringBuilder.length() - 1)
.toString();
String sql = "select * from customer where id in (" + placeHolders + ")";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 1; i <= ids.size(); i++) {
preparedStatement.setInt(i, ids.get(i - 1));
}
return preparedStatement.executeQuery();
}
public static ResultSet populateParamsWithStream(Connection connection, List<Integer> ids) throws SQLException {
var sql = String.format("select * from customer where id IN (%s)", ids.stream()
.map(v -> "?")
.collect(Collectors.joining(", ")));
|
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 1; i <= ids.size(); i++) {
preparedStatement.setInt(i, ids.get(i - 1));
}
return preparedStatement.executeQuery();
}
public static ResultSet populateParamsWithArray(Connection connection, List<Integer> ids) throws SQLException {
String sql = "SELECT * FROM customer where id IN (select * from table(x int = ?))";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
Array array = preparedStatement.getConnection()
.createArrayOf("int", ids.toArray());
preparedStatement.setArray(1, array);
return preparedStatement.executeQuery();
}
}
|
repos\tutorials-master\persistence-modules\core-java-persistence-3\src\main\java\preparedstatementinclause\PreparedStatementInClause.java
| 1
|
请完成以下Java代码
|
private static I_C_SubscriptionProgress retrieveFirstPauseRecordSearchBackwards(final I_C_SubscriptionProgress firstSp)
{
final SubscriptionProgressQuery query = SubscriptionProgressQuery.endingRightBefore(firstSp)
.includedContractStatus(X_C_SubscriptionProgress.CONTRACTSTATUS_DeliveryPause)
.build();
final I_C_SubscriptionProgress preceedingPauseRecord = Services.get(ISubscriptionDAO.class).retrieveFirstSubscriptionProgress(query);
final I_C_SubscriptionProgress firstPauseRecord = preceedingPauseRecord != null ? preceedingPauseRecord : firstSp;
return firstPauseRecord;
}
private static int deletePauseBeginEndRecordsAndUpdatePausedRecords(@NonNull final List<I_C_SubscriptionProgress> allPauseRecords)
{
int seqNoOffset = 0;
for (final I_C_SubscriptionProgress pauseRecord : allPauseRecords)
{
final boolean pauseStartOrEnd = X_C_SubscriptionProgress.EVENTTYPE_BeginOfPause.equals(pauseRecord.getEventType()) || X_C_SubscriptionProgress.EVENTTYPE_EndOfPause.equals(pauseRecord.getEventType());
if (pauseStartOrEnd)
{
delete(pauseRecord);
seqNoOffset++;
continue;
}
else if (isWithinPause(pauseRecord))
{
pauseRecord.setContractStatus(X_C_SubscriptionProgress.CONTRACTSTATUS_Running);
|
if (pauseRecord.getM_ShipmentSchedule_ID() > 0)
{
Services.get(IShipmentScheduleBL.class).openShipmentSchedule(InterfaceWrapperHelper.load(pauseRecord.getM_ShipmentSchedule_ID(), I_M_ShipmentSchedule.class));
}
}
subtractFromSeqNoAndSave(pauseRecord, seqNoOffset);
}
return seqNoOffset;
}
private static void subtractFromSeqNoAndSave(final I_C_SubscriptionProgress record, final int seqNoOffset)
{
record.setSeqNo(record.getSeqNo() - seqNoOffset); // might be a not-within-pause-record if there are multiple pause periods between pausesFrom and pausesUntil
save(record);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\subscriptioncommands\RemovePauses.java
| 1
|
请完成以下Java代码
|
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getContentId() {
return contentId;
}
public void setContentId(String contentId) {
this.contentId = contentId;
}
public ByteArrayEntity getContent() {
return content;
|
}
public void setContent(ByteArrayEntity content) {
this.content = content;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AttachmentEntityImpl.java
| 1
|
请完成以下Java代码
|
public static <T> ValueRestriction<T> equalsTo(@NonNull final T onlyValue)
{
return new ValueRestriction<>(Type.EQUALS_TO, onlyValue);
}
public static <T> ValueRestriction<T> equalsToOrNull(@Nullable final T onlyValue)
{
return onlyValue != null
? new ValueRestriction<>(Type.EQUALS_TO_OR_NULL, onlyValue)
: isNull();
}
private enum Type
{
ANY, IS_NULL, NOT_NULL, EQUALS_TO, EQUALS_TO_OR_NULL
}
private static final ValueRestriction<Object> ANY = new ValueRestriction<>(Type.ANY, null);
private static final ValueRestriction<Object> IS_NULL = new ValueRestriction<>(Type.IS_NULL, null);
private static final ValueRestriction<Object> NOT_NULL = new ValueRestriction<>(Type.NOT_NULL, null);
private final @NonNull Type type;
private final @Nullable T onlyValue;
private ValueRestriction(final @NonNull Type type, final @Nullable T onlyValue)
{
this.type = type;
this.onlyValue = onlyValue;
}
public interface CaseMappingFunction<T, R>
{
R anyValue();
R valueIsNull();
R valueIsNotNull();
R valueEqualsTo(@NonNull T value);
R valueEqualsToOrNull(@NonNull T value);
}
public <R> R map(@NonNull final CaseMappingFunction<T, R> mappingFunction)
{
switch (type)
{
case ANY:
return mappingFunction.anyValue();
case IS_NULL:
return mappingFunction.valueIsNull();
case NOT_NULL:
return mappingFunction.valueIsNotNull();
case EQUALS_TO:
return mappingFunction.valueEqualsTo(Objects.requireNonNull(onlyValue));
case EQUALS_TO_OR_NULL:
return mappingFunction.valueEqualsToOrNull(Objects.requireNonNull(onlyValue));
default:
throw new AdempiereException("Unhandled type: " + type); // shall not happen
}
}
|
public <RecordType> void appendFilter(@NonNull final IQueryBuilder<RecordType> queryBuilder, @NonNull final String columnName)
{
map(new CaseMappingFunction<T, Void>()
{
@Override
public Void anyValue()
{
// do nothing
return null;
}
@Override
public Void valueIsNull()
{
queryBuilder.addEqualsFilter(columnName, null);
return null;
}
@Override
public Void valueIsNotNull()
{
queryBuilder.addNotNull(columnName);
return null;
}
@Override
public Void valueEqualsTo(@NonNull final T value)
{
queryBuilder.addEqualsFilter(columnName, value);
return null;
}
@Override
public Void valueEqualsToOrNull(@NonNull final T value)
{
//noinspection unchecked
queryBuilder.addInArrayFilter(columnName, null, value);
return null;
}
});
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\ValueRestriction.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DashboardController {
@RequestMapping(value = "/welcome", method = RequestMethod.GET)
public ModelAndView welcome(){
ModelAndView model = new ModelAndView();
model.setViewName("welcome");
return model;
}
private List getUsers() {
User user = new User();
user.setEmail("johndoe123@gmail.com");
user.setName("John Doe");
user.setAddress("Bangalore, Karnataka");
User user1 = new User();
|
user1.setEmail("amitsingh@yahoo.com");
user1.setName("Amit Singh");
user1.setAddress("Chennai, Tamilnadu");
User user2 = new User();
user2.setEmail("bipulkumar@gmail.com");
user2.setName("Bipul Kumar");
user2.setAddress("Bangalore, Karnataka");
User user3 = new User();
user3.setEmail("prakashranjan@gmail.com");
user3.setName("Prakash Ranjan");
user3.setAddress("Chennai, Tamilnadu");
return Arrays.asList(user, user1, user2, user3);
}
}
|
repos\Spring-Boot-Advanced-Projects-main\Springboot integrated with JSP\SpringJSPUpdate\src\main\java\spring\jsp\DashboardController.java
| 2
|
请完成以下Java代码
|
String getEnvironmentName_FromEnvironmentVariables() {
return environmentName;
}
@GetMapping("/java_home_and_environment")
String getJavaHomeAndEnvironmentName_FromEnvironmentVariables() {
return javaHomeAndEnvironmentName;
}
@GetMapping("non_existent_property")
String getNonexistentProperty_FromEnvironmentVariables() {
return nonExistentProperty;
}
@GetMapping("baeldung_presentation_from_value")
|
String getBaeldungPresentation_FromValue() {
return baeldungPresentation;
}
@GetMapping("baeldung_presentation_from_environment")
String getBaeldungPresentation_FromEnvironment() {
return environment.getProperty("baeldung.presentation");
}
@GetMapping("baeldung_configuration_properties")
String getBaeldungPresentation_FromConfigurationProperties() {
return baeldungProperties.getPresentation();
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-properties\src\main\java\com\baeldung\envvariables\MyController.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Login createLogin() {
return new Login();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetAuth }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link GetAuth }{@code >}
*/
@XmlElementDecl(namespace = "http://dpd.com/common/service/types/LoginService/2.0", name = "getAuth")
public JAXBElement<GetAuth> createGetAuth(GetAuth value) {
return new JAXBElement<GetAuth>(_GetAuth_QNAME, GetAuth.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetAuthResponse }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link GetAuthResponse }{@code >}
*/
@XmlElementDecl(namespace = "http://dpd.com/common/service/types/LoginService/2.0", name = "getAuthResponse")
public JAXBElement<GetAuthResponse> createGetAuthResponse(GetAuthResponse value) {
|
return new JAXBElement<GetAuthResponse>(_GetAuthResponse_QNAME, GetAuthResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link LoginException }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link LoginException }{@code >}
*/
@XmlElementDecl(namespace = "http://dpd.com/common/service/types/LoginService/2.0", name = "LoginException")
public JAXBElement<LoginException> createLoginException(LoginException value) {
return new JAXBElement<LoginException>(_LoginException_QNAME, LoginException.class, null, value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\ws\loginservice\v2_0\types\ObjectFactory.java
| 2
|
请完成以下Java代码
|
private JSONDashboardItemDataChangedEvent toJson(final UserDashboardItemDataResponse itemData, final KPIJsonOptions jsonOpts)
{
final JsonKPIDataResult jsonData = JsonKPIDataResult.of(itemData, jsonOpts);
return JSONDashboardItemDataChangedEvent.of(itemData.getDashboardId(), itemData.getItemId(), jsonData);
}
private Result computeNewResult()
{
final UserDashboardDataProvider dataProvider = dashboardDataService
.getData(getUserDashboardKey())
.orElse(null);
// no user dashboard was found.
// might be that the user dashboard was deactivated in meantime.
if (dataProvider == null)
{
return Result.EMPTY;
}
final UserDashboardDataResponse data = dataProvider
.getAllItems(UserDashboardDataRequest.builder()
.context(kpiDataContext)
.build());
return Result.ofCollection(data.getItems());
}
private static KPIJsonOptions newKpiJsonOptions(final JSONOptions jsonOpts)
{
return KPIJsonOptions.builder()
.adLanguage(jsonOpts.getAdLanguage())
.zoneId(jsonOpts.getZoneId())
.prettyValues(true)
.build();
}
//
//
//
//
//
@ToString
private static class Result
{
public static Result ofMap(@NonNull final Map<UserDashboardItemId, UserDashboardItemDataResponse> map)
{
return !map.isEmpty() ? new Result(map) : EMPTY;
}
public static Result ofCollection(@NonNull final Collection<UserDashboardItemDataResponse> itemDataList)
{
return ofMap(Maps.uniqueIndex(itemDataList, UserDashboardItemDataResponse::getItemId));
}
private static final Result EMPTY = new Result(ImmutableMap.of());
private final ImmutableMap<UserDashboardItemId, UserDashboardItemDataResponse> map;
private Result(final Map<UserDashboardItemId, UserDashboardItemDataResponse> map)
{
this.map = ImmutableMap.copyOf(map);
|
}
public ImmutableList<UserDashboardItemDataResponse> getChangesFromOldVersion(@Nullable final Result oldResult)
{
if (oldResult == null)
{
return toList();
}
final ImmutableList.Builder<UserDashboardItemDataResponse> resultEffective = ImmutableList.builder();
for (final Map.Entry<UserDashboardItemId, UserDashboardItemDataResponse> e : map.entrySet())
{
final UserDashboardItemId itemId = e.getKey();
final UserDashboardItemDataResponse newValue = e.getValue();
final UserDashboardItemDataResponse oldValue = oldResult.get(itemId);
if (oldValue == null || !newValue.isSameDataAs(oldValue))
{
resultEffective.add(newValue);
}
}
return resultEffective.build();
}
@Nullable
private UserDashboardItemDataResponse get(final UserDashboardItemId itemId)
{
return map.get(itemId);
}
public ImmutableList<UserDashboardItemDataResponse> toList()
{
return ImmutableList.copyOf(map.values());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\websocket\UserDashboardWebsocketProducer.java
| 1
|
请完成以下Java代码
|
public boolean writeData(List<Object[]> products, OutputType outputType, String outputPath) {
try (Writer outputWriter = new OutputStreamWriter(new FileOutputStream(new File(outputPath)), "UTF-8")) {
switch (outputType) {
case CSV: {
CsvWriter writer = new CsvWriter(outputWriter, new CsvWriterSettings());
writer.writeRowsAndClose(products);
}
break;
case TSV: {
TsvWriter writer = new TsvWriter(outputWriter, new TsvWriterSettings());
writer.writeRowsAndClose(products);
}
break;
case FIXED_WIDTH: {
FixedWidthFields fieldLengths = new FixedWidthFields(8, 30, 10);
FixedWidthWriterSettings settings = new FixedWidthWriterSettings(fieldLengths);
FixedWidthWriter writer = new FixedWidthWriter(outputWriter, settings);
writer.writeRowsAndClose(products);
}
break;
default:
logger.warn("Invalid OutputType: " + outputType);
return false;
}
return true;
} catch (IOException e) {
logger.error(e.getMessage());
return false;
}
}
public boolean writeBeanToFixedWidthFile(List<Product> products, String outputPath) {
try (Writer outputWriter = new OutputStreamWriter(new FileOutputStream(new File(outputPath)), "UTF-8")) {
BeanWriterProcessor<Product> rowProcessor = new BeanWriterProcessor<Product>(Product.class);
|
FixedWidthFields fieldLengths = new FixedWidthFields(8, 30, 10);
FixedWidthWriterSettings settings = new FixedWidthWriterSettings(fieldLengths);
settings.setHeaders("product_no", "description", "unit_price");
settings.setRowWriterProcessor(rowProcessor);
FixedWidthWriter writer = new FixedWidthWriter(outputWriter, settings);
writer.writeHeaders();
for (Product product : products) {
writer.processRecord(product);
}
writer.close();
return true;
} catch (IOException e) {
logger.error(e.getMessage());
return false;
}
}
}
|
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\univocity\OutputService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getProtocol() {
return this.protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public Charset getDefaultEncoding() {
return this.defaultEncoding;
}
public void setDefaultEncoding(Charset defaultEncoding) {
this.defaultEncoding = defaultEncoding;
}
public Map<String, String> getProperties() {
return this.properties;
}
public @Nullable String getJndiName() {
return this.jndiName;
}
public void setJndiName(@Nullable String jndiName) {
this.jndiName = jndiName;
}
public Ssl getSsl() {
return this.ssl;
}
public static class Ssl {
/**
* Whether to enable SSL support. If enabled, 'mail.(protocol).ssl.enable'
* property is set to 'true'.
*/
private boolean enabled;
/**
* SSL bundle name. If set, 'mail.(protocol).ssl.socketFactory' property is set to
* an SSLSocketFactory obtained from the corresponding SSL bundle.
|
* <p>
* Note that the STARTTLS command can use the corresponding SSLSocketFactory, even
* if the 'mail.(protocol).ssl.enable' property is not set.
*/
private @Nullable String bundle;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public @Nullable String getBundle() {
return this.bundle;
}
public void setBundle(@Nullable String bundle) {
this.bundle = bundle;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-mail\src\main\java\org\springframework\boot\mail\autoconfigure\MailProperties.java
| 2
|
请完成以下Java代码
|
public class UserNotAuthorizedException extends AdempiereException
{
public UserNotAuthorizedException()
{
super("Not authorized");
}
public UserNotAuthorizedException(@NonNull final String message)
{
super(message);
}
public UserNotAuthorizedException(@Nullable final Throwable cause)
{
super(buildMsg(cause), cause);
// setParameter("authTokenString", authTokenString); // NOTE: don't include token in message because it might be a security issue
|
}
private static String buildMsg(@Nullable final Throwable cause)
{
final StringBuilder msg = new StringBuilder();
msg.append("Token not authorized.");
// NOTE: don't include token in message because it might be a security issue
if (cause != null)
{
msg.append(" Cause: ").append(extractMessage(cause));
}
return msg.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\UserNotAuthorizedException.java
| 1
|
请完成以下Java代码
|
public void addUrlMappings(String... urlMappings) {
Assert.notNull(urlMappings, "'urlMappings' must not be null");
this.urlMappings.addAll(Arrays.asList(urlMappings));
}
/**
* Sets the {@code loadOnStartup} priority. See
* {@link ServletRegistration.Dynamic#setLoadOnStartup} for details.
* @param loadOnStartup if load on startup is enabled
*/
public void setLoadOnStartup(int loadOnStartup) {
this.loadOnStartup = loadOnStartup;
}
/**
* Set the {@link MultipartConfigElement multi-part configuration}.
* @param multipartConfig the multipart configuration to set or {@code null}
*/
public void setMultipartConfig(@Nullable MultipartConfigElement multipartConfig) {
this.multipartConfig = multipartConfig;
}
/**
* Returns the {@link MultipartConfigElement multi-part configuration} to be applied
* or {@code null}.
* @return the multipart config
*/
public @Nullable MultipartConfigElement getMultipartConfig() {
return this.multipartConfig;
}
@Override
protected String getDescription() {
Assert.state(this.servlet != null, "Unable to return description for null servlet");
return "servlet " + getServletName();
}
@Override
protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) {
String name = getServletName();
return servletContext.addServlet(name, this.servlet);
}
|
/**
* Configure registration settings. Subclasses can override this method to perform
* additional configuration if required.
* @param registration the registration
*/
@Override
protected void configure(ServletRegistration.Dynamic registration) {
super.configure(registration);
String[] urlMapping = StringUtils.toStringArray(this.urlMappings);
if (urlMapping.length == 0 && this.alwaysMapUrl) {
urlMapping = DEFAULT_MAPPINGS;
}
if (!ObjectUtils.isEmpty(urlMapping)) {
registration.addMapping(urlMapping);
}
registration.setLoadOnStartup(this.loadOnStartup);
if (this.multipartConfig != null) {
registration.setMultipartConfig(this.multipartConfig);
}
}
/**
* Returns the servlet name that will be registered.
* @return the servlet name
*/
public String getServletName() {
return getOrDeduceName(this.servlet);
}
@Override
public String toString() {
return getServletName() + " urls=" + getUrlMappings();
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\ServletRegistrationBean.java
| 1
|
请完成以下Java代码
|
public Quantity getQty()
{
return huStorage.getQuantity(getProductId(), getC_UOM());
}
@Override
public final Quantity getQty(final I_C_UOM uom)
{
final UOMConversionContext conversionCtx = UOMConversionContext.of(getProductId());
final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
return uomConversionBL.convertQuantityTo(getQty(), conversionCtx, uom);
}
@Override
public final Quantity getQtyInStockingUOM()
{
final I_C_UOM productUOM = Services.get(IProductBL.class).getStockUOM(getProductId());
return getQty(productUOM);
}
@Override
public BigDecimal getQtyCapacity()
{
return capacityTotal.toBigDecimal();
}
@Override
public IAllocationRequest addQty(final IAllocationRequest request)
{
throw new AdempiereException("Adding Qty is not supported on this level");
}
@Override
public IAllocationRequest removeQty(final IAllocationRequest request)
{
throw new AdempiereException("Removing Qty is not supported on this level");
}
/**
* Returns always false because negative storages are not supported (see {@link #removeQty(IAllocationRequest)})
*
* @return false
*/
@Override
public boolean isAllowNegativeStorage()
|
{
return false;
}
@Override
public void markStaled()
{
// nothing, so far, itemStorage is always database coupled, no in memory values
}
@Override
public boolean isEmpty()
{
return huStorage.isEmpty(getProductId());
}
@Override
public I_M_HU getM_HU()
{
return huStorage.getM_HU();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUProductStorage.java
| 1
|
请完成以下Java代码
|
public final class OidcClientRegistrationAuthenticationConverter implements AuthenticationConverter {
private final HttpMessageConverter<OidcClientRegistration> clientRegistrationHttpMessageConverter = new OidcClientRegistrationHttpMessageConverter();
@Override
public Authentication convert(HttpServletRequest request) {
Authentication principal = SecurityContextHolder.getContext().getAuthentication();
if ("POST".equals(request.getMethod())) {
OidcClientRegistration clientRegistration;
try {
clientRegistration = this.clientRegistrationHttpMessageConverter.read(OidcClientRegistration.class,
new ServletServerHttpRequest(request));
}
catch (Exception ex) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST,
"OpenID Client Registration Error: " + ex.getMessage(),
"https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationError");
throw new OAuth2AuthenticationException(error, ex);
|
}
return new OidcClientRegistrationAuthenticationToken(principal, clientRegistration);
}
MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getQueryParameters(request);
// client_id (REQUIRED)
String clientId = parameters.getFirst(OAuth2ParameterNames.CLIENT_ID);
if (!StringUtils.hasText(clientId) || parameters.get(OAuth2ParameterNames.CLIENT_ID).size() != 1) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST);
}
return new OidcClientRegistrationAuthenticationToken(principal, clientId);
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\web\authentication\OidcClientRegistrationAuthenticationConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getTaskUrl() {
return taskUrl;
}
public void setTaskUrl(String taskUrl) {
this.taskUrl = taskUrl;
}
public String getProcessInstanceId() {
|
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\CommentResponse.java
| 2
|
请完成以下Java代码
|
public org.compiere.model.I_M_DiscountSchema_Calculated_Surcharge getM_DiscountSchema_Calculated_Surcharge()
{
return get_ValueAsPO(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, org.compiere.model.I_M_DiscountSchema_Calculated_Surcharge.class);
}
@Override
public void setM_DiscountSchema_Calculated_Surcharge(final org.compiere.model.I_M_DiscountSchema_Calculated_Surcharge M_DiscountSchema_Calculated_Surcharge)
{
set_ValueFromPO(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, org.compiere.model.I_M_DiscountSchema_Calculated_Surcharge.class, M_DiscountSchema_Calculated_Surcharge);
}
@Override
public void setM_DiscountSchema_Calculated_Surcharge_ID (final int M_DiscountSchema_Calculated_Surcharge_ID)
{
if (M_DiscountSchema_Calculated_Surcharge_ID < 1)
set_Value (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, null);
else
set_Value (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, M_DiscountSchema_Calculated_Surcharge_ID);
}
@Override
public int getM_DiscountSchema_Calculated_Surcharge_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID);
}
@Override
public void setM_DiscountSchema_ID (final int M_DiscountSchema_ID)
{
if (M_DiscountSchema_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_ID, M_DiscountSchema_ID);
}
@Override
public int getM_DiscountSchema_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
|
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setScript (final @Nullable java.lang.String Script)
{
set_Value (COLUMNNAME_Script, Script);
}
@Override
public java.lang.String getScript()
{
return get_ValueAsString(COLUMNNAME_Script);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchema.java
| 1
|
请完成以下Java代码
|
default URL getIssuer() {
return this.getClaimAsURL(JwtClaimNames.ISS);
}
/**
* Returns the Subject {@code (sub)} claim which identifies the principal that is the
* subject of the JWT.
* @return the Subject identifier
*/
default String getSubject() {
return this.getClaimAsString(JwtClaimNames.SUB);
}
/**
* Returns the Audience {@code (aud)} claim which identifies the recipient(s) that the
* JWT is intended for.
* @return the Audience(s) that this JWT intended for
*/
default List<String> getAudience() {
return this.getClaimAsStringList(JwtClaimNames.AUD);
}
/**
* Returns the Expiration time {@code (exp)} claim which identifies the expiration
* time on or after which the JWT MUST NOT be accepted for processing.
* @return the Expiration time on or after which the JWT MUST NOT be accepted for
* processing
*/
default Instant getExpiresAt() {
return this.getClaimAsInstant(JwtClaimNames.EXP);
}
/**
* Returns the Not Before {@code (nbf)} claim which identifies the time before which
* the JWT MUST NOT be accepted for processing.
* @return the Not Before time before which the JWT MUST NOT be accepted for
* processing
*/
|
default Instant getNotBefore() {
return this.getClaimAsInstant(JwtClaimNames.NBF);
}
/**
* Returns the Issued at {@code (iat)} claim which identifies the time at which the
* JWT was issued.
* @return the Issued at claim which identifies the time at which the JWT was issued
*/
default Instant getIssuedAt() {
return this.getClaimAsInstant(JwtClaimNames.IAT);
}
/**
* Returns the JWT ID {@code (jti)} claim which provides a unique identifier for the
* JWT.
* @return the JWT ID claim which provides a unique identifier for the JWT
*/
default String getId() {
return this.getClaimAsString(JwtClaimNames.JTI);
}
}
|
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtClaimAccessor.java
| 1
|
请完成以下Java代码
|
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice
* @return result
* @throws Throwable throws IllegalArgumentException
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
if (log.isDebugEnabled()) {
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
|
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
throw e;
}
}
}
|
repos\Spring-Boot-Advanced-Projects-main\springboot2-springaop-example\src\main\java\net\alanbinu\springboot2\springboot2jpacrudexample\aspect\LoggingAspect.java
| 1
|
请完成以下Java代码
|
public final I_M_HU_PI_Attribute getM_HU_PI_Attribute()
{
return huPIAttribute;
}
@Override
public final I_C_UOM getC_UOM()
{
final int uomId = huPIAttribute.getC_UOM_ID();
if (uomId > 0)
{
return Services.get(IUOMDAO.class).getById(uomId);
}
else
{
// fallback to M_Attribute's UOM
return super.getC_UOM();
}
}
@Override
public final boolean isReadonlyUI()
{
return huPIAttribute.isReadOnly();
}
@Override
public final boolean isDisplayedUI()
{
return huPIAttribute.isDisplayed();
|
}
@Override
public final boolean isMandatory()
{
return huPIAttribute.isMandatory();
}
@Override
public final int getDisplaySeqNo()
{
final int seqNo = huPIAttribute.getSeqNo();
if (seqNo > 0)
{
return seqNo;
}
// Fallback: if SeqNo was not set, return max int (i.e. show them last)
return Integer.MAX_VALUE;
}
@Override
public boolean isOnlyIfInProductAttributeSet()
{
return huPIAttribute.isOnlyIfInProductAttributeSet();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\AbstractHUAttributeValue.java
| 1
|
请完成以下Java代码
|
@Nullable String getErrorReport() {
Map<String, List<PropertyMigration>> content = getContent(LegacyProperties::getUnsupported);
if (content.isEmpty()) {
return null;
}
StringBuilder report = new StringBuilder();
report.append(String
.format("%nThe use of configuration keys that are no longer supported was found in the environment:%n%n"));
append(report, content);
report.append(String.format("%n"));
report.append("Please refer to the release notes or reference guide for potential alternatives.");
report.append(String.format("%n"));
return report.toString();
}
private Map<String, List<PropertyMigration>> getContent(
Function<LegacyProperties, List<PropertyMigration>> extractor) {
return this.content.entrySet()
.stream()
.filter((entry) -> !extractor.apply(entry.getValue()).isEmpty())
.collect(
Collectors.toMap(Map.Entry::getKey, (entry) -> new ArrayList<>(extractor.apply(entry.getValue()))));
}
private void append(StringBuilder report, Map<String, List<PropertyMigration>> content) {
content.forEach((name, properties) -> {
report.append(String.format("Property source '%s':%n", name));
properties.sort(PropertyMigration.COMPARATOR);
properties.forEach((property) -> {
report.append(String.format("\tKey: %s%n", property.getProperty().getName()));
if (property.getLineNumber() != null) {
report.append(String.format("\t\tLine: %d%n", property.getLineNumber()));
}
report.append(String.format("\t\t%s%n", property.determineReason()));
});
report.append(String.format("%n"));
});
|
}
/**
* Register a new property source.
* @param name the name of the property source
* @param properties the {@link PropertyMigration} instances
*/
void add(String name, List<PropertyMigration> properties) {
this.content.put(name, new LegacyProperties(properties));
}
private static class LegacyProperties {
private final List<PropertyMigration> properties;
LegacyProperties(List<PropertyMigration> properties) {
this.properties = new ArrayList<>(properties);
}
List<PropertyMigration> getRenamed() {
return this.properties.stream().filter(PropertyMigration::isCompatibleType).toList();
}
List<PropertyMigration> getUnsupported() {
return this.properties.stream().filter((property) -> !property.isCompatibleType()).toList();
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-properties-migrator\src\main\java\org\springframework\boot\context\properties\migrator\PropertiesMigrationReport.java
| 1
|
请完成以下Java代码
|
public void setUser2(final org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
@Override
public void setUser2_ID (final int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, User2_ID);
}
@Override
public int getUser2_ID()
{
return get_ValueAsInt(COLUMNNAME_User2_ID);
}
@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);
}
@Override
public void setC_Flatrate_Term_ID (final int C_Flatrate_Term_ID)
{
if (C_Flatrate_Term_ID < 1)
set_Value (COLUMNNAME_C_Flatrate_Term_ID, null);
else
set_Value (COLUMNNAME_C_Flatrate_Term_ID, C_Flatrate_Term_ID);
}
@Override
public int getC_Flatrate_Term_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Flatrate_Term_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoiceLine.java
| 1
|
请完成以下Java代码
|
public final class VRowIDRenderer implements TableCellRenderer
{
/**
* Constructor
*/
public VRowIDRenderer(boolean enableSelection)
{
m_select = enableSelection;
} // VRowIDRenderer
private boolean m_select = false;
private JButton m_button = new JButton();
private JCheckBox m_check = null;
/**
* Enable Selection to be displayed
*/
public void setEnableSelection(boolean showSelection)
{
m_select = showSelection;
} // setEnableSelection
/**
* Return TableCell Renderer Component
|
*/
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column)
{
if (m_select)
{
if (m_check == null)
m_check = new JCheckBox();
Object[] data = (Object[])value;
if (data == null || data[1] == null)
m_check.setSelected(false);
else
{
Boolean sel = (Boolean)data[1];
m_check.setSelected(sel.booleanValue());
}
return m_check;
}
else
return m_button;
} // getTableCellRenderereComponent
} // VRowIDRenderer
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VRowIDRenderer.java
| 1
|
请完成以下Java代码
|
public boolean hasOddId() {
return id % 2 != 0;
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof Employee)) return false;
final Employee other = (Employee) o;
if (!other.canEqual((Object) this)) return false;
if (this.getId() != other.getId()) return false;
if (this.getAge() != other.getAge()) return false;
if (this.hasOddId() != other.hasOddId()) return false;
final Object this$name = this.getName();
final Object other$name = other.getName();
if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
|
return true;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = result * PRIME + this.getId();
result = result * PRIME + this.getAge();
result = result * PRIME + (this.hasOddId() ? 79 : 97);
final Object $name = this.getName();
result = result * PRIME + ($name == null ? 43 : $name.hashCode());
return result;
}
}
|
repos\tutorials-master\lombok-modules\lombok\src\main\java\com\baeldung\lombok\equalsandhashcode\include\methodlevel\EmployeeDelomboked.java
| 1
|
请完成以下Java代码
|
public class DataStore extends BaseElement {
protected String name;
protected String dataState;
protected String itemSubjectRef;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDataState() {
return dataState;
}
public void setDataState(String dataState) {
this.dataState = dataState;
}
public String getItemSubjectRef() {
|
return itemSubjectRef;
}
public void setItemSubjectRef(String itemSubjectRef) {
this.itemSubjectRef = itemSubjectRef;
}
public DataStore clone() {
DataStore clone = new DataStore();
clone.setValues(this);
return clone;
}
public void setValues(DataStore otherElement) {
super.setValues(otherElement);
setName(otherElement.getName());
setDataState(otherElement.getDataState());
setItemSubjectRef(otherElement.getItemSubjectRef());
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\DataStore.java
| 1
|
请完成以下Java代码
|
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
ProcessDefinitionImpl that = (ProcessDefinitionImpl) o;
return (
version == that.version &&
Objects.equals(id, that.id) &&
Objects.equals(name, that.name) &&
Objects.equals(description, that.description) &&
Objects.equals(key, that.key) &&
Objects.equals(formKey, that.formKey)
);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), id, name, description, version, key, formKey);
}
@Override
public String toString() {
|
return (
"ProcessDefinition{" +
"id='" +
id +
'\'' +
", name='" +
name +
'\'' +
", key='" +
key +
'\'' +
", description='" +
description +
'\'' +
", formKey='" +
formKey +
'\'' +
", version=" +
version +
'}'
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessDefinitionImpl.java
| 1
|
请完成以下Java代码
|
public class Fact {
@Position(0)
private String element;
@Position(1)
private String place;
public Fact(String element, String place) {
this.element = element;
this.place = place;
}
public String getElement() {
return element;
}
public void setElement(String element) {
this.element = element;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((element == null) ? 0 : element.hashCode());
result = prime * result + ((place == null) ? 0 : place.hashCode());
return result;
|
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Fact other = (Fact) obj;
if (element == null) {
if (other.element != null)
return false;
} else if (!element.equals(other.element))
return false;
if (place == null) {
if (other.place != null)
return false;
} else if (!place.equals(other.place))
return false;
return true;
}
@Override
public String toString() {
return "Fact{" + "element='" + element + '\'' + ", place='" + place + '\'' + '}';
}
}
|
repos\tutorials-master\drools\src\main\java\com\baeldung\drools\model\Fact.java
| 1
|
请完成以下Java代码
|
private DestinationTopic.Type getDestinationTopicType(Long backOffValue) {
return this.isSameIntervalReuse && hasDuplicates(backOffValue) ? Type.REUSABLE_RETRY_TOPIC : Type.RETRY;
}
private int reusableTopicAttempts() {
if (this.isSameIntervalReuse && this.backOffValues.size() > 1) {
// Assuming that duplicates are always at the end of the list.
return amountOfDuplicates(this.backOffValues.get(this.backOffValues.size() - 1)) - 1;
}
return 0;
}
private boolean hasDuplicates(Long thisBackOffValue) {
return amountOfDuplicates(thisBackOffValue) > 1;
}
private int amountOfDuplicates(Long thisBackOffValue) {
return Long.valueOf(this.backOffValues
.stream()
.filter(thisBackOffValue::equals)
.count())
.intValue();
}
private DestinationTopic.Properties createProperties(long delayMs, String suffix) {
return new DestinationTopic.Properties(delayMs, suffix, getDestinationTopicType(delayMs), this.maxAttempts,
this.numPartitions, this.dltStrategy, this.kafkaOperations, this.shouldRetryOn, this.timeout);
|
}
private String joinWithRetrySuffix(long parameter) {
return String.join("-", this.destinationTopicSuffixes.getRetrySuffix(), String.valueOf(parameter));
}
public static class DestinationTopicSuffixes {
private final String retryTopicSuffix;
private final String dltSuffix;
public DestinationTopicSuffixes(@Nullable String retryTopicSuffix, @Nullable String dltSuffix) {
this.retryTopicSuffix = StringUtils.hasText(retryTopicSuffix)
? retryTopicSuffix
: RetryTopicConstants.DEFAULT_RETRY_SUFFIX;
this.dltSuffix = StringUtils.hasText(dltSuffix) ? dltSuffix : RetryTopicConstants.DEFAULT_DLT_SUFFIX;
}
public String getRetrySuffix() {
return this.retryTopicSuffix;
}
public String getDltSuffix() {
return this.dltSuffix;
}
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DestinationTopicPropertiesFactory.java
| 1
|
请完成以下Java代码
|
public int getM_Product_Category_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Category_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
|
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_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_C_RfQ_TopicSubscriberOnly.java
| 1
|
请完成以下Java代码
|
public String getCustomPropertiesResolverImplementation() {
return customPropertiesResolverImplementation;
}
public void setCustomPropertiesResolverImplementation(String customPropertiesResolverImplementation) {
this.customPropertiesResolverImplementation = customPropertiesResolverImplementation;
}
public Object getInstance() {
return instance;
}
public void setInstance(Object instance) {
this.instance = instance;
}
public ActivitiListener clone() {
ActivitiListener clone = new ActivitiListener();
clone.setValues(this);
return clone;
|
}
public void setValues(ActivitiListener otherListener) {
setEvent(otherListener.getEvent());
setImplementation(otherListener.getImplementation());
setImplementationType(otherListener.getImplementationType());
fieldExtensions = new ArrayList<FieldExtension>();
if (otherListener.getFieldExtensions() != null && !otherListener.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherListener.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ActivitiListener.java
| 1
|
请完成以下Java代码
|
public TbMsgBuilder data(String data) {
this.data = data;
return this;
}
public TbMsgBuilder ruleChainId(RuleChainId ruleChainId) {
this.ruleChainId = ruleChainId;
return this;
}
public TbMsgBuilder ruleNodeId(RuleNodeId ruleNodeId) {
this.ruleNodeId = ruleNodeId;
return this;
}
public TbMsgBuilder resetRuleNodeId() {
return ruleNodeId(null);
}
public TbMsgBuilder correlationId(UUID correlationId) {
this.correlationId = correlationId;
return this;
}
public TbMsgBuilder partition(Integer partition) {
this.partition = partition;
return this;
}
public TbMsgBuilder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) {
this.previousCalculatedFieldIds = new CopyOnWriteArrayList<>(previousCalculatedFieldIds);
return this;
}
public TbMsgBuilder ctx(TbMsgProcessingCtx ctx) {
|
this.ctx = ctx;
return this;
}
public TbMsgBuilder callback(TbMsgCallback callback) {
this.callback = callback;
return this;
}
public TbMsg build() {
return new TbMsg(queueName, id, ts, internalType, type, originator, customerId, metaData, dataType, data, ruleChainId, ruleNodeId, correlationId, partition, previousCalculatedFieldIds, ctx, callback);
}
public String toString() {
return "TbMsg.TbMsgBuilder(queueName=" + this.queueName + ", id=" + this.id + ", ts=" + this.ts +
", type=" + this.type + ", internalType=" + this.internalType + ", originator=" + this.originator +
", customerId=" + this.customerId + ", metaData=" + this.metaData + ", dataType=" + this.dataType +
", data=" + this.data + ", ruleChainId=" + this.ruleChainId + ", ruleNodeId=" + this.ruleNodeId +
", correlationId=" + this.correlationId + ", partition=" + this.partition + ", previousCalculatedFields=" + this.previousCalculatedFieldIds +
", ctx=" + this.ctx + ", callback=" + this.callback + ")";
}
}
}
|
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\TbMsg.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static final class DefaultCodecCustomizer implements CodecCustomizer, Ordered {
private final boolean logRequestDetails;
private final @Nullable DataSize maxInMemorySize;
DefaultCodecCustomizer(boolean logRequestDetails, @Nullable DataSize maxInMemorySize) {
this.logRequestDetails = logRequestDetails;
this.maxInMemorySize = maxInMemorySize;
}
@Override
public void customize(CodecConfigurer configurer) {
PropertyMapper map = PropertyMapper.get();
CodecConfigurer.DefaultCodecs defaultCodecs = configurer.defaultCodecs();
defaultCodecs.enableLoggingRequestDetails(this.logRequestDetails);
map.from(this.maxInMemorySize).asInt(DataSize::toBytes).to(defaultCodecs::maxInMemorySize);
}
@Override
public int getOrder() {
return 0;
}
}
}
|
static class NoJacksonOrJackson2Preferred extends AnyNestedCondition {
NoJacksonOrJackson2Preferred() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper")
static class NoJackson {
}
@ConditionalOnProperty(name = "spring.http.codecs.preferred-json-mapper", havingValue = "jackson2")
static class Jackson2Preferred {
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-codec\src\main\java\org\springframework\boot\http\codec\autoconfigure\CodecsAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public String toString() {
StringBuilder strb = new StringBuilder();
strb.append("[Validation set: '").append(validatorSetName).append("' | Problem: '").append(problem).append("'] : ");
strb.append(defaultDescription);
strb.append(" - [Extra info : ");
boolean extraInfoAlreadyPresent = false;
if (caseDefinitionId != null) {
strb.append("caseDefinitionId = ").append(caseDefinitionId);
extraInfoAlreadyPresent = true;
}
if (caseDefinitionName != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("caseDefinitionName = ").append(caseDefinitionName).append(" | ");
extraInfoAlreadyPresent = true;
}
if (itemId != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
|
}
strb.append("id = ").append(itemId).append(" | ");
extraInfoAlreadyPresent = true;
}
if (itemName != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("name = ").append(itemName).append(" | ");
extraInfoAlreadyPresent = true;
}
strb.append("]");
if (xmlLineNumber > 0 && xmlColumnNumber > 0) {
strb.append(" ( line: ").append(xmlLineNumber).append(", column: ").append(xmlColumnNumber).append(")");
}
return strb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-case-validation\src\main\java\org\flowable\cmmn\validation\validator\ValidationEntry.java
| 1
|
请完成以下Java代码
|
public final class BearerTokenErrors {
private static final BearerTokenError DEFAULT_INVALID_REQUEST = invalidRequest("Invalid request");
private static final BearerTokenError DEFAULT_INVALID_TOKEN = invalidToken("Invalid token");
private static final BearerTokenError DEFAULT_INSUFFICIENT_SCOPE = insufficientScope("Insufficient scope", null);
private static final String DEFAULT_URI = "https://tools.ietf.org/html/rfc6750#section-3.1";
private BearerTokenErrors() {
}
/**
* Create a {@link BearerTokenError} caused by an invalid request
* @param message a description of the error
* @return a {@link BearerTokenError}
*/
public static BearerTokenError invalidRequest(String message) {
try {
return new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST, message,
DEFAULT_URI);
}
catch (IllegalArgumentException ex) {
// some third-party library error messages are not suitable for RFC 6750's
// error message charset
return DEFAULT_INVALID_REQUEST;
}
}
/**
* Create a {@link BearerTokenError} caused by an invalid token
|
* @param message a description of the error
* @return a {@link BearerTokenError}
*/
public static BearerTokenError invalidToken(String message) {
try {
return new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED, message,
DEFAULT_URI);
}
catch (IllegalArgumentException ex) {
// some third-party library error messages are not suitable for RFC 6750's
// error message charset
return DEFAULT_INVALID_TOKEN;
}
}
/**
* Create a {@link BearerTokenError} caused by an invalid token
* @param scope the scope attribute to use in the error
* @return a {@link BearerTokenError}
*/
public static BearerTokenError insufficientScope(String message, String scope) {
try {
return new BearerTokenError(BearerTokenErrorCodes.INSUFFICIENT_SCOPE, HttpStatus.FORBIDDEN, message,
DEFAULT_URI, scope);
}
catch (IllegalArgumentException ex) {
// some third-party library error messages are not suitable for RFC 6750's
// error message charset
return DEFAULT_INSUFFICIENT_SCOPE;
}
}
}
|
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\BearerTokenErrors.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("field", fieldName)
.add("class", classRef)
.toString();
}
public Field getField()
{
// Get if not expired
{
final WeakReference<Field> weakRef = fieldRef.get();
final Field field = weakRef != null ? weakRef.get() : null;
if (field != null)
{
return field;
}
}
|
// Load the class
try
{
final Class<?> clazz = classRef.getReferencedClass();
final Field fieldNew = clazz.getDeclaredField(fieldName);
fieldRef.set(new WeakReference<>(fieldNew));
return fieldNew;
}
catch (final Exception ex)
{
throw new IllegalStateException("Cannot load expired field: " + classRef + "/" + fieldName, ex);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\reflect\FieldReference.java
| 1
|
请完成以下Java代码
|
public void saveMovie() {
EntityManager em = HibernateOperations.getEntityManager();
em.getTransaction()
.begin();
Movie movie = new Movie();
movie.setId(1L);
movie.setMovieName("The Godfather");
movie.setReleaseYear(1972);
movie.setLanguage("English");
em.persist(movie);
em.getTransaction()
.commit();
}
/**
* Method to illustrate the querying support in EntityManager when the result is a single object.
* @return Movie
*/
public Movie queryForMovieById() {
EntityManager em = HibernateOperations.getEntityManager();
Movie movie = (Movie) em.createQuery("SELECT movie from Movie movie where movie.id = ?1")
.setParameter(1, Long.valueOf(1L))
.getSingleResult();
return movie;
}
/**
* Method to illustrate the querying support in EntityManager when the result is a list.
* @return
*/
public List<?> queryForMovies() {
EntityManager em = HibernateOperations.getEntityManager();
List<?> movies = em.createQuery("SELECT movie from Movie movie where movie.language = ?1")
.setParameter(1, "English")
.getResultList();
return movies;
}
/**
* Method to illustrate the usage of find() method.
* @param movieId
* @return Movie
|
*/
public Movie getMovie(Long movieId) {
EntityManager em = HibernateOperations.getEntityManager();
Movie movie = em.find(Movie.class, Long.valueOf(movieId));
return movie;
}
/**
* Method to illustrate the usage of merge() function.
*/
public void mergeMovie() {
EntityManager em = HibernateOperations.getEntityManager();
Movie movie = getMovie(1L);
em.detach(movie);
movie.setLanguage("Italian");
em.getTransaction()
.begin();
em.merge(movie);
em.getTransaction()
.commit();
}
/**
* Method to illustrate the usage of remove() function.
*/
public void removeMovie() {
EntityManager em = HibernateOperations.getEntityManager();
em.getTransaction()
.begin();
Movie movie = em.find(Movie.class, Long.valueOf(1L));
em.remove(movie);
em.getTransaction()
.commit();
}
}
|
repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\operations\HibernateOperations.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getBytes() {
return bytes;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public Object getPersistentState() {
return ResourceEntity.class;
}
public void setGenerated(boolean generated) {
this.generated = generated;
}
/**
* Indicated whether or not the resource has been generated while deploying rather than
* being actual part of the deployment.
*/
public boolean isGenerated() {
return generated;
}
public String getTenantId() {
return tenantId;
|
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", name=" + name
+ ", deploymentId=" + deploymentId
+ ", generated=" + generated
+ ", tenantId=" + tenantId
+ ", type=" + type
+ ", createTime=" + createTime
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ResourceEntity.java
| 1
|
请完成以下Java代码
|
public class CalledProcessInstanceDto extends ProcessInstanceDto {
protected String processDefinitionId;
protected String processDefinitionKey;
protected String processDefinitionName;
protected List<IncidentStatisticsDto> incidents;
protected String callActivityInstanceId;
protected String callActivityId;
public CalledProcessInstanceDto() {}
public String getId() {
return id;
}
public String getBusinessKey() {
return businessKey;
}
public String getCallActivityInstanceId() {
return callActivityInstanceId;
}
public String getCallActivityId() {
return callActivityId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
|
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionName() {
return processDefinitionName;
}
public List<IncidentStatisticsDto> getIncidents() {
return incidents;
}
public void setIncidents(List<IncidentStatisticsDto> incidents) {
this.incidents = incidents;
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\CalledProcessInstanceDto.java
| 1
|
请完成以下Java代码
|
public class LiquibaseDatatypes {
public static void main(String[] args) {
List<LiquibaseDataType> dataTypes = getDataTypes();
List<AbstractJdbcDatabase> databases = getDatabases();
for (LiquibaseDataType dataTypeInstance : dataTypes) {
try {
LiquibaseDataType dataType = dataTypeInstance;
dataType.finishInitialization("");
System.out.println(dataType.getName());
for (AbstractJdbcDatabase databaseInstance : databases) {
try {
Database database = databaseInstance;
String databaseType = dataType.toDatabaseDataType(database)
.toString();
System.out.println(databaseInstance.getName() + ": " + databaseType);
} catch (Exception e) {
System.err.println("Error initializing database class " + databaseInstance.getName() + ": " + e.getMessage());
}
}
System.out.println();
} catch (Exception e) {
System.err.println("Error initializing data type class " + dataTypeInstance.getName() + ": " + e.getMessage());
}
}
}
private static List<LiquibaseDataType> getDataTypes() {
return List.of(
new BooleanType(),
new TinyIntType(),
new IntType(),
new MediumIntType(),
new BigIntType(),
new FloatType(),
new DoubleType(),
new DecimalType(),
new NumberType(),
new BlobType(),
new DateTimeType(),
new TimeType(),
new TimestampType(),
new DateType(),
new CharType(),
new VarcharType(),
new NCharType(),
|
new NVarcharType(),
new ClobType(),
new CurrencyType(),
new UUIDType());
}
private static List<AbstractJdbcDatabase> getDatabases() {
return List.of(
new MySQLDatabase(),
new SQLiteDatabase(),
new H2Database(),
new PostgresDatabase(),
new DB2Database(),
new MSSQLDatabase(),
new OracleDatabase(),
new HsqlDatabase(),
new FirebirdDatabase(),
new DerbyDatabase(),
new InformixDatabase(),
new SybaseDatabase(),
new SybaseASADatabase());
}
}
|
repos\tutorials-master\persistence-modules\liquibase\src\main\java\com\baeldung\liquibase\utility\LiquibaseDatatypes.java
| 1
|
请完成以下Java代码
|
public void deployResources(String deploymentNameHint, Resource[] resources, RepositoryService repositoryService) {
DeploymentBuilder deploymentBuilder = repositoryService
.createDeployment()
.enableDuplicateFiltering()
.name(deploymentNameHint);
int validProcessCount = 0;
for (final Resource resource : resources) {
final String resourceName = determineResourceName(resource);
if (validateModel(resource, repositoryService)) {
validProcessCount++;
deploymentBuilder.addInputStream(resourceName, resource);
} else {
LOGGER.error(
|
"The following resource wasn't included in the deployment since it is invalid:\n{}",
resourceName
);
}
}
deploymentBuilder = loadApplicationUpgradeContext(deploymentBuilder);
if (validProcessCount != 0) {
deploymentBuilder.deploy();
} else {
throw new ActivitiException("No process definition was deployed.");
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\autodeployment\FailOnNoProcessAutoDeploymentStrategy.java
| 1
|
请完成以下Java代码
|
public class FileValueMapper extends AbstractTypedValueMapper<FileValue> {
protected EngineClient engineClient;
public FileValueMapper(EngineClient engineClient) {
super(FILE);
this.engineClient = engineClient;
}
public FileValue convertToTypedValue(UntypedValueImpl untypedValue) {
throw new UnsupportedOperationException("Currently no automatic conversation from UntypedValue to FileValue");
}
public FileValue readValue(TypedValueField value, boolean deserializeValue) {
Map<String, Object> valueInfo = value.getValueInfo();
String filename = (String) valueInfo.get(VALUE_INFO_FILE_NAME);
DeferredFileValueImpl fileValue = new DeferredFileValueImpl(filename, engineClient);
String mimeType = (String) valueInfo.get(VALUE_INFO_FILE_MIME_TYPE);
if (mimeType != null) {
fileValue.setMimeType(mimeType);
}
String encoding = (String) valueInfo.get(VALUE_INFO_FILE_ENCODING);
if (encoding != null) {
fileValue.setEncoding(encoding);
}
return fileValue;
}
public void writeValue(FileValue fileValue, TypedValueField typedValueField) {
Map<String, Object> valueInfo = new HashMap<>();
valueInfo.put(VALUE_INFO_FILE_NAME, fileValue.getFilename());
if (fileValue.getEncoding() != null) {
valueInfo.put(VALUE_INFO_FILE_ENCODING, fileValue.getEncoding());
}
|
if (fileValue.getMimeType() != null) {
valueInfo.put(VALUE_INFO_FILE_MIME_TYPE, fileValue.getMimeType());
}
typedValueField.setValueInfo(valueInfo);
byte[] bytes = ((FileValueImpl) fileValue).getByteArray();
if (bytes != null) {
typedValueField.setValue(Base64.encodeBase64String(bytes));
}
}
protected boolean canWriteValue(TypedValue typedValue) {
if (typedValue == null || typedValue.getType() == null) {
// untyped value
return false;
}
return typedValue.getType().getName().equals(valueType.getName()) && !isDeferred(typedValue);
}
protected boolean canReadValue(TypedValueField typedValueField) {
Object value = typedValueField.getValue();
return value == null || value instanceof String;
}
protected boolean isDeferred(Object variableValue) {
return variableValue instanceof DeferredFileValue && !((DeferredFileValue) variableValue).isLoaded();
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\mapper\FileValueMapper.java
| 1
|
请完成以下Java代码
|
public static int compareLevel(String name1, String name2) {
PositionLevelEnum pos1 = getByName(name1);
PositionLevelEnum pos2 = getByName(name2);
if (pos1 == null || pos2 == null) {
return 0;
}
// 等级数字越小代表职级越高
return pos2.getLevel() - pos1.getLevel();
}
/**
* 判断是否为更高等级
* @param currentName 当前职级名称
* @param targetName 目标职级名称
* @return true-目标职级更高,false-目标职级不高于当前职级
*/
public static boolean isHigherLevel(String currentName, String targetName) {
return compareLevel(targetName, currentName) > 0;
}
/**
* 获取所有职员层级名称
* @return 职员层级名称列表
*/
public static List<String> getStaffLevelNames() {
return Arrays.asList(MINISTER.getName(), VICE_MINISTER.getName(), STAFF.getName());
}
/**
* 获取所有领导层级名称
* @return 领导层级名称列表
*/
public static List<String> getLeaderLevelNames() {
|
return Arrays.asList(CHAIRMAN.getName(), GENERAL_MANAGER.getName(), VICE_GENERAL_MANAGER.getName());
}
/**
* 获取所有职级名称(按等级排序)
* @return 所有职级名称列表
*/
public static List<String> getAllPositionNames() {
return Arrays.asList(
CHAIRMAN.getName(), GENERAL_MANAGER.getName(), VICE_GENERAL_MANAGER.getName(),
MINISTER.getName(), VICE_MINISTER.getName(), STAFF.getName()
);
}
/**
* 获取指定等级范围的职级
* @param minLevel 最小等级
* @param maxLevel 最大等级
* @return 职级名称列表
*/
public static List<String> getPositionsByLevelRange(int minLevel, int maxLevel) {
return Arrays.stream(values())
.filter(p -> p.getLevel() >= minLevel && p.getLevel() <= maxLevel)
.map(PositionLevelEnum::getName)
.collect(java.util.stream.Collectors.toList());
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\PositionLevelEnum.java
| 1
|
请完成以下Java代码
|
public String getVariableId() {
return variableId;
}
public String getVariableName() {
return variableName;
}
public String[] getVariableNames() {
return variableNames;
}
public String getVariableNameLike() {
return variableNameLike;
}
public String[] getExecutionIds() {
return executionIds;
}
public String[] getProcessInstanceIds() {
return processInstanceIds;
}
public String[] getCaseExecutionIds() {
return caseExecutionIds;
}
public String[] getCaseInstanceIds() {
|
return caseInstanceIds;
}
public String[] getTaskIds() {
return taskIds;
}
public String[] getBatchIds() {
return batchIds;
}
public String[] getVariableScopeIds() {
return variableScopeIds;
}
public String[] getActivityInstanceIds() {
return activityInstanceIds;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\VariableInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public String getSKU ()
{
return (String)get_Value(COLUMNNAME_SKU);
}
/** Set Symbol.
@param UOMSymbol
Symbol for a Unit of Measure
*/
public void setUOMSymbol (String UOMSymbol)
{
set_ValueNoCheck (COLUMNNAME_UOMSymbol, UOMSymbol);
}
/** Get Symbol.
@return Symbol for a Unit of Measure
*/
public String getUOMSymbol ()
{
return (String)get_Value(COLUMNNAME_UOMSymbol);
}
/** Set UPC/EAN.
@param UPC
Bar Code (Universal Product Code or its superset European Article Number)
*/
public void setUPC (String UPC)
{
set_ValueNoCheck (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
public String getUPC ()
{
return (String)get_Value(COLUMNNAME_UPC);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
|
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Warehouse.
@param WarehouseName
Warehouse Name
*/
public void setWarehouseName (String WarehouseName)
{
set_ValueNoCheck (COLUMNNAME_WarehouseName, WarehouseName);
}
/** Get Warehouse.
@return Warehouse Name
*/
public String getWarehouseName ()
{
return (String)get_Value(COLUMNNAME_WarehouseName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_RV_WarehousePrice.java
| 1
|
请完成以下Java代码
|
public void setSektionNo (final @Nullable java.lang.String SektionNo)
{
set_Value (COLUMNNAME_SektionNo, SektionNo);
}
@Override
public java.lang.String getSektionNo()
{
return get_ValueAsString(COLUMNNAME_SektionNo);
}
/**
* Type AD_Reference_ID=541287
* Reference name: ESR_Type
*/
public static final int TYPE_AD_Reference_ID=541287;
/** QRR = QRR */
public static final String TYPE_QRR = "QRR";
/** ESR = ISR Reference */
|
public static final String TYPE_ESR = "ISR Reference";
/** SCOR = SCOR Reference */
public static final String TYPE_SCOR = "SCOR";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_ImportLine.java
| 1
|
请完成以下Java代码
|
public int getC_Invoice_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Invoice_ID);
}
@Override
public void setEDI_cctop_120_v_ID (final int EDI_cctop_120_v_ID)
{
if (EDI_cctop_120_v_ID < 1)
set_ValueNoCheck (COLUMNNAME_EDI_cctop_120_v_ID, null);
else
set_ValueNoCheck (COLUMNNAME_EDI_cctop_120_v_ID, EDI_cctop_120_v_ID);
}
@Override
public int getEDI_cctop_120_v_ID()
{
return get_ValueAsInt(COLUMNNAME_EDI_cctop_120_v_ID);
}
@Override
public de.metas.esb.edi.model.I_EDI_cctop_invoic_v getEDI_cctop_invoic_v()
{
return get_ValueAsPO(COLUMNNAME_EDI_cctop_invoic_v_ID, de.metas.esb.edi.model.I_EDI_cctop_invoic_v.class);
}
@Override
public void setEDI_cctop_invoic_v(final de.metas.esb.edi.model.I_EDI_cctop_invoic_v EDI_cctop_invoic_v)
{
set_ValueFromPO(COLUMNNAME_EDI_cctop_invoic_v_ID, de.metas.esb.edi.model.I_EDI_cctop_invoic_v.class, EDI_cctop_invoic_v);
}
@Override
public void setEDI_cctop_invoic_v_ID (final int EDI_cctop_invoic_v_ID)
{
if (EDI_cctop_invoic_v_ID < 1)
set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, null);
else
set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, EDI_cctop_invoic_v_ID);
}
@Override
public int getEDI_cctop_invoic_v_ID()
{
return get_ValueAsInt(COLUMNNAME_EDI_cctop_invoic_v_ID);
}
@Override
public void setISO_Code (final @Nullable java.lang.String ISO_Code)
{
set_Value (COLUMNNAME_ISO_Code, ISO_Code);
}
@Override
public java.lang.String getISO_Code()
{
return get_ValueAsString(COLUMNNAME_ISO_Code);
}
@Override
public void setnetdate (final @Nullable java.sql.Timestamp netdate)
{
set_Value (COLUMNNAME_netdate, netdate);
}
@Override
public java.sql.Timestamp getnetdate()
{
return get_ValueAsTimestamp(COLUMNNAME_netdate);
}
|
@Override
public void setNetDays (final int NetDays)
{
set_Value (COLUMNNAME_NetDays, NetDays);
}
@Override
public int getNetDays()
{
return get_ValueAsInt(COLUMNNAME_NetDays);
}
@Override
public void setsinglevat (final @Nullable BigDecimal singlevat)
{
set_Value (COLUMNNAME_singlevat, singlevat);
}
@Override
public BigDecimal getsinglevat()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_singlevat);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void settaxfree (final boolean taxfree)
{
set_Value (COLUMNNAME_taxfree, taxfree);
}
@Override
public boolean istaxfree()
{
return get_ValueAsBoolean(COLUMNNAME_taxfree);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_120_v.java
| 1
|
请完成以下Java代码
|
public String eq(ModelMap map) {
map.addAttribute("name", "neo");
map.addAttribute("age", 30);
map.addAttribute("flag", "yes");
return "eq";
}
@RequestMapping("/switch")
public String switchcase(ModelMap map) {
map.addAttribute("sex", "woman");
return "switch";
}
@RequestMapping("/inline")
public String inline(ModelMap map) {
map.addAttribute("userName", "neo");
return "inline";
}
@RequestMapping("/object")
public String object(HttpServletRequest request) {
request.setAttribute("request","i am request");
request.getSession().setAttribute("session","i am session");
return "object";
}
@RequestMapping("/utility")
public String utility(ModelMap map) {
map.addAttribute("userName", "neo");
|
map.addAttribute("users", getUserList());
map.addAttribute("count", 12);
map.addAttribute("date", new Date());
return "utility";
}
private List<User> getUserList(){
List<User> list=new ArrayList<User>();
User user1=new User("大牛",12,"123456");
User user2=new User("小牛",6,"123563");
User user3=new User("纯洁的微笑",66,"666666");
list.add(user1);
list.add(user2);
list.add(user3);
return list;
}
}
|
repos\spring-boot-leaning-master\2.x_42_courses\第 2-4 课 模板引擎 Thymeleaf 高阶用法\spring-boot-thymeleaf\src\main\java\com\neo\web\ExampleController.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DefaultNativeAssetRepository extends AbstractNativeRepository implements NativeAssetRepository {
private final String COUNT_QUERY = "SELECT count(id) FROM asset;";
public DefaultNativeAssetRepository(NamedParameterJdbcTemplate jdbcTemplate, TransactionTemplate transactionTemplate) {
super(jdbcTemplate, transactionTemplate);
}
@Override
public PageData<ProfileEntityIdInfo> findProfileEntityIdInfos(Pageable pageable) {
String PROFILE_ASSET_ID_INFO_QUERY = "SELECT tenant_id as tenantId, customer_id as customerId, asset_profile_id as profileId, id as id FROM asset ORDER BY created_time ASC LIMIT %s OFFSET %s";
return find(COUNT_QUERY, PROFILE_ASSET_ID_INFO_QUERY, pageable, DefaultNativeAssetRepository::toInfo);
}
@Override
|
public PageData<ProfileEntityIdInfo> findProfileEntityIdInfosByTenantId(UUID tenantId, Pageable pageable) {
String PROFILE_ASSET_ID_INFO_QUERY = String.format("SELECT tenant_id as tenantId, customer_id as customerId, asset_profile_id as profileId, id as id FROM asset WHERE tenant_id = '%s' ORDER BY created_time ASC LIMIT %%s OFFSET %%s", tenantId);
return find(COUNT_QUERY, PROFILE_ASSET_ID_INFO_QUERY, pageable, DefaultNativeAssetRepository::toInfo);
}
private static ProfileEntityIdInfo toInfo(Map<String, Object> row) {
var tenantIdObj = row.get("tenantId");
UUID tenantId = tenantIdObj != null ? (UUID) tenantIdObj : TenantId.SYS_TENANT_ID.getId();
AssetId id = new AssetId((UUID) row.get("id"));
CustomerId customerId = new CustomerId((UUID) row.get("customerId"));
EntityId ownerId = !customerId.isNullUid() ? customerId : TenantId.fromUUID(tenantId);
AssetProfileId profileId = new AssetProfileId((UUID) row.get("profileId"));
return ProfileEntityIdInfo.create(tenantId, ownerId, profileId, id);
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\device\DefaultNativeAssetRepository.java
| 2
|
请完成以下Java代码
|
public void removeBottomCategory(BottomCategory bottomCategory) {
bottomCategory.setMiddleCategory(null);
bottomCategories.remove(bottomCategory);
}
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<BottomCategory> getBottomCategories() {
return bottomCategories;
}
public void setBottomCategories(List<BottomCategory> bottomCategories) {
this.bottomCategories = bottomCategories;
}
public TopCategory getTopCategory() {
return topCategory;
}
|
public void setTopCategory(TopCategory topCategory) {
this.topCategory = topCategory;
}
@Override
public int hashCode() {
return 2018;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof MiddleCategory)) {
return false;
}
return id != null && id.equals(((MiddleCategory) obj).id);
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoSqlResultSetMapping\src\main\java\com\app\entity\MiddleCategory.java
| 1
|
请完成以下Java代码
|
protected void validate() {
super.validate();
Assert.notNull(getClaims().get(OidcProviderMetadataClaimNames.JWKS_URI), "jwksUri cannot be null");
Assert.notNull(getClaims().get(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED),
"subjectTypes cannot be null");
Assert.isInstanceOf(List.class, getClaims().get(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED),
"subjectTypes must be of type List");
Assert.notEmpty((List<?>) getClaims().get(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED),
"subjectTypes cannot be empty");
Assert.notNull(getClaims().get(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED),
"idTokenSigningAlgorithms cannot be null");
Assert.isInstanceOf(List.class,
getClaims().get(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED),
"idTokenSigningAlgorithms must be of type List");
Assert.notEmpty(
(List<?>) getClaims().get(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED),
"idTokenSigningAlgorithms cannot be empty");
if (getClaims().get(OidcProviderMetadataClaimNames.USER_INFO_ENDPOINT) != null) {
validateURL(getClaims().get(OidcProviderMetadataClaimNames.USER_INFO_ENDPOINT),
"userInfoEndpoint must be a valid URL");
}
if (getClaims().get(OidcProviderMetadataClaimNames.END_SESSION_ENDPOINT) != null) {
validateURL(getClaims().get(OidcProviderMetadataClaimNames.END_SESSION_ENDPOINT),
"endSessionEndpoint must be a valid URL");
}
}
@SuppressWarnings("unchecked")
private void addClaimToClaimList(String name, String value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
getClaims().computeIfAbsent(name, (k) -> new LinkedList<String>());
|
((List<String>) getClaims().get(name)).add(value);
}
@SuppressWarnings("unchecked")
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
getClaims().computeIfAbsent(name, (k) -> new LinkedList<String>());
List<String> values = (List<String>) getClaims().get(name);
valuesConsumer.accept(values);
}
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\OidcProviderConfiguration.java
| 1
|
请完成以下Java代码
|
protected void prepare()
{
for (ProcessInfoParameter para : getParametersAsArray())
{
final String name = para.getParameterName();
if (para.getParameter() == null)
{
continue;
}
else if (name.equals(PARAM_AD_User_ID))
{
p_AD_User_ID = para.getParameterAsInt();
}
}
}
@Override
protected String doIt()
{
Check.assume(p_AD_User_ID > 0, "User should not be empty! ");
final int targetUser_ID = getRecord_ID();
Check.assume(targetUser_ID > 0, "There is no record selected! ");
final I_AD_User targetUser = Services.get(IUserDAO.class).getById(targetUser_ID);
Check.assume(targetUser.isSystemUser(), "Selected user is not system user! ");
final String whereClause = I_AD_TreeBar.COLUMNNAME_AD_User_ID + " = ? ";
final List<I_AD_TreeBar> treBars = new TypedSqlQuery<I_AD_TreeBar>(getCtx(), I_AD_TreeBar.class, whereClause, get_TrxName())
.setOnlyActiveRecords(true)
.setParameters(p_AD_User_ID)
.list();
int cnt = 0;
for (final I_AD_TreeBar treeBar : treBars)
{
if (!existsAlready(targetUser_ID, treeBar.getNode_ID()))
{
final I_AD_TreeBar tb = InterfaceWrapperHelper.create(getCtx(), I_AD_TreeBar.class, get_TrxName());
tb.setAD_Org_ID(treeBar.getAD_Org_ID());
tb.setNode_ID(treeBar.getNode_ID());
tb.setAD_User_ID(targetUser_ID);
InterfaceWrapperHelper.save(tb);
cnt++;
}
|
}
return "Count: " + cnt;
}
/**
* check if the TreeBar already exists
*/
private boolean existsAlready(final int AD_User_ID, final int Node_ID)
{
final String whereClause = I_AD_TreeBar.COLUMNNAME_AD_User_ID + " = ? AND "
+ I_AD_TreeBar.COLUMNNAME_Node_ID + " = ?";
return new TypedSqlQuery<I_AD_TreeBar>(getCtx(), I_AD_TreeBar.class, whereClause, get_TrxName())
.setOnlyActiveRecords(true)
.setParameters(AD_User_ID, Node_ID)
.anyMatch();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\process\AD_User_CopyFavoritesPanel.java
| 1
|
请完成以下Java代码
|
public static String normalizeFilterFactoryName(Class<? extends GatewayFilterFactory> clazz) {
return removeGarbage(clazz.getSimpleName().replace(GatewayFilterFactory.class.getSimpleName(), ""));
}
public static String normalizeGlobalFilterName(Class<? extends GlobalFilter> clazz) {
return removeGarbage(clazz.getSimpleName().replace(GlobalFilter.class.getSimpleName(), "")).replace("Filter",
"");
}
public static String normalizeFilterFactoryNameAsProperty(Class<? extends GatewayFilterFactory> clazz) {
return normalizeToCanonicalPropertyFormat(normalizeFilterFactoryName(clazz));
}
public static String normalizeGlobalFilterNameAsProperty(Class<? extends GlobalFilter> filterClass) {
return normalizeToCanonicalPropertyFormat(normalizeGlobalFilterName(filterClass));
}
public static String normalizeToCanonicalPropertyFormat(String name) {
Matcher matcher = NAME_PATTERN.matcher(name);
StringBuffer stringBuffer = new StringBuffer();
while (matcher.find()) {
if (stringBuffer.length() != 0) {
matcher.appendReplacement(stringBuffer, "-" + matcher.group(1));
}
else {
|
matcher.appendReplacement(stringBuffer, matcher.group(1));
}
}
return stringBuffer.toString().toLowerCase(Locale.ROOT);
}
private static String removeGarbage(String s) {
int garbageIdx = s.indexOf("$Mockito");
if (garbageIdx > 0) {
return s.substring(0, garbageIdx);
}
return s;
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\NameUtils.java
| 1
|
请完成以下Java代码
|
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;
}
public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); }
/** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent
|
*/
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoiceBatch.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.