instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public Date getTimeBefore(Date endTime) {
// FUTURE_TODO: implement QUARTZ-423
return null;
}
/**
* NOT YET IMPLEMENTED: Returns the final time that the
* <code>CronExpression</code> will match.
*/
public Date getFinalFireTime() {
// FUTURE_TODO: implement QUARTZ-423
return null;
}
protected boolean isLeapYear(int year) {
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
}
protected int getLastDayOfMonth(int monthNum, int year) {
switch (monthNum) {
case 1:
return 31;
case 2:
return (isLeapYear(year)) ? 29 : 28;
case 3:
return 31;
case 4:
return 30;
case 5:
return 31;
case 6:
return 30;
case 7:
return 31;
case 8:
return 31;
case 9:
return 30;
|
case 10:
return 31;
case 11:
return 30;
case 12:
return 31;
default:
throw new IllegalArgumentException("Illegal month number: "
+ monthNum);
}
}
private void readObject(java.io.ObjectInputStream stream)
throws java.io.IOException, ClassNotFoundException {
stream.defaultReadObject();
try {
buildExpression(cronExpression);
} catch (Exception ignore) {
} // never happens
}
@Override
@Deprecated
public Object clone() {
return new CronExpression(this);
}
}
class ValueSet {
public int value;
public int pos;
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\cron\CronExpression.java
| 1
|
请完成以下Java代码
|
public final class DeviceId
{
private final String value;
private DeviceId(@NonNull final String value)
{
this.value = StringUtils.trimBlankToNull(value);
if (this.value == null)
{
throw new AdempiereException("Invalid deviceId: " + value);
}
}
@JsonCreator
public static DeviceId ofString(@NonNull final String value)
{
return new DeviceId(value);
}
@Nullable
public static DeviceId ofNullableString(@Nullable final String value)
{
final String valueNorm = StringUtils.trimBlankToNull(value);
|
return valueNorm != null ? new DeviceId(valueNorm) : null;
}
@Override
@Deprecated
public String toString()
{
return getAsString();
}
@JsonValue
public String getAsString()
{
return value;
}
public static boolean equals(@Nullable final DeviceId deviceId1, @Nullable final DeviceId deviceId2) {return Objects.equals(deviceId1, deviceId2);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\accessor\DeviceId.java
| 1
|
请完成以下Java代码
|
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getSuggest() {
return suggest;
}
public void setSuggest(String suggest) {
this.suggest = suggest;
}
public Integer getBusinessSystemId() {
return businessSystemId;
}
public void setBusinessSystemId(Integer businessSystemId) {
this.businessSystemId = businessSystemId;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getOccurCount() {
return occurCount;
}
public void setOccurCount(Integer occurCount) {
this.occurCount = occurCount;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Date getResponsedTime() {
return responsedTime;
}
public void setResponsedTime(Date responsedTime) {
this.responsedTime = responsedTime;
}
public String getResponsedBy() {
return responsedBy;
}
public void setResponsedBy(String responsedBy) {
this.responsedBy = responsedBy;
}
public Date getResolvedTime() {
return resolvedTime;
}
public void setResolvedTime(Date resolvedTime) {
this.resolvedTime = resolvedTime;
}
public String getResolvedBy() {
|
return resolvedBy;
}
public void setResolvedBy(String resolvedBy) {
this.resolvedBy = resolvedBy;
}
public Date getClosedTime() {
return closedTime;
}
public void setClosedTime(Date closedTime) {
this.closedTime = closedTime;
}
public String getClosedBy() {
return closedBy;
}
public void setClosedBy(String closedBy) {
this.closedBy = closedBy;
}
@Override
public String toString() {
return "Event{" +
"id=" + id +
", rawEventId=" + rawEventId +
", host=" + host +
", ip=" + ip +
", source=" + source +
", type=" + type +
", startTime=" + startTime +
", endTime=" + endTime +
", content=" + content +
", dataType=" + dataType +
", suggest=" + suggest +
", businessSystemId=" + businessSystemId +
", departmentId=" + departmentId +
", status=" + status +
", occurCount=" + occurCount +
", owner=" + owner +
", responsedTime=" + responsedTime +
", responsedBy=" + responsedBy +
", resolvedTime=" + resolvedTime +
", resolvedBy=" + resolvedBy +
", closedTime=" + closedTime +
", closedBy=" + closedBy +
'}';
}
}
|
repos\springBoot-master\springboot-shiro\src\main\java\com\us\bean\Event.java
| 1
|
请完成以下Java代码
|
public int hashCode() {
int hash = 3;
hash = 79 * hash + Objects.hashCode(this.name);
hash = 79 * hash + this.age;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
|
if (getClass() != obj.getClass()) {
return false;
}
final AuthorNameAge other = (AuthorNameAge) obj;
if (this.age != other.age) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoViaClassBasedProjections\src\main\java\com\bookstore\projection\AuthorNameAge.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ProductId getCommissionProduct(@NonNull final ConditionsId conditionsId)
{
final I_C_Flatrate_Conditions conditionsRecord = InterfaceWrapperHelper.loadOutOfTrx(conditionsId, I_C_Flatrate_Conditions.class);
final TypeConditions typeConditions = TypeConditions.ofCode(conditionsRecord.getType_Conditions());
switch (typeConditions)
{
case COMMISSION:
final I_C_HierarchyCommissionSettings commissionSettings = InterfaceWrapperHelper.loadOutOfTrx(conditionsRecord.getC_HierarchyCommissionSettings_ID(), I_C_HierarchyCommissionSettings.class);
return ProductId.ofRepoId(commissionSettings.getCommission_Product_ID());
case MEDIATED_COMMISSION:
final I_C_MediatedCommissionSettings mediatedCommissionSettings = InterfaceWrapperHelper.loadOutOfTrx(conditionsRecord.getC_MediatedCommissionSettings_ID(), I_C_MediatedCommissionSettings.class);
return ProductId.ofRepoId(mediatedCommissionSettings.getCommission_Product_ID());
case MARGIN_COMMISSION:
final I_C_Customer_Trade_Margin customerTradeMargin = InterfaceWrapperHelper.loadOutOfTrx(conditionsRecord.getC_Customer_Trade_Margin_ID(), I_C_Customer_Trade_Margin.class);
return ProductId.ofRepoId(customerTradeMargin.getCommission_Product_ID());
case LICENSE_FEE:
final I_C_LicenseFeeSettings licenseFeeSettings = InterfaceWrapperHelper.loadOutOfTrx(conditionsRecord.getC_LicenseFeeSettings_ID(), I_C_LicenseFeeSettings.class);
return ProductId.ofRepoId(licenseFeeSettings.getCommission_Product_ID());
default:
throw new AdempiereException("Unexpected typeConditions for C_Flatrate_Conditions_ID:" + conditionsId)
.appendParametersToMessage()
.setParameter("typeConditions", typeConditions);
}
}
|
public boolean productPreventsCommissioning(@Nullable final ProductId productId)
{
if (productId == null)
{
return false; // no product also means nothing is prevented
}
final IProductDAO productDAO = Services.get(IProductDAO.class);
final I_M_Product productRecord = productDAO.getById(productId);
if (!productRecord.isCommissioned())
{
logger.debug("M_Product_ID={} of invoice candidate has Commissioned=false; -> not going to invoke commission system", productRecord.getM_Product_ID());
}
return !productRecord.isCommissioned();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\CommissionProductService.java
| 2
|
请完成以下Java代码
|
public class BulkDeleteOperation {
protected String statement;
protected Object parameter;
public BulkDeleteOperation(String statement, Object parameter) {
this.statement = statement;
this.parameter = parameter;
}
public void execute(SqlSession sqlSession, Class<? extends Entity> clazz) {
sqlSession.delete(statement, parameter);
}
public String getStatement() {
return statement;
}
|
public void setStatement(String statement) {
this.statement = statement;
}
public Object getParameter() {
return parameter;
}
public void setParameter(Object parameter) {
this.parameter = parameter;
}
@Override
public String toString() {
return "bulk delete: " + statement + "(" + parameter + ")";
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\db\BulkDeleteOperation.java
| 1
|
请完成以下Java代码
|
public boolean isClientOnly()
{
return this == ClientOnly;
}
/**
* @return true if it has Organization flag set
*/
public boolean isOrganization()
{
return (accesses & Organization.accesses) > 0;
}
/**
* @return true if it has only the Organization flag set (i.e. it's {@value #Organization})
*/
public boolean isOrganizationOnly()
{
return this == Organization;
}
/**
* @return user friendly AD_Message of this access level.
*/
public String getAD_Message()
{
return adMessage;
}
/**
* Gets user friendly description of enabled flags.
*
* e.g. "3 - Client - Org"
*
* @return user friendly description of enabled flags
*/
public String getDescription()
{
final StringBuilder accessLevelInfo = new StringBuilder();
|
accessLevelInfo.append(getAccessLevelString());
if (isSystem())
{
accessLevelInfo.append(" - System");
}
if (isClient())
{
accessLevelInfo.append(" - Client");
}
if (isOrganization())
{
accessLevelInfo.append(" - Org");
}
return accessLevelInfo.toString();
}
// --------------------------------------
// Pre-indexed values for optimization
private static ImmutableMap<Integer, TableAccessLevel> accessLevelInt2accessLevel;
static
{
final ImmutableMap.Builder<Integer, TableAccessLevel> builder = new ImmutableMap.Builder<Integer, TableAccessLevel>();
for (final TableAccessLevel l : values())
{
builder.put(l.getAccessLevelInt(), l);
}
accessLevelInt2accessLevel = builder.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\TableAccessLevel.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PlainSqlEntityFieldBinding implements SqlEntityFieldBinding
{
public static PlainSqlEntityFieldBinding mandatoryIntField(final String columnName)
{
return builder()
.columnName(columnName)
.widgetType(DocumentFieldWidgetType.Integer)
.mandatory(true)
.build();
}
String columnName;
SqlSelectValue sqlSelectValue;
DocumentFieldWidgetType widgetType;
Class<?> sqlValueClass;
SqlOrderByValue sqlOrderBy;
boolean virtualColumn;
boolean mandatory;
@Builder
private PlainSqlEntityFieldBinding(
@NonNull final String columnName,
final SqlSelectValue sqlSelectValue,
|
@NonNull final DocumentFieldWidgetType widgetType,
final Class<?> sqlValueClass,
final SqlOrderByValue sqlOrderBy,
final boolean virtualColumn,
final boolean mandatory)
{
this.columnName = columnName;
this.sqlSelectValue = sqlSelectValue;
this.widgetType = widgetType;
this.sqlValueClass = sqlValueClass != null ? sqlValueClass : widgetType.getValueClass();
this.sqlOrderBy = sqlOrderBy;
this.virtualColumn = virtualColumn;
this.mandatory = mandatory;
}
@Override
public boolean isMandatory()
{
return mandatory;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\PlainSqlEntityFieldBinding.java
| 2
|
请完成以下Java代码
|
final class ClassPathIndexFile {
private final File root;
private final Set<String> lines;
private ClassPathIndexFile(File root, List<String> lines) {
this.root = root;
this.lines = lines.stream().map(this::extractName).collect(Collectors.toCollection(LinkedHashSet::new));
}
private String extractName(String line) {
if (line.startsWith("- \"") && line.endsWith("\"")) {
return line.substring(3, line.length() - 1);
}
throw new IllegalStateException("Malformed classpath index line [" + line + "]");
}
int size() {
return this.lines.size();
}
boolean containsEntry(String name) {
if (name == null || name.isEmpty()) {
return false;
}
return this.lines.contains(name);
}
List<URL> getUrls() {
return this.lines.stream().map(this::asUrl).toList();
}
private URL asUrl(String line) {
try {
return new File(this.root, line).toURI().toURL();
}
catch (MalformedURLException ex) {
throw new IllegalStateException(ex);
}
}
|
static ClassPathIndexFile loadIfPossible(File root, String location) throws IOException {
return loadIfPossible(root, new File(root, location));
}
private static ClassPathIndexFile loadIfPossible(File root, File indexFile) throws IOException {
if (indexFile.exists() && indexFile.isFile()) {
List<String> lines = Files.readAllLines(indexFile.toPath())
.stream()
.filter(ClassPathIndexFile::lineHasText)
.toList();
return new ClassPathIndexFile(root, lines);
}
return null;
}
private static boolean lineHasText(String line) {
return !line.trim().isEmpty();
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\ClassPathIndexFile.java
| 1
|
请完成以下Java代码
|
protected @Nullable Object headerValueToAddIn(@Nullable Header header) {
if (header == null || header.value() == null) {
return null;
}
String mapped = mapRawIn(header.key(), header.value());
return mapped != null ? mapped : header.value();
}
@Nullable
private String mapRawIn(String header, byte[] value) {
Boolean asString = this.rawMappedHeaders.get(header);
if (Boolean.TRUE.equals(asString)) {
return new String(value, this.charset);
}
return null;
}
/**
* A matcher for headers.
* @since 2.3
*/
protected interface HeaderMatcher {
/**
* Return true if the header matches.
* @param headerName the header name.
* @return true for a match.
*/
boolean matchHeader(String headerName);
/**
* Return true if this matcher is a negative matcher.
* @return true for a negative matcher.
*/
boolean isNegated();
}
/**
* A matcher that never matches a set of headers.
* @since 2.3
*/
protected static class NeverMatchHeaderMatcher implements HeaderMatcher {
private final Set<String> neverMatchHeaders;
protected NeverMatchHeaderMatcher(String... headers) {
this.neverMatchHeaders = Arrays.stream(headers)
.collect(Collectors.toSet());
}
@Override
public boolean matchHeader(String headerName) {
return this.neverMatchHeaders.contains(headerName);
}
@Override
public boolean isNegated() {
return true;
}
}
/**
* A pattern-based header matcher that matches if the specified
* header matches the specified simple pattern.
* <p> The {@code negate == true} state indicates if the matching should be treated as "not matched".
* @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
*/
protected static class SimplePatternBasedHeaderMatcher implements HeaderMatcher {
private static final LogAccessor LOGGER =
new LogAccessor(LogFactory.getLog(SimplePatternBasedHeaderMatcher.class));
private final String pattern;
|
private final boolean negate;
protected SimplePatternBasedHeaderMatcher(String pattern) {
this(pattern.startsWith("!") ? pattern.substring(1) : pattern, pattern.startsWith("!"));
}
SimplePatternBasedHeaderMatcher(String pattern, boolean negate) {
Assert.notNull(pattern, "Pattern must no be null");
this.pattern = pattern.toLowerCase(Locale.ROOT);
this.negate = negate;
}
@Override
public boolean matchHeader(String headerName) {
String header = headerName.toLowerCase(Locale.ROOT);
if (PatternMatchUtils.simpleMatch(this.pattern, header)) {
LOGGER.debug(() ->
MessageFormat.format(
"headerName=[{0}] WILL " + (this.negate ? "NOT " : "")
+ "be mapped, matched pattern=" + (this.negate ? "!" : "") + "{1}",
headerName, this.pattern));
return true;
}
return false;
}
@Override
public boolean isNegated() {
return this.negate;
}
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\AbstractKafkaHeaderMapper.java
| 1
|
请完成以下Java代码
|
public int getC_MembershipMonth_ID()
{
return get_ValueAsInt(COLUMNNAME_C_MembershipMonth_ID);
}
@Override
public org.compiere.model.I_C_Year getC_Year()
{
return get_ValueAsPO(COLUMNNAME_C_Year_ID, org.compiere.model.I_C_Year.class);
}
@Override
public void setC_Year(final org.compiere.model.I_C_Year C_Year)
{
set_ValueFromPO(COLUMNNAME_C_Year_ID, org.compiere.model.I_C_Year.class, C_Year);
}
@Override
public void setC_Year_ID (final int C_Year_ID)
{
if (C_Year_ID < 1)
set_Value (COLUMNNAME_C_Year_ID, null);
else
set_Value (COLUMNNAME_C_Year_ID, C_Year_ID);
|
}
@Override
public int getC_Year_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Year_ID);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_ValueNoCheck (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\compiere\model\X_C_MembershipMonth.java
| 1
|
请完成以下Java代码
|
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 Message {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String text;
public Message() {
}
public Message(String text) {
this.text = text;
}
public String getText() {
|
return text;
}
public void setText(String text) {
this.text = text;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
|
repos\tutorials-master\persistence-modules\java-jpa-4\src\main\java\com\baeldung\jpa\stringcast\Message.java
| 2
|
请完成以下Java代码
|
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getExternalTaskId() {
return externalTaskId;
}
public void setExternalTaskId(String externalTaskId) {
this.externalTaskId = externalTaskId;
}
|
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContextEntry.java
| 1
|
请完成以下Java代码
|
public void setIdAttribute(String namespaceUri, String localName, String value) {
setAttribute(namespaceUri, localName, value, true);
}
public void removeAttribute(String localName) {
removeAttribute(getNamespaceURI(), localName);
}
public void removeAttribute(String namespaceUri, String localName) {
synchronized(document) {
XmlQName xmlQName = new XmlQName(this, namespaceUri, localName);
if (xmlQName.hasLocalNamespace()) {
element.removeAttributeNS(null, xmlQName.getLocalName());
}
else {
element.removeAttributeNS(xmlQName.getNamespaceUri(), xmlQName.getLocalName());
}
}
}
public String getTextContent() {
synchronized(document) {
return element.getTextContent();
}
}
public void setTextContent(String textContent) {
synchronized(document) {
element.setTextContent(textContent);
}
}
public void addCDataSection(String data) {
synchronized (document) {
CDATASection cdataSection = document.createCDATASection(data);
element.appendChild(cdataSection);
}
}
public ModelElementInstance getModelElementInstance() {
synchronized(document) {
return (ModelElementInstance) element.getUserData(MODEL_ELEMENT_KEY);
}
}
public void setModelElementInstance(ModelElementInstance modelElementInstance) {
synchronized(document) {
element.setUserData(MODEL_ELEMENT_KEY, modelElementInstance, null);
}
}
public String registerNamespace(String namespaceUri) {
synchronized(document) {
String lookupPrefix = lookupPrefix(namespaceUri);
if (lookupPrefix == null) {
// check if a prefix is known
String prefix = XmlQName.KNOWN_PREFIXES.get(namespaceUri);
// check if prefix is not already used
if (prefix != null && getRootElement() != null &&
getRootElement().hasAttribute(XMLNS_ATTRIBUTE_NS_URI, prefix)) {
|
prefix = null;
}
if (prefix == null) {
// generate prefix
prefix = ((DomDocumentImpl) getDocument()).getUnusedGenericNsPrefix();
}
registerNamespace(prefix, namespaceUri);
return prefix;
}
else {
return lookupPrefix;
}
}
}
public void registerNamespace(String prefix, String namespaceUri) {
synchronized(document) {
element.setAttributeNS(XMLNS_ATTRIBUTE_NS_URI, XMLNS_ATTRIBUTE + ":" + prefix, namespaceUri);
}
}
public String lookupPrefix(String namespaceUri) {
synchronized(document) {
return element.lookupPrefix(namespaceUri);
}
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DomElementImpl that = (DomElementImpl) o;
return element.equals(that.element);
}
public int hashCode() {
return element.hashCode();
}
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\instance\DomElementImpl.java
| 1
|
请完成以下Java代码
|
default GatewayFilter apply(@Nullable String routeId, Consumer<C> consumer) {
C config = newConfig();
consumer.accept(config);
return apply(routeId, config);
}
default GatewayFilter apply(Consumer<C> consumer) {
C config = newConfig();
consumer.accept(config);
return apply(config);
}
default Class<C> getConfigClass() {
throw new UnsupportedOperationException("getConfigClass() not implemented");
}
@Override
default C newConfig() {
|
throw new UnsupportedOperationException("newConfig() not implemented");
}
GatewayFilter apply(C config);
default GatewayFilter apply(@Nullable String routeId, C config) {
if (config instanceof HasRouteId) {
HasRouteId hasRouteId = (HasRouteId) config;
hasRouteId.setRouteId(routeId);
}
return apply(config);
}
default String name() {
// TODO: deal with proxys
return NameUtils.normalizeFilterFactoryName(getClass());
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\GatewayFilterFactory.java
| 1
|
请完成以下Java代码
|
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
log.trace("[{}] Received msg: {}", ctx.channel().id(), msg);
if (msg instanceof HAProxyMessage) {
HAProxyMessage proxyMsg = (HAProxyMessage) msg;
if (proxyMsg.sourceAddress() != null && proxyMsg.sourcePort() > 0) {
InetSocketAddress address = new InetSocketAddress(proxyMsg.sourceAddress(), proxyMsg.sourcePort());
if (!context.checkAddress(address)) {
closeChannel(ctx);
} else {
log.trace("[{}] Setting address: {}", ctx.channel().id(), address);
ctx.channel().attr(MqttTransportService.ADDRESS).set(address);
// We no longer need this channel in the pipeline. Similar to HAProxyMessageDecoder
ctx.pipeline().remove(this);
}
} else {
log.trace("Received local health-check connection message: {}", proxyMsg);
closeChannel(ctx);
}
}
}
|
private void closeChannel(ChannelHandlerContext ctx) {
while (ctx.pipeline().last() != this) {
ChannelHandler handler = ctx.pipeline().removeLast();
if (handler instanceof ChannelInboundHandlerAdapter) {
try {
((ChannelInboundHandlerAdapter) handler).channelUnregistered(ctx);
} catch (Exception e) {
log.error("Failed to unregister channel: [{}]", ctx, e);
}
}
}
ctx.pipeline().remove(this);
ctx.close();
}
}
|
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\limits\ProxyIpFilter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static JsonReportError toJsonReportError(final Throwable throwable, final String adLanguage)
{
final Throwable cause = AdempiereException.extractCause(throwable);
final String adLanguageEffective = Check.isNotBlank(adLanguage)
? adLanguage
: Language.getBaseAD_Language();
return JsonReportError.builder()
.message(AdempiereException.extractMessageTrl(cause).translate(adLanguageEffective))
.stackTrace(Trace.toOneLineStackTraceString(cause.getStackTrace()))
.parameters(extractParameters(throwable, adLanguageEffective))
.build();
}
private static Map<String, String> extractParameters(@NonNull final Throwable throwable, @NonNull final String adLanguage)
{
return AdempiereException.extractParameters(throwable)
.entrySet()
.stream()
.map(e -> GuavaCollectors.entry(e.getKey(), convertParameterToJson(e.getValue(), adLanguage)))
.collect(GuavaCollectors.toImmutableMap());
}
@NonNull
private static String convertParameterToJson(final Object value, final String adLanguage)
{
if (Null.isNull(value))
|
{
return "<null>";
}
else if (value instanceof ITranslatableString)
{
return ((ITranslatableString)value).translate(adLanguage);
}
else if (value instanceof RepoIdAware)
{
return String.valueOf(((RepoIdAware)value).getRepoId());
}
else if (value instanceof ReferenceListAwareEnum)
{
return ((ReferenceListAwareEnum)value).getCode();
}
else
{
return value.toString();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\rest\ReportRestController.java
| 2
|
请完成以下Java代码
|
protected void doRollback() throws Exception {
// managed transaction, mark rollback-only if not done so already
Transaction transaction = getTransaction();
int status = transaction.getStatus();
if (status != Status.STATUS_NO_TRANSACTION && status != Status.STATUS_ROLLEDBACK) {
transaction.setRollbackOnly();
}
}
@Override
protected void addTransactionListener(TransactionState transactionState, final TransactionListener transactionListener, CommandContext commandContext) throws Exception{
getTransaction().registerSynchronization(new JtaTransactionStateSynchronization(transactionState, transactionListener, commandContext));
}
protected Transaction getTransaction() {
try {
return transactionManager.getTransaction();
} catch (Exception e) {
throw LOG.exceptionWhileInteractingWithTransaction("getting transaction", e);
}
}
@Override
|
protected boolean isTransactionActiveInternal() throws Exception {
return transactionManager.getStatus() != Status.STATUS_MARKED_ROLLBACK && transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION;
}
public static class JtaTransactionStateSynchronization extends TransactionStateSynchronization implements Synchronization {
public JtaTransactionStateSynchronization(TransactionState transactionState, TransactionListener transactionListener, CommandContext commandContext) {
super(transactionState, transactionListener, commandContext);
}
@Override
protected boolean isRolledBack(int status) {
return Status.STATUS_ROLLEDBACK == status;
}
@Override
protected boolean isCommitted(int status) {
return Status.STATUS_COMMITTED == status;
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\jta\JakartaTransactionContext.java
| 1
|
请完成以下Java代码
|
public class ListAndSetContainsBenchmark {
public static void main(String[] args) throws IOException, RunnerException {
Options opt = new OptionsBuilder()
.include(ListAndSetContainsBenchmark.class.getSimpleName())
.forks(1)
.addProfiler("gc")
.build();
new Runner(opt).run();
}
@Benchmark
public void searchElementInArrayList(Params param, Blackhole blackhole) {
blackhole.consume(param.arrayList.contains(param.searchElement));
}
@Benchmark
public void searchElementInHashSet(Params param, Blackhole blackhole) {
blackhole.consume(param.hashSet.contains(param.searchElement));
}
@State(Scope.Benchmark)
|
public static class Params {
@Param({"5000000"})
public int searchElement;
@Param({"10000000"})
public int collectionSize;
public List<Integer> arrayList;
public Set<Integer> hashSet;
@Setup(Level.Iteration)
public void setup() {
arrayList = new ArrayList<>();
hashSet = new HashSet<>();
for (int i = 0; i < collectionSize; i++) {
arrayList.add(i);
hashSet.add(i);
}
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-list-3\src\main\java\com\baeldung\listandset\benchmark\ListAndSetContainsBenchmark.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DemoApplicationConfiguration {
private Logger logger = LoggerFactory.getLogger(DemoApplicationConfiguration.class);
@Bean
public UserDetailsService myUserDetailsService() {
InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
String[][] usersGroupsAndRoles = {
{ "bob", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam" },
{ "john", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam" },
{ "hannah", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam" },
{ "other", "password", "ROLE_ACTIVITI_USER", "GROUP_otherTeam" },
{ "system", "password", "ROLE_ACTIVITI_USER" },
{ "admin", "password", "ROLE_ACTIVITI_ADMIN" },
};
for (String[] user : usersGroupsAndRoles) {
List<String> authoritiesStrings = asList(Arrays.copyOfRange(user, 2, user.length));
logger.info(
"> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings + "]"
);
inMemoryUserDetailsManager.createUser(
new User(
user[0],
passwordEncoder().encode(user[1]),
|
authoritiesStrings
.stream()
.map(s -> new SimpleGrantedAuthority(s))
.collect(Collectors.toList())
)
);
}
return inMemoryUserDetailsManager;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
|
repos\Activiti-develop\activiti-examples\activiti-api-basic-full-example-bean\src\main\java\org\activiti\examples\DemoApplicationConfiguration.java
| 2
|
请完成以下Java代码
|
public int getC_JobRemuneration_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_JobRemuneration_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Remuneration getC_Remuneration() throws RuntimeException
{
return (I_C_Remuneration)MTable.get(getCtx(), I_C_Remuneration.Table_Name)
.getPO(getC_Remuneration_ID(), get_TrxName()); }
/** Set Remuneration.
@param C_Remuneration_ID
Wage or Salary
*/
public void setC_Remuneration_ID (int C_Remuneration_ID)
{
if (C_Remuneration_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Remuneration_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Remuneration_ID, Integer.valueOf(C_Remuneration_ID));
}
/** Get Remuneration.
@return Wage or Salary
*/
public int getC_Remuneration_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Remuneration_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
|
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_JobRemuneration.java
| 1
|
请完成以下Java代码
|
public class BaseResp<T> {
/**
* 返回码
*/
private int code;
/**
* 返回信息描述
*/
private String message;
/**
* 返回数据
*/
private T data;
private long currentTime;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public long getCurrentTime() {
return currentTime;
}
public void setCurrentTime(long currentTime) {
this.currentTime = currentTime;
}
public BaseResp(){}
|
/**
*
* @param code 错误码
* @param message 信息
* @param data 数据
*/
public BaseResp(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
this.currentTime = new Date().getTime();
}
/**
* 不带数据的返回结果
* @param resultStatus
*/
public BaseResp(ResultStatus resultStatus) {
this.code = resultStatus.getErrorCode();
this.message = resultStatus.getErrorMsg();
this.data = data;
this.currentTime = new Date().getTime();
}
/**
* 带数据的返回结果
* @param resultStatus
* @param data
*/
public BaseResp(ResultStatus resultStatus, T data) {
this.code = resultStatus.getErrorCode();
this.message = resultStatus.getErrorMsg();
this.data = data;
this.currentTime = new Date().getTime();
}
}
|
repos\spring-boot-quick-master\quick-exception\src\main\java\com\quick\exception\utils\BaseResp.java
| 1
|
请完成以下Java代码
|
public void deleteHistoricVariableInstancesByTaskId(String taskId) {
if (isHistoryEnabled()) {
HistoricVariableInstanceQuery historicProcessVariableQuery = new HistoricVariableInstanceQueryImpl().taskIdIn(taskId);
List<HistoricVariableInstance> historicProcessVariables = historicProcessVariableQuery.list();
for(HistoricVariableInstance historicProcessVariable : historicProcessVariables) {
((HistoricVariableInstanceEntity) historicProcessVariable).delete();
}
}
}
public DbOperation addRemovalTimeToVariableInstancesByRootProcessInstanceId(String rootProcessInstanceId, Date removalTime, Integer batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("rootProcessInstanceId", rootProcessInstanceId);
parameters.put("removalTime", removalTime);
parameters.put("maxResults", batchSize);
return getDbEntityManager()
.updatePreserveOrder(HistoricVariableInstanceEntity.class, "updateHistoricVariableInstancesByRootProcessInstanceId", parameters);
}
public DbOperation addRemovalTimeToVariableInstancesByProcessInstanceId(String processInstanceId, Date removalTime, Integer batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processInstanceId", processInstanceId);
parameters.put("removalTime", removalTime);
parameters.put("maxResults", batchSize);
return getDbEntityManager()
.updatePreserveOrder(HistoricVariableInstanceEntity.class, "updateHistoricVariableInstancesByProcessInstanceId", parameters);
}
|
@SuppressWarnings("unchecked")
public List<HistoricVariableInstance> findHistoricVariableInstancesByNativeQuery(Map<String, Object> parameterMap, int firstResult, int
maxResults) {
return getDbEntityManager().selectListWithRawParameter("selectHistoricVariableInstanceByNativeQuery", parameterMap, firstResult, maxResults);
}
public long findHistoricVariableInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbEntityManager().selectOne("selectHistoricVariableInstanceCountByNativeQuery", parameterMap);
}
protected void configureQuery(HistoricVariableInstanceQueryImpl query) {
getAuthorizationManager().configureHistoricVariableInstanceQuery(query);
getTenantManager().configureQuery(query);
}
public DbOperation deleteHistoricVariableInstancesByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
parameters.put("batchSize", batchSize);
return getDbEntityManager()
.deletePreserveOrder(HistoricVariableInstanceEntity.class, "deleteHistoricVariableInstancesByRemovalTime",
new ListQueryParameterObject(parameters, 0, batchSize));
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricVariableInstanceManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class TitleId implements RepoIdAware
{
@JsonCreator
public static TitleId ofRepoId(final int repoId)
{
return new TitleId(repoId);
}
public static TitleId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new TitleId(repoId) : null;
}
public static int toRepoId(@Nullable final TitleId titleId)
{
return toRepoIdOr(titleId, -1);
}
public static int toRepoIdOr(
@Nullable final TitleId titleId,
|
final int defaultValue)
{
return titleId != null ? titleId.getRepoId() : defaultValue;
}
int repoId;
private TitleId(final int titleRepoId)
{
this.repoId = Check.assumeGreaterThanZero(titleRepoId, "titleRepoId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\title\TitleId.java
| 2
|
请完成以下Java代码
|
public Integer value1() {
return getId();
}
@Override
public String value2() {
return getFirstName();
}
@Override
public String value3() {
return getLastName();
}
@Override
public Integer value4() {
return getAge();
}
@Override
public AuthorRecord value1(Integer value) {
setId(value);
return this;
}
@Override
public AuthorRecord value2(String value) {
setFirstName(value);
return this;
}
@Override
public AuthorRecord value3(String value) {
setLastName(value);
return this;
}
@Override
public AuthorRecord value4(Integer value) {
setAge(value);
return this;
}
@Override
public AuthorRecord values(Integer value1, String value2, String value3, Integer value4) {
|
value1(value1);
value2(value2);
value3(value3);
value4(value4);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached AuthorRecord
*/
public AuthorRecord() {
super(Author.AUTHOR);
}
/**
* Create a detached, initialised AuthorRecord
*/
public AuthorRecord(Integer id, String firstName, String lastName, Integer age) {
super(Author.AUTHOR);
set(0, id);
set(1, firstName);
set(2, lastName);
set(3, age);
}
}
|
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\records\AuthorRecord.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RedisMessageListener extends MessageListenerAdapter {
private static final Logger logger = LoggerFactory.getLogger(RedisPublisher.class);
@Autowired
CacheManager cacheManager;
@Override
public void onMessage(Message message, byte[] pattern) {
super.onMessage(message, pattern);
ChannelTopicEnum channelTopic = ChannelTopicEnum.getChannelTopicEnum(new String(message.getChannel()));
logger.info("redis消息订阅者接收到频道【{}】发布的消息。消息内容:{}", channelTopic.getChannelTopicStr(), message.toString().getBytes());
// 解析订阅发布的信息,获取缓存的名称和缓存的key
String ms = new String(message.getBody());
@SuppressWarnings("unchecked")
Map<String, Object> map = JSON.parseObject(ms, HashMap.class);
String cacheName = (String) map.get("cacheName");
Object key = map.get("key");
// 根据缓存名称获取多级缓存
Cache cache = cacheManager.getCache(cacheName);
// 判断缓存是否是多级缓存
if (cache != null && cache instanceof LayeringCache) {
switch (channelTopic) {
|
case REDIS_CACHE_DELETE_TOPIC:
// 获取一级缓存,并删除一级缓存数据
((LayeringCache) cache).getFirstCache().evict(key);
logger.info("删除一级缓存{}数据,key:{}", cacheName, key.toString().getBytes());
break;
case REDIS_CACHE_CLEAR_TOPIC:
// 获取一级缓存,并删除一级缓存数据
((LayeringCache) cache).getFirstCache().clear();
logger.info("清除一级缓存{}数据", cacheName);
break;
default:
logger.info("接收到没有定义的订阅消息频道数据");
break;
}
}
}
}
|
repos\spring-boot-student-master\spring-boot-student-cache-redis-caffeine\src\main\java\com\xiaolyuh\cache\listener\RedisMessageListener.java
| 2
|
请完成以下Spring Boot application配置
|
#redis\u914D\u7F6E
#redis
#database name
spring.redis.database=0
#server host
#spring.redis.host=192.168.3.34
spring.redis.host=192.168.1.2
#server passw
|
ord
spring.redis.password=
#connection port
spring.redis.port=6378
|
repos\spring-boot-student-master\spring-boot-student-hystrix\src\main\resources\application-dev2.properties
| 2
|
请完成以下Java代码
|
public class PRTADPrinterHWTypeConverter
{
protected final transient ObjectFactory factory = new ObjectFactory();
public List<PRTADPrinterHWType> mkPRTADPrinterHWs(final PrinterHWList printerHWList, final int sessionId)
{
final List<PrinterHW> printers = printerHWList.getHwPrinters();
if (printerHWList == null || printerHWList.getHwPrinters().isEmpty())
{
return Collections.emptyList();
}
final List<PRTADPrinterHWType> result = new ArrayList<PRTADPrinterHWType>();
for (final PrinterHW printer : printers)
{
if (printer == null)
{
throw new IllegalArgumentException("Printer needs to be set.");
}
// first, add the printer
final PRTADPrinterHWType printerHW = mkPRTADPrinterHW(printer);
printerHW.setADSessionIDAttr(BigInteger.valueOf(sessionId));
// next, add it's size, tray and calibration
if (printer.getPrinterHWMediaSizes() != null)
{
for (final PrinterHWMediaSize size : printer.getPrinterHWMediaSizes())
{
PRTADPrinterHWMediaSizeType printerHWsize = mkPRTADPrinterHWMediaSize(size);
printerHW.getPRTADPrinterHWMediaSize().add(printerHWsize);
}
}
if (printer.getPrinterHWMediaTrays() != null)
{
for (final PrinterHWMediaTray tray : printer.getPrinterHWMediaTrays())
{
PRTADPrinterHWMediaTrayType printerHWtray = mkPRTADPrinterHWMediaTray(tray);
printerHW.getPRTADPrinterHWMediaTray().add(printerHWtray);
}
}
result.add(printerHW);
}
return result;
}
private PRTADPrinterHWType mkPRTADPrinterHW(final PrinterHW printer)
{
final PRTADPrinterHWType printerHW = new PRTADPrinterHWType();
|
printerHW.setName(printer.getName());
// ADempiere Specific Data
printerHW.setReplicationEventAttr(ReplicationEventEnum.AfterChange);
printerHW.setReplicationModeAttr(ReplicationModeEnum.Table);
printerHW.setReplicationTypeAttr(ReplicationTypeEnum.Merge);
printerHW.setVersionAttr(JAXBConstants.PRT_AD_PRINTER_HW_FORMAT_VERSION);
return printerHW;
}
private PRTADPrinterHWMediaSizeType mkPRTADPrinterHWMediaSize(final PrinterHWMediaSize size)
{
final PRTADPrinterHWMediaSizeType printerHWMediaSize = new PRTADPrinterHWMediaSizeType();
printerHWMediaSize.setName(size.getName());
return printerHWMediaSize;
}
private PRTADPrinterHWMediaTrayType mkPRTADPrinterHWMediaTray(final PrinterHWMediaTray tray)
{
final PRTADPrinterHWMediaTrayType printerHWMediaTray = new PRTADPrinterHWMediaTrayType();
printerHWMediaTray.setName(tray.getName());
printerHWMediaTray.setTrayNumber(BigInteger.valueOf(Integer.valueOf(tray.getTrayNumber())));
return printerHWMediaTray;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.esb.base\src\main\java\de\metas\printing\esb\base\inout\bean\PRTADPrinterHWTypeConverter.java
| 1
|
请完成以下Java代码
|
public void modifyVariables(PatchVariablesDto patch) {
VariableMap variableModifications = null;
try {
variableModifications = VariableValueDto.toMap(patch.getModifications(), engine, objectMapper);
} catch (RestException e) {
String errorMessage = String.format("Cannot modify variables for %s: %s", getResourceTypeName(), e.getMessage());
throw new InvalidRequestException(e.getStatus(), e, errorMessage);
}
List<String> variableDeletions = patch.getDeletions();
try {
updateVariableEntities(variableModifications, variableDeletions);
} catch (AuthorizationException e) {
throw e;
} catch (ProcessEngineException e) {
String errorMessage = String.format("Cannot modify variables for %s %s: %s", getResourceTypeName(), resourceId, e.getMessage());
throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage);
}
|
}
protected abstract VariableMap getVariableEntities(boolean deserializeValues);
protected abstract void updateVariableEntities(VariableMap variables, List<String> deletions);
protected abstract TypedValue getVariableEntity(String variableKey, boolean deserializeValue);
protected abstract void setVariableEntity(String variableKey, TypedValue variableValue);
protected abstract void removeVariableEntity(String variableKey);
protected abstract String getResourceTypeName();
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\impl\AbstractVariablesResource.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Article {\n");
sb.append(" customerNumber: ").append(toIndentedString(customerNumber)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" description: ").append(toIndentedString(description)).append("\n");
sb.append(" additionalDescription: ").append(toIndentedString(additionalDescription)).append("\n");
sb.append(" manufacturer: ").append(toIndentedString(manufacturer)).append("\n");
sb.append(" manufacturerNumber: ").append(toIndentedString(manufacturerNumber)).append("\n");
sb.append(" therapyIds: ").append(toIndentedString(therapyIds)).append("\n");
sb.append(" billableTherapies: ").append(toIndentedString(billableTherapies)).append("\n");
sb.append(" productGroupId: ").append(toIndentedString(productGroupId)).append("\n");
sb.append(" size: ").append(toIndentedString(size)).append("\n");
sb.append(" inventoryType: ").append(toIndentedString(inventoryType)).append("\n");
sb.append(" prescriptionType: ").append(toIndentedString(prescriptionType)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" statusAnnotation: ").append(toIndentedString(statusAnnotation)).append("\n");
sb.append(" medicalAidPositionNumber: ").append(toIndentedString(medicalAidPositionNumber)).append("\n");
sb.append(" unavailableFrom: ").append(toIndentedString(unavailableFrom)).append("\n");
sb.append(" unavailableTo: ").append(toIndentedString(unavailableTo)).append("\n");
sb.append(" stars: ").append(toIndentedString(stars)).append("\n");
sb.append(" assortmentType: ").append(toIndentedString(assortmentType)).append("\n");
sb.append(" pharmacyPrice: ").append(toIndentedString(pharmacyPrice)).append("\n");
sb.append(" fixedPrice: ").append(toIndentedString(fixedPrice)).append("\n");
sb.append(" purchaseRating: ").append(toIndentedString(purchaseRating)).append("\n");
sb.append(" packagingUnits: ").append(toIndentedString(packagingUnits)).append("\n");
|
sb.append(" pharmacyOnly: ").append(toIndentedString(pharmacyOnly)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\Article.java
| 2
|
请完成以下Java代码
|
public void format(LogEvent event, StringBuilder toAppendTo) {
StringBuilder buf = new StringBuilder();
for (PatternFormatter formatter : this.formatters) {
formatter.format(event, buf);
}
if (!buf.isEmpty()) {
AnsiElement element = this.styling;
if (element == null) {
// Assume highlighting
element = LEVELS.get(event.getLevel().intLevel());
element = (element != null) ? element : AnsiColor.GREEN;
}
appendAnsiString(toAppendTo, buf.toString(), element);
}
}
protected void appendAnsiString(StringBuilder toAppendTo, String in, AnsiElement element) {
toAppendTo.append(AnsiOutput.toString(element, in));
}
/**
* Creates a new instance of the class. Required by Log4J2.
* @param config the configuration
* @param options the options
* @return a new instance, or {@code null} if the options are invalid
|
*/
public static @Nullable ColorConverter newInstance(@Nullable Configuration config, @Nullable String[] options) {
if (options.length < 1) {
LOGGER.error("Incorrect number of options on style. Expected at least 1, received {}", options.length);
return null;
}
if (options[0] == null) {
LOGGER.error("No pattern supplied on style");
return null;
}
PatternParser parser = PatternLayout.createPatternParser(config);
List<PatternFormatter> formatters = parser.parse(options[0]);
AnsiElement element = (options.length != 1) ? ELEMENTS.get(options[1]) : null;
return new ColorConverter(formatters, element);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\log4j2\ColorConverter.java
| 1
|
请完成以下Java代码
|
public void setReplenishType (java.lang.String ReplenishType)
{
set_Value (COLUMNNAME_ReplenishType, ReplenishType);
}
@Override
public java.lang.String getReplenishType()
{
return (java.lang.String)get_Value(COLUMNNAME_ReplenishType);
}
@Override
public void setTimeToMarket (int TimeToMarket)
{
set_Value (COLUMNNAME_TimeToMarket, Integer.valueOf(TimeToMarket));
}
|
@Override
public int getTimeToMarket()
{
return get_ValueAsInt(COLUMNNAME_TimeToMarket);
}
@Override
public void setWarehouseValue (java.lang.String WarehouseValue)
{
set_Value (COLUMNNAME_WarehouseValue, WarehouseValue);
}
@Override
public java.lang.String getWarehouseValue()
{
return (java.lang.String)get_Value(COLUMNNAME_WarehouseValue);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Replenish.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BPartnerAttachmentsProcessor implements Processor
{
@Override
public void process(final Exchange exchange)
{
final BPartnerAttachmentsRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_ATTACH_FILE_CONTEXT, BPartnerAttachmentsRouteContext.class);
final JsonBPartnerAttachment jsonBPartnerAttachment = context.getJsonBPartnerAttachment();
final JsonAttachmentRequest attachmentRequest = getAttachmentRequest(jsonBPartnerAttachment, context.getExportDirectoriesBasePathNotNull());
exchange.getIn().setBody(attachmentRequest, JsonAttachmentRequest.class);
}
@NonNull
private JsonAttachmentRequest getAttachmentRequest(
@NonNull final JsonBPartnerAttachment jsonBPartnerAttachment,
@NonNull final String basePathForExportDirectories)
{
|
final JsonAttachment attachment = JsonAttachmentUtil.createLocalFileJsonAttachment(basePathForExportDirectories, jsonBPartnerAttachment.getAttachmentFilePath());
return JsonAttachmentRequest.builder()
.targets(ImmutableList.of(JsonExternalReferenceTarget.ofTypeAndId(EXTERNAL_REF_TYPE_BPARTNER, jsonBPartnerAttachment.getMetasfreshId())))
.orgCode(getAuthOrgCode())
.attachment(attachment)
.build();
}
@NonNull
private String getAuthOrgCode()
{
return ((TokenCredentials)SecurityContextHolder.getContext().getAuthentication().getCredentials()).getOrgCode();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\attachment\processor\BPartnerAttachmentsProcessor.java
| 2
|
请完成以下Java代码
|
public class BpmnPlaneImpl extends PlaneImpl implements BpmnPlane {
protected static AttributeReference<BaseElement> bpmnElementAttribute;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(BpmnPlane.class, BPMNDI_ELEMENT_BPMN_PLANE)
.namespaceUri(BPMNDI_NS)
.extendsType(Plane.class)
.instanceProvider(new ModelTypeInstanceProvider<BpmnPlane>() {
public BpmnPlane newInstance(ModelTypeInstanceContext instanceContext) {
return new BpmnPlaneImpl(instanceContext);
}
});
bpmnElementAttribute = typeBuilder.stringAttribute(BPMNDI_ATTRIBUTE_BPMN_ELEMENT)
.qNameAttributeReference(BaseElement.class)
.build();
|
typeBuilder.build();
}
public BpmnPlaneImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public BaseElement getBpmnElement() {
return bpmnElementAttribute.getReferenceTargetElement(this);
}
public void setBpmnElement(BaseElement bpmnElement) {
bpmnElementAttribute.setReferenceTargetElement(this, bpmnElement);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\bpmndi\BpmnPlaneImpl.java
| 1
|
请完成以下Java代码
|
private void registerArchiveAwareTables()
{
final Properties ctx = Env.getCtx();
final List<I_AD_Column> archiveColumns = new Query(ctx, I_AD_Column.Table_Name, I_AD_Column.COLUMNNAME_ColumnName + "=?", ITrx.TRXNAME_None)
.setParameters(org.compiere.model.I_AD_Archive.COLUMNNAME_AD_Archive_ID)
.setOnlyActiveRecords(true)
.list(I_AD_Column.class);
if (archiveColumns.isEmpty())
{
return;
}
//
// Services
final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class);
final AdProcessId processId = adProcessDAO.retrieveProcessIdByClassIfUnique(ExportArchivePDF.class);
|
if (processId == null)
{
final AdempiereException ex = new AdempiereException("No AD_Process_ID found for " + ExportArchivePDF.class);
Archive_Main_Validator.logger.error(ex.getLocalizedMessage(), ex);
return;
}
for (final I_AD_Column column : archiveColumns)
{
if (!DisplayType.isLookup(column.getAD_Reference_ID()))
{
continue;
}
final AdTableId adTableId = AdTableId.ofRepoId(column.getAD_Table_ID());
adProcessDAO.registerTableProcess(adTableId, processId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\interceptor\Archive_Main_Validator.java
| 1
|
请完成以下Java代码
|
public class DefaultOidcUser extends DefaultOAuth2User implements OidcUser {
@Serial
private static final long serialVersionUID = -2378469202439157250L;
private final OidcIdToken idToken;
private final OidcUserInfo userInfo;
/**
* Constructs a {@code DefaultOidcUser} using the provided parameters.
* @param authorities the authorities granted to the user
* @param idToken the {@link OidcIdToken ID Token} containing claims about the user
*/
public DefaultOidcUser(Collection<? extends GrantedAuthority> authorities, OidcIdToken idToken) {
this(authorities, idToken, IdTokenClaimNames.SUB);
}
/**
* Constructs a {@code DefaultOidcUser} using the provided parameters.
* @param authorities the authorities granted to the user
* @param idToken the {@link OidcIdToken ID Token} containing claims about the user
* @param nameAttributeKey the key used to access the user's "name" from
* {@link #getAttributes()}
*/
public DefaultOidcUser(Collection<? extends GrantedAuthority> authorities, OidcIdToken idToken,
String nameAttributeKey) {
this(authorities, idToken, null, nameAttributeKey);
}
/**
* Constructs a {@code DefaultOidcUser} using the provided parameters.
* @param authorities the authorities granted to the user
* @param idToken the {@link OidcIdToken ID Token} containing claims about the user
* @param userInfo the {@link OidcUserInfo UserInfo} containing claims about the user,
* may be {@code null}
*/
public DefaultOidcUser(Collection<? extends GrantedAuthority> authorities, OidcIdToken idToken,
OidcUserInfo userInfo) {
this(authorities, idToken, userInfo, IdTokenClaimNames.SUB);
}
|
/**
* Constructs a {@code DefaultOidcUser} using the provided parameters.
* @param authorities the authorities granted to the user
* @param idToken the {@link OidcIdToken ID Token} containing claims about the user
* @param userInfo the {@link OidcUserInfo UserInfo} containing claims about the user,
* may be {@code null}
* @param nameAttributeKey the key used to access the user's "name" from
* {@link #getAttributes()}
*/
public DefaultOidcUser(Collection<? extends GrantedAuthority> authorities, OidcIdToken idToken,
OidcUserInfo userInfo, String nameAttributeKey) {
super(authorities, OidcUserAuthority.collectClaims(idToken, userInfo), nameAttributeKey);
this.idToken = idToken;
this.userInfo = userInfo;
}
@Override
public Map<String, Object> getClaims() {
return this.getAttributes();
}
@Override
public OidcIdToken getIdToken() {
return this.idToken;
}
@Override
public OidcUserInfo getUserInfo() {
return this.userInfo;
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\user\DefaultOidcUser.java
| 1
|
请完成以下Java代码
|
public static void setDeferredContext(Supplier<SecurityContext> deferredContext) {
strategy.setDeferredContext(deferredContext);
}
/**
* Changes the preferred strategy. Do <em>NOT</em> call this method more than once for
* a given JVM, as it will re-initialize the strategy and adversely affect any
* existing threads using the old strategy.
* @param strategyName the fully qualified class name of the strategy that should be
* used.
*/
public static void setStrategyName(String strategyName) {
SecurityContextHolder.strategyName = strategyName;
initialize();
}
/**
* Use this {@link SecurityContextHolderStrategy}.
*
* Call either {@link #setStrategyName(String)} or this method, but not both.
*
* This method is not thread safe. Changing the strategy while requests are in-flight
* may cause race conditions.
*
* {@link SecurityContextHolder} maintains a static reference to the provided
* {@link SecurityContextHolderStrategy}. This means that the strategy and its members
* will not be garbage collected until you remove your strategy.
*
* To ensure garbage collection, remember the original strategy like so:
*
* <pre>
* SecurityContextHolderStrategy original = SecurityContextHolder.getContextHolderStrategy();
* SecurityContextHolder.setContextHolderStrategy(myStrategy);
* </pre>
*
* And then when you are ready for {@code myStrategy} to be garbage collected you can
* do:
*
* <pre>
* SecurityContextHolder.setContextHolderStrategy(original);
* </pre>
* @param strategy the {@link SecurityContextHolderStrategy} to use
* @since 5.6
*/
public static void setContextHolderStrategy(SecurityContextHolderStrategy strategy) {
Assert.notNull(strategy, "securityContextHolderStrategy cannot be null");
SecurityContextHolder.strategyName = MODE_PRE_INITIALIZED;
|
SecurityContextHolder.strategy = strategy;
initialize();
}
/**
* Allows retrieval of the context strategy. See SEC-1188.
* @return the configured strategy for storing the security context.
*/
public static SecurityContextHolderStrategy getContextHolderStrategy() {
return strategy;
}
/**
* Delegates the creation of a new, empty context to the configured strategy.
*/
public static SecurityContext createEmptyContext() {
return strategy.createEmptyContext();
}
@Override
public String toString() {
return "SecurityContextHolder[strategy='" + strategy.getClass().getSimpleName() + "'; initializeCount="
+ initializeCount + "]";
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\core\context\SecurityContextHolder.java
| 1
|
请完成以下Java代码
|
private boolean isPickingSlotRackSystem(final PickingCandidate pickingCandidate)
{
final PickingSlotId pickingSlotId = pickingCandidate.getPickingSlotId();
return pickingSlotId != null && huPickingSlotBL.isPickingRackSystem(pickingSlotId);
}
private void close(final PickingCandidate pickingCandidate)
{
try
{
pickingCandidate.assertProcessed();
final PickingSlotId pickingSlotId = pickingCandidate.getPickingSlotId();
if (pickingSlotId != null)
{
huPickingSlotBL.addToPickingSlotQueue(pickingSlotId, pickingCandidate.getPackedToHuId());
}
changeStatusToProcessedAndSave(pickingCandidate);
}
catch (final Exception ex)
|
{
if (failOnError)
{
throw AdempiereException.wrapIfNeeded(ex).setParameter("pickingCandidate", pickingCandidate);
}
else
{
logger.warn("Failed closing {}. Skipped", pickingCandidate, ex);
}
}
}
private void changeStatusToProcessedAndSave(final PickingCandidate pickingCandidate)
{
pickingCandidate.changeStatusToClosed();
pickingCandidateRepository.save(pickingCandidate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\ClosePickingCandidateCommand.java
| 1
|
请完成以下Java代码
|
public final Quantity getQtyForProductStorages(@NonNull final I_C_UOM uom)
{
return getProductStorages()
.stream()
.map(productStorage -> productStorage.getQty(uom))
.reduce(Quantity.zero(uom), Quantity::add);
}
@Override
public Quantity getQtyForProductStorages()
{
final List<IHUProductStorage> productStorages = getProductStorages();
if (Check.isEmpty(productStorages))
{
final I_C_UOM uomWEach = Services.get(IUOMDAO.class).getEachUOM();
return Quantity.zero(CoalesceUtil.coalesce(getC_UOMOrNull(), uomWEach));
}
return getQtyForProductStorages(productStorages.get(0).getC_UOM());
}
private final IHUProductStorage createProductStorage(final I_M_HU_Storage storage)
{
final ProductId productId = ProductId.ofRepoId(storage.getM_Product_ID());
final I_C_UOM uom = IHUStorageBL.extractUOM(storage);
final HUProductStorage productStorage = new HUProductStorage(this, productId, uom);
return productStorage;
}
@Override
public boolean isVirtual()
{
return virtualHU;
}
@Override
public I_M_HU getM_HU()
{
return hu;
}
@Override
public String toString()
{
return "HUStorage [hu=" + hu + ", virtualHU=" + virtualHU + "]";
}
@Override
public I_C_UOM getC_UOMOrNull()
{
return dao.getC_UOMOrNull(hu);
}
@Override
public boolean isSingleProductWithQtyEqualsTo(@NonNull final ProductId productId, @NonNull final Quantity qty)
|
{
final List<IHUProductStorage> productStorages = getProductStorages();
return productStorages.size() == 1
&& ProductId.equals(productStorages.get(0).getProductId(), productId)
&& productStorages.get(0).getQty(qty.getUOM()).compareTo(qty) == 0;
}
@Override
public boolean isSingleProductStorageMatching(@NonNull final ProductId productId)
{
final List<IHUProductStorage> productStorages = getProductStorages();
return isSingleProductStorageMatching(productStorages, productId);
}
private static boolean isSingleProductStorageMatching(@NonNull final List<IHUProductStorage> productStorages, @NotNull final ProductId productId)
{
return productStorages.size() == 1 && ProductId.equals(productStorages.get(0).getProductId(), productId);
}
@Override
public boolean isEmptyOrSingleProductStorageMatching(@NonNull final ProductId productId)
{
final List<IHUProductStorage> productStorages = getProductStorages();
return productStorages.isEmpty() || isSingleProductStorageMatching(productStorages, productId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUStorage.java
| 1
|
请完成以下Java代码
|
public final class JwtTypeValidator implements OAuth2TokenValidator<Jwt> {
private final Collection<String> validTypes;
private boolean allowEmpty;
public JwtTypeValidator(Collection<String> validTypes) {
Assert.notEmpty(validTypes, "validTypes cannot be empty");
this.validTypes = new ArrayList<>(validTypes);
}
public JwtTypeValidator(String... validTypes) {
this(List.of(validTypes));
}
/**
* Require that the {@code typ} header be {@code JWT} or absent
*/
public static JwtTypeValidator jwt() {
JwtTypeValidator validator = new JwtTypeValidator(List.of("JWT"));
validator.setAllowEmpty(true);
return validator;
}
/**
* Whether to allow the {@code typ} header to be empty. The default value is
* {@code false}
*/
public void setAllowEmpty(boolean allowEmpty) {
this.allowEmpty = allowEmpty;
}
@Override
|
public OAuth2TokenValidatorResult validate(Jwt token) {
String typ = (String) token.getHeaders().get(JoseHeaderNames.TYP);
if (this.allowEmpty && !StringUtils.hasText(typ)) {
return OAuth2TokenValidatorResult.success();
}
for (String validType : this.validTypes) {
if (validType.equalsIgnoreCase(typ)) {
return OAuth2TokenValidatorResult.success();
}
}
return OAuth2TokenValidatorResult.failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN,
"the given typ value needs to be one of " + this.validTypes,
"https://datatracker.ietf.org/doc/html/rfc7515#section-4.1.9"));
}
}
|
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtTypeValidator.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8088
spring:
ai:
openai:
base-url: https://api.openai.com/
api-key: sk-xxx
embedding:
options:
model: text-davinci-003
chat:
#指定某一个API配置(覆盖全局配置)
api-key
|
: sk-xxx
base-url: http://localhost:11434
options:
model: qwen:0.5b # 模型配置
|
repos\springboot-demo-master\Qwen\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
public void setHR_Payroll_ID (int HR_Payroll_ID)
{
if (HR_Payroll_ID < 1)
set_Value (COLUMNNAME_HR_Payroll_ID, null);
else
set_Value (COLUMNNAME_HR_Payroll_ID, Integer.valueOf(HR_Payroll_ID));
}
/** Get Payroll.
@return Payroll */
public int getHR_Payroll_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_Payroll_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Employee.
@param IsEmployee
Indicates if this Business Partner is an employee
*/
public void setIsEmployee (boolean IsEmployee)
{
set_Value (COLUMNNAME_IsEmployee, Boolean.valueOf(IsEmployee));
}
/** Get Employee.
@return Indicates if this Business Partner is an employee
*/
public boolean isEmployee ()
{
Object oo = get_Value(COLUMNNAME_IsEmployee);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
|
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_List.java
| 1
|
请完成以下Java代码
|
private AdWindowId getWindowId(final I_M_InOut inout)
{
return inout.isSOTrx() ? WINDOW_RETURN_FROM_CUSTOMER : WINDOW_RETURN_TO_VENDOR;
}
private AdMessageKey getNotificationAD_Message(final I_M_InOut inout) {return inout.isSOTrx() ? MSG_Event_RETURN_FROM_CUSTOMER_Generated : MSG_Event_RETURN_TO_VENDOR_Generated;}
private UserId getNotificationRecipientUserId(final I_M_InOut inout)
{
//
// In case of reversal i think we shall notify the current user too
final DocStatus docStatus = DocStatus.ofCode(inout.getDocStatus());
if (docStatus.isReversedOrVoided())
{
final int currentUserId = Env.getAD_User_ID(Env.getCtx()); // current/triggering user
if (currentUserId > 0)
{
return UserId.ofRepoId(currentUserId);
}
|
return UserId.ofRepoId(inout.getUpdatedBy()); // last updated
}
//
// Fallback: notify only the creator
else
{
return UserId.ofRepoId(inout.getCreatedBy());
}
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
Services.get(INotificationBL.class).sendAfterCommit(notifications);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\event\ReturnInOutUserNotificationsProducer.java
| 1
|
请完成以下Java代码
|
public void setExternalId (final String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setExternallyUpdatedAt (final @Nullable java.sql.Timestamp ExternallyUpdatedAt)
{
set_Value (COLUMNNAME_ExternallyUpdatedAt, ExternallyUpdatedAt);
}
@Override
public java.sql.Timestamp getExternallyUpdatedAt()
{
return get_ValueAsTimestamp(COLUMNNAME_ExternallyUpdatedAt);
}
@Override
public void setIsPrivateSale (final boolean IsPrivateSale)
{
set_Value (COLUMNNAME_IsPrivateSale, IsPrivateSale);
}
@Override
public boolean isPrivateSale()
{
return get_ValueAsBoolean(COLUMNNAME_IsPrivateSale);
}
@Override
public void setIsRentalEquipment (final boolean IsRentalEquipment)
{
set_Value (COLUMNNAME_IsRentalEquipment, IsRentalEquipment);
}
@Override
public boolean isRentalEquipment()
{
return get_ValueAsBoolean(COLUMNNAME_IsRentalEquipment);
}
@Override
public void setSalesLineId (final @Nullable String SalesLineId)
{
set_Value (COLUMNNAME_SalesLineId, SalesLineId);
}
|
@Override
public String getSalesLineId()
{
return get_ValueAsString(COLUMNNAME_SalesLineId);
}
@Override
public void setTimePeriod (final @Nullable BigDecimal TimePeriod)
{
set_Value (COLUMNNAME_TimePeriod, TimePeriod);
}
@Override
public BigDecimal getTimePeriod()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TimePeriod);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUnit (final @Nullable String Unit)
{
set_Value (COLUMNNAME_Unit, Unit);
}
@Override
public String getUnit()
{
return get_ValueAsString(COLUMNNAME_Unit);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_OrderedArticleLine.java
| 1
|
请完成以下Java代码
|
public RefundMode extractRefundMode(@NonNull final List<RefundConfig> refundConfigs)
{
final RefundMode refundMode = extractSingleElement(
refundConfigs,
RefundConfig::getRefundMode);
return refundMode;
}
public ProductId extractProductId(@NonNull final List<RefundConfig> refundConfigs)
{
final ProductId productId = extractSingleElement(
refundConfigs,
RefundConfig::getProductId);
return productId;
}
public void assertValid(@NonNull final List<RefundConfig> refundConfigs)
{
Check.assumeNotEmpty(refundConfigs, "refundConfigs");
if (hasDifferentValues(refundConfigs, RefundConfig::getRefundBase))
{
Loggables.addLog("The given refundConfigs need to all have the same RefundBase; refundConfigs={}", refundConfigs);
throw new AdempiereException(MSG_REFUND_CONFIG_SAME_REFUND_BASE).markAsUserValidationError();
}
if (hasDifferentValues(refundConfigs, RefundConfig::getRefundMode))
{
Loggables.addLog("The given refundConfigs need to all have the same RefundMode; refundConfigs={}", refundConfigs);
|
throw new AdempiereException(MSG_REFUND_CONFIG_SAME_REFUND_MODE).markAsUserValidationError();
}
if (RefundMode.APPLY_TO_ALL_QTIES.equals(extractRefundMode(refundConfigs)))
{
// we have one IC with different configs, so those configs need to have the consistent settings
if (hasDifferentValues(refundConfigs, RefundConfig::getInvoiceSchedule))
{
Loggables.addLog(
"Because refundMode={}, all the given refundConfigs need to all have the same invoiceSchedule; refundConfigs={}",
RefundMode.APPLY_TO_ALL_QTIES, refundConfigs);
throw new AdempiereException(MSG_REFUND_CONFIG_SAME_INVOICE_SCHEDULE).markAsUserValidationError();
}
if (hasDifferentValues(refundConfigs, RefundConfig::getRefundInvoiceType))
{
Loggables.addLog(
"Because refundMode={}, all the given refundConfigs need to all have the same refundInvoiceType; refundConfigs={}",
RefundMode.APPLY_TO_ALL_QTIES, refundConfigs);
throw new AdempiereException(MSG_REFUND_CONFIG_SAME_REFUND_INVOICE_TYPE).markAsUserValidationError();
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\RefundConfigs.java
| 1
|
请完成以下Java代码
|
public Aggregation getAggregation(final Properties ctx, final I_C_BPartner bpartner, final boolean isSOTrx, final String aggregationUsageLevel)
{
final IAggregationDAO aggregationDAO = Services.get(IAggregationDAO.class);
final AggregationId aggregationId = getInvoice_Aggregation_ID(bpartner, isSOTrx, aggregationUsageLevel);
final Aggregation aggregation;
if (aggregationId != null)
{
aggregation = aggregationDAO.retrieveAggregation(ctx, aggregationId);
}
else
{
aggregation = aggregationDAO.retrieveDefaultAggregationOrNull(ctx, I_C_Invoice_Candidate.class, isSOTrx, aggregationUsageLevel);
if (aggregation == null)
{
throw new AdempiereException("@NotFound@ @C_Aggregation_ID@ (@IsDefault@=@Y@)"
+ "\n @C_BPartner_ID@: " + bpartner
+ "\n @IsSOTrx@: @" + isSOTrx + "@"
+ "\n @AggregationUsageLevel@: " + aggregationUsageLevel
+ "\n @TableName@: " + I_C_Invoice_Candidate.Table_Name);
}
}
return aggregation;
}
@Override
public IAggregationKeyBuilder<I_C_Invoice_Candidate> getPrepayOrderAggregationKeyBuilder(final Properties ctx)
{
final IAggregationFactory aggregationFactory = Services.get(IAggregationFactory.class);
final AggregationId aggregationId = getPrepayOrder_Invoice_Aggregation_ID();
final IAggregationKeyBuilder<I_C_Invoice_Candidate> aggregation;
if (aggregationId != null)
|
{
aggregation = aggregationFactory.getAggregationKeyBuilder(ctx, I_C_Invoice_Candidate.class, aggregationId);
}
else
{
aggregation = aggregationFactory.getDefaultAggregationKeyBuilder(ctx, I_C_Invoice_Candidate.class, true, X_C_Aggregation.AGGREGATIONUSAGELEVEL_Header);
}
return aggregation;
}
@Nullable
private AggregationId getPrepayOrder_Invoice_Aggregation_ID()
{
return AggregationId.ofRepoIdOrNull(Services.get(ISysConfigBL.class).getIntValue(INVOICE_AGGREGATION_ID_FOR_PREPAYORDER, -1));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceAggregationFactory.java
| 1
|
请完成以下Java代码
|
protected SuspendedJobEntityManager getSuspendedJobEntityManager() {
return getProcessEngineConfiguration().getSuspendedJobEntityManager();
}
protected DeadLetterJobEntityManager getDeadLetterJobEntityManager() {
return getProcessEngineConfiguration().getDeadLetterJobEntityManager();
}
protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricProcessInstanceEntityManager();
}
protected HistoricDetailEntityManager getHistoricDetailEntityManager() {
return getProcessEngineConfiguration().getHistoricDetailEntityManager();
}
protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricActivityInstanceEntityManager();
}
protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricVariableInstanceEntityManager();
}
|
protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricTaskInstanceEntityManager();
}
protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return getProcessEngineConfiguration().getHistoricIdentityLinkEntityManager();
}
protected AttachmentEntityManager getAttachmentEntityManager() {
return getProcessEngineConfiguration().getAttachmentEntityManager();
}
protected CommentEntityManager getCommentEntityManager() {
return getProcessEngineConfiguration().getCommentEntityManager();
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\AbstractManager.java
| 1
|
请完成以下Java代码
|
public CaseInstanceBuilder caseDefinitionTenantId(String tenantId) {
this.caseDefinitionTenantId = tenantId;
isTenantIdSet = true;
return this;
}
public CaseInstanceBuilder caseDefinitionWithoutTenantId() {
this.caseDefinitionTenantId = null;
isTenantIdSet = true;
return this;
}
public CaseInstanceBuilder setVariable(String variableName, Object variableValue) {
ensureNotNull(NotValidException.class, "variableName", variableName);
if (variables == null) {
variables = Variables.createVariables();
}
variables.putValue(variableName, variableValue);
return this;
}
public CaseInstanceBuilder setVariables(Map<String, Object> variables) {
if (variables != null) {
if (this.variables == null) {
this.variables = Variables.fromMap(variables);
}
else {
this.variables.putAll(variables);
}
}
return this;
}
public CaseInstance create() {
if (isTenantIdSet && caseDefinitionId != null) {
throw LOG.exceptionCreateCaseInstanceByIdAndTenantId();
}
try {
CreateCaseInstanceCmd command = new CreateCaseInstanceCmd(this);
if(commandExecutor != null) {
return commandExecutor.execute(command);
} else {
return command.execute(commandContext);
}
} catch (CaseDefinitionNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
} catch (NullValueException e) {
throw new NotValidException(e.getMessage(), e);
} catch (CaseIllegalStateTransitionException e) {
throw new NotAllowedException(e.getMessage(), e);
|
}
}
// getters ////////////////////////////////////
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getBusinessKey() {
return businessKey;
}
public VariableMap getVariables() {
return variables;
}
public String getCaseDefinitionTenantId() {
return caseDefinitionTenantId;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\CaseInstanceBuilderImpl.java
| 1
|
请完成以下Java代码
|
public void deleteTaggedAndInvalidateCache(final Collection<Integer> invoiceCandidateIds)
{
if (Check.isEmpty(invoiceCandidateIds))
{
return;
}
invoiceCandDAO.deleteRecomputeMarkersAndInvalidateCache(this, invoiceCandidateIds);
}
@Override
public int untag()
{
return invoiceCandDAO.untag(this);
}
@Override
public Iterator<I_C_Invoice_Candidate> retrieveInvoiceCandidates()
{
final Properties ctx = getCtx();
final String trxName = getTrxName();
final InvoiceCandRecomputeTag recomputeTag = getRecomputeTag();
return invoiceCandDAO.fetchInvalidInvoiceCandidates(ctx, recomputeTag, trxName);
}
@Override
public IInvoiceCandRecomputeTagger setContext(final Properties ctx, final String trxName)
{
this._ctx = ctx;
this._trxName = trxName;
return this;
}
@Override
public final Properties getCtx()
{
Check.assumeNotNull(_ctx, "_ctx not null");
return _ctx;
}
String getTrxName()
{
return _trxName;
}
@Override
public IInvoiceCandRecomputeTagger setRecomputeTag(final InvoiceCandRecomputeTag recomputeTag)
{
this._recomputeTagToUseForTagging = recomputeTag;
return this;
}
private void generateRecomputeTagIfNotSet()
{
// Do nothing if the recompute tag was already generated
if (!InvoiceCandRecomputeTag.isNull(_recomputeTag))
{
return;
}
// Use the recompute tag which was suggested
if (!InvoiceCandRecomputeTag.isNull(_recomputeTagToUseForTagging))
{
_recomputeTag = _recomputeTagToUseForTagging;
return;
}
// Generate a new recompute tag
_recomputeTag = invoiceCandDAO.generateNewRecomputeTag();
}
/**
* @return recompute tag; never returns null
*/
final InvoiceCandRecomputeTag getRecomputeTag()
{
Check.assumeNotNull(_recomputeTag, "_recomputeTag not null");
return _recomputeTag;
}
@Override
public InvoiceCandRecomputeTagger setLockedBy(final ILock lockedBy)
{
this._lockedBy = lockedBy;
return this;
}
/* package */ILock getLockedBy()
{
return _lockedBy;
|
}
@Override
public InvoiceCandRecomputeTagger setTaggedWith(@Nullable final InvoiceCandRecomputeTag tag)
{
_taggedWith = tag;
return this;
}
@Override
public InvoiceCandRecomputeTagger setTaggedWithNoTag()
{
return setTaggedWith(InvoiceCandRecomputeTag.NULL);
}
@Override
public IInvoiceCandRecomputeTagger setTaggedWithAnyTag()
{
return setTaggedWith(null);
}
/* package */
@Nullable
InvoiceCandRecomputeTag getTaggedWith()
{
return _taggedWith;
}
@Override
public InvoiceCandRecomputeTagger setLimit(final int limit)
{
this._limit = limit;
return this;
}
/* package */int getLimit()
{
return _limit;
}
@Override
public void setOnlyInvoiceCandidateIds(@NonNull final InvoiceCandidateIdsSelection onlyInvoiceCandidateIds)
{
this.onlyInvoiceCandidateIds = onlyInvoiceCandidateIds;
}
@Override
@Nullable
public final InvoiceCandidateIdsSelection getOnlyInvoiceCandidateIds()
{
return onlyInvoiceCandidateIds;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandRecomputeTagger.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static final class SpringResource implements net.shibboleth.shared.resource.Resource {
private final Resource resource;
SpringResource(Resource resource) {
this.resource = resource;
}
@Override
public boolean exists() {
return this.resource.exists();
}
@Override
public boolean isReadable() {
return this.resource.isReadable();
}
@Override
public boolean isOpen() {
return this.resource.isOpen();
}
@Override
public URL getURL() throws IOException {
return this.resource.getURL();
}
@Override
public URI getURI() throws IOException {
return this.resource.getURI();
}
@Override
public File getFile() throws IOException {
return this.resource.getFile();
}
@NonNull
@Override
public InputStream getInputStream() throws IOException {
return this.resource.getInputStream();
}
@Override
public long contentLength() throws IOException {
return this.resource.contentLength();
}
@Override
public long lastModified() throws IOException {
return this.resource.lastModified();
}
@Override
public net.shibboleth.shared.resource.Resource createRelativeResource(String relativePath)
|
throws IOException {
return new SpringResource(this.resource.createRelative(relativePath));
}
@Override
public String getFilename() {
return this.resource.getFilename();
}
@Override
public String getDescription() {
return this.resource.getDescription();
}
}
}
private static final class CriteriaSetResolverWrapper extends MetadataResolverAdapter {
CriteriaSetResolverWrapper(MetadataResolver metadataResolver) {
super(metadataResolver);
}
@Override
EntityDescriptor resolveSingle(EntityIdCriterion entityId) throws Exception {
return super.metadataResolver.resolveSingle(new CriteriaSet(entityId));
}
@Override
Iterable<EntityDescriptor> resolve(EntityRoleCriterion role) throws Exception {
return super.metadataResolver.resolve(new CriteriaSet(role));
}
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\registration\OpenSaml5AssertingPartyMetadataRepository.java
| 2
|
请完成以下Java代码
|
public class MigratingIncident implements MigratingInstance {
protected IncidentEntity incident;
protected ScopeImpl targetScope;
protected String targetJobDefinitionId;
public MigratingIncident(IncidentEntity incident, ScopeImpl targetScope) {
this.incident = incident;
this.targetScope = targetScope;
}
public void setTargetJobDefinitionId(String targetJobDefinitionId) {
this.targetJobDefinitionId = targetJobDefinitionId;
}
@Override
public boolean isDetached() {
return incident.getExecutionId() == null;
}
public void detachState() {
incident.setExecution(null);
}
public void attachState(MigratingScopeInstance newOwningInstance) {
attachTo(newOwningInstance.resolveRepresentativeExecution());
}
@Override
public void attachState(MigratingTransitionInstance targetTransitionInstance) {
attachTo(targetTransitionInstance.resolveRepresentativeExecution());
}
public void migrateState() {
incident.setActivityId(targetScope.getId());
incident.setProcessDefinitionId(targetScope.getProcessDefinition().getId());
|
incident.setJobDefinitionId(targetJobDefinitionId);
migrateHistory();
}
protected void migrateHistory() {
HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel();
if (historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_MIGRATE, this)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricIncidentMigrateEvt(incident);
}
});
}
}
public void migrateDependentEntities() {
// nothing to do
}
protected void attachTo(ExecutionEntity execution) {
incident.setExecution(execution);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingIncident.java
| 1
|
请完成以下Java代码
|
public boolean isMandatory()
{
return IsMandatory;
}
public boolean isKey()
{
return IsKey;
}
public boolean isParent()
{
return IsParent;
}
public boolean isStaleable()
{
return IsStaleable;
}
public boolean isLookup()
{
return org.compiere.util.DisplayType.isLookup(displayType);
}
public int getAD_Sequence_ID()
{
return AD_Sequence_ID;
}
public boolean isIdentifier()
{
return IsIdentifier;
}
@Nullable
public String getReferencedTableNameOrNull()
{
return _referencedTableName.orElse(null);
|
}
private static Optional<String> computeReferencedTableName(
final int displayType,
@Nullable final TableName adReferenceValueTableName)
{
// Special lookups (Location, Locator etc)
final String refTableName = DisplayType.getTableName(displayType);
if (refTableName != null)
{
return Optional.of(refTableName);
}
if (DisplayType.isLookup(displayType) && adReferenceValueTableName != null)
{
return Optional.of(adReferenceValueTableName.getAsString());
}
return Optional.empty();
}
public boolean isPasswordColumn()
{
return DisplayType.isPassword(ColumnName, displayType);
}
} // POInfoColumn
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POInfoColumn.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ObjectName getObjectName(Object managedBean, @Nullable String beanKey) throws MalformedObjectNameException {
ObjectName name = super.getObjectName(managedBean, beanKey);
if (this.ensureUniqueRuntimeObjectNames) {
return JmxUtils.appendIdentityToObjectName(name, managedBean);
}
if (parentContextContainsSameBean(this.applicationContext, beanKey)) {
return appendToObjectName(name, "context", ObjectUtils.getIdentityHexString(this.applicationContext));
}
return name;
}
private boolean parentContextContainsSameBean(ApplicationContext context, @Nullable String beanKey) {
if (context.getParent() == null) {
return false;
}
try {
ApplicationContext parent = this.applicationContext.getParent();
Assert.state(parent != null, "'parent' must not be null");
|
Assert.state(beanKey != null, "'beanKey' must not be null");
parent.getBean(beanKey);
return true;
}
catch (BeansException ex) {
return parentContextContainsSameBean(context.getParent(), beanKey);
}
}
private ObjectName appendToObjectName(ObjectName name, String key, String value)
throws MalformedObjectNameException {
Hashtable<String, String> keyProperties = name.getKeyPropertyList();
keyProperties.put(key, value);
return ObjectNameManager.getInstance(name.getDomain(), keyProperties);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\jmx\ParentAwareNamingStrategy.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public int hashCode() {
return Objects.hash(maintenanceCode, maintenanceInterval, lastServiceDate, nextServiceDate);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DeviceToCreateMaintenances {\n");
sb.append(" maintenanceCode: ").append(toIndentedString(maintenanceCode)).append("\n");
sb.append(" maintenanceInterval: ").append(toIndentedString(maintenanceInterval)).append("\n");
sb.append(" lastServiceDate: ").append(toIndentedString(lastServiceDate)).append("\n");
sb.append(" nextServiceDate: ").append(toIndentedString(nextServiceDate)).append("\n");
sb.append("}");
|
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\DeviceToCreateMaintenances.java
| 2
|
请完成以下Java代码
|
public void setFilterChainDecorator(WebFilterChainDecorator filterChainDecorator) {
Assert.notNull(filterChainDecorator, "filterChainDecorator cannot be null");
this.filterChainDecorator = filterChainDecorator;
}
/**
* A strategy for decorating the provided filter chain with one that accounts for the
* {@link SecurityFilterChain} for a given request.
*
* @author Josh Cummings
* @since 6.0
*/
public interface WebFilterChainDecorator {
/**
* Provide a new {@link WebFilterChain} that accounts for needed security
* considerations when there are no security filters.
* @param original the original {@link WebFilterChain}
* @return a security-enabled {@link WebFilterChain}
*/
default WebFilterChain decorate(WebFilterChain original) {
return decorate(original, Collections.emptyList());
}
/**
* Provide a new {@link WebFilterChain} that accounts for the provided filters as
* well as the original filter chain.
* @param original the original {@link WebFilterChain}
* @param filters the security filters
* @return a security-enabled {@link WebFilterChain} that includes the provided
* filters
*/
WebFilterChain decorate(WebFilterChain original, List<WebFilter> filters);
}
/**
* A {@link WebFilterChainDecorator} that uses the {@link DefaultWebFilterChain}
*
* @author Josh Cummings
* @since 6.0
*/
public static class DefaultWebFilterChainDecorator implements WebFilterChainDecorator {
|
/**
* {@inheritDoc}
*/
@Override
public WebFilterChain decorate(WebFilterChain original) {
return original;
}
/**
* {@inheritDoc}
*/
@Override
public WebFilterChain decorate(WebFilterChain original, List<WebFilter> filters) {
return new DefaultWebFilterChain(original::filter, filters);
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\WebFilterChainProxy.java
| 1
|
请完成以下Java代码
|
public int size()
{
assertNotAll();
return documentIds.size();
}
public boolean contains(final DocumentId documentId)
{
return all || documentIds.contains(documentId);
}
public Set<DocumentId> toSet()
{
assertNotAll();
return documentIds;
}
public <T> ImmutableSet<T> toSet(@NonNull final Function<DocumentId, T> mapper)
{
assertNotAll();
if (documentIds.isEmpty())
{
return ImmutableSet.of();
}
return documentIds.stream().map(mapper).collect(ImmutableSet.toImmutableSet());
}
@NonNull
public ImmutableList<DocumentId> toImmutableList()
{
assertNotAll();
if (documentIds.isEmpty())
{
return ImmutableList.of();
}
return ImmutableList.copyOf(documentIds);
}
@NonNull
public <T> ImmutableList<T> toImmutableList(@NonNull final Function<DocumentId, T> mapper)
{
assertNotAll();
if (documentIds.isEmpty())
{
return ImmutableList.of();
}
return documentIds.stream().map(mapper).collect(ImmutableList.toImmutableList());
}
public Set<Integer> toIntSet()
{
return toSet(DocumentId::toInt);
}
public <ID extends RepoIdAware> ImmutableSet<ID> toIds(@NonNull final Function<Integer, ID> idMapper)
{
return toSet(idMapper.compose(DocumentId::toInt));
}
public <ID extends RepoIdAware> ImmutableSet<ID> toIdsFromInt(@NonNull final IntFunction<ID> idMapper)
{
return toSet(documentId -> idMapper.apply(documentId.toInt()));
}
/**
* Similar to {@link #toIds(Function)} but this returns a list, so it preserves the order
*/
public <ID extends RepoIdAware> ImmutableList<ID> toIdsList(@NonNull final Function<Integer, ID> idMapper)
{
return toImmutableList(idMapper.compose(DocumentId::toInt));
}
public Set<String> toJsonSet()
{
if (all)
{
return ALL_StringSet;
}
|
return toSet(DocumentId::toJson);
}
public SelectionSize toSelectionSize()
{
if (isAll())
{
return SelectionSize.ofAll();
}
return SelectionSize.ofSize(size());
}
public DocumentIdsSelection addAll(@NonNull final DocumentIdsSelection documentIdsSelection)
{
if (this.isEmpty())
{
return documentIdsSelection;
}
else if (documentIdsSelection.isEmpty())
{
return this;
}
if (this.all)
{
return this;
}
else if (documentIdsSelection.all)
{
return documentIdsSelection;
}
final ImmutableSet<DocumentId> combinedIds = Stream.concat(this.stream(), documentIdsSelection.stream()).collect(ImmutableSet.toImmutableSet());
final DocumentIdsSelection result = DocumentIdsSelection.of(combinedIds);
if (this.equals(result))
{
return this;
}
else if (documentIdsSelection.equals(result))
{
return documentIdsSelection;
}
else
{
return result;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentIdsSelection.java
| 1
|
请完成以下Java代码
|
public class MRefTable extends X_AD_Ref_Table
{
/**
*
*/
private static final long serialVersionUID = 9123965213307214868L;
/**
* Standard Constructor
* @param ctx context
* @param AD_Reference_ID id warning if you are referring to reference list or table type should be used AD_Reference_Value_ID
* @param trxName trx
*/
public MRefTable (Properties ctx, int AD_Reference_ID, String trxName)
{
super (ctx, AD_Reference_ID, trxName);
if (AD_Reference_ID == 0)
{
// setAD_Table_ID (0);
// setAD_Display (0);
// setAD_Key (0);
setEntityType (ENTITYTYPE_UserMaintained); // U
setIsValueDisplayed (false);
}
} // MRefTable
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
public MRefTable (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MRefTable
|
// metas: begin
private static final CCache<Integer, MRefTable> s_cache = new CCache<Integer, MRefTable>(Table_Name, 50, 0);
public static MRefTable get(Properties ctx, int AD_Reference_ID)
{
if (AD_Reference_ID <= 0)
return null;
MRefTable retValue = s_cache.get(AD_Reference_ID);
if (retValue != null)
return retValue;
retValue = new Query(ctx, Table_Name, COLUMNNAME_AD_Reference_ID + "=?", null)
.setParameters(AD_Reference_ID)
.firstOnly(MRefTable.class);
if (retValue != null)
{
s_cache.put(AD_Reference_ID, retValue);
}
return retValue;
}
// metas: end
} // MRefTable
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MRefTable.java
| 1
|
请完成以下Java代码
|
public Void execute(CommandContext commandContext) {
ensureNotNull("jobId", jobId);
final JobEntity job = commandContext.getDbEntityManager().selectById(JobEntity.class, jobId);
final ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
final IdentityService identityService = processEngineConfiguration.getIdentityService();
final JobExecutorContext jobExecutorContext = Context.getJobExecutorContext();
if (job == null) {
if (jobExecutorContext != null) {
// CAM-1842
// Job was acquired but does not exist anymore. This is not a problem.
// It usually means that the job has been deleted after it was acquired which can happen if the
// the activity instance corresponding to the job is cancelled.
LOG.debugAcquiredJobNotFound(jobId);
return null;
} else {
throw LOG.jobNotFoundException(jobId);
}
}
jobFailureCollector.setJob(job);
if (jobExecutorContext == null) { // if null, then we are not called by the job executor
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkUpdateJob(job);
}
// write a user operation log since we're not called by the job executor
commandContext.getOperationLogManager().logJobOperation(UserOperationLogEntry.OPERATION_TYPE_EXECUTE,
jobId, job.getJobDefinitionId(), job.getProcessInstanceId(), job.getProcessDefinitionId(),
job.getProcessDefinitionKey(), PropertyChange.EMPTY_CHANGE);
} else {
jobExecutorContext.setCurrentJob(job);
|
// if the job is called by the job executor then set the tenant id of the job
// as authenticated tenant to enable tenant checks
String tenantId = job.getTenantId();
if (tenantId != null) {
identityService.setAuthentication(null, null, Collections.singletonList(tenantId));
}
}
try {
// register as command context close lister to intercept exceptions on flush
commandContext.registerCommandContextListener(jobFailureCollector);
commandContext.setCurrentJob(job);
job.execute(commandContext);
} catch (Throwable t) {
String failedActivityId = Context.getCommandInvocationContext()
.getProcessDataContext()
.getLatestActivityId();
jobFailureCollector.setFailedActivityId(failedActivityId);
throw t;
} finally {
if (jobExecutorContext != null) {
jobExecutorContext.setCurrentJob(null);
identityService.clearAuthentication();
}
}
return null;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ExecuteJobsCmd.java
| 1
|
请完成以下Java代码
|
public int getC_Project_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Project_ID);
}
/**
* C_Project_Role AD_Reference_ID=540905
* Reference name: c_project_role
*/
public static final int C_PROJECT_ROLE_AD_Reference_ID=540905;
/** Project Manager = PM */
public static final String C_PROJECT_ROLE_ProjectManager = "PM";
/** Project Team Member = PT */
public static final String C_PROJECT_ROLE_ProjectTeamMember = "PT";
/** Dozent = SD */
public static final String C_PROJECT_ROLE_Dozent = "SD";
/** Teilnehmer = ST */
public static final String C_PROJECT_ROLE_Teilnehmer = "ST";
/** Ansprechpartner Hotel = SH */
public static final String C_PROJECT_ROLE_AnsprechpartnerHotel = "SH";
/** Aussendienst = SA */
public static final String C_PROJECT_ROLE_Aussendienst = "SA";
@Override
public void setC_Project_Role (final @Nullable java.lang.String C_Project_Role)
{
set_Value (COLUMNNAME_C_Project_Role, C_Project_Role);
}
@Override
public java.lang.String getC_Project_Role()
{
return get_ValueAsString(COLUMNNAME_C_Project_Role);
}
@Override
public void setC_Project_User_ID (final int C_Project_User_ID)
{
if (C_Project_User_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Project_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Project_User_ID, C_Project_User_ID);
}
@Override
public int getC_Project_User_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Project_User_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsAccommodationBooking (final boolean IsAccommodationBooking)
{
set_Value (COLUMNNAME_IsAccommodationBooking, IsAccommodationBooking);
|
}
@Override
public boolean isAccommodationBooking()
{
return get_ValueAsBoolean(COLUMNNAME_IsAccommodationBooking);
}
@Override
public org.compiere.model.I_R_Status getR_Status()
{
return get_ValueAsPO(COLUMNNAME_R_Status_ID, org.compiere.model.I_R_Status.class);
}
@Override
public void setR_Status(final org.compiere.model.I_R_Status R_Status)
{
set_ValueFromPO(COLUMNNAME_R_Status_ID, org.compiere.model.I_R_Status.class, R_Status);
}
@Override
public void setR_Status_ID (final int R_Status_ID)
{
if (R_Status_ID < 1)
set_Value (COLUMNNAME_R_Status_ID, null);
else
set_Value (COLUMNNAME_R_Status_ID, R_Status_ID);
}
@Override
public int getR_Status_ID()
{
return get_ValueAsInt(COLUMNNAME_R_Status_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_User.java
| 1
|
请完成以下Java代码
|
public class Dijkstra
{
public static List<Vertex> compute(Graph graph)
{
List<Vertex> resultList = new LinkedList<Vertex>();
Vertex[] vertexes = graph.getVertexes();
List<EdgeFrom>[] edgesTo = graph.getEdgesTo();
double[] d = new double[vertexes.length];
Arrays.fill(d, Double.MAX_VALUE);
d[d.length - 1] = 0;
int[] path = new int[vertexes.length];
Arrays.fill(path, -1);
PriorityQueue<State> que = new PriorityQueue<State>();
que.add(new State(0, vertexes.length - 1));
while (!que.isEmpty())
{
State p = que.poll();
|
if (d[p.vertex] < p.cost) continue;
for (EdgeFrom edgeFrom : edgesTo[p.vertex])
{
if (d[edgeFrom.from] > d[p.vertex] + edgeFrom.weight)
{
d[edgeFrom.from] = d[p.vertex] + edgeFrom.weight;
que.add(new State(d[edgeFrom.from], edgeFrom.from));
path[edgeFrom.from] = p.vertex;
}
}
}
for (int t = 0; t != -1; t = path[t])
{
resultList.add(vertexes[t]);
}
return resultList;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\Dijkstra.java
| 1
|
请完成以下Java代码
|
public String getMachineId() {
return machineId;
}
public ClusterGroupEntity setMachineId(String machineId) {
this.machineId = machineId;
return this;
}
public String getIp() {
return ip;
}
public ClusterGroupEntity setIp(String ip) {
this.ip = ip;
return this;
}
public Integer getPort() {
return port;
}
public ClusterGroupEntity setPort(Integer port) {
this.port = port;
return this;
}
public Set<String> getClientSet() {
return clientSet;
}
public ClusterGroupEntity setClientSet(Set<String> clientSet) {
this.clientSet = clientSet;
return this;
}
|
public Boolean getBelongToApp() {
return belongToApp;
}
public ClusterGroupEntity setBelongToApp(Boolean belongToApp) {
this.belongToApp = belongToApp;
return this;
}
@Override
public String toString() {
return "ClusterGroupEntity{" +
"machineId='" + machineId + '\'' +
", ip='" + ip + '\'' +
", port=" + port +
", clientSet=" + clientSet +
", belongToApp=" + belongToApp +
'}';
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\ClusterGroupEntity.java
| 1
|
请完成以下Java代码
|
public void setCertificateVerifier(Consumer<OAuth2ClientAuthenticationContext> certificateVerifier) {
Assert.notNull(certificateVerifier, "certificateVerifier cannot be null");
this.certificateVerifier = certificateVerifier;
}
private void verifyX509Certificate(OAuth2ClientAuthenticationContext clientAuthenticationContext) {
OAuth2ClientAuthenticationToken clientAuthentication = clientAuthenticationContext.getAuthentication();
if (ClientAuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH
.equals(clientAuthentication.getClientAuthenticationMethod())) {
this.selfSignedCertificateVerifier.accept(clientAuthenticationContext);
}
else {
verifyX509CertificateSubjectDN(clientAuthenticationContext);
}
}
private void verifyX509CertificateSubjectDN(OAuth2ClientAuthenticationContext clientAuthenticationContext) {
OAuth2ClientAuthenticationToken clientAuthentication = clientAuthenticationContext.getAuthentication();
RegisteredClient registeredClient = clientAuthenticationContext.getRegisteredClient();
X509Certificate[] clientCertificateChain = (X509Certificate[]) clientAuthentication.getCredentials();
X509Certificate clientCertificate = clientCertificateChain[0];
|
String expectedSubjectDN = registeredClient.getClientSettings().getX509CertificateSubjectDN();
if (!StringUtils.hasText(expectedSubjectDN)
|| !clientCertificate.getSubjectX500Principal().getName().equals(expectedSubjectDN)) {
throwInvalidClient("x509_certificate_subject_dn");
}
}
private static void throwInvalidClient(String parameterName) {
throwInvalidClient(parameterName, null);
}
private static void throwInvalidClient(String parameterName, Throwable cause) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT,
"Client authentication failed: " + parameterName, ERROR_URI);
throw new OAuth2AuthenticationException(error, error.toString(), cause);
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\X509ClientCertificateAuthenticationProvider.java
| 1
|
请完成以下Java代码
|
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
|
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_SortPref_Line_Product.java
| 1
|
请完成以下Java代码
|
private static void deepCopyInto(final Map<String, Object> target, final Map<String, Object> source)
{
for (Map.Entry<String, Object> entry : source.entrySet())
{
final String key = entry.getKey();
final Object valueOld = target.get(key);
final Object valueNew = combineValue(valueOld, entry.getValue());
target.put(key, valueNew);
}
}
@Nullable
private static Object combineValue(@Nullable final Object target, @Nullable final Object source)
{
if (source instanceof Map)
{
//noinspection unchecked
final Map<String, Object> sourceMap = (Map<String, Object>)source;
final LinkedHashMap<String, Object> result = new LinkedHashMap<>();
if (target instanceof Map)
{
//noinspection unchecked
final Map<String, Object> targetMap = (Map<String, Object>)target;
deepCopyInto(result, targetMap);
deepCopyInto(result, sourceMap);
return result;
}
else
{
deepCopyInto(result, sourceMap);
return result;
}
|
}
else
{
return source;
}
}
public JsonMessages toJson()
{
return JsonMessages.builder()
.language(adLanguage)
.messages(map)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\AdMessagesTree.java
| 1
|
请完成以下Java代码
|
public class ToStringSerializer<T> implements Serializer<T> {
/**
* Kafka config property for enabling/disabling adding type headers.
*/
public static final String ADD_TYPE_INFO_HEADERS = "spring.message.add.type.headers";
/**
* Header for the type of key.
*/
public static final String KEY_TYPE = "spring.message.key.type";
/**
* Header for the type of value.
*/
public static final String VALUE_TYPE = "spring.message.value.type";
private boolean addTypeInfo = true;
private Charset charset = StandardCharsets.UTF_8;
private String typeInfoHeader = VALUE_TYPE;
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
if (isKey) {
this.typeInfoHeader = KEY_TYPE;
}
if (configs.containsKey(ADD_TYPE_INFO_HEADERS)) {
Object config = configs.get(ADD_TYPE_INFO_HEADERS);
if (config instanceof Boolean) {
this.addTypeInfo = (Boolean) config;
}
else if (config instanceof String) {
this.addTypeInfo = Boolean.parseBoolean((String) config);
}
else {
throw new IllegalStateException(
ADD_TYPE_INFO_HEADERS + " must be Boolean or String");
}
}
}
@Override
public byte[] serialize(String topic, @Nullable T data) {
return serialize(topic, null, data);
}
@Override
@SuppressWarnings("NullAway") // Dataflow analysis limitation
public byte[] serialize(String topic, @Nullable Headers headers, @Nullable T data) {
if (data == null) {
return null;
}
if (this.addTypeInfo && headers != null) {
headers.add(this.typeInfoHeader, data.getClass().getName().getBytes());
}
return data.toString().getBytes(this.charset);
}
@Override
public void close() {
// No-op
}
/**
|
* Get the addTypeInfo property.
* @return the addTypeInfo
*/
public boolean isAddTypeInfo() {
return this.addTypeInfo;
}
/**
* Set to false to disable adding type info headers.
* @param addTypeInfo true to add headers
*/
public void setAddTypeInfo(boolean addTypeInfo) {
this.addTypeInfo = addTypeInfo;
}
/**
* Set a charset to use when converting {@link String} to byte[]. Default UTF-8.
* @param charset the charset.
*/
public void setCharset(Charset charset) {
Assert.notNull(charset, "'charset' cannot be null");
this.charset = charset;
}
/**
* Get the configured charset.
* @return the charset.
*/
public Charset getCharset() {
return this.charset;
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\ToStringSerializer.java
| 1
|
请完成以下Java代码
|
public ZonedDateTime getDatePromised()
{
final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(order.getAD_Org_ID()));
return TimeUtil.asZonedDateTime(order.getDatePromised(), timeZone);
}
public OrderFactory shipBPartner(
@NonNull final BPartnerId bpartnerId,
@Nullable final BPartnerLocationId bpartnerLocationId,
@Nullable final BPartnerContactId contactId)
{
assertNotBuilt();
OrderDocumentLocationAdapterFactory
.locationAdapter(order)
.setFrom(DocumentLocation.builder()
.bpartnerId(bpartnerId)
.bpartnerLocationId(bpartnerLocationId)
.contactId(contactId)
.build());
return this;
}
public OrderFactory shipBPartner(final BPartnerId bpartnerId)
{
shipBPartner(bpartnerId, null, null);
return this;
}
public BPartnerId getShipBPartnerId()
{
return BPartnerId.ofRepoId(order.getC_BPartner_ID());
}
public OrderFactory pricingSystemId(@NonNull final PricingSystemId pricingSystemId)
{
assertNotBuilt();
order.setM_PricingSystem_ID(pricingSystemId.getRepoId());
return this;
}
public OrderFactory poReference(@Nullable final String poReference)
{
assertNotBuilt();
order.setPOReference(poReference);
return this;
}
public OrderFactory salesRepId(@Nullable final UserId salesRepId)
{
assertNotBuilt();
|
order.setSalesRep_ID(UserId.toRepoId(salesRepId));
return this;
}
public OrderFactory projectId(@Nullable final ProjectId projectId)
{
assertNotBuilt();
order.setC_Project_ID(ProjectId.toRepoId(projectId));
return this;
}
public OrderFactory campaignId(final int campaignId)
{
assertNotBuilt();
order.setC_Campaign_ID(campaignId);
return this;
}
public DocTypeId getDocTypeTargetId()
{
return docTypeTargetId;
}
public void setDocTypeTargetId(final DocTypeId docTypeTargetId)
{
this.docTypeTargetId = docTypeTargetId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderFactory.java
| 1
|
请完成以下Java代码
|
public void setMargin (java.math.BigDecimal Margin)
{
set_Value (COLUMNNAME_Margin, Margin);
}
/** Get Margin %.
@return Margin for a product as a percentage
*/
@Override
public java.math.BigDecimal getMargin ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Margin);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Offer Amount.
@param OfferAmt
Amount of the Offer
*/
@Override
public void setOfferAmt (java.math.BigDecimal OfferAmt)
{
set_Value (COLUMNNAME_OfferAmt, OfferAmt);
}
/** Get Offer Amount.
@return Amount of the Offer
*/
@Override
public java.math.BigDecimal getOfferAmt ()
|
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OfferAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQLineQty.java
| 1
|
请完成以下Java代码
|
public class DbCallStats {
private final TenantId tenantId;
private final ConcurrentMap<String, MethodCallStats> methodStats = new ConcurrentHashMap<>();
private final AtomicInteger successCalls = new AtomicInteger();
private final AtomicInteger failureCalls = new AtomicInteger();
public void onMethodCall(String methodName, boolean success, long executionTime) {
var methodCallStats = methodStats.computeIfAbsent(methodName, m -> new MethodCallStats());
methodCallStats.getExecutions().incrementAndGet();
methodCallStats.getTiming().addAndGet(executionTime);
if (success) {
successCalls.incrementAndGet();
} else {
failureCalls.incrementAndGet();
|
methodCallStats.getFailures().incrementAndGet();
}
}
public DbCallStatsSnapshot snapshot() {
return DbCallStatsSnapshot.builder()
.tenantId(tenantId)
.totalSuccess(successCalls.get())
.totalFailure(failureCalls.get())
.methodStats(methodStats.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().snapshot())))
.totalTiming(methodStats.values().stream().map(MethodCallStats::getTiming).map(AtomicLong::get).reduce(0L, Long::sum))
.build();
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\aspect\DbCallStats.java
| 1
|
请完成以下Java代码
|
public class HibernateUtil {
private static SessionFactory sessionFactory;
private HibernateUtil() {
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
private static SessionFactory buildSessionFactory() {
try {
ServiceRegistry serviceRegistry = configureServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(Student.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.applyBasicType(LocalDateStringType.INSTANCE)
.build();
return metadata.getSessionFactoryBuilder().build();
|
} catch (IOException ex) {
throw new ExceptionInInitializerError(ex);
}
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties();
return new StandardServiceRegistryBuilder().applySettings(properties).build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource("hibernate.properties");
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\criteriaquery\HibernateUtil.java
| 1
|
请完成以下Spring Boot application配置
|
management.endpoint.health.probes.enabled=true
management.health.livenessState.enabled=true
management.health.readinessState.enabled=true
management.endpoint.health.show-details=always
management.endpoint.health.status.http-mapping.down=500
management.endpoint.health.status.http-mapping.out_of_service=503
management.endpoint.health.status.http-mapping.warning=500
## Configuring info endpoint
info.app.name=Spring Sample Application
info.app.description=Thi
|
s is my first spring boot application G1
info.app.version=1.0.0
info.java-vendor = ${java.specification.vendor}
management.endpoints.web.exposure.include=*
management.endpoint.shutdown.enabled=true
|
repos\tutorials-master\spring-boot-modules\spring-boot-actuator\src\main\resources\application.properties
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private void schedulerAdd(String id, String jobClassName, String cronExpression, String parameter) {
try {
// 启动调度器
scheduler.start();
// 构建job信息
JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(id).usingJobData("parameter", parameter).build();
// 表达式调度构建器(即任务执行的时间)
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
// 按新的cronExpression表达式构建一个新的trigger
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(id).withSchedule(scheduleBuilder).build();
scheduler.scheduleJob(jobDetail, trigger);
} catch (SchedulerException e) {
throw new JeecgBootException("创建定时任务失败", e);
} catch (RuntimeException e) {
throw new JeecgBootException(e.getMessage(), e);
}catch (Exception e) {
throw new JeecgBootException("后台找不到该类名:" + jobClassName, e);
}
}
/**
* 删除定时任务
*
|
* @param id
*/
private void schedulerDelete(String id) {
try {
scheduler.pauseTrigger(TriggerKey.triggerKey(id));
scheduler.unscheduleJob(TriggerKey.triggerKey(id));
scheduler.deleteJob(JobKey.jobKey(id));
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new JeecgBootException("删除定时任务失败");
}
}
private static Job getClass(String classname) throws Exception {
Class<?> class1 = Class.forName(classname);
return (Job) class1.newInstance();
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\quartz\service\impl\QuartzJobServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ConditionConfig {
/**
* 该Abc class位于类路径上时
*/
@ConditionalOnClass(DynamicAttrConfig.class)
@Bean
public String abc() {
System.err.println("ConditionalOnClass true");
return "";
}
@Bean
public DynamicAttrConfig createAbcBean() {
return new DynamicAttrConfig();
}
//
/**
* 存在Abc类的实例时
*/
@ConditionalOnBean(DynamicAttrConfig.class)
@Bean
public String bean() {
System.err.println("ConditionalOnBean is exist");
return "";
}
@ConditionalOnMissingBean(DynamicAttrConfig.class)
@Bean
public String missBean() {
System.err.println("ConditionalOnBean is missing");
return "";
}
/**
* 表达式为true时
* spel http://itmyhome.com/spring/expressions.html
*/
@ConditionalOnExpression(value = "2 > 1")
@Bean
public String expresssion() {
System.err.println("expresssion is true");
return "";
}
/**
* 配置文件属性是否为true
|
*/
@ConditionalOnProperty(value = {"spring.activemq.switch"}, matchIfMissing = false)
@Bean
public String property() {
System.err.println("property is true");
return "";
}
/**
* 打印容器里的所有bean name (box name 为方法名)
* @param appContext
* @return
*/
@Bean
public CommandLineRunner run(ApplicationContext appContext) {
return args -> {
String[] beans = appContext.getBeanDefinitionNames();
Arrays.stream(beans).sorted().forEach(System.out::println);
};
}
}
|
repos\spring-boot-quick-master\quick-dynamic-bean\src\main\java\com\dynamic\bean\config\ConditionConfig.java
| 2
|
请完成以下Java代码
|
private Stream<InventoryLineHU> streamLineHUs()
{
return lines.stream().flatMap(line -> line.getInventoryLineHUs().stream());
}
public ImmutableSet<HuId> getHuIds()
{
return InventoryLineHU.extractHuIds(streamLineHUs());
}
public Inventory assigningTo(@NonNull final UserId newResponsibleId)
{
return assigningTo(newResponsibleId, false);
}
public Inventory reassigningTo(@NonNull final UserId newResponsibleId)
{
return assigningTo(newResponsibleId, true);
}
private Inventory assigningTo(@NonNull final UserId newResponsibleId, boolean allowReassignment)
{
// no responsible change
if (UserId.equals(responsibleId, newResponsibleId))
{
return this;
}
if (!newResponsibleId.isRegularUser())
{
throw new AdempiereException("Only regular users can be assigned to an inventory");
}
if (!allowReassignment && responsibleId != null)
{
throw new AdempiereException("Inventory is already assigned");
}
return toBuilder().responsibleId(newResponsibleId).build();
}
public Inventory unassign()
{
return responsibleId == null ? this : toBuilder().responsibleId(null).build();
}
public void assertHasAccess(@NonNull final UserId calledId)
{
|
if (!UserId.equals(responsibleId, calledId))
{
throw new AdempiereException("No access");
}
}
public Stream<InventoryLine> streamLines(@Nullable final InventoryLineId onlyLineId)
{
return onlyLineId != null
? Stream.of(getLineById(onlyLineId))
: lines.stream();
}
public Set<LocatorId> getLocatorIdsEligibleForCounting(@Nullable final InventoryLineId onlyLineId)
{
return streamLines(onlyLineId)
.filter(InventoryLine::isEligibleForCounting)
.map(InventoryLine::getLocatorId)
.collect(ImmutableSet.toImmutableSet());
}
public Inventory updatingLineById(@NonNull final InventoryLineId lineId, @NonNull UnaryOperator<InventoryLine> updater)
{
final ImmutableList<InventoryLine> newLines = CollectionUtils.map(
this.lines,
line -> InventoryLineId.equals(line.getId(), lineId) ? updater.apply(line) : line
);
return this.lines == newLines
? this
: toBuilder().lines(newLines).build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\Inventory.java
| 1
|
请完成以下Java代码
|
public static int divideListElements(List<Integer> values, Integer divider) {
return values.stream()
.reduce(0, (a, b) -> {
try {
return a / divider + b / divider;
} catch (ArithmeticException e) {
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
}
return 0;
});
}
public static int divideListElementsWithExtractedTryCatchBlock(List<Integer> values, int divider) {
return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider));
}
public static int divideListElementsWithApplyFunctionMethod(List<Integer> values, int divider) {
BiFunction<Integer, Integer, Integer> division = (a, b) -> a / b;
return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider));
}
private static int divide(int value, int factor) {
int result = 0;
|
try {
result = value / factor;
} catch (ArithmeticException e) {
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
}
return result;
}
private static int applyFunction(BiFunction<Integer, Integer, Integer> function, int a, int b) {
try {
return function.apply(a, b);
}
catch(Exception e) {
LOGGER.log(Level.INFO, "Exception thrown!");
}
return 0;
}
}
|
repos\tutorials-master\core-java-modules\core-java-streams-7\src\main\java\com\baeldung\streams\reduce\utilities\NumberUtils.java
| 1
|
请完成以下Java代码
|
public void setAnonymousAuthorizedClientRepository(
ServerOAuth2AuthorizedClientRepository anonymousAuthorizedClientRepository) {
Assert.notNull(anonymousAuthorizedClientRepository, "anonymousAuthorizedClientRepository cannot be null");
this.anonymousAuthorizedClientRepository = anonymousAuthorizedClientRepository;
}
@Override
public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId,
Authentication principal, ServerWebExchange exchange) {
if (this.isPrincipalAuthenticated(principal)) {
return this.authorizedClientService.loadAuthorizedClient(clientRegistrationId, principal.getName());
}
return this.anonymousAuthorizedClientRepository.loadAuthorizedClient(clientRegistrationId, principal, exchange);
}
@Override
public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
ServerWebExchange exchange) {
if (this.isPrincipalAuthenticated(principal)) {
return this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal);
|
}
return this.anonymousAuthorizedClientRepository.saveAuthorizedClient(authorizedClient, principal, exchange);
}
@Override
public Mono<Void> removeAuthorizedClient(String clientRegistrationId, Authentication principal,
ServerWebExchange exchange) {
if (this.isPrincipalAuthenticated(principal)) {
return this.authorizedClientService.removeAuthorizedClient(clientRegistrationId, principal.getName());
}
return this.anonymousAuthorizedClientRepository.removeAuthorizedClient(clientRegistrationId, principal,
exchange);
}
private boolean isPrincipalAuthenticated(Authentication authentication) {
return this.authenticationTrustResolver.isAuthenticated(authentication);
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\server\AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository.java
| 1
|
请完成以下Java代码
|
public void addFile(JarOutputStream target, String rootPath, String source) throws IOException {
BufferedInputStream in = null;
String remaining = "";
if (rootPath.endsWith(File.separator))
remaining = source.substring(rootPath.length());
else
remaining = source.substring(rootPath.length() + 1);
String name = remaining.replace("\\", "/");
JarEntry entry = new JarEntry(name);
entry.setTime(new File(source).lastModified());
target.putNextEntry(entry);
in = new BufferedInputStream(new FileInputStream(source));
byte[] buffer = new byte[1024];
while (true) {
int count = in.read(buffer);
if (count == -1)
break;
target.write(buffer, 0, count);
}
target.closeEntry();
in.close();
}
|
public JarOutputStream openJar(String jarFile) throws IOException {
JarOutputStream target = new JarOutputStream(new FileOutputStream(jarFile), manifest);
return target;
}
public void setMainClass(String mainFQCN) {
if (mainFQCN != null && !mainFQCN.equals(""))
manifest.getMainAttributes()
.put(Attributes.Name.MAIN_CLASS, mainFQCN);
}
public void startManifest() {
manifest.getMainAttributes()
.put(Attributes.Name.MANIFEST_VERSION, "1.0");
}
}
|
repos\tutorials-master\core-java-modules\core-java-jar\src\main\java\com\baeldung\createjar\JarTool.java
| 1
|
请完成以下Java代码
|
public Pet getPet(String name, boolean ignoreNew) {
for (Pet pet : getPets()) {
String compName = pet.getName();
if (compName != null && compName.equalsIgnoreCase(name)) {
if (!ignoreNew || !pet.isNew()) {
return pet;
}
}
}
return null;
}
@Override
public String toString() {
return new ToStringCreator(this).append("id", this.getId())
.append("new", this.isNew())
.append("lastName", this.getLastName())
.append("firstName", this.getFirstName())
.append("address", this.address)
.append("city", this.city)
.append("telephone", this.telephone)
.toString();
}
/**
* Adds the given {@link Visit} to the {@link Pet} with the given identifier.
|
* @param petId the identifier of the {@link Pet}, must not be {@literal null}.
* @param visit the visit to add, must not be {@literal null}.
*/
public void addVisit(Integer petId, Visit visit) {
Assert.notNull(petId, "Pet identifier must not be null!");
Assert.notNull(visit, "Visit must not be null!");
Pet pet = getPet(petId);
Assert.notNull(pet, "Invalid Pet identifier!");
pet.addVisit(visit);
}
}
|
repos\spring-petclinic-main\src\main\java\org\springframework\samples\petclinic\owner\Owner.java
| 1
|
请完成以下Java代码
|
public void setPriorityRule (final @Nullable java.lang.String PriorityRule)
{
set_Value (COLUMNNAME_PriorityRule, PriorityRule);
}
@Override
public java.lang.String getPriorityRule()
{
return get_ValueAsString(COLUMNNAME_PriorityRule);
}
@Override
public void setReferenceNo (final @Nullable java.lang.String ReferenceNo)
{
set_Value (COLUMNNAME_ReferenceNo, ReferenceNo);
}
@Override
public java.lang.String getReferenceNo()
{
return get_ValueAsString(COLUMNNAME_ReferenceNo);
}
@Override
public void setSalesRep_ID (final int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, SalesRep_ID);
}
@Override
public int getSalesRep_ID()
{
return get_ValueAsInt(COLUMNNAME_SalesRep_ID);
}
@Override
public void setSalesRep_Name (final @Nullable java.lang.String SalesRep_Name)
{
set_Value (COLUMNNAME_SalesRep_Name, SalesRep_Name);
}
@Override
public java.lang.String getSalesRep_Name()
{
return get_ValueAsString(COLUMNNAME_SalesRep_Name);
}
@Override
public void setTaxID (final @Nullable java.lang.String TaxID)
{
set_Value (COLUMNNAME_TaxID, TaxID);
}
@Override
public java.lang.String getTaxID()
{
return get_ValueAsString(COLUMNNAME_TaxID);
}
@Override
public void setTitle (final @Nullable java.lang.String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
@Override
public java.lang.String getTitle()
{
return get_ValueAsString(COLUMNNAME_Title);
}
|
@Override
public void setVolume (final @Nullable BigDecimal Volume)
{
set_Value (COLUMNNAME_Volume, Volume);
}
@Override
public BigDecimal getVolume()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Volume);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public org.compiere.model.I_C_Location getWarehouse_Location()
{
return get_ValueAsPO(COLUMNNAME_Warehouse_Location_ID, org.compiere.model.I_C_Location.class);
}
@Override
public void setWarehouse_Location(final org.compiere.model.I_C_Location Warehouse_Location)
{
set_ValueFromPO(COLUMNNAME_Warehouse_Location_ID, org.compiere.model.I_C_Location.class, Warehouse_Location);
}
@Override
public void setWarehouse_Location_ID (final int Warehouse_Location_ID)
{
if (Warehouse_Location_ID < 1)
set_Value (COLUMNNAME_Warehouse_Location_ID, null);
else
set_Value (COLUMNNAME_Warehouse_Location_ID, Warehouse_Location_ID);
}
@Override
public int getWarehouse_Location_ID()
{
return get_ValueAsInt(COLUMNNAME_Warehouse_Location_ID);
}
@Override
public void setWeight (final @Nullable BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
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_DD_Order_Header_v.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ServiceRepairProjectTask withUpdatedStatus()
{
final ServiceRepairProjectTaskStatus newStatus = computeStatus();
return !newStatus.equals(getStatus())
? toBuilder().status(newStatus).build()
: this;
}
private ServiceRepairProjectTaskStatus computeStatus()
{
final @NonNull ServiceRepairProjectTaskType type = getType();
switch (type)
{
case REPAIR_ORDER:
return computeStatusForRepairOrderType();
case SPARE_PARTS:
return computeStatusForSparePartsType();
default:
throw new AdempiereException("Unknown type for " + this);
}
}
private ServiceRepairProjectTaskStatus computeStatusForRepairOrderType()
{
if (getRepairOrderId() == null)
{
return ServiceRepairProjectTaskStatus.NOT_STARTED;
}
else
{
return isRepairOrderDone()
? ServiceRepairProjectTaskStatus.COMPLETED
: ServiceRepairProjectTaskStatus.IN_PROGRESS;
}
}
private ServiceRepairProjectTaskStatus computeStatusForSparePartsType()
{
if (getQtyToReserve().signum() <= 0)
{
return ServiceRepairProjectTaskStatus.COMPLETED;
}
else if (getQtyReservedOrConsumed().signum() == 0)
{
return ServiceRepairProjectTaskStatus.NOT_STARTED;
}
else
{
|
return ServiceRepairProjectTaskStatus.IN_PROGRESS;
}
}
public ServiceRepairProjectTask withRepairOrderId(@NonNull final PPOrderId repairOrderId)
{
return toBuilder()
.repairOrderId(repairOrderId)
.build()
.withUpdatedStatus();
}
public ServiceRepairProjectTask withRepairOrderDone(
@Nullable final String repairOrderSummary,
@Nullable final ProductId repairServicePerformedId)
{
return toBuilder()
.isRepairOrderDone(true)
.repairOrderSummary(repairOrderSummary)
.repairServicePerformedId(repairServicePerformedId)
.build()
.withUpdatedStatus();
}
public ServiceRepairProjectTask withRepairOrderNotDone()
{
return toBuilder()
.isRepairOrderDone(false)
.repairOrderSummary(null)
.repairServicePerformedId(null)
.build()
.withUpdatedStatus();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\model\ServiceRepairProjectTask.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
protected String getDeploymentMode() {
return DEPLOYMENT_MODE;
}
@Override
protected void deployResourcesInternal(String deploymentNameHint, Resource[] resources, ProcessEngine engine) {
RepositoryService repositoryService = engine.getRepositoryService();
// Create a single deployment for all resources using the name hint as the literal name
final DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(deploymentNameHint);
for (final Resource resource : resources) {
addResource(resource, deploymentBuilder);
}
|
try {
deploymentBuilder.deploy();
} catch (RuntimeException e) {
if (isThrowExceptionOnDeploymentFailure()) {
throw e;
} else {
LOGGER.warn("Exception while autodeploying process definitions. "
+ "This exception can be ignored if the root cause indicates a unique constraint violation, "
+ "which is typically caused by two (or more) servers booting up at the exact same time and deploying the same definitions. ", e);
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-spring\src\main\java\org\flowable\spring\configurator\DefaultAutoDeploymentStrategy.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public CustomerMapping _id(UUID _id) {
this._id = _id;
return this;
}
/**
* Alberta-Id
* @return _id
**/
@Schema(example = "a4adecb6-126a-4fa6-8fac-e80165ac4264", required = true, description = "Alberta-Id")
public UUID getId() {
return _id;
}
public void setId(UUID _id) {
this._id = _id;
}
public CustomerMapping customerId(String customerId) {
this.customerId = customerId;
return this;
}
/**
* Id aus WaWi
* @return customerId
**/
@Schema(example = "D32399", required = true, description = "Id aus WaWi")
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public CustomerMapping updated(OffsetDateTime updated) {
this.updated = updated;
return this;
}
/**
* Der Zeitstempel der letzten Änderung
* @return updated
**/
@Schema(example = "2019-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung")
public OffsetDateTime getUpdated() {
return updated;
}
public void setUpdated(OffsetDateTime updated) {
this.updated = updated;
}
|
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CustomerMapping customerMapping = (CustomerMapping) o;
return Objects.equals(this._id, customerMapping._id) &&
Objects.equals(this.customerId, customerMapping.customerId) &&
Objects.equals(this.updated, customerMapping.updated);
}
@Override
public int hashCode() {
return Objects.hash(_id, customerId, updated);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CustomerMapping {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" customerId: ").append(toIndentedString(customerId)).append("\n");
sb.append(" updated: ").append(toIndentedString(updated)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\CustomerMapping.java
| 2
|
请完成以下Java代码
|
protected ObjectMapper getObjectMapper() {
return JsonMapper.builder()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.build();
}
private String trimMarkdown(String text) {
if (text.startsWith("```json") && text.endsWith("```")) {
text = text.substring(7, text.length() - 3);
}
return text;
}
private String generateJsonSchemaForValueType(Class<V> valueType) {
try {
|
JacksonModule jacksonModule = new JacksonModule();
SchemaGeneratorConfig config = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON)
.with(jacksonModule)
.build();
SchemaGenerator generator = new SchemaGenerator(config);
JsonNode jsonNode = generator.generateSchema(valueType);
ObjectWriter objectWriter = new ObjectMapper().writer(new DefaultPrettyPrinter().withObjectIndenter(new DefaultIndenter().withLinefeed(System.lineSeparator())));
return objectWriter.writeValueAsString(jsonNode);
} catch (JsonProcessingException e) {
throw new RuntimeException("Could not generate JSON schema for value type: " + valueType.getName(), e);
}
}
}
|
repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springaistructuredoutput\converters\GenericMapOutputConverter.java
| 1
|
请完成以下Spring Boot application配置
|
events:
queues:
shipping:
simple-pojo-conversion-queue: shipping_pojo_conversion_queue
custom-object-mapper-queue: shipping_custom_object_mapper_queue
subclass-deserialization-queue: subclass_deserialization_queue
headers:
type
|
s:
shipping:
header-name: SHIPPING_TYPE
international: INTERNATIONAL
domestic: DOMESTIC
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-aws-v3\src\main\resources\application-shipping.yaml
| 2
|
请完成以下Java代码
|
public void onNew(final ICalloutRecord calloutRecord)
{
final I_SAP_GLJournalLine glJournalLine = calloutRecord.getModel(I_SAP_GLJournalLine.class);
final SAPGLJournalId glJournalId = SAPGLJournalId.ofRepoId(glJournalLine.getSAP_GLJournal_ID());
final SeqNo seqNo = glJournalService.getNextSeqNo(glJournalId);
glJournalLine.setLine(seqNo.toInt());
}
@CalloutMethod(columnNames = I_SAP_GLJournalLine.COLUMNNAME_PostingSign)
public void onPostingSign(final I_SAP_GLJournalLine glJournalLine)
{
updateAmtAcct(glJournalLine);
}
@CalloutMethod(columnNames = I_SAP_GLJournalLine.COLUMNNAME_C_ValidCombination_ID)
public void onC_ValidCombination_ID(final I_SAP_GLJournalLine glJournalLine)
{
glJournalService.updateTrxInfo(glJournalLine);
}
@CalloutMethod(columnNames = I_SAP_GLJournalLine.COLUMNNAME_Amount)
public void onAmount(final I_SAP_GLJournalLine glJournalLine)
{
|
updateAmtAcct(glJournalLine);
}
private void updateAmtAcct(final I_SAP_GLJournalLine glJournalLine)
{
final SAPGLJournalCurrencyConversionCtx conversionCtx = getConversionCtx(glJournalLine);
final Money amtAcct = glJournalService.getCurrencyConverter().convertToAcctCurrency(glJournalLine.getAmount(), conversionCtx);
glJournalLine.setAmtAcct(amtAcct.toBigDecimal());
}
private static SAPGLJournalCurrencyConversionCtx getConversionCtx(final I_SAP_GLJournalLine glJournalLine)
{
// NOTE: calling model getter because we expect to be fetched from webui Document
final I_SAP_GLJournal glJournal = glJournalLine.getSAP_GLJournal();
return SAPGLJournalLoaderAndSaver.extractConversionCtx(glJournal);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\callout\SAP_GLJournalLine.java
| 1
|
请完成以下Java代码
|
public static class SuspensionStateUtil {
public static void setSuspensionState(ProcessDefinitionEntity processDefinitionEntity, SuspensionState state) {
if (processDefinitionEntity.getSuspensionState() == state.getStateCode()) {
throw new ActivitiException(
"Cannot set suspension state '" +
state +
"' for " +
processDefinitionEntity +
"': already in state '" +
state +
"'."
);
}
processDefinitionEntity.setSuspensionState(state.getStateCode());
dispatchStateChangeEvent(processDefinitionEntity, state);
}
public static void setSuspensionState(ExecutionEntity executionEntity, SuspensionState state) {
if (executionEntity.getSuspensionState() == state.getStateCode()) {
throw new ActivitiException(
"Cannot set suspension state '" +
state +
"' for " +
executionEntity +
"': already in state '" +
state +
"'."
);
}
executionEntity.setSuspensionState(state.getStateCode());
dispatchStateChangeEvent(executionEntity, state);
}
public static void setSuspensionState(TaskEntity taskEntity, SuspensionState state) {
if (taskEntity.getSuspensionState() == state.getStateCode()) {
throw new ActivitiException(
"Cannot set suspension state '" +
state +
"' for " +
taskEntity +
"': already in state '" +
state +
"'."
|
);
}
taskEntity.setSuspensionState(state.getStateCode());
dispatchStateChangeEvent(taskEntity, state);
}
protected static void dispatchStateChangeEvent(Object entity, SuspensionState state) {
if (Context.getCommandContext() != null && Context.getCommandContext().getEventDispatcher().isEnabled()) {
ActivitiEventType eventType = null;
if (state == SuspensionState.ACTIVE) {
eventType = ActivitiEventType.ENTITY_ACTIVATED;
} else {
eventType = ActivitiEventType.ENTITY_SUSPENDED;
}
Context.getCommandContext()
.getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(eventType, entity));
}
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\SuspensionState.java
| 1
|
请完成以下Java代码
|
public class DefaultDynamicStateManager extends AbstractDynamicStateManager implements DynamicStateManager {
@Override
public void moveExecutionState(ChangeActivityStateBuilderImpl changeActivityStateBuilder, CommandContext commandContext) {
List<MoveExecutionEntityContainer> moveExecutionEntityContainerList = resolveMoveExecutionEntityContainers(changeActivityStateBuilder,
changeActivityStateBuilder.getProcessInstanceVariables(), commandContext);
List<ExecutionEntity> executions = null;
if (!moveExecutionEntityContainerList.isEmpty()) {
executions = moveExecutionEntityContainerList.iterator().next().getExecutions();
}
List<EnableActivityContainer> enableActivityContainerList = resolveEnableActivityContainers(changeActivityStateBuilder);
String processInstanceId = null;
if (executions != null && !executions.isEmpty()) {
processInstanceId = executions.iterator().next().getProcessInstanceId();
} else {
processInstanceId = changeActivityStateBuilder.getProcessInstanceId();
}
ProcessInstanceChangeState processInstanceChangeState = new ProcessInstanceChangeState()
.setProcessInstanceId(processInstanceId)
.setMoveExecutionEntityContainers(moveExecutionEntityContainerList)
.setEnableActivityContainers(enableActivityContainerList)
.setLocalVariables(changeActivityStateBuilder.getLocalVariables())
.setProcessInstanceVariables(changeActivityStateBuilder.getProcessInstanceVariables());
|
doMoveExecutionState(processInstanceChangeState, commandContext);
}
@Override
protected Map<String, List<ExecutionEntity>> resolveActiveEmbeddedSubProcesses(String processInstanceId, CommandContext commandContext) {
ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
List<ExecutionEntity> childExecutions = executionEntityManager.findChildExecutionsByProcessInstanceId(processInstanceId);
Map<String, List<ExecutionEntity>> activeSubProcessesByActivityId = childExecutions.stream()
.filter(ExecutionEntity::isActive)
.filter(executionEntity -> executionEntity.getCurrentFlowElement() instanceof SubProcess)
.collect(Collectors.groupingBy(ExecutionEntity::getActivityId));
return activeSubProcessesByActivityId;
}
@Override
protected boolean isDirectFlowElementExecutionMigration(FlowElement currentFlowElement, FlowElement newFlowElement) {
return false;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\DefaultDynamicStateManager.java
| 1
|
请完成以下Java代码
|
public static String saveErrorTxtByList(List<String> msg, String name) {
Date d = new Date();
String saveDir = "logs" + File.separator + DateUtils.yyyyMMdd.get().format(d) + File.separator;
String saveFullDir = uploadPath + File.separator + saveDir;
File saveFile = new File(saveFullDir);
if (!saveFile.exists()) {
saveFile.mkdirs();
}
name += DateUtils.yyyymmddhhmmss.get().format(d) + Math.round(Math.random() * 10000);
String saveFilePath = saveFullDir + name + ".txt";
try {
//封装目的地
BufferedWriter bw = new BufferedWriter(new FileWriter(saveFilePath));
//遍历集合
for (String s : msg) {
//写数据
if (s.indexOf("_") > 0) {
String[] arr = s.split("_");
|
bw.write("第" + arr[0] + "行:" + arr[1]);
} else {
bw.write(s);
}
//bw.newLine();
bw.write("\r\n");
}
//释放资源
bw.flush();
bw.close();
} catch (Exception e) {
log.info("excel导入生成错误日志文件异常:" + e.getMessage());
}
return saveDir + name + ".txt";
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\PmsUtil.java
| 1
|
请完成以下Java代码
|
public void processSave(final IHUContext huContext, final I_M_HU_Trx_Attribute trxAttribute, final Object referencedModel)
{
if (!HUConstants.DEBUG_07277_processHUTrxAttribute)
{
return; // FIXME debuging
}
final I_M_HU hu = InterfaceWrapperHelper.create(referencedModel, I_M_HU.class);
final IHUAttributesDAO huAttributesDAO = huContext.getHUAttributeStorageFactory().getHUAttributesDAO();
final I_M_HU_Attribute huAttributeExisting = retrieveHUAttribute(huAttributesDAO, trxAttribute);
final I_M_HU_Attribute huAttribute;
if (huAttributeExisting == null)
{
// Create new attribute
huAttribute = InterfaceWrapperHelper.newInstance(I_M_HU_Attribute.class, hu);
huAttribute.setAD_Org_ID(hu.getAD_Org_ID());
huAttribute.setM_HU(hu);
huAttribute.setM_Attribute_ID(trxAttribute.getM_Attribute_ID());
huAttribute.setM_HU_PI_Attribute_ID(trxAttribute.getM_HU_PI_Attribute_ID());
}
else
{
huAttribute = huAttributeExisting;
}
//
// Update values
huAttribute.setValue(trxAttribute.getValue());
huAttribute.setValueNumber(trxAttribute.getValueNumber());
// TODO tsa: why following line was missing?!?
// huAttribute.setValueDate(trxAttribute.getValueDate());
huAttributesDAO.save(huAttribute);
}
|
@Override
public void processDrop(final IHUContext huContext, final I_M_HU_Trx_Attribute huTrxAttribute, final Object referencedModel)
{
final IHUAttributesDAO huAttributesDAO = huContext.getHUAttributeStorageFactory().getHUAttributesDAO();
final I_M_HU_Attribute huAttributeExisting = retrieveHUAttribute(huAttributesDAO, huTrxAttribute);
if (huAttributeExisting == null)
{
throw new InvalidAttributeValueException("Retrieved HUAttribute cannot be null (" + huTrxAttribute.getM_Attribute_ID() + "): " + huTrxAttribute);
}
huAttributesDAO.delete(huAttributeExisting);
}
private I_M_HU_Attribute retrieveHUAttribute(final IHUAttributesDAO huAttributesDAO, final I_M_HU_Trx_Attribute trx)
{
if (trx.getM_HU_Attribute_ID() > 0)
{
final I_M_HU_Attribute huAttributeExisting = trx.getM_HU_Attribute();
if (huAttributeExisting != null && huAttributeExisting.getM_HU_Attribute_ID() > 0)
{
return huAttributeExisting;
}
}
final I_M_HU hu = trx.getM_HU();
final AttributeId attributeId = AttributeId.ofRepoId(trx.getM_Attribute_ID());
final I_M_HU_Attribute huAttribute = huAttributesDAO.retrieveAttribute(hu, attributeId);
return huAttribute;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\spi\impl\HUTrxAttributeProcessor_HU.java
| 1
|
请完成以下Java代码
|
private static List<Geometry> buildPolygonsFromJson(JsonArray polygonsJsonArray) {
List<Geometry> polygons = new LinkedList<>();
for (JsonElement polygonJsonArray : polygonsJsonArray) {
polygons.add(
buildPolygonFromCoordinates(parseCoordinates(polygonJsonArray.getAsJsonArray()))
);
}
return polygons;
}
private static Geometry buildPolygonFromCoordinates(List<Coordinate> coordinates) {
if (coordinates.size() == 2) {
Coordinate a = coordinates.get(0);
Coordinate c = coordinates.get(1);
coordinates.clear();
Coordinate b = new Coordinate(a.x, c.y);
Coordinate d = new Coordinate(c.x, a.y);
coordinates.addAll(List.of(a, b, c, d, a));
}
CoordinateSequence coordinateSequence = jtsCtx
.getShapeFactory()
.getGeometryFactory()
.getCoordinateSequenceFactory()
.create(coordinates.toArray(new Coordinate[0]));
return GeometryFixer.fix(jtsCtx.getShapeFactory().getGeometryFactory().createPolygon(coordinateSequence));
}
private static List<Coordinate> parseCoordinates(JsonArray coordinatesJson) {
|
List<Coordinate> result = new LinkedList<>();
for (JsonElement coords : coordinatesJson) {
double x = coords.getAsJsonArray().get(0).getAsDouble();
double y = coords.getAsJsonArray().get(1).getAsDouble();
result.add(new Coordinate(x, y));
}
if (result.size() >= 3) {
result.add(result.get(0));
}
return result;
}
private static boolean containsPrimitives(JsonArray array) {
for (JsonElement element : array) {
return element.isJsonPrimitive();
}
return false;
}
private static boolean containsArrayWithPrimitives(JsonArray array) {
for (JsonElement element : array) {
if (!containsPrimitives(element.getAsJsonArray())) {
return false;
}
}
return true;
}
}
|
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\geo\GeoUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public CommonResult<CommonPage<PmsProductAttribute>> getList(@PathVariable Long cid,
@RequestParam(value = "type") Integer type,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
List<PmsProductAttribute> productAttributeList = productAttributeService.getList(cid, type, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(productAttributeList));
}
@ApiOperation("添加商品属性信息")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult create(@RequestBody PmsProductAttributeParam productAttributeParam) {
int count = productAttributeService.create(productAttributeParam);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("修改商品属性信息")
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult update(@PathVariable Long id, @RequestBody PmsProductAttributeParam productAttributeParam) {
int count = productAttributeService.update(id, productAttributeParam);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("查询单个商品属性")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<PmsProductAttribute> getItem(@PathVariable Long id) {
|
PmsProductAttribute productAttribute = productAttributeService.getItem(id);
return CommonResult.success(productAttribute);
}
@ApiOperation("批量删除商品属性")
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(@RequestParam("ids") List<Long> ids) {
int count = productAttributeService.delete(ids);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("根据商品分类的id获取商品属性及属性分类")
@RequestMapping(value = "/attrInfo/{productCategoryId}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<ProductAttrInfo>> getAttrInfo(@PathVariable Long productCategoryId) {
List<ProductAttrInfo> productAttrInfoList = productAttributeService.getProductAttrInfo(productCategoryId);
return CommonResult.success(productAttrInfoList);
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\PmsProductAttributeController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
// 创建 TaskExecutorBuilder 对象
TaskExecutorBuilder builder = createTskExecutorBuilder(this.taskExecutionProperties());
// 创建 ThreadPoolTaskExecutor 对象
return builder.build();
}
}
private static TaskExecutorBuilder createTskExecutorBuilder(TaskExecutionProperties properties) {
// Pool 属性
TaskExecutionProperties.Pool pool = properties.getPool();
TaskExecutorBuilder builder = new TaskExecutorBuilder();
builder = builder.queueCapacity(pool.getQueueCapacity());
builder = builder.corePoolSize(pool.getCoreSize());
|
builder = builder.maxPoolSize(pool.getMaxSize());
builder = builder.allowCoreThreadTimeOut(pool.isAllowCoreThreadTimeout());
builder = builder.keepAlive(pool.getKeepAlive());
// Shutdown 属性
TaskExecutionProperties.Shutdown shutdown = properties.getShutdown();
builder = builder.awaitTermination(shutdown.isAwaitTermination());
builder = builder.awaitTerminationPeriod(shutdown.getAwaitTerminationPeriod());
// 其它基本属性
builder = builder.threadNamePrefix(properties.getThreadNamePrefix());
// builder = builder.customizers(taskExecutorCustomizers.orderedStream()::iterator);
// builder = builder.taskDecorator(taskDecorator.getIfUnique());
return builder;
}
}
|
repos\SpringBoot-Labs-master\lab-29\lab-29-async-two\src\main\java\cn\iocoder\springboot\lab29\asynctask\config\AsyncConfig.java
| 2
|
请完成以下Java代码
|
protected List<String> extractCandidates(String str) {
return Arrays.asList(str.split("[\\s]*,[\\s]*"));
}
protected Expression getActiveValue(Expression originalValue, String propertyName, ObjectNode taskElementProperties) {
Expression activeValue = originalValue;
if (taskElementProperties != null) {
JsonNode overrideValueNode = taskElementProperties.get(propertyName);
if (overrideValueNode != null) {
if (overrideValueNode.isNull()) {
activeValue = null;
} else {
activeValue = Context.getProcessEngineConfiguration().getExpressionManager().createExpression(overrideValueNode.asString());
}
}
}
return activeValue;
}
protected Set<Expression> getActiveValueSet(Set<Expression> originalValues, String propertyName, ObjectNode taskElementProperties) {
Set<Expression> activeValues = originalValues;
if (taskElementProperties != null) {
JsonNode overrideValuesNode = taskElementProperties.get(propertyName);
if (overrideValuesNode != null) {
if (overrideValuesNode.isNull() || !overrideValuesNode.isArray() || overrideValuesNode.isEmpty()) {
activeValues = null;
} else {
ExpressionManager expressionManager = Context.getProcessEngineConfiguration().getExpressionManager();
activeValues = new HashSet<>();
for (JsonNode valueNode : overrideValuesNode) {
|
activeValues.add(expressionManager.createExpression(valueNode.asString()));
}
}
}
}
return activeValues;
}
// getters and setters //////////////////////////////////////////////////////
public TaskDefinition getTaskDefinition() {
return taskDefinition;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\UserTaskActivityBehavior.java
| 1
|
请完成以下Java代码
|
public boolean hasAttributes()
{
return false;
}
@Override
public IViewRowAttributes getAttributes() throws EntityNotFoundException
{
throw new EntityNotFoundException("Row does not support attributes");
}
@Override
public ViewId getIncludedViewId()
{
return includedViewId;
}
public ShipmentScheduleId getShipmentScheduleId()
{
|
return shipmentScheduleId;
}
public Optional<OrderLineId> getSalesOrderLineId()
{
return salesOrderLineId;
}
public ProductId getProductId()
{
return product != null ? ProductId.ofRepoIdOrNull(product.getIdAsInt()) : null;
}
public Quantity getQtyOrderedWithoutPicked()
{
return qtyOrdered.subtract(qtyPicked).toZeroIfNegative();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\PackageableRow.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isIncludeUnsampled() {
return this.includeUnsampled;
}
public void setIncludeUnsampled(boolean includeUnsampled) {
this.includeUnsampled = includeUnsampled;
}
public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public int getMaxBatchSize() {
return this.maxBatchSize;
}
public void setMaxBatchSize(int maxBatchSize) {
this.maxBatchSize = maxBatchSize;
}
public int getMaxQueueSize() {
return this.maxQueueSize;
}
|
public void setMaxQueueSize(int maxQueueSize) {
this.maxQueueSize = maxQueueSize;
}
public Duration getScheduleDelay() {
return this.scheduleDelay;
}
public void setScheduleDelay(Duration scheduleDelay) {
this.scheduleDelay = scheduleDelay;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\OpenTelemetryTracingProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final AddressRepository addressRepository;
public UserServiceImpl(UserRepository userRepository,
AddressRepository addressRepository) {
this.userRepository = userRepository;
this.addressRepository = addressRepository;
}
@Transactional
@Override
public String createUser(String name, String email) {
String id = UUID.randomUUID().toString();
AddressEntity address = createAddress();
UserEntity userEntity = new UserEntity();
userEntity.setId(id);
userEntity.setAddress(address);
userEntity.setName(name);
userEntity.setEmail(email);
userEntity.setEnabled(true);
addressRepository.save(address);
userRepository.save(userEntity);
return id;
}
|
@Override
public Collection<UserEntity> getAll() {
return userRepository.findAll();
}
@Transactional
@Override
public void deleteUser(String id) {
UserEntity userEntity = new UserEntity();
userEntity.setId(id);
userRepository.delete(userEntity);
}
private AddressEntity createAddress() {
String id = UUID.randomUUID().toString();
AddressEntity addressEntity = new AddressEntity();
addressEntity.setId(id);
addressEntity.setStreet("street");
addressEntity.setCity("city");
return addressEntity;
}
}
|
repos\spring-examples-java-17\spring-data\src\main\java\itx\examples\springdata\service\UserServiceImpl.java
| 2
|
请完成以下Java代码
|
public I_M_HU_LUTU_Configuration createAndEdit(final Function<I_M_HU_LUTU_Configuration, I_M_HU_LUTU_Configuration> lutuConfigurationEditor)
{
final ILUTUConfigurationEditor editor = startEditing();
editor.updateFromModel();
if (lutuConfigurationEditor != null)
{
editor.edit(lutuConfigurationEditor);
if (!editor.isEditing())
{
return null;
}
}
// Save the edited configuration and push it back to model
editor.pushBackToModel();
return editor.getLUTUConfiguration();
}
@Override
public ILUTUConfigurationEditor startEditing()
{
return new LUTUConfigurationEditor(this);
}
@Override
public I_M_HU_LUTU_Configuration getCreateLUTUConfiguration()
{
//
// If there is an already existing configuration, return it without any changes
final I_M_HU_LUTU_Configuration lutuConfigurationExisting = getCurrentLUTUConfigurationOrNull();
if (lutuConfigurationExisting != null && lutuConfigurationExisting.getM_HU_LUTU_Configuration_ID() > 0)
{
return lutuConfigurationExisting;
}
//
// Create a new LU/TU configuration and return it
return createNewLUTUConfiguration();
}
@Override
public I_M_HU_LUTU_Configuration getCurrentLUTUConfigurationOrNull()
{
final T documentLine = getDocumentLine();
return handler.getCurrentLUTUConfigurationOrNull(documentLine);
}
@Override
public void setCurrentLUTUConfigurationAndSave(final I_M_HU_LUTU_Configuration lutuConfiguration)
{
// Update the document line
final T documentLine = getDocumentLine();
|
handler.setCurrentLUTUConfiguration(documentLine, lutuConfiguration);
// Save it
handler.save(documentLine);
}
protected I_M_HU_LUTU_Configuration createNewLUTUConfiguration()
{
final T documentLine = getDocumentLine();
return handler.createNewLUTUConfiguration(documentLine);
}
private T getDocumentLine()
{
return _documentLine;
}
@Override
public void updateLUTUConfigurationFromModel(final I_M_HU_LUTU_Configuration lutuConfiguration)
{
final T documentLine = getDocumentLine();
handler.updateLUTUConfigurationFromDocumentLine(lutuConfiguration, documentLine);
}
@Override
public I_M_HU_PI_Item_Product getM_HU_PI_Item_Product()
{
final T documentLine = getDocumentLine();
return handler.getM_HU_PI_Item_Product(documentLine);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\DocumentLUTUConfigurationManager.java
| 1
|
请完成以下Java代码
|
public static SimpleSequence create()
{
return new SimpleSequence(0, 10);
}
/**
* The first invocation of {@link #next()} will return {code initial + 10}.
*/
public static SimpleSequence createWithInitial(final int initial)
{
return new SimpleSequence(initial, 10);
}
@Builder
private SimpleSequence(final int initial, final int increment)
{
|
this.initial = initial;
Check.errorIf(increment == 0, "The given increment may not be zero");
this.increment = increment;
current = initial;
}
public int next()
{
current = current + increment;
return current;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\SimpleSequence.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
ServerRSocketConnector serverRSocketConnector(ServerRSocketMessageHandler messageHandler) {
return new ServerRSocketConnector(messageHandler);
}
}
@Configuration(proxyBeanMethods = false)
protected static class IntegrationRSocketClientConfiguration {
@Bean
@ConditionalOnMissingBean
@Conditional(RemoteRSocketServerAddressConfigured.class)
ClientRSocketConnector clientRSocketConnector(IntegrationProperties integrationProperties,
RSocketStrategies rSocketStrategies) {
IntegrationProperties.RSocket.Client client = integrationProperties.getRsocket().getClient();
ClientRSocketConnector clientRSocketConnector;
if (client.getUri() != null) {
clientRSocketConnector = new ClientRSocketConnector(client.getUri());
}
else if (client.getHost() != null && client.getPort() != null) {
clientRSocketConnector = new ClientRSocketConnector(client.getHost(), client.getPort());
}
else {
throw new IllegalStateException("Neither uri nor host and port is set");
}
clientRSocketConnector.setRSocketStrategies(rSocketStrategies);
return clientRSocketConnector;
}
/**
* Check if a remote address is configured for the RSocket Integration client.
|
*/
static class RemoteRSocketServerAddressConfigured extends AnyNestedCondition {
RemoteRSocketServerAddressConfigured() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty("spring.integration.rsocket.client.uri")
static class WebSocketAddressConfigured {
}
@ConditionalOnProperty({ "spring.integration.rsocket.client.host",
"spring.integration.rsocket.client.port" })
static class TcpAddressConfigured {
}
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-integration\src\main\java\org\springframework\boot\integration\autoconfigure\IntegrationAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public void setJvmRoute(String jvmRoute) {
this.jvmRoute = "." + jvmRoute;
}
/**
* Set if the Base64 encoding of cookie value should be used. This is valuable in
* order to support <a href="https://tools.ietf.org/html/rfc6265">RFC 6265</a> which
* recommends using Base 64 encoding to the cookie value.
* @param useBase64Encoding the flag to indicate whether to use Base64 encoding
*/
public void setUseBase64Encoding(boolean useBase64Encoding) {
this.useBase64Encoding = useBase64Encoding;
}
/**
* Set the request attribute name that indicates remember-me login. If specified, the
* cookie will be written as Integer.MAX_VALUE.
* @param rememberMeRequestAttribute the remember-me request attribute name
* @since 1.3.0
*/
public void setRememberMeRequestAttribute(String rememberMeRequestAttribute) {
if (rememberMeRequestAttribute == null) {
throw new IllegalArgumentException("rememberMeRequestAttribute cannot be null");
}
this.rememberMeRequestAttribute = rememberMeRequestAttribute;
}
/**
* Set the value for the {@code SameSite} cookie directive. The default value is
* {@code Lax}.
* @param sameSite the SameSite directive value
* @since 2.1.0
*/
public void setSameSite(String sameSite) {
this.sameSite = sameSite;
}
private String getDomainName(HttpServletRequest request) {
if (this.domainName != null) {
return this.domainName;
}
if (this.domainNamePattern != null) {
Matcher matcher = this.domainNamePattern.matcher(request.getServerName());
if (matcher.matches()) {
|
return matcher.group(1);
}
}
return null;
}
private String getCookiePath(HttpServletRequest request) {
if (this.cookiePath == null) {
String contextPath = request.getContextPath();
return (contextPath != null && contextPath.length() > 0) ? contextPath : "/";
}
return this.cookiePath;
}
/**
* Gets the name of the request attribute that is checked to see if the cookie should
* be written with {@link Integer#MAX_VALUE}.
* @return the remember me request attribute
* @since 3.2
*/
public String getRememberMeRequestAttribute() {
return this.rememberMeRequestAttribute;
}
/**
* Allows defining whether the generated cookie carries the Partitioned attribute.
* @param partitioned whether the generate cookie is partitioned
* @since 3.4
*/
public void setPartitioned(boolean partitioned) {
this.partitioned = partitioned;
}
}
|
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\DefaultCookieSerializer.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.