instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public I_M_Attribute getAttribute()
{
return attribute;
}
@Override
public AttributeCode getAttributeCode()
{
return AttributeCode.ofString(getAttribute().getValue());
}
@Override
public IHUAttributePropagationContext getParent()
{
return parent;
}
@Override
public void setUpdateStorageValue(final boolean updateStorageValue)
{
this.updateStorageValue = updateStorageValue;
}
@Override
public boolean isUpdateStorageValue()
{
return updateStorageValue;
}
@Override
public void setValueUpdateInvocation()
{
valueUpdateInvocation = true;
}
@Override
public boolean isValueUpdateInvocation()
{
return valueUpdateInvocation;
}
@Override
public boolean isValueUpdatedBefore()
{
return isValueUpdatedBefore(getAttributeCode());
}
@Override
public boolean isValueUpdatedBefore(final AttributeCode attributeCode)
{
return getLastPropagatorOrNull(attributeCode) != null;
}
@Override
public IHUAttributePropagator getLastPropagatorOrNull(@NonNull final AttributeCode attributeCode)
{
// Iterate up chain of parents, starting with the parent context. for each parent context, we check if the attribute was updated in that context
// NOTE: we are skipping current node because we want to check if that attribute was updated before
for (IHUAttributePropagationContext currentParentContext = parent; currentParentContext != null; currentParentContext = currentParentContext.getParent())
{
if (!currentParentContext.isValueUpdateInvocation())
{
continue;
}
final IAttributeStorage currentAttributeStorage = currentParentContext.getAttributeStorage();
|
if (!currentAttributeStorage.equals(attributeStorage))
{
continue;
}
final AttributeCode currentAttributeCode = currentParentContext.getAttributeCode();
if (!AttributeCode.equals(currentAttributeCode, attributeCode))
{
continue;
}
return currentParentContext.getPropagator();
}
return null;
}
@Override
public IAttributeValueContext copy()
{
return cloneForPropagation(getAttributeStorage(), getAttribute(), getPropagator());
}
@Override
public IHUAttributePropagationContext cloneForPropagation(final IAttributeStorage attributeStorage, final I_M_Attribute attribute, final IHUAttributePropagator propagatorToUse)
{
final HUAttributePropagationContext propagationContextClone = new HUAttributePropagationContext(this, attributeStorage, propagatorToUse, attribute, getParameters());
return propagationContextClone;
}
@Override
public boolean isExternalInput()
{
// NOTE: we consider External Input if this is the first context created (i.e. has no parents => no previous calls)
return Util.same(getParent(), IHUAttributePropagationContext.NULL);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\propagation\impl\HUAttributePropagationContext.java
| 1
|
请完成以下Java代码
|
public void setC_Currency_ID (final int C_Currency_ID)
{
if (C_Currency_ID < 1)
set_Value (COLUMNNAME_C_Currency_ID, null);
else
set_Value (COLUMNNAME_C_Currency_ID, C_Currency_ID);
}
@Override
public int getC_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Currency_ID);
}
@Override
public void setC_Currency_To_ID (final int C_Currency_To_ID)
{
if (C_Currency_To_ID < 1)
set_Value (COLUMNNAME_C_Currency_To_ID, null);
else
set_Value (COLUMNNAME_C_Currency_To_ID, C_Currency_To_ID);
}
@Override
public int getC_Currency_To_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Currency_To_ID);
}
@Override
|
public void setMultiplyRate_Max (final @Nullable BigDecimal MultiplyRate_Max)
{
set_Value (COLUMNNAME_MultiplyRate_Max, MultiplyRate_Max);
}
@Override
public BigDecimal getMultiplyRate_Max()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MultiplyRate_Max);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setMultiplyRate_Min (final @Nullable BigDecimal MultiplyRate_Min)
{
set_Value (COLUMNNAME_MultiplyRate_Min, MultiplyRate_Min);
}
@Override
public BigDecimal getMultiplyRate_Min()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MultiplyRate_Min);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ConversionRate_Rule.java
| 1
|
请完成以下Java代码
|
public void setClassname (final @Nullable java.lang.String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
@Override
public java.lang.String getClassname()
{
return get_ValueAsString(COLUMNNAME_Classname);
}
@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 de.metas.invoicecandidate.model.I_M_ProductGroup getM_ProductGroup()
{
return get_ValueAsPO(COLUMNNAME_M_ProductGroup_ID, de.metas.invoicecandidate.model.I_M_ProductGroup.class);
}
@Override
public void setM_ProductGroup(final de.metas.invoicecandidate.model.I_M_ProductGroup M_ProductGroup)
{
set_ValueFromPO(COLUMNNAME_M_ProductGroup_ID, de.metas.invoicecandidate.model.I_M_ProductGroup.class, M_ProductGroup);
}
@Override
public void setM_ProductGroup_ID (final int M_ProductGroup_ID)
{
if (M_ProductGroup_ID < 1)
set_Value (COLUMNNAME_M_ProductGroup_ID, null);
else
set_Value (COLUMNNAME_M_ProductGroup_ID, M_ProductGroup_ID);
}
@Override
public int getM_ProductGroup_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ProductGroup_ID);
}
|
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_Invoice_Candidate_Agg.java
| 1
|
请完成以下Java代码
|
public static <E> PeekIterator<E> asPeekIterator(final Iterator<E> iterator)
{
if (iterator instanceof PeekIterator)
{
final PeekIterator<E> peekIterator = (PeekIterator<E>)iterator;
return peekIterator;
}
else
{
return new PeekIteratorWrapper<>(iterator);
}
}
public static <IT, OT> Iterator<OT> map(@NonNull final Iterator<IT> iterator, @NonNull final Function<IT, OT> mapper)
{
return new MappingIteratorWrapper<>(iterator, mapper);
}
public static <T> Iterator<T> unmodifiableIterator(final Iterator<T> iterator)
{
return new UnmodifiableIterator<>(iterator);
}
public static <T> Iterator<T> emptyIterator()
{
return EmptyIterator.getInstance();
}
|
/**
* @param iterator
* @return the iterator wrapped to stream
*/
public static <T> Stream<T> stream(final Iterator<T> iterator)
{
Spliterator<T> spliterator = Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED);
final boolean parallel = false;
return StreamSupport.stream(spliterator, parallel);
}
public static <T> Stream<T> stream(final BlindIterator<T> blindIterator)
{
return stream(asIterator(blindIterator));
}
public static <T> PagedIteratorBuilder<T> newPagedIterator()
{
return PagedIterator.builder();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\IteratorUtils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable Set<String> getEnabledProtocols() {
return this.enabledProtocols;
}
public void setEnabledProtocols(@Nullable Set<String> enabledProtocols) {
this.enabledProtocols = enabledProtocols;
}
}
public static class Key {
/**
* The password used to access the key in the key store.
*/
private @Nullable String password;
/**
* The alias that identifies the key in the key store.
*/
private @Nullable String alias;
public @Nullable String getPassword() {
|
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public @Nullable String getAlias() {
return this.alias;
}
public void setAlias(@Nullable String alias) {
this.alias = alias;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\SslBundleProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setM_PriceList_ID (final int M_PriceList_ID)
{
if (M_PriceList_ID < 1)
set_Value (COLUMNNAME_M_PriceList_ID, null);
else
set_Value (COLUMNNAME_M_PriceList_ID, M_PriceList_ID);
}
@Override
public int getM_PriceList_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_ID);
}
@Override
public void setM_PricingSystem_ID (final int M_PricingSystem_ID)
{
if (M_PricingSystem_ID < 1)
set_Value (COLUMNNAME_M_PricingSystem_ID, null);
else
set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID);
}
@Override
public int getM_PricingSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID);
}
@Override
public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setOpenAmt (final BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
@Override
public BigDecimal getOpenAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_OpenAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPaidAmt (final BigDecimal PaidAmt)
{
set_Value (COLUMNNAME_PaidAmt, PaidAmt);
}
@Override
public BigDecimal getPaidAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PaidAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
|
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
/**
* Status AD_Reference_ID=541890
* Reference name: C_POS_Order_Status
*/
public static final int STATUS_AD_Reference_ID=541890;
/** Drafted = DR */
public static final String STATUS_Drafted = "DR";
/** WaitingPayment = WP */
public static final String STATUS_WaitingPayment = "WP";
/** Completed = CO */
public static final String STATUS_Completed = "CO";
/** Voided = VO */
public static final String STATUS_Voided = "VO";
/** Closed = CL */
public static final String STATUS_Closed = "CL";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
@Override
public void setTaxAmt (final BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
@Override
public BigDecimal getTaxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Order.java
| 2
|
请完成以下Java代码
|
public void setPP_Cost_Collector(final org.eevolution.model.I_PP_Cost_Collector PP_Cost_Collector)
{
set_ValueFromPO(COLUMNNAME_PP_Cost_Collector_ID, org.eevolution.model.I_PP_Cost_Collector.class, PP_Cost_Collector);
}
@Override
public void setPP_Cost_Collector_ID (final int PP_Cost_Collector_ID)
{
if (PP_Cost_Collector_ID < 1)
set_Value (COLUMNNAME_PP_Cost_Collector_ID, null);
else
set_Value (COLUMNNAME_PP_Cost_Collector_ID, PP_Cost_Collector_ID);
}
@Override
public int getPP_Cost_Collector_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Cost_Collector_ID);
}
@Override
public org.eevolution.model.I_PP_Order_BOMLine getPP_Order_BOMLine()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_BOMLine_ID, org.eevolution.model.I_PP_Order_BOMLine.class);
}
@Override
public void setPP_Order_BOMLine(final org.eevolution.model.I_PP_Order_BOMLine PP_Order_BOMLine)
{
set_ValueFromPO(COLUMNNAME_PP_Order_BOMLine_ID, org.eevolution.model.I_PP_Order_BOMLine.class, PP_Order_BOMLine);
}
@Override
public void setPP_Order_BOMLine_ID (final int PP_Order_BOMLine_ID)
{
if (PP_Order_BOMLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_BOMLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_BOMLine_ID, PP_Order_BOMLine_ID);
|
}
@Override
public int getPP_Order_BOMLine_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_BOMLine_ID);
}
@Override
public void setQtyToIssue (final BigDecimal QtyToIssue)
{
set_Value (COLUMNNAME_QtyToIssue, QtyToIssue);
}
@Override
public BigDecimal getQtyToIssue()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToIssue);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Candidate_IssueToOrder.java
| 1
|
请完成以下Java代码
|
public class State {
private Board board;
private int playerNo;
private int visitCount;
private double winScore;
public State() {
board = new Board();
}
public State(State state) {
this.board = new Board(state.getBoard());
this.playerNo = state.getPlayerNo();
this.visitCount = state.getVisitCount();
this.winScore = state.getWinScore();
}
public State(Board board) {
this.board = new Board(board);
}
Board getBoard() {
return board;
}
void setBoard(Board board) {
this.board = board;
}
int getPlayerNo() {
return playerNo;
}
void setPlayerNo(int playerNo) {
this.playerNo = playerNo;
}
int getOpponent() {
return 3 - playerNo;
}
public int getVisitCount() {
return visitCount;
}
public void setVisitCount(int visitCount) {
this.visitCount = visitCount;
}
double getWinScore() {
return winScore;
}
void setWinScore(double winScore) {
this.winScore = winScore;
}
public List<State> getAllPossibleStates() {
List<State> possibleStates = new ArrayList<>();
List<Position> availablePositions = this.board.getEmptyPositions();
availablePositions.forEach(p -> {
|
State newState = new State(this.board);
newState.setPlayerNo(3 - this.playerNo);
newState.getBoard().performMove(newState.getPlayerNo(), p);
possibleStates.add(newState);
});
return possibleStates;
}
void incrementVisit() {
this.visitCount++;
}
void addScore(double score) {
if (this.winScore != Integer.MIN_VALUE)
this.winScore += score;
}
void randomPlay() {
List<Position> availablePositions = this.board.getEmptyPositions();
int totalPossibilities = availablePositions.size();
int selectRandom = (int) (Math.random() * totalPossibilities);
this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
}
void togglePlayer() {
this.playerNo = 3 - this.playerNo;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\mcts\montecarlo\State.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the year
*/
public Integer getYear() {
return year;
}
/**
* @param year the year to set
*/
public void setYear(Integer year) {
this.year = year;
}
/**
* @return the sku
*/
public String getSku() {
return sku;
}
/**
* @param sku the sku to set
*/
public void setSku(String sku) {
this.sku = sku;
}
/**
* @return the maker
*/
public CarMaker getMaker() {
return maker;
}
/**
* @param maker the maker to set
*/
public void setMaker(CarMaker maker) {
this.maker = maker;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
|
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((maker == null) ? 0 : maker.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sku == null) ? 0 : sku.hashCode());
result = prime * result + ((year == null) ? 0 : year.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CarModel other = (CarModel) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (maker == null) {
if (other.maker != null)
return false;
} else if (!maker.equals(other.maker))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (sku == null) {
if (other.sku != null)
return false;
} else if (!sku.equals(other.sku))
return false;
if (year == null) {
if (other.year != null)
return false;
} else if (!year.equals(other.year))
return false;
return true;
}
}
|
repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\domain\CarModel.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((count == null) ? 0 : count.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NameAgeEntity other = (NameAgeEntity) obj;
if (age == null) {
if (other.age != null)
|
return false;
} else if (!age.equals(other.age))
return false;
if (count == null) {
if (other.count != null)
return false;
} else if (!count.equals(other.count))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "NameAgeEntity [age=" + age + ", count=" + count + ", name=" + name + "]";
}
}
|
repos\tutorials-master\spring-web-modules\spring-thymeleaf-attributes\accessing-session-attributes\src\main\java\com\baeldung\accesing_session_attributes\business\entities\NameAgeEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WebServiceConfig extends WsConfigurerAdapter {
@Value("${ws.api.path:/ws/api/v1/*}")
private String webserviceApiPath;
@Value("${ws.port.type.name:ProductsPort}")
private String webservicePortTypeName;
@Value("${ws.target.namespace:http://www.baeldung.com/springbootsoap/keycloak}")
private String webserviceTargetNamespace;
@Value("${ws.location.uri:http://localhost:18080/ws/api/v1/}")
private String locationUri;
@Bean
public ServletRegistrationBean<MessageDispatcherServlet> messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean<>(servlet, webserviceApiPath);
}
@Bean(name = "products")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema productsSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName(webservicePortTypeName);
wsdl11Definition.setTargetNamespace(webserviceTargetNamespace);
wsdl11Definition.setLocationUri(locationUri);
wsdl11Definition.setSchema(productsSchema);
return wsdl11Definition;
}
@Bean
public XsdSchema productsSchema() {
return new SimpleXsdSchema(new ClassPathResource("products.xsd"));
}
@Bean
public Map<String, Product> getProducts()
{
|
Map<String, Product> map = new HashMap<>();
Product foldsack= new Product();
foldsack.setId("1");
foldsack.setName("Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops");
foldsack.setDescription("Your perfect pack for everyday use and walks in the forest. ");
Product shirt= new Product();
shirt.setId("2");
shirt.setName("Mens Casual Premium Slim Fit T-Shirts");
shirt.setDescription("Slim-fitting style, contrast raglan long sleeve, three-button henley placket.");
map.put("1", foldsack);
map.put("2", shirt);
return map;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-keycloak-2\src\main\java\com\baeldung\keycloak\keycloaksoap\WebServiceConfig.java
| 2
|
请完成以下Java代码
|
public boolean isEmpty()
{
return elements.isEmpty();
}
public AcctSchemaElementsMap onlyDisplayedInEditor()
{
final ImmutableList<AcctSchemaElement> elementsFiltered = elements.stream()
.filter(AcctSchemaElement::isDisplayedInEditor)
.collect(ImmutableList.toImmutableList());
if (elementsFiltered.size() == elements.size())
{
return this;
}
else
{
return of(elementsFiltered);
}
}
public boolean isElementEnabled(@NonNull final AcctSchemaElementType elementType)
{
return elementsByType.get(elementType) != null;
}
@Nullable
public AcctSchemaElement getByElementType(@NonNull final AcctSchemaElementType elementType)
{
return elementsByType.get(elementType);
}
public ImmutableSet<AcctSchemaElementType> getElementTypes()
{
return elementsByType.keySet();
}
@Override
|
public Iterator<AcctSchemaElement> iterator()
{
return elements.iterator();
}
public ChartOfAccountsId getChartOfAccountsId()
{
final AcctSchemaElement accountSchemaElement = getByElementType(AcctSchemaElementType.Account);
if (accountSchemaElement == null)
{
throw new AdempiereException("No schema element of type " + AcctSchemaElementType.Account + " found");
}
final ChartOfAccountsId chartOfAccountsId = accountSchemaElement.getChartOfAccountsId();
if (chartOfAccountsId == null)
{
throw new AdempiereException("No Chart of Accounts defined for " + accountSchemaElement);
}
return chartOfAccountsId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\AcctSchemaElementsMap.java
| 1
|
请完成以下Java代码
|
public List<String> shortcutFieldOrder() {
return Arrays.asList(BASE_MSG, PRE_LOGGER, POST_LOGGER);
}
@Override
public GatewayFilter apply(Config config) {
return new OrderedGatewayFilter((exchange, chain) -> {
if (config.isPreLogger())
logger.info("Pre GatewayFilter logging: " + config.getBaseMessage());
return chain.filter(exchange)
.then(Mono.fromRunnable(() -> {
if (config.isPostLogger())
logger.info("Post GatewayFilter logging: " + config.getBaseMessage());
}));
}, 1);
}
public static class Config {
private String baseMessage;
private boolean preLogger;
private boolean postLogger;
public Config() {
};
public Config(String baseMessage, boolean preLogger, boolean postLogger) {
super();
this.baseMessage = baseMessage;
this.preLogger = preLogger;
this.postLogger = postLogger;
}
public String getBaseMessage() {
return this.baseMessage;
|
}
public boolean isPreLogger() {
return preLogger;
}
public boolean isPostLogger() {
return postLogger;
}
public void setBaseMessage(String baseMessage) {
this.baseMessage = baseMessage;
}
public void setPreLogger(boolean preLogger) {
this.preLogger = preLogger;
}
public void setPostLogger(boolean postLogger) {
this.postLogger = postLogger;
}
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\LoggingGatewayFilterFactory.java
| 1
|
请完成以下Java代码
|
public int getDropShip_Location_Value_ID()
{
return delegate.getDropShip_Location_Value_ID();
}
@Override
public void setDropShip_Location_Value_ID(final int DropShip_Location_Value_ID)
{
delegate.setDropShip_Location_Value_ID(DropShip_Location_Value_ID);
}
@Override
public int getDropShip_User_ID()
{
return delegate.getDropShip_User_ID();
}
@Override
public void setDropShip_User_ID(final int DropShip_User_ID)
{
delegate.setDropShip_User_ID(DropShip_User_ID);
}
@Override
public int getM_Warehouse_ID()
{
return -1;
}
@Override
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
|
IDocumentDeliveryLocationAdapter.super.setRenderedAddress(from);
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public ContractDropshipLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new ContractDropshipLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Flatrate_Term.class));
}
@Override
public I_C_Flatrate_Term getWrappedRecord()
{
return delegate;
}
public void setFrom(final @NonNull BPartnerLocationAndCaptureId dropshipLocationId, final @Nullable BPartnerContactId dropshipContactId)
{
setDropShip_BPartner_ID(dropshipLocationId.getBpartnerRepoId());
setDropShip_Location_ID(dropshipLocationId.getBPartnerLocationRepoId());
setDropShip_Location_Value_ID(dropshipLocationId.getLocationCaptureRepoId());
setDropShip_User_ID(dropshipContactId == null ? -1 : dropshipContactId.getRepoId());
}
public void setFrom(final @NonNull BPartnerLocationAndCaptureId dropshipLocationId)
{
setDropShip_BPartner_ID(dropshipLocationId.getBpartnerRepoId());
setDropShip_Location_ID(dropshipLocationId.getBPartnerLocationRepoId());
setDropShip_Location_Value_ID(dropshipLocationId.getLocationCaptureRepoId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\location\adapter\ContractDropshipLocationAdapter.java
| 1
|
请完成以下Java代码
|
private ContextId getContextId(ConfigurableApplicationContext applicationContext) {
ApplicationContext parent = applicationContext.getParent();
if (parent != null && parent.containsBean(ContextId.class.getName())) {
return parent.getBean(ContextId.class).createChildId();
}
return new ContextId(getApplicationId(applicationContext.getEnvironment()));
}
private String getApplicationId(ConfigurableEnvironment environment) {
String name = environment.getProperty("spring.application.name");
return StringUtils.hasText(name) ? name : "application";
}
/**
* The ID of a context.
*/
static class ContextId {
|
private final AtomicLong children = new AtomicLong();
private final String id;
ContextId(String id) {
this.id = id;
}
ContextId createChildId() {
return new ContextId(this.id + "-" + this.children.incrementAndGet());
}
String getId() {
return this.id;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\ContextIdApplicationContextInitializer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getControlTotalQualifier() {
return controlTotalQualifier;
}
/**
* Sets the value of the controlTotalQualifier property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setControlTotalQualifier(String value) {
this.controlTotalQualifier = value;
}
/**
* Gets the value of the controlTotalValue property.
*
* @return
* possible object is
* {@link String }
*
*/
|
public String getControlTotalValue() {
return controlTotalValue;
}
/**
* Sets the value of the controlTotalValue property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setControlTotalValue(String value) {
this.controlTotalValue = value;
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DocumentExtensionType.java
| 2
|
请完成以下Java代码
|
public java.math.BigDecimal getPrev_CurrentCostPriceLL ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Prev_CurrentCostPriceLL);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Previous Current Qty.
@param Prev_CurrentQty Previous Current Qty */
@Override
public void setPrev_CurrentQty (java.math.BigDecimal Prev_CurrentQty)
{
set_Value (COLUMNNAME_Prev_CurrentQty, Prev_CurrentQty);
}
/** Get Previous Current Qty.
@return Previous Current Qty */
@Override
public java.math.BigDecimal getPrev_CurrentQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Prev_CurrentQty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
|
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@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.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector_CostDetailAdjust.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PriceListId implements RepoIdAware
{
@JsonCreator
public static PriceListId ofRepoId(final int repoId)
{
if (repoId == NONE.repoId)
{
return NONE;
}
return new PriceListId(repoId);
}
@Nullable
public static PriceListId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int getRepoId(final @org.jetbrains.annotations.Nullable PriceListId PriceListId)
{
return PriceListId != null ? PriceListId.getRepoId() : -1;
}
public static final PriceListId NONE = new PriceListId(100);
int repoId;
|
private PriceListId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "repoId");
}
public boolean isNone()
{
return repoId == NONE.repoId;
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable PriceListId priceList1, @Nullable PriceListId priceList2) {return Objects.equals(priceList1, priceList2);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\PriceListId.java
| 2
|
请完成以下Java代码
|
public String getChargingTime() {
return chargingTime;
}
public void setChargingTime(String chargingTime) {
this.chargingTime = chargingTime;
}
}
public static class FuelVehicle extends Vehicle {
String fuelType;
String transmissionType;
public String getFuelType() {
|
return fuelType;
}
public void setFuelType(String fuelType) {
this.fuelType = fuelType;
}
public String getTransmissionType() {
return transmissionType;
}
public void setTransmissionType(String transmissionType) {
this.transmissionType = transmissionType;
}
}
}
|
repos\tutorials-master\jackson-modules\jackson-polymorphic-deserialization\src\main\java\com\baeldung\jackson\polymorphic\deserialization\typeHandlingAnnotations\Vehicle.java
| 1
|
请完成以下Java代码
|
public static void main(String[] args) {
Car car = new Car();
car.drive(50);
car.stop();
car.fuel();
car.сhangeOil("oil");
CarBattery carBattery = new CarBattery();
car.replaceBattery(carBattery);
car.сhangeEngine(new ToyotaEngine());
car.startWithHasLength(" ");
|
car.startWithHasText("t");
car.startWithNotContain("132");
List<String> repairPartsCollection = new ArrayList<>();
repairPartsCollection.add("part");
car.repair(repairPartsCollection);
Map<String, String> repairPartsMap = new HashMap<>();
repairPartsMap.put("1", "part");
car.repair(repairPartsMap);
String[] repairPartsArray = { "part" };
car.repair(repairPartsArray);
}
}
|
repos\tutorials-master\spring-5\src\main\java\com\baeldung\assertions\Car.java
| 1
|
请完成以下Java代码
|
public Object get(Object key) {
if ((key == null) || !String.class.isAssignableFrom(key.getClass())) {
return null;
}
return beanFactory.getBean((String) key);
}
@Override
public boolean containsKey(Object key) {
if ((key == null) || !String.class.isAssignableFrom(key.getClass())) {
return false;
}
return beanFactory.containsBean((String) key);
}
@Override
public Set<Object> keySet() {
throw new FlowableException("unsupported operation on configuration beans");
// List<String> beanNames =
// Arrays.asList(beanFactory.getBeanDefinitionNames());
// return new HashSet<Object>(beanNames);
}
@Override
public void clear() {
throw new FlowableException("can't clear configuration beans");
}
@Override
public boolean containsValue(Object value) {
throw new FlowableException("can't search values in configuration beans");
}
@Override
public Set<Map.Entry<Object, Object>> entrySet() {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public boolean isEmpty() {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public Object put(Object key, Object value) {
throw new FlowableException("unsupported operation on configuration beans");
|
}
@Override
public void putAll(Map<? extends Object, ? extends Object> m) {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public Object remove(Object key) {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public int size() {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public Collection<Object> values() {
throw new FlowableException("unsupported operation on configuration beans");
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\cfg\SpringBeanFactoryProxyMap.java
| 1
|
请完成以下Java代码
|
public Collection<PlanItemDefinition> getPlanItemDefinitions() {
return planItemDefinitionCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Stage.class, CMMN_ELEMENT_STAGE)
.namespaceUri(CMMN11_NS)
.extendsType(PlanFragment.class)
.instanceProvider(new ModelTypeInstanceProvider<Stage>() {
public Stage newInstance(ModelTypeInstanceContext instanceContext) {
return new StageImpl(instanceContext);
}
});
autoCompleteAttribute = typeBuilder.booleanAttribute(CMMN_ATTRIBUTE_AUTO_COMPLETE)
.defaultValue(false)
.build();
exitCriteriaRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXIT_CRITERIA_REFS)
.namespace(CMMN10_NS)
|
.idAttributeReferenceCollection(Sentry.class, CmmnAttributeElementReferenceCollection.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
planningTableChild = sequenceBuilder.element(PlanningTable.class)
.build();
planItemDefinitionCollection = sequenceBuilder.elementCollection(PlanItemDefinition.class)
.build();
exitCriterionCollection = sequenceBuilder.elementCollection(ExitCriterion.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\StageImpl.java
| 1
|
请完成以下Java代码
|
public void newLU(final HuPackingInstructionsId luPackingInstructionsId) {consolidate_FromTUs_ToNewLU(fromTUs, luPackingInstructionsId);}
@Override
public void existingLU(final HuId luId, final HUQRCode luQRCode) {consolidate_FromTUs_ToExistingLU(fromTUs, luId);}
});
}
private void consolidate_FromTUs_ToNewLU(@NonNull final List<I_M_HU> fromTUs, @NonNull final HuPackingInstructionsId luPackingInstructionsId)
{
if (fromTUs.isEmpty())
{
return;
}
final I_M_HU firstTU = fromTUs.get(0);
final I_M_HU lu = huTransformService.tuToNewLU(firstTU, QtyTU.ONE, luPackingInstructionsId)
.getSingleLURecord();
|
if (fromTUs.size() > 1)
{
final List<I_M_HU> remainingTUs = fromTUs.subList(1, fromTUs.size());
huTransformService.tusToExistingLU(remainingTUs, lu);
}
final HuId luId = HuId.ofRepoId(lu.getM_HU_ID());
final HUQRCode qrCode = huQRCodesService.getQRCodeByHuId(luId);
setCurrentTarget(HUConsolidationTarget.ofExistingLU(luId, qrCode));
}
private void consolidate_FromTUs_ToExistingLU(@NonNull final List<I_M_HU> fromTUs, @NonNull final HuId luId)
{
huTransformService.tusToExistingLUId(fromTUs, luId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\commands\consolidate\ConsolidateCommand.java
| 1
|
请完成以下Java代码
|
private static LookupDescriptor computeLookupDescriptor(@NonNull final AttributesIncludedTabFieldDescriptor includedTabField, @NonNull final AttributesIncludedTabService attributesIncludedTabService)
{
if (includedTabField.getAttributeValueType().isList())
{
final IAttributeValuesProvider attributeValuesProvider = attributesIncludedTabService.createAttributeValuesProvider(includedTabField.getAttributeId());
if (attributeValuesProvider != null)
{
return ASILookupDescriptor.of(attributeValuesProvider);
}
}
return null;
}
public static String computeFieldName(final AttributesIncludedTabFieldDescriptor includedTabField)
{
return includedTabField.getAttributeCode().getCode();
}
private static AttributesIncludedTabDataField writeValueAsLocalDate(AttributesIncludedTabDataField dataField, IDocumentFieldView documentField)
{
return dataField.withDateValue(documentField.getValueAs(LocalDate.class));
}
private static AttributesIncludedTabDataField writeValueAsInteger(AttributesIncludedTabDataField dataField, IDocumentFieldView documentField)
{
return dataField.withNumberValue(documentField.getValueAs(Integer.class));
}
private static AttributesIncludedTabDataField writeValueAsBigDecimal(AttributesIncludedTabDataField dataField, IDocumentFieldView documentField)
{
return dataField.withNumberValue(documentField.getValueAs(BigDecimal.class));
}
private static AttributesIncludedTabDataField writeValueAsString(AttributesIncludedTabDataField dataField, IDocumentFieldView documentField)
{
return dataField.withStringValue(documentField.getValueAs(String.class));
}
private static AttributesIncludedTabDataField writeValueAsListItem(final AttributesIncludedTabDataField dataField, final IDocumentFieldView documentField)
{
final StringLookupValue lookupValue = documentField.getValueAs(StringLookupValue.class);
final String valueString = lookupValue != null ? lookupValue.getIdAsString() : null;
final AttributeValueId valueItemId = documentField.getDescriptor().getLookupDescriptor().get().cast(ASILookupDescriptor.class).getAttributeValueId(valueString);
return dataField.withListValue(valueString, valueItemId);
}
|
public Object getValue(final @NonNull AttributesIncludedTabData data)
{
return valueReader.readValue(data, attributeId);
}
public AttributesIncludedTabDataField updateData(final @NonNull AttributesIncludedTabDataField dataField, final IDocumentFieldView documentField)
{
return valueWriter.writeValue(dataField, documentField);
}
//
//
//
//
//
@FunctionalInterface
private interface ValueReader
{
Object readValue(AttributesIncludedTabData data, AttributeId attributeId);
}
@FunctionalInterface
private interface ValueWriter
{
AttributesIncludedTabDataField writeValue(AttributesIncludedTabDataField dataField, IDocumentFieldView documentField);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attributes_included_tab\AttributesIncludedTabFieldBinding.java
| 1
|
请完成以下Java代码
|
public String getClassname ()
{
return (String)get_Value(COLUMNNAME_Classname);
}
/** 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 Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
|
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementMatcher.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int updateSort(Long id, Integer sort) {
SmsHomeRecommendSubject recommendSubject = new SmsHomeRecommendSubject();
recommendSubject.setId(id);
recommendSubject.setSort(sort);
return smsHomeRecommendSubjectMapper.updateByPrimaryKeySelective(recommendSubject);
}
@Override
public int delete(List<Long> ids) {
SmsHomeRecommendSubjectExample example = new SmsHomeRecommendSubjectExample();
example.createCriteria().andIdIn(ids);
return smsHomeRecommendSubjectMapper.deleteByExample(example);
}
@Override
public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) {
SmsHomeRecommendSubjectExample example = new SmsHomeRecommendSubjectExample();
example.createCriteria().andIdIn(ids);
SmsHomeRecommendSubject record = new SmsHomeRecommendSubject();
record.setRecommendStatus(recommendStatus);
|
return smsHomeRecommendSubjectMapper.updateByExampleSelective(record,example);
}
@Override
public List<SmsHomeRecommendSubject> list(String subjectName, Integer recommendStatus, Integer pageSize, Integer pageNum) {
PageHelper.startPage(pageNum,pageSize);
SmsHomeRecommendSubjectExample example = new SmsHomeRecommendSubjectExample();
SmsHomeRecommendSubjectExample.Criteria criteria = example.createCriteria();
if(!StrUtil.isEmpty(subjectName)){
criteria.andSubjectNameLike("%"+subjectName+"%");
}
if(recommendStatus!=null){
criteria.andRecommendStatusEqualTo(recommendStatus);
}
example.setOrderByClause("sort desc");
return smsHomeRecommendSubjectMapper.selectByExample(example);
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\SmsHomeRecommendSubjectServiceImpl.java
| 2
|
请完成以下Java代码
|
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Integer getLoginType() {
return loginType;
}
public void setLoginType(Integer loginType) {
this.loginType = loginType;
}
|
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", memberId=").append(memberId);
sb.append(", createTime=").append(createTime);
sb.append(", ip=").append(ip);
sb.append(", city=").append(city);
sb.append(", loginType=").append(loginType);
sb.append(", province=").append(province);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberLoginLog.java
| 1
|
请完成以下Java代码
|
public static boolean isEligibleHU(final HURow row)
{
final IHUContextFactory huContextFactory = Services.get(IHUContextFactory.class);
final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
final I_M_HU hu = handlingUnitsBL.getById(row.getHuId());
// Multi product HUs are not allowed - see https://github.com/metasfresh/metasfresh/issues/6709
return huContextFactory
.createMutableHUContext()
.getHUStorageFactory()
.getStorage(hu)
.isSingleProductStorage();
}
@Nullable
public static HURow toHURowOrNull(final IViewRow viewRow)
{
if (viewRow instanceof HUEditorRow)
{
final HUEditorRow huRow = HUEditorRow.cast(viewRow);
return HURow.builder()
.huId(huRow.getHuId())
.topLevelHU(huRow.isTopLevel())
.huStatusActive(huRow.isHUStatusActive())
.build();
}
else if (viewRow instanceof PPOrderLineRow)
{
final PPOrderLineRow ppOrderLineRow = PPOrderLineRow.cast(viewRow);
// this process does not apply to source HUs
if (ppOrderLineRow.isSourceHU())
{
return null;
}
if (!ppOrderLineRow.getType().isHUOrHUStorage())
{
return null;
}
return HURow.builder()
.huId(ppOrderLineRow.getHuId())
.topLevelHU(ppOrderLineRow.isTopLevelHU())
.huStatusActive(ppOrderLineRow.isHUStatusActive())
.qty(ppOrderLineRow.getQty())
.build();
}
else
{
//noinspection ThrowableNotThrown
new AdempiereException("Row type not supported: " + viewRow).throwIfDeveloperModeOrLogWarningElse(logger);
return null;
}
}
|
public static ImmutableList<HURow> getHURowsFromIncludedRows(final PPOrderLinesView view)
{
return view.streamByIds(DocumentIdsSelection.ALL)
.filter(row -> row.getType().isMainProduct() || row.isReceipt())
.flatMap(row -> row.getIncludedRows().stream())
.map(row -> toHURowOrNull(row))
.filter(Objects::nonNull)
.filter(HURow::isTopLevelHU)
.filter(HURow::isHuStatusActive)
.filter(row -> isEligibleHU(row))
.collect(ImmutableList.toImmutableList());
}
public static void pickAndProcessSingleHU(@NonNull final PickRequest pickRequest, @NonNull final ProcessPickingRequest processRequest)
{
pickHU(pickRequest);
processHUs(processRequest);
}
public static void pickHU(@NonNull final PickRequest request)
{
pickingCandidateService.pickHU(request);
}
public static void processHUs(@NonNull final ProcessPickingRequest request)
{
pickingCandidateService.processForHUIds(request.getHuIds(),
request.getShipmentScheduleId(),
OnOverDelivery.ofTakeWholeHUFlag(request.isTakeWholeHU()),
request.getPpOrderId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\util\WEBUI_PP_Order_ProcessHelper.java
| 1
|
请完成以下Java代码
|
public long getResourceSize(TenantId tenantId, TbResourceId resourceId) {
return resourceRepository.getDataSizeById(resourceId.getId());
}
@Override
public TbResourceDataInfo getResourceDataInfo(TenantId tenantId, TbResourceId resourceId) {
return resourceRepository.getDataInfoById(resourceId.getId());
}
@Override
public Long sumDataSizeByTenantId(TenantId tenantId) {
return resourceRepository.sumDataSizeByTenantId(tenantId.getId());
}
@Override
public TbResource findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(resourceRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public PageData<TbResource> findByTenantId(UUID tenantId, PageLink pageLink) {
return findAllByTenantId(TenantId.fromUUID(tenantId), pageLink);
}
|
@Override
public PageData<TbResourceId> findIdsByTenantId(UUID tenantId, PageLink pageLink) {
return DaoUtil.pageToPageData(resourceRepository.findIdsByTenantId(tenantId, DaoUtil.toPageable(pageLink))
.map(TbResourceId::new));
}
@Override
public TbResourceId getExternalIdByInternal(TbResourceId internalId) {
return DaoUtil.toEntityId(resourceRepository.getExternalIdByInternal(internalId.getId()), TbResourceId::new);
}
@Override
public EntityType getEntityType() {
return EntityType.TB_RESOURCE;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\resource\JpaTbResourceDao.java
| 1
|
请完成以下Java代码
|
public ResponseEntity<JsonError> handleException(@NonNull final Exception e)
{
final ResponseStatus responseStatus = e.getClass().getAnnotation(ResponseStatus.class);
if (responseStatus != null)
{
return logAndCreateError(e, responseStatus.reason(), responseStatus.code());
}
return logAndCreateError(e, HttpStatus.UNPROCESSABLE_ENTITY);
}
private ResponseEntity<JsonError> logAndCreateError(
@NonNull final Exception e,
@NonNull final HttpStatus status)
{
return logAndCreateError(e, null, status);
}
private ResponseEntity<JsonError> logAndCreateError(
@NonNull final Exception e,
|
@Nullable final String detail,
@NonNull final HttpStatus status)
{
final String logMessage = coalesceSuppliers(
() -> detail,
e::getMessage,
() -> e.getClass().getSimpleName());
Loggables.withFallbackToLogger(logger, Level.ERROR).addLog(logMessage, e);
final String adLanguage = Env.getADLanguageOrBaseLanguage();
final JsonError error = JsonError.builder()
.error(JsonErrors.ofThrowable(e, adLanguage, TranslatableStrings.constant(detail)))
.build();
return new ResponseEntity<>(error, status);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\exception\RestResponseEntityExceptionHandler.java
| 1
|
请完成以下Java代码
|
public void setAD_Replication_Run_ID (int AD_Replication_Run_ID)
{
if (AD_Replication_Run_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Replication_Run_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Replication_Run_ID, Integer.valueOf(AD_Replication_Run_ID));
}
/** Get Replication Run.
@return Data Replication Run
*/
public int getAD_Replication_Run_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Replication_Run_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getAD_Replication_Run_ID()));
}
public I_AD_ReplicationTable getAD_ReplicationTable() throws RuntimeException
{
return (I_AD_ReplicationTable)MTable.get(getCtx(), I_AD_ReplicationTable.Table_Name)
.getPO(getAD_ReplicationTable_ID(), get_TrxName()); }
/** Set Replication Table.
@param AD_ReplicationTable_ID
Data Replication Strategy Table Info
*/
public void setAD_ReplicationTable_ID (int AD_ReplicationTable_ID)
{
if (AD_ReplicationTable_ID < 1)
set_Value (COLUMNNAME_AD_ReplicationTable_ID, null);
else
set_Value (COLUMNNAME_AD_ReplicationTable_ID, Integer.valueOf(AD_ReplicationTable_ID));
}
/** Get Replication Table.
@return Data Replication Strategy Table Info
*/
public int getAD_ReplicationTable_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_ReplicationTable_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Replicated.
@param IsReplicated
The data is successfully replicated
*/
public void setIsReplicated (boolean IsReplicated)
|
{
set_Value (COLUMNNAME_IsReplicated, Boolean.valueOf(IsReplicated));
}
/** Get Replicated.
@return The data is successfully replicated
*/
public boolean isReplicated ()
{
Object oo = get_Value(COLUMNNAME_IsReplicated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Message.
@param P_Msg Process Message */
public void setP_Msg (String P_Msg)
{
set_Value (COLUMNNAME_P_Msg, P_Msg);
}
/** Get Process Message.
@return Process Message */
public String getP_Msg ()
{
return (String)get_Value(COLUMNNAME_P_Msg);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication_Log.java
| 1
|
请完成以下Java代码
|
public ReferrerAddressType getReferrer() {
return referrer;
}
/**
* Sets the value of the referrer property.
*
* @param value
* allowed object is
* {@link ReferrerAddressType }
*
*/
public void setReferrer(ReferrerAddressType value) {
this.referrer = value;
}
/**
* Gets the value of the employer property.
*
* @return
* possible object is
* {@link EmployerAddressType }
*
*/
public EmployerAddressType getEmployer() {
return employer;
}
/**
* Sets the value of the employer property.
*
* @param value
* allowed object is
* {@link EmployerAddressType }
|
*
*/
public void setEmployer(EmployerAddressType value) {
this.employer = value;
}
/**
* Gets the value of the paymentPeriod property.
*
* @return
* possible object is
* {@link Duration }
*
*/
public Duration getPaymentPeriod() {
return paymentPeriod;
}
/**
* Sets the value of the paymentPeriod property.
*
* @param value
* allowed object is
* {@link Duration }
*
*/
public void setPaymentPeriod(Duration value) {
this.paymentPeriod = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\GarantType.java
| 1
|
请完成以下Java代码
|
private void checkInvoiceCandidate(@NonNull final I_C_Flatrate_DataEntry dataEntry)
{
final InvoiceCandidateId invoiceCandId = InvoiceCandidateId.ofRepoIdOrNull(dataEntry.getC_Invoice_Candidate_ID());
if (invoiceCandId != null)
{
final I_C_Invoice_Candidate invoiceCandidate = invoiceCandDAO.getById(invoiceCandId);
failIfInvoiced(invoiceCandidate);
}
final InvoiceCandidateId icCorrId = InvoiceCandidateId.ofRepoIdOrNull(dataEntry.getC_Invoice_Candidate_Corr_ID());
if (icCorrId != null)
{
final I_C_Invoice_Candidate icCorr = invoiceCandDAO.getById(icCorrId);
failIfInvoiced(icCorr);
}
final List<I_C_Invoice_Candidate> referencingICs = invoiceCandDAO.retrieveReferencing(TableRecordReference.of(dataEntry));
referencingICs.forEach(C_Flatrate_DataEntry::failIfInvoiced);
}
private static void failIfInvoiced(@Nullable final I_C_Invoice_Candidate icRecord)
{
if (icRecord != null && icRecord.getQtyInvoiced().signum() != 0)
{
throw new AdempiereException("@" + MSG_DATA_ENTRY_ALREADY_INVOICED_0P + "@");
}
}
private void deleteInvoiceCandidate(@NonNull final I_C_Flatrate_DataEntry dataEntry)
{
final InvoiceCandidateId invoiceCandId = InvoiceCandidateId.ofRepoIdOrNull(dataEntry.getC_Invoice_Candidate_ID());
if (invoiceCandId != null)
{
final I_C_Invoice_Candidate invoiceCandidate = invoiceCandDAO.getById(invoiceCandId);
if (invoiceCandidate != null)
{
dataEntry.setC_Invoice_Candidate_ID(0);
InterfaceWrapperHelper.delete(invoiceCandidate);
|
}
}
invoiceCandDAO.deleteAllReferencingInvoiceCandidates(dataEntry);
}
private void deleteInvoiceCandidateCorr(@NonNull final I_C_Flatrate_DataEntry dataEntry)
{
final InvoiceCandidateId invoiceCandId = InvoiceCandidateId.ofRepoIdOrNull(dataEntry.getC_Invoice_Candidate_Corr_ID());
if (invoiceCandId != null)
{
final I_C_Invoice_Candidate icCorr = invoiceCandDAO.getById(invoiceCandId);
if (icCorr != null)
{
dataEntry.setC_Invoice_Candidate_Corr_ID(0);
InterfaceWrapperHelper.delete(icCorr);
}
}
}
private void afterReactivate(final I_C_Flatrate_DataEntry dataEntry)
{
if (X_C_Flatrate_DataEntry.TYPE_Invoicing_PeriodBased.equals(dataEntry.getType()))
{
final IFlatrateDAO flatrateDB = Services.get(IFlatrateDAO.class);
final List<I_C_Invoice_Clearing_Alloc> allocLines = flatrateDB.retrieveClearingAllocs(dataEntry);
for (final I_C_Invoice_Clearing_Alloc alloc : allocLines)
{
final I_C_Invoice_Candidate candToClear = alloc.getC_Invoice_Cand_ToClear();
candToClear.setQtyInvoiced(BigDecimal.ZERO);
InterfaceWrapperHelper.save(candToClear);
alloc.setC_Invoice_Candidate_ID(0);
InterfaceWrapperHelper.save(alloc);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_Flatrate_DataEntry.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public Boolean getFailed() {
return failed;
}
public void setFailed(Boolean failed) {
this.failed = failed;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getTenantId() {
return tenantId;
}
|
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getDecisionKey() {
return decisionKey;
}
public void setDecisionKey(String decisionKey) {
this.decisionKey = decisionKey;
}
public String getDecisionName() {
return decisionName;
}
public void setDecisionName(String decisionName) {
this.decisionName = decisionName;
}
public String getDecisionVersion() {
return decisionVersion;
}
public void setDecisionVersion(String decisionVersion) {
this.decisionVersion = decisionVersion;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\history\HistoricDecisionExecutionResponse.java
| 2
|
请完成以下Java代码
|
public class GrpcExceptionServerCall<ReqT, RespT> extends SimpleForwardingServerCall<ReqT, RespT> {
private final GrpcExceptionResponseHandler exceptionHandler;
/**
* Creates a new exception handling grpc server call.
*
* @param delegate The call to delegate to (Required).
* @param exceptionHandler The exception handler to use (Required).
*/
protected GrpcExceptionServerCall(
final ServerCall<ReqT, RespT> delegate,
final GrpcExceptionResponseHandler exceptionHandler) {
super(delegate);
|
this.exceptionHandler = exceptionHandler;
}
@Override
public void close(final Status status, final Metadata trailers) {
// For error responses sent via StreamObserver#onError
if (status.getCode() == Code.UNKNOWN && status.getCause() != null) {
final Throwable cause = status.getCause();
this.exceptionHandler.handleError(delegate(), cause);
} else {
super.close(status, trailers);
}
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\error\GrpcExceptionServerCall.java
| 1
|
请完成以下Java代码
|
public static String fileChose() {
JFileChooser fc = new JFileChooser();
int ret = fc.showOpenDialog(null);
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
return file.getAbsolutePath();
} else {
return null;
}
}
public static void main(String[] args) throws IOException {
if (!modelPath.exists()) {
logger.info("The model not found. Have you trained it?");
return;
}
|
MultiLayerNetwork model = ModelSerializer.restoreMultiLayerNetwork(modelPath);
String path = fileChose();
File file = new File(path);
INDArray image = new NativeImageLoader(height, width, channels).asMatrix(file);
new ImagePreProcessingScaler(0, 1).transform(image);
// Pass through to neural Net
INDArray output = model.output(image);
logger.info("File: {}", path);
logger.info("Probabilities: {}", output);
}
}
|
repos\tutorials-master\deeplearning4j\src\main\java\com\baeldung\logreg\MnistPrediction.java
| 1
|
请完成以下Java代码
|
protected IHUItemStorage getHUItemStorage(final I_M_HU_Item item, final IAllocationRequest request)
{
final IHUItemStorage storage = super.getHUItemStorage(item, request);
// make sure that the capacity is forced by the user, not the system
// If capacityOverride is null it means that we were asked to take the defaults
if (capacityOverride != null && !storage.isPureVirtual())
{
storage.setCustomCapacity(capacityOverride);
}
return storage;
}
@Override
protected IAllocationResult allocateOnIncludedHUItem(
@NonNull final I_M_HU_Item item,
@NonNull final IAllocationRequest request)
{
// Prevent allocating on a included HU item
final HUItemType itemType = services.getItemType(item);
if (HUItemType.HandlingUnit.equals(itemType))
{
if (services.isDeveloperMode())
{
throw new AdempiereException("HUs which are used in " + this + " shall not have included HUs. They shall be pure TUs."
+ "\n Item: " + item
// + "\n PI: " + handlingUnitsBL.getPI(item.getM_HU()).getName()
+ "\n Request: " + request);
}
return AllocationUtils.nullResult();
}
|
//
// We are about to allocate to Virtual HUs linked to given "item" (which shall be of type Material).
// In this case we rely on the standard logic.
return super.allocateOnIncludedHUItem(item, request);
}
/**
* Does nothing, returns null result.
*/
@Override
protected IAllocationResult allocateRemainingOnIncludedHUItem(final I_M_HU_Item item, final IAllocationRequest request)
{
return AllocationUtils.nullResult();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\strategy\UpperBoundAllocationStrategy.java
| 1
|
请完成以下Java代码
|
public Element setLang(String lang)
{
addAttribute("lang",lang);
addAttribute("xml:lang",lang);
return this;
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public frameset addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public frameset addElement(String hashcode,String element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public frameset addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public frameset addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
|
@param hashcode the name of the element to be removed.
*/
public frameset removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
/**
The onload event occurs when the user agent finishes loading a window
or all frames within a frameset. This attribute may be used with body
and frameset elements.
@param The script
*/
public void setOnLoad(String script)
{
addAttribute ( "onload", script );
}
/**
The onunload event occurs when the user agent removes a document from a
window or frame. This attribute may be used with body and frameset
elements.
@param The script
*/
public void setOnUnload(String script)
{
addAttribute ( "onunload", script );
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\frameset.java
| 1
|
请完成以下Java代码
|
public void setC_Queue_WorkPackage_ID (int C_Queue_WorkPackage_ID)
{
if (C_Queue_WorkPackage_ID < 1)
set_Value (COLUMNNAME_C_Queue_WorkPackage_ID, null);
else
set_Value (COLUMNNAME_C_Queue_WorkPackage_ID, Integer.valueOf(C_Queue_WorkPackage_ID));
}
/** Get WorkPackage Queue.
@return WorkPackage Queue */
@Override
public int getC_Queue_WorkPackage_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set WorkPackage Notified.
@param C_Queue_WorkPackage_Notified_ID WorkPackage Notified */
@Override
public void setC_Queue_WorkPackage_Notified_ID (int C_Queue_WorkPackage_Notified_ID)
{
if (C_Queue_WorkPackage_Notified_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Notified_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Notified_ID, Integer.valueOf(C_Queue_WorkPackage_Notified_ID));
}
/** Get WorkPackage Notified.
@return WorkPackage Notified */
|
@Override
public int getC_Queue_WorkPackage_Notified_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_Notified_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Notified.
@param IsNotified Notified */
@Override
public void setIsNotified (boolean IsNotified)
{
set_Value (COLUMNNAME_IsNotified, Boolean.valueOf(IsNotified));
}
/** Get Notified.
@return Notified */
@Override
public boolean isNotified ()
{
Object oo = get_Value(COLUMNNAME_IsNotified);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage_Notified.java
| 1
|
请完成以下Java代码
|
public static void writeStringToFile(String content, String filePath) {
BufferedOutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(getFile(filePath)));
outputStream.write(content.getBytes());
outputStream.flush();
}
catch(Exception e) {
throw LOG.exceptionWhileWritingToFile(filePath, e);
}
finally {
IoUtil.closeSilently(outputStream);
}
}
/**
* Closes the given stream. The same as calling {@link Closeable#close()}, but
* errors while closing are silently ignored.
*/
public static void closeSilently(Closeable closeable) {
try {
if(closeable != null) {
closeable.close();
}
}
catch(IOException ignore) {
LOG.debugCloseException(ignore);
}
|
}
/**
* Flushes the given object. The same as calling {@link Flushable#flush()}, but
* errors while flushing are silently ignored.
*/
public static void flushSilently(Flushable flushable) {
try {
if(flushable != null) {
flushable.flush();
}
}
catch(IOException ignore) {
LOG.debugCloseException(ignore);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\IoUtil.java
| 1
|
请完成以下Java代码
|
public class IsNumeric {
private final Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");
public boolean usingCoreJava(String strNum) {
if (strNum == null) {
return false;
}
try {
Double.parseDouble(strNum);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
public boolean usingPreCompiledRegularExpressions(String strNum) {
if (strNum == null) {
return false;
}
return pattern.matcher(strNum)
.matches();
}
|
public boolean usingNumberUtils_isCreatable(String strNum) {
return NumberUtils.isCreatable(strNum);
}
public boolean usingNumberUtils_isParsable(String strNum) {
return NumberUtils.isParsable(strNum);
}
public boolean usingStringUtils_isNumeric(String strNum) {
return StringUtils.isNumeric(strNum);
}
public boolean usingStringUtils_isNumericSpace(String strNum) {
return StringUtils.isNumericSpace(strNum);
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-operations\src\main\java\com\baeldung\isnumeric\IsNumeric.java
| 1
|
请完成以下Java代码
|
private IContextMenuAction getInstance(final IContextMenuActionContext menuCtx, final Class<? extends IContextMenuAction> actionClass)
{
try
{
final IContextMenuAction action = actionClass.newInstance();
action.setContext(menuCtx);
if (!action.isAvailable())
{
return null;
}
return action;
}
catch (Exception e)
{
logger.warn("Cannot create action for " + actionClass + ": " + e.getLocalizedMessage() + " [SKIP]", e);
return null;
}
}
// @Cached(cacheName = I_AD_Field_ContextMenu.Table_Name + "#By#AD_Client_ID") // not needed, we are caching the classname lists
private final List<I_AD_Field_ContextMenu> retrieveContextMenuForClient(@CacheCtx final Properties ctx, final int adClientId)
{
return Services.get(IQueryBL.class).createQueryBuilder(I_AD_Field_ContextMenu.class, ctx, ITrx.TRXNAME_None)
.addInArrayOrAllFilter(I_AD_Field_ContextMenu.COLUMN_AD_Client_ID, 0, adClientId)
.addOnlyActiveRecordsFilter()
//
.orderBy()
.addColumn(I_AD_Field_ContextMenu.COLUMN_SeqNo)
.addColumn(I_AD_Field_ContextMenu.COLUMN_AD_Field_ContextMenu_ID)
.endOrderBy()
//
.create()
.list(I_AD_Field_ContextMenu.class);
|
}
@Override
public IContextMenuActionContext createContext(final VEditor editor)
{
final VTable vtable = null;
final int viewRow = IContextMenuActionContext.ROW_NA;
final int viewColumn = IContextMenuActionContext.COLUMN_NA;
return createContext(editor, vtable, viewRow, viewColumn);
}
@Override
public IContextMenuActionContext createContext(final VEditor editor, final VTable vtable, final int rowIndexView, final int columnIndexView)
{
return new DefaultContextMenuActionContext(editor, vtable, rowIndexView, columnIndexView);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\impl\ContextMenuProvider.java
| 1
|
请完成以下Java代码
|
default String getPhoneNumber() {
return this.getClaimAsString(StandardClaimNames.PHONE_NUMBER);
}
/**
* Returns {@code true} if the user's phone number has been verified
* {@code (phone_number_verified)}, otherwise {@code false}.
* @return {@code true} if the user's phone number has been verified, otherwise
* {@code false}
*/
default Boolean getPhoneNumberVerified() {
return this.getClaimAsBoolean(StandardClaimNames.PHONE_NUMBER_VERIFIED);
}
/**
* Returns the user's preferred postal address {@code (address)}.
* @return the user's preferred postal address
|
*/
default AddressStandardClaim getAddress() {
Map<String, Object> addressFields = this.getClaimAsMap(StandardClaimNames.ADDRESS);
return (!CollectionUtils.isEmpty(addressFields) ? new DefaultAddressStandardClaim.Builder(addressFields).build()
: new DefaultAddressStandardClaim.Builder().build());
}
/**
* Returns the time the user's information was last updated {@code (updated_at)}.
* @return the time the user's information was last updated
*/
default Instant getUpdatedAt() {
return this.getClaimAsInstant(StandardClaimNames.UPDATED_AT);
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\StandardClaimAccessor.java
| 1
|
请完成以下Java代码
|
public Message<?> preSend(Message<?> message, MessageChannel channel) {
setup(message);
return message;
}
@Override
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, @Nullable Exception ex) {
cleanup();
}
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
setup(message);
return message;
}
@Override
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler,
@Nullable Exception ex) {
cleanup();
}
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy strategy) {
this.securityContextHolderStrategy = strategy;
this.empty = this.securityContextHolderStrategy.createEmptyContext();
}
private void setup(Message<?> message) {
SecurityContext currentContext = this.securityContextHolderStrategy.getContext();
Stack<SecurityContext> contextStack = originalContext.get();
if (contextStack == null) {
contextStack = new Stack<>();
originalContext.set(contextStack);
}
contextStack.push(currentContext);
Object user = message.getHeaders().get(this.authenticationHeaderName);
Authentication authentication = getAuthentication(user);
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(authentication);
this.securityContextHolderStrategy.setContext(context);
}
private Authentication getAuthentication(@Nullable Object user) {
if ((user instanceof Authentication)) {
return (Authentication) user;
}
return this.anonymous;
}
private void cleanup() {
|
Stack<SecurityContext> contextStack = originalContext.get();
if (contextStack == null || contextStack.isEmpty()) {
this.securityContextHolderStrategy.clearContext();
originalContext.remove();
return;
}
SecurityContext context = contextStack.pop();
try {
if (SecurityContextChannelInterceptor.this.empty.equals(context)) {
this.securityContextHolderStrategy.clearContext();
originalContext.remove();
}
else {
this.securityContextHolderStrategy.setContext(context);
}
}
catch (Throwable ex) {
this.securityContextHolderStrategy.clearContext();
}
}
}
|
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\context\SecurityContextChannelInterceptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Mono<Void> requestPasswordReset(@RequestBody String mail) {
return userService
.requestPasswordReset(mail)
.doOnSuccess(user -> {
if (Objects.nonNull(user)) {
mailService.sendPasswordResetMail(user);
} else {
// Pretend the request has been successful to prevent checking which emails really exist
// but log that an invalid attempt has been made
log.warn("Password reset requested for non existing mail");
}
})
.then();
}
/**
* {@code POST /account/reset-password/finish} : Finish to reset the password of the user.
*
* @param keyAndPassword the generated key and the new password.
* @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect.
|
* @throws RuntimeException {@code 500 (Internal Server Error)} if the password could not be reset.
*/
@PostMapping(path = "/account/reset-password/finish")
public Mono<Void> finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) {
if (isPasswordLengthInvalid(keyAndPassword.getNewPassword())) {
throw new InvalidPasswordException();
}
return userService
.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey())
.switchIfEmpty(Mono.error(new AccountResourceException("No user was found for this reset key")))
.then();
}
private static boolean isPasswordLengthInvalid(String password) {
return (
StringUtils.isEmpty(password) ||
password.length() < ManagedUserVM.PASSWORD_MIN_LENGTH ||
password.length() > ManagedUserVM.PASSWORD_MAX_LENGTH
);
}
}
|
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\web\rest\AccountResource.java
| 2
|
请完成以下Java代码
|
public void addExecutionListener(String eventName, ExecutionListener executionListener, int index) {
super.addListener(eventName, executionListener, index);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Deprecated
public Map<String, List<ExecutionListener>> getExecutionListeners() {
return (Map) super.getListeners();
}
// getters and setters //////////////////////////////////////////////////////
public List<ActivityImpl> getActivities() {
return flowActivities;
}
public Set<ActivityImpl> getEventActivities() {
return eventActivities;
|
}
public boolean isSubProcessScope() {
return isSubProcessScope;
}
public void setSubProcessScope(boolean isSubProcessScope) {
this.isSubProcessScope = isSubProcessScope;
}
@Override
public ProcessDefinitionImpl getProcessDefinition() {
return processDefinition;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\ScopeImpl.java
| 1
|
请完成以下Java代码
|
public void apply(final Document document, final JSONIncludedTabInfo jsonIncludedTabInfo)
{
if (isReadonly(document))
{
jsonIncludedTabInfo.setAllowCreateNew(false, "no document access");
jsonIncludedTabInfo.setAllowDelete(false, "no document access");
}
}
public void apply(final DocumentPath documentPath, final JSONIncludedTabInfo jsonIncludedTabInfo)
{
// TODO: implement... but it's not so critical atm
}
private boolean isReadonly(@NonNull final Document document)
{
return readonlyDocuments.computeIfAbsent(document.getDocumentPath(), documentPath -> !DocumentPermissionsHelper.canEdit(document, permissions));
}
public DocumentFieldLogicExpressionResultRevaluator getLogicExpressionResultRevaluator()
{
DocumentFieldLogicExpressionResultRevaluator logicExpressionRevaluator = this.logicExpressionRevaluator;
if (logicExpressionRevaluator == null)
{
logicExpressionRevaluator = this.logicExpressionRevaluator = DocumentFieldLogicExpressionResultRevaluator.using(permissions);
}
return logicExpressionRevaluator;
}
public Set<DocumentStandardAction> getStandardActions(@NonNull final Document document)
{
final HashSet<DocumentStandardAction> standardActions = new HashSet<>(document.getStandardActions());
Boolean allowWindowEdit = null;
Boolean allowDocumentEdit = null;
for (final Iterator<DocumentStandardAction> it = standardActions.iterator(); it.hasNext(); )
{
final DocumentStandardAction action = it.next();
if (action.isDocumentWriteAccessRequired())
{
|
if (allowDocumentEdit == null)
{
allowDocumentEdit = DocumentPermissionsHelper.canEdit(document, permissions);
}
if (!allowDocumentEdit)
{
it.remove();
continue;
}
}
if (action.isWindowWriteAccessRequired())
{
if (allowWindowEdit == null)
{
final DocumentEntityDescriptor entityDescriptor = document.getEntityDescriptor();
final AdWindowId adWindowId = entityDescriptor.getDocumentType().isWindow()
? entityDescriptor.getWindowId().toAdWindowId()
: null;
allowWindowEdit = adWindowId != null && permissions.checkWindowPermission(adWindowId).hasWriteAccess();
}
if (!allowWindowEdit)
{
it.remove();
//noinspection UnnecessaryContinue
continue;
}
}
}
return ImmutableSet.copyOf(standardActions);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentPermissions.java
| 1
|
请完成以下Java代码
|
static <T> ConfigurationPropertyState search(Iterable<T> source, Predicate<T> predicate) {
Assert.notNull(source, "'source' must not be null");
Assert.notNull(predicate, "'predicate' must not be null");
for (T item : source) {
if (predicate.test(item)) {
return PRESENT;
}
}
return ABSENT;
}
/**
* Search the given iterable using a predicate to determine if content is
* {@link #PRESENT} or {@link #ABSENT}.
* @param <T> the data type
* @param source the source iterable to search
* @param startInclusive the first index to cover
* @param endExclusive index immediately past the last index to cover
|
* @param predicate the predicate used to test for presence
* @return {@link #PRESENT} if the iterable contains a matching item, otherwise
* {@link #ABSENT}.
*/
static <T> ConfigurationPropertyState search(T[] source, int startInclusive, int endExclusive,
Predicate<T> predicate) {
Assert.notNull(source, "'source' must not be null");
Assert.notNull(predicate, "'predicate' must not be null");
for (int i = startInclusive; i < endExclusive; i++) {
if (predicate.test(source[i])) {
return PRESENT;
}
}
return ABSENT;
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\ConfigurationPropertyState.java
| 1
|
请完成以下Java代码
|
public void drawString(String text, String artChar, Settings settings) {
BufferedImage image = getImageIntegerMode(settings.width, settings.height);
Graphics2D graphics2D = getGraphics2D(image.getGraphics(), settings);
graphics2D.drawString(text, 6, ((int) (settings.height * 0.67)));
for (int y = 0; y < settings.height; y++) {
StringBuilder stringBuilder = new StringBuilder();
for (int x = 0; x < settings.width; x++) {
stringBuilder.append(image.getRGB(x, y) == -16777216 ? " " : artChar);
}
if (stringBuilder.toString()
.trim()
.isEmpty()) {
continue;
}
System.out.println(stringBuilder);
}
}
private BufferedImage getImageIntegerMode(int width, int height) {
return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
|
private Graphics2D getGraphics2D(Graphics graphics, Settings settings) {
graphics.setFont(settings.font);
Graphics2D graphics2D = (Graphics2D) graphics;
graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
return graphics2D;
}
public class Settings {
public Font font;
public int width;
public int height;
public Settings(Font font, int width, int height) {
this.font = font;
this.width = width;
this.height = height;
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-console\src\main\java\com\baeldung\asciiart\AsciiArt.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BigDecimal getQuantity() {
return quantity;
}
/**
* Sets the value of the quantity property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setQuantity(BigDecimal value) {
this.quantity = value;
}
/**
* Gets the value of the measurementUnitCode property.
*
* @return
* possible object is
* {@link String }
*
*/
|
public String getMeasurementUnitCode() {
return measurementUnitCode;
}
/**
* Sets the value of the measurementUnitCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMeasurementUnitCode(String value) {
this.measurementUnitCode = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ExtendedQuantityType.java
| 2
|
请完成以下Spring Boot application配置
|
##########################################################
################## 所有profile共有的配置 #################
##########################################################
################### 自定义配置 ###################
common:
csvVtoll: /var/csv/
csvCanton: /var/csv/
csvExeOffice: /var/csv/
csvApp: /var/csv/
csvLog: /var/csv/
################### spring配置 ###################
spring:
profiles:
active: test
batch:
job:
enabled: false
initializer:
enabled: false
################### mybatis-plus配置 ###################
mybatis-plus:
mapper-locations: classpath*:com/xncoding/trans/dao/repository/mapping/*.xml
typeAliasesPackage: >
com.xncoding.trans.dao.entity
global-config:
id-type: 1 # 0:数据库ID自增 1:用户输入id 2:全局唯一id(IdWorker) 3:全局唯一ID(uuid)
db-column-underline: false
refresh-mapper: true
configuration:
jdbcTypeForNull: NULL
map-underscore-to-camel-case: true
cache-enabled: true #配置的缓存的全局开关
lazyLoadingEnabled: true #延时加载的开关
multipleResultSetsEnabled: true #开启的话,延时加载一个属性时会加载该对象全部属性,否则按需加载属性
logging:
level:
org.springframework.web.servlet: ERROR
---
#####################################################################
######################## 开发环境profile ##########################
#####################################################################
spring:
profiles: dev
datasource:
driver-class-name: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@127.0.0.1:1521:orcl11g
username: adm_real
password: adm_real
|
common:
location: 1
csvDir: E:/
logging:
level:
ROOT: INFO
com:
xncoding: DEBUG
file: /var/logs/batch.log
---
#####################################################################
######################## 测试环境profile ##########################
#####################################################################
spring:
profiles: test
datasource:
driver-class-name: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@127.0.0.1:1521:orcl11g
username: adm_123
password: adm_123
common:
csvDir: /var/csv/
location: 2
logging:
level:
ROOT: INFO
com:
xncoding: DEBUG
file: /var/logs/batch.log
|
repos\SpringBootBucket-master\springboot-batch\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public void setReverse(boolean reverse) {
synchronized (this.httpExchanges) {
this.reverse = reverse;
}
}
/**
* Set the capacity of the in-memory repository.
* @param capacity the capacity
*/
public void setCapacity(int capacity) {
synchronized (this.httpExchanges) {
this.capacity = capacity;
}
}
@Override
public List<HttpExchange> findAll() {
synchronized (this.httpExchanges) {
return List.copyOf(this.httpExchanges);
}
}
|
@Override
public void add(HttpExchange exchange) {
synchronized (this.httpExchanges) {
while (this.httpExchanges.size() >= this.capacity) {
this.httpExchanges.remove(this.reverse ? this.capacity - 1 : 0);
}
if (this.reverse) {
this.httpExchanges.add(0, exchange);
}
else {
this.httpExchanges.add(exchange);
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\web\exchanges\InMemoryHttpExchangeRepository.java
| 1
|
请完成以下Java代码
|
public void setIdIn(String[] ids) {
this.idIn = ids;
}
@CamundaQueryParam("firstName")
public void setFirstName(String userFirstName) {
this.firstName = userFirstName;
}
@CamundaQueryParam("firstNameLike")
public void setFirstNameLike(String userFirstNameLike) {
this.firstNameLike = userFirstNameLike;
}
@CamundaQueryParam("lastName")
public void setLastName(String userLastName) {
this.lastName = userLastName;
}
@CamundaQueryParam("lastNameLike")
public void setLastNameLike(String userLastNameLike) {
this.lastNameLike = userLastNameLike;
}
@CamundaQueryParam("email")
public void setEmail(String userEmail) {
this.email = userEmail;
}
@CamundaQueryParam("emailLike")
public void setEmailLike(String userEmailLike) {
this.emailLike = userEmailLike;
}
@CamundaQueryParam("memberOfGroup")
public void setMemberOfGroup(String memberOfGroup) {
this.memberOfGroup = memberOfGroup;
}
@CamundaQueryParam("potentialStarter")
public void setPotentialStarter(String potentialStarter) {
this.potentialStarter = potentialStarter;
}
@CamundaQueryParam("memberOfTenant")
public void setMemberOfTenant(String tenantId) {
this.tenantId = tenantId;
}
@Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected UserQuery createNewQuery(ProcessEngine engine) {
return engine.getIdentityService().createUserQuery();
}
@Override
protected void applyFilters(UserQuery query) {
if (id != null) {
query.userId(id);
}
if(idIn != null) {
query.userIdIn(idIn);
|
}
if (firstName != null) {
query.userFirstName(firstName);
}
if (firstNameLike != null) {
query.userFirstNameLike(firstNameLike);
}
if (lastName != null) {
query.userLastName(lastName);
}
if (lastNameLike != null) {
query.userLastNameLike(lastNameLike);
}
if (email != null) {
query.userEmail(email);
}
if (emailLike != null) {
query.userEmailLike(emailLike);
}
if (memberOfGroup != null) {
query.memberOfGroup(memberOfGroup);
}
if (potentialStarter != null) {
query.potentialStarter(potentialStarter);
}
if (tenantId != null) {
query.memberOfTenant(tenantId);
}
}
@Override
protected void applySortBy(UserQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_USER_ID_VALUE)) {
query.orderByUserId();
} else if (sortBy.equals(SORT_BY_USER_FIRSTNAME_VALUE)) {
query.orderByUserFirstName();
} else if (sortBy.equals(SORT_BY_USER_LASTNAME_VALUE)) {
query.orderByUserLastName();
} else if (sortBy.equals(SORT_BY_USER_EMAIL_VALUE)) {
query.orderByUserEmail();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\UserQueryDto.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer ("X_A_RegistrationProduct[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_A_RegistrationAttribute getA_RegistrationAttribute() throws RuntimeException
{
return (I_A_RegistrationAttribute)MTable.get(getCtx(), I_A_RegistrationAttribute.Table_Name)
.getPO(getA_RegistrationAttribute_ID(), get_TrxName()); }
/** Set Registration Attribute.
@param A_RegistrationAttribute_ID
Asset Registration Attribute
*/
public void setA_RegistrationAttribute_ID (int A_RegistrationAttribute_ID)
{
if (A_RegistrationAttribute_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_RegistrationAttribute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_RegistrationAttribute_ID, Integer.valueOf(A_RegistrationAttribute_ID));
}
/** Get Registration Attribute.
@return Asset Registration Attribute
*/
public int getA_RegistrationAttribute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_RegistrationAttribute_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);
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_RegistrationProduct.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class LoggingGlobalFilterProperties {
private boolean enabled;
private boolean requestHeaders;
private boolean requestBody;
private boolean responseHeaders;
private boolean responseBody;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isRequestHeaders() {
return requestHeaders;
}
public void setRequestHeaders(boolean requestHeaders) {
this.requestHeaders = requestHeaders;
}
public boolean isRequestBody() {
return requestBody;
}
public void setRequestBody(boolean requestBody) {
this.requestBody = requestBody;
}
|
public boolean isResponseHeaders() {
return responseHeaders;
}
public void setResponseHeaders(boolean responseHeaders) {
this.responseHeaders = responseHeaders;
}
public boolean isResponseBody() {
return responseBody;
}
public void setResponseBody(boolean responseBody) {
this.responseBody = responseBody;
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway-2\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\global\LoggingGlobalFilterProperties.java
| 2
|
请完成以下Java代码
|
class StringToUniqueInt {
private static final Map<String, Integer> lookupMap = new HashMap<>();
private static final AtomicInteger counter = new AtomicInteger(Integer.MIN_VALUE);
public static int toIntByHashCode(String value) {
return value.hashCode();
}
public static int toIntByCR32(String value) {
CRC32 crc32 = new CRC32();
crc32.update(value.getBytes());
return (int) crc32.getValue();
}
public static int toIntByCharFormula(String value) {
return value.chars()
.reduce(17, (a, b) -> a * 13 + (b / a));
}
public static int toIntByMD5(String value) {
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
|
byte[] hash = digest.digest(value.getBytes());
return ((hash[0] & 0xFF) << 24) | ((hash[1] & 0xFF) << 16) | ((hash[2] & 0xFF) << 8) | (hash[3] & 0xFF);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 not supported", e);
}
}
public static int toIntByLookup(String value) {
Integer found = lookupMap.get(value);
if (found != null) {
return found;
}
Integer intValue = counter.incrementAndGet();
lookupMap.put(value, intValue);
return intValue;
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-algorithms-5\src\main\java\com\baeldung\uniqueint\StringToUniqueInt.java
| 1
|
请完成以下Java代码
|
private static <T> T returnNullOnMoreThanOneUniqueValue(@NonNull final List<T> values)
{
return null;
}
private static class ValueAggregator<T>
{
@NonNull
private final List<T> values = new ArrayList<>();
public void setValue(@Nullable final T newValue)
{
values.add(newValue);
}
@Nullable
public T getAggregatedValue(@NonNull final Function<List<T>, T> onMoreThanOneUniqueValue)
{
if (values.isEmpty())
|
{
return null;
}
final T initialValue = values.get(0);
for (final T value : values)
{
if (!Objects.equals(initialValue, value))
{
return onMoreThanOneUniqueValue.apply(values);
}
}
return initialValue;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderCreateRequestBuilder.java
| 1
|
请完成以下Java代码
|
protected void prepare()
{
paySelectionUpdater = paySelectionBL.newPaySelectionUpdater();
final PaySelectionId paySelectionId = PaySelectionId.ofRepoId(getRecord_ID());
final I_C_PaySelection paySelection = paySelectionDAO.getById(paySelectionId).orElseThrow(AdempiereException::notFound);
paySelectionUpdater.setC_PaySelection(paySelection);
for (final ProcessInfoParameter para : getParametersAsArray())
{
final String name = para.getParameterName();
if (para.getParameter() == null)
{
}
else if (name.equals(PARAM_OnlyDiscount))
{
final boolean p_OnlyDiscount = para.getParameterAsBoolean();
paySelectionUpdater.setOnlyDiscount(p_OnlyDiscount);
}
else if (name.equals(PARAM_OnlyDue))
{
final boolean p_OnlyDue = para.getParameterAsBoolean();
paySelectionUpdater.setOnlyDue(p_OnlyDue);
}
else if (name.equals(PARAM_IncludeInDispute))
{
final boolean p_IncludeInDispute = para.getParameterAsBoolean();
paySelectionUpdater.setIncludeInDispute(p_IncludeInDispute);
}
else if (name.equals(PARAM_MatchRequirement))
{
final PaySelectionMatchingMode matchRequirement = PaySelectionMatchingMode.ofCode(para.getParameterAsString());
|
paySelectionUpdater.setMatchRequirement(matchRequirement);
}
else if (name.equals(PARAM_PayDate))
{
final Timestamp p_PayDate = para.getParameterAsTimestamp();
paySelectionUpdater.setPayDate(p_PayDate);
}
else if (name.equals(PARAM_PaymentRule))
{
final PaymentRule paymentRule = PaymentRule.ofNullableCode(para.getParameterAsString());
paySelectionUpdater.setPaymentRule(paymentRule);
}
else if (name.equals(PARAM_C_BPartner_ID))
{
final int p_C_BPartner_ID = para.getParameterAsInt();
paySelectionUpdater.setC_BPartner_ID(p_C_BPartner_ID);
}
else if (name.equals(PARAM_C_BP_Group_ID))
{
final int p_C_BP_Group_ID = para.getParameterAsInt();
paySelectionUpdater.setC_BP_Group_ID(p_C_BP_Group_ID);
}
}
}
@Override
protected String doIt()
{
paySelectionUpdater.update();
return paySelectionUpdater.getSummary();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\process\C_PaySelection_CreateFrom.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public SignatureVerificationType getSignatureVerification() {
return signatureVerification;
}
/**
* Sets the value of the signatureVerification property.
*
* @param value
* allowed object is
* {@link SignatureVerificationType }
*
*/
public void setSignatureVerification(SignatureVerificationType value) {
this.signatureVerification = value;
}
/**
* Contains all routing information. May include EDIFACT-specific data.
*
* @return
* possible object is
* {@link InterchangeHeaderType }
*
*/
public InterchangeHeaderType getInterchangeHeader() {
return interchangeHeader;
}
/**
* Sets the value of the interchangeHeader property.
*
* @param value
* allowed object is
* {@link InterchangeHeaderType }
*
*/
public void setInterchangeHeader(InterchangeHeaderType value) {
this.interchangeHeader = value;
}
/**
* The ID represents the unique number of the message.
*
* @return
* possible object is
* {@link String }
*
*/
public String getID() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
|
public void setID(String value) {
this.id = value;
}
/**
* This segment contains references related to the message.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReferences() {
return references;
}
/**
* Sets the value of the references property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReferences(String value) {
this.references = value;
}
/**
* Flag indicating whether the message is a test message or not.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isTestIndicator() {
return testIndicator;
}
/**
* Sets the value of the testIndicator property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setTestIndicator(Boolean value) {
this.testIndicator = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\ErpelBusinessDocumentHeaderType.java
| 2
|
请完成以下Java代码
|
public static boolean isInVowelsString(char c) {
return VOWELS.indexOf(c) != -1;
}
public static boolean isInVowelsString(String c) {
return VOWELS.contains(c);
}
public static boolean isVowelBySwitch(char c) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
|
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
return true;
default:
return false;
}
}
public static boolean isVowelByRegex(String c) {
return VOWELS_PATTERN.matcher(c).matches();
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-operations-4\src\main\java\com\baeldung\checkvowels\CheckVowels.java
| 1
|
请完成以下Java代码
|
public class AudioMedia extends Media {
private int bitrate;
private String frequency;
@Override
public void printTitle() {
System.out.println("AudioMedia Title");
}
public int getBitrate() {
return bitrate;
}
public void setBitrate(int bitrate) {
this.bitrate = bitrate;
}
public String getFrequency() {
return frequency;
}
|
public void setFrequency(String frequency) {
this.frequency = frequency;
}
@Override
public String toString() {
return "AudioMedia{" +
"id=" + this.getId() +
", title='" + this.getTitle() + '\'' +
", artist='" + this.getArtist() + '\'' +
", bitrate=" + bitrate +
", frequency='" + frequency + '\'' +
"} ";
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-4\src\main\java\com\baeldung\implementsvsextends\media\model\AudioMedia.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setUserSearchFilter(String userSearchFilter) {
this.userSearchFilter = userSearchFilter;
}
/**
* Search base for user searches. Defaults to "". Only used with
* {@link #setUserSearchFilter(String)}.
* @param userSearchBase search base for user searches
*/
public void setUserSearchBase(String userSearchBase) {
this.userSearchBase = userSearchBase;
}
/**
* Returns the configured {@link AuthenticationManager} that can be used to perform
* LDAP authentication.
* @return the configured {@link AuthenticationManager}
*/
public final AuthenticationManager createAuthenticationManager() {
LdapAuthenticationProvider ldapAuthenticationProvider = getProvider();
return new ProviderManager(ldapAuthenticationProvider);
}
private LdapAuthenticationProvider getProvider() {
AbstractLdapAuthenticator authenticator = getAuthenticator();
LdapAuthenticationProvider provider;
if (this.ldapAuthoritiesPopulator != null) {
provider = new LdapAuthenticationProvider(authenticator, this.ldapAuthoritiesPopulator);
}
else {
provider = new LdapAuthenticationProvider(authenticator);
}
if (this.authoritiesMapper != null) {
provider.setAuthoritiesMapper(this.authoritiesMapper);
|
}
if (this.userDetailsContextMapper != null) {
provider.setUserDetailsContextMapper(this.userDetailsContextMapper);
}
return provider;
}
private AbstractLdapAuthenticator getAuthenticator() {
AbstractLdapAuthenticator authenticator = createDefaultLdapAuthenticator();
if (this.userSearchFilter != null) {
authenticator.setUserSearch(
new FilterBasedLdapUserSearch(this.userSearchBase, this.userSearchFilter, this.contextSource));
}
if (this.userDnPatterns != null && this.userDnPatterns.length > 0) {
authenticator.setUserDnPatterns(this.userDnPatterns);
}
authenticator.afterPropertiesSet();
return authenticator;
}
/**
* Allows subclasses to supply the default {@link AbstractLdapAuthenticator}.
* @return the {@link AbstractLdapAuthenticator} that will be configured for LDAP
* authentication
*/
protected abstract T createDefaultLdapAuthenticator();
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\AbstractLdapAuthenticationManagerFactory.java
| 2
|
请完成以下Java代码
|
public void selectById(int id)
{
selectById(id, true);
}
public void selectById(int id, boolean fireEvent)
{
if (idColumnIndex < 0)
return;
boolean fireSelectionEventOld = fireSelectionEvent;
try
{
fireSelectionEvent = fireEvent;
if (id < 0)
{
this.getSelectionModel().removeSelectionInterval(0, this.getRowCount());
return;
}
|
for (int i = 0; i < this.getRowCount(); i++)
{
IDColumn key = (IDColumn)this.getModel().getValueAt(i, idColumnIndex);
if (key != null && id > 0 && key.getRecord_ID() == id)
{
this.getSelectionModel().setSelectionInterval(i, i);
break;
}
}
}
finally
{
fireSelectionEvent = fireSelectionEventOld;
}
}
private boolean fireSelectionEvent = true;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\ui\swing\MiniTable2.java
| 1
|
请完成以下Java代码
|
public class JdbcDemoTest extends BaseTest {
@Test
public void testJdbcDemo() {
String sql = "select `id`, `user_name`, `age`, `address` from person where user_name = ?";
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
// 注册 JDBC 驱动
Class.forName("org.h2.Driver");
// 打开连接
conn = DriverManager.getConnection("jdbc:h2:mem:ssb_test", "root", "root");
initH2db(conn);
// 创建 Statement
stmt = conn.prepareStatement(sql);
stmt.setString(1, "wyf");
// 执行查询
resultSet = stmt.executeQuery();
// 处理结果
// 展开结果集数据库
List<Person> peoples = new ArrayList<>();
while (resultSet.next()) {
Person person = new Person();
// 通过字段检索
person.setId(resultSet.getLong("id"));
person.setUserName(resultSet.getString("user_name"));
person.setAge(resultSet.getInt("age"));
person.setAddress(resultSet.getString("address"));
peoples.add(person);
}
System.out.println(JSON.toJSONString(peoples));
|
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
if (Objects.nonNull(resultSet)) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (Objects.nonNull(stmt)) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (Objects.nonNull(conn)) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
|
repos\spring-boot-student-master\spring-boot-student-mybatis\src\main\java\com\xiaolyuh\jdbc\JdbcDemoTest.java
| 1
|
请完成以下Java代码
|
class DTO {
private Long customer_id;
private Long order_id;
private Long product_id;
public DTO(Long customer_id, Long order_id, Long product_id) {
this.customer_id = customer_id;
this.order_id = order_id;
this.product_id = product_id;
}
}
@Entity
@IdClass(DTO.class)
public class ResultDTO {
@Id
private Long customer_id;
@Id
private Long order_id;
@Id
private Long product_id;
public void setCustomer_id(Long customer_id) {
this.customer_id = customer_id;
}
public Long getProduct_id() {
return product_id;
}
public void setProduct_id(Long product_id) {
this.product_id = product_id;
}
public ResultDTO(Long customer_id, Long order_id, Long product_id, String customerName, String customerEmail, LocalDate orderDate, String productName, Double productPrice) {
this.customer_id = customer_id;
this.order_id = order_id;
this.product_id = product_id;
this.customerName = customerName;
this.customerEmail = customerEmail;
this.orderDate = orderDate;
this.productName = productName;
this.productPrice = productPrice;
}
private String customerName;
private String customerEmail;
private LocalDate orderDate;
private String productName;
private Double productPrice;
public Long getCustomer_id() {
return customer_id;
}
public void setCustoemr_id(Long custoemr_id) {
this.customer_id = custoemr_id;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerEmail() {
return customerEmail;
|
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
public Long getOrder_id() {
return order_id;
}
public void setOrder_id(Long order_id) {
this.order_id = order_id;
}
public LocalDate getOrderDate() {
return orderDate;
}
public void setOrderDate(LocalDate orderDate) {
this.orderDate = orderDate;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Double getProductPrice() {
return productPrice;
}
public void setProductPrice(Double productPrice) {
this.productPrice = productPrice;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\DTO\ResultDTO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonDataImportResponseWrapper
{
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@Nullable
List<JsonErrorItem> errors;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Nullable
JsonDataImportResponse response;
public static JsonDataImportResponseWrapper ok(final JsonDataImportResponse response)
{
final List<JsonErrorItem> errors = null;
return new JsonDataImportResponseWrapper(errors, response);
}
public static JsonDataImportResponseWrapper error(@NonNull final List<JsonErrorItem> errors)
|
{
final JsonDataImportResponse response = null;
return new JsonDataImportResponseWrapper(errors, response);
}
public static JsonDataImportResponseWrapper error(@NonNull final JsonDataImportResponse response)
{
final List<JsonErrorItem> errors = null;
return new JsonDataImportResponseWrapper(errors, response);
}
public static JsonDataImportResponseWrapper error(final Throwable throwable, final String adLanguage)
{
final List<JsonErrorItem> errors = ImmutableList.of(JsonErrors.ofThrowable(throwable, adLanguage));
final JsonDataImportResponse response = null;
return new JsonDataImportResponseWrapper(errors, response);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\data_import\JsonDataImportResponseWrapper.java
| 2
|
请完成以下Java代码
|
public void setC_CycleStep_ID (int C_CycleStep_ID)
{
if (C_CycleStep_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CycleStep_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CycleStep_ID, Integer.valueOf(C_CycleStep_ID));
}
/** Get Cycle Step.
@return The step for this Cycle
*/
public int getC_CycleStep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CycleStep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Phase getC_Phase() throws RuntimeException
{
return (I_C_Phase)MTable.get(getCtx(), I_C_Phase.Table_Name)
.getPO(getC_Phase_ID(), get_TrxName()); }
/** Set Standard Phase.
@param C_Phase_ID
|
Standard Phase of the Project Type
*/
public void setC_Phase_ID (int C_Phase_ID)
{
if (C_Phase_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Phase_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Phase_ID, Integer.valueOf(C_Phase_ID));
}
/** Get Standard Phase.
@return Standard Phase of the Project Type
*/
public int getC_Phase_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Phase_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CyclePhase.java
| 1
|
请完成以下Java代码
|
protected void makeChannelDefinitionsConsistentWithPersistedVersions(ParsedDeployment parsedDeployment) {
for (ChannelDefinitionEntity channelDefinition : parsedDeployment.getAllChannelDefinitions()) {
ChannelDefinitionEntity persistedChannelDefinition = channelDeploymentHelper.getPersistedInstanceOfChannelDefinition(channelDefinition);
if (persistedChannelDefinition != null) {
channelDefinition.setId(persistedChannelDefinition.getId());
channelDefinition.setVersion(persistedChannelDefinition.getVersion());
}
}
}
public IdGenerator getIdGenerator() {
return idGenerator;
}
public void setIdGenerator(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
}
public ParsedDeploymentBuilderFactory getExParsedDeploymentBuilderFactory() {
return parsedDeploymentBuilderFactory;
}
public void setParsedDeploymentBuilderFactory(ParsedDeploymentBuilderFactory parsedDeploymentBuilderFactory) {
this.parsedDeploymentBuilderFactory = parsedDeploymentBuilderFactory;
}
public EventDefinitionDeploymentHelper getEventDeploymentHelper() {
return eventDeploymentHelper;
}
public void setEventDeploymentHelper(EventDefinitionDeploymentHelper eventDeploymentHelper) {
|
this.eventDeploymentHelper = eventDeploymentHelper;
}
public ChannelDefinitionDeploymentHelper getChannelDeploymentHelper() {
return channelDeploymentHelper;
}
public void setChannelDeploymentHelper(ChannelDefinitionDeploymentHelper channelDeploymentHelper) {
this.channelDeploymentHelper = channelDeploymentHelper;
}
public CachingAndArtifactsManager getCachingAndArtifcatsManager() {
return cachingAndArtifactsManager;
}
public void setCachingAndArtifactsManager(CachingAndArtifactsManager manager) {
this.cachingAndArtifactsManager = manager;
}
public boolean isUsePrefixId() {
return usePrefixId;
}
public void setUsePrefixId(boolean usePrefixId) {
this.usePrefixId = usePrefixId;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\deployer\EventDefinitionDeployer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WSHandler implements WebSocketHandler {
private static final Logger LOG = LoggerFactory.getLogger(WSHandler.class);
private final Map<String, WebSocketSession> sessions;
private final ScheduledExecutorService executorService;
public WSHandler() {
this.sessions = new ConcurrentHashMap<>();
this.executorService = Executors.newScheduledThreadPool(1);
this.executorService.scheduleWithFixedDelay(new WSPublisher(this.sessions), 0L, 20L, TimeUnit.SECONDS);
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
LOG.info("WS session: {}", session.getId());
this.sessions.put(session.getId(), session);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
TextMessage textMessage = (TextMessage)message;
String payload = textMessage.getPayload();
LOG.info("WS message: {} message={}", session.getId(), payload);
session.sendMessage(new TextMessage("Echo: " + payload));
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
LOG.info("WS transport error: {}", session.getId());
this.sessions.remove(session.getId(), session);
|
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
LOG.info("WS connection closed: {}", session.getId());
this.sessions.remove(session.getId(), session);
}
@Override
public boolean supportsPartialMessages() {
return false;
}
@PreDestroy
public void close() throws Exception {
LOG.info("WS shutdown");
this.executorService.shutdownNow();
}
}
|
repos\spring-examples-java-17\spring-websockets\src\main\java\itx\examples\springboot\websockets\config\WSHandler.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Builder singleSignOnServiceLocation(String singleSignOnServiceLocation) {
return (Builder) super.singleSignOnServiceLocation(singleSignOnServiceLocation);
}
/**
* {@inheritDoc}
*/
@Override
public Builder singleSignOnServiceBinding(Saml2MessageBinding singleSignOnServiceBinding) {
return (Builder) super.singleSignOnServiceBinding(singleSignOnServiceBinding);
}
/**
* {@inheritDoc}
*/
@Override
public Builder singleLogoutServiceLocation(String singleLogoutServiceLocation) {
return (Builder) super.singleLogoutServiceLocation(singleLogoutServiceLocation);
}
/**
* {@inheritDoc}
*/
@Override
public Builder singleLogoutServiceResponseLocation(String singleLogoutServiceResponseLocation) {
return (Builder) super.singleLogoutServiceResponseLocation(singleLogoutServiceResponseLocation);
}
/**
* {@inheritDoc}
*/
@Override
public Builder singleLogoutServiceBinding(Saml2MessageBinding singleLogoutServiceBinding) {
|
return (Builder) super.singleLogoutServiceBinding(singleLogoutServiceBinding);
}
/**
* Build an
* {@link org.springframework.security.saml2.provider.service.registration.OpenSamlAssertingPartyDetails}
* @return
*/
@Override
public OpenSamlAssertingPartyDetails build() {
return new OpenSamlAssertingPartyDetails(super.build(), this.descriptor);
}
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\registration\OpenSamlAssertingPartyDetails.java
| 2
|
请完成以下Java代码
|
public class CalculatedFieldEntity extends BaseVersionedEntity<CalculatedField> implements BaseEntity<CalculatedField> {
@Column(name = CALCULATED_FIELD_TENANT_ID_COLUMN)
private UUID tenantId;
@Column(name = CALCULATED_FIELD_ENTITY_TYPE)
private String entityType;
@Column(name = CALCULATED_FIELD_ENTITY_ID)
private UUID entityId;
@Column(name = CALCULATED_FIELD_TYPE)
private String type;
@Column(name = CALCULATED_FIELD_NAME)
private String name;
@Column(name = CALCULATED_FIELD_CONFIGURATION_VERSION)
private int configurationVersion;
@Convert(converter = JsonConverter.class)
@Column(name = CALCULATED_FIELD_CONFIGURATION)
private JsonNode configuration;
@Column(name = CALCULATED_FIELD_VERSION)
private Long version;
@Column(name = DEBUG_SETTINGS)
private String debugSettings;
public CalculatedFieldEntity() {
super();
}
public CalculatedFieldEntity(CalculatedField calculatedField) {
this.setUuid(calculatedField.getUuidId());
this.createdTime = calculatedField.getCreatedTime();
this.tenantId = calculatedField.getTenantId().getId();
this.entityType = calculatedField.getEntityId().getEntityType().name();
this.entityId = calculatedField.getEntityId().getId();
this.type = calculatedField.getType().name();
this.name = calculatedField.getName();
|
this.configurationVersion = calculatedField.getConfigurationVersion();
this.configuration = JacksonUtil.valueToTree(calculatedField.getConfiguration());
this.version = calculatedField.getVersion();
this.debugSettings = JacksonUtil.toString(calculatedField.getDebugSettings());
}
@Override
public CalculatedField toData() {
CalculatedField calculatedField = new CalculatedField(new CalculatedFieldId(id));
calculatedField.setCreatedTime(createdTime);
calculatedField.setTenantId(TenantId.fromUUID(tenantId));
calculatedField.setEntityId(EntityIdFactory.getByTypeAndUuid(entityType, entityId));
calculatedField.setType(CalculatedFieldType.valueOf(type));
calculatedField.setName(name);
calculatedField.setConfigurationVersion(configurationVersion);
calculatedField.setConfiguration(JacksonUtil.treeToValue(configuration, CalculatedFieldConfiguration.class));
calculatedField.setVersion(version);
calculatedField.setDebugSettings(JacksonUtil.fromString(debugSettings, DebugSettings.class));
return calculatedField;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\CalculatedFieldEntity.java
| 1
|
请完成以下Java代码
|
protected String addSqlStatementPiece(String sqlStatement, String line) {
if (sqlStatement==null) {
return line;
}
return sqlStatement + " \n" + line;
}
protected String readNextTrimmedLine(BufferedReader reader) throws IOException {
String line = reader.readLine();
if (line!=null) {
line = line.trim();
}
return line;
}
protected boolean isMissingTablesException(Exception e) {
Throwable cause = e.getCause();
if (cause != null) {
String exceptionMessage = cause.getMessage();
if(cause.getMessage() != null) {
// Matches message returned from H2
if ((exceptionMessage.contains("Table")) && (exceptionMessage.contains("not found"))) {
return true;
}
// Message returned from MySQL and Oracle
if ((exceptionMessage.contains("Table") || exceptionMessage.contains("table")) && (exceptionMessage.contains("doesn't exist"))) {
return true;
}
// Message returned from Postgres
return (exceptionMessage.contains("relation") || exceptionMessage.contains("table")) && (exceptionMessage.contains("does not exist"));
|
}
}
return false;
}
protected String[] getTableTypes() {
// the PostgreSQL JDBC API changed in 42.2.11 and partitioned tables
// are not detected unless the corresponding table type flag is added.
if (DatabaseUtil.checkDatabaseType(DbSqlSessionFactory.POSTGRES)) {
return PG_JDBC_METADATA_TABLE_TYPES;
}
return JDBC_METADATA_TABLE_TYPES;
}
// getters and setters //////////////////////////////////////////////////////
public SqlSession getSqlSession() {
return sqlSession;
}
public DbSqlSessionFactory getDbSqlSessionFactory() {
return dbSqlSessionFactory;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\sql\DbSqlSession.java
| 1
|
请完成以下Java代码
|
public void setInheritBusinessKey(boolean inheritBusinessKey) {
this.inheritBusinessKey = inheritBusinessKey;
}
@Override
public List<IOParameter> getInParameters() {
return inParameters;
}
@Override
public void addInParameter(IOParameter inParameter) {
inParameters.add(inParameter);
}
@Override
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
|
@Override
public List<IOParameter> getOutParameters() {
return outParameters;
}
@Override
public void addOutParameter(IOParameter outParameter) {
outParameters.add(outParameter);
}
@Override
public void setOutParameters(List<IOParameter> outParameters) {
this.outParameters = outParameters;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\ChildTask.java
| 1
|
请完成以下Java代码
|
public boolean equals(Object obj) {
return this.delegate.equals(obj);
}
@Override
public int hashCode() {
return this.delegate.hashCode();
}
@Override
public void print(boolean b) throws IOException {
trackContentLength(b);
this.delegate.print(b);
}
@Override
public void print(char c) throws IOException {
trackContentLength(c);
this.delegate.print(c);
}
@Override
public void print(double d) throws IOException {
trackContentLength(d);
this.delegate.print(d);
}
@Override
public void print(float f) throws IOException {
trackContentLength(f);
this.delegate.print(f);
}
@Override
public void print(int i) throws IOException {
trackContentLength(i);
this.delegate.print(i);
}
@Override
public void print(long l) throws IOException {
trackContentLength(l);
this.delegate.print(l);
}
@Override
public void print(String s) throws IOException {
trackContentLength(s);
this.delegate.print(s);
}
@Override
public void println() throws IOException {
trackContentLengthLn();
this.delegate.println();
}
@Override
public void println(boolean b) throws IOException {
trackContentLength(b);
trackContentLengthLn();
this.delegate.println(b);
}
@Override
public void println(char c) throws IOException {
trackContentLength(c);
trackContentLengthLn();
this.delegate.println(c);
}
@Override
public void println(double d) throws IOException {
trackContentLength(d);
|
trackContentLengthLn();
this.delegate.println(d);
}
@Override
public void println(float f) throws IOException {
trackContentLength(f);
trackContentLengthLn();
this.delegate.println(f);
}
@Override
public void println(int i) throws IOException {
trackContentLength(i);
trackContentLengthLn();
this.delegate.println(i);
}
@Override
public void println(long l) throws IOException {
trackContentLength(l);
trackContentLengthLn();
this.delegate.println(l);
}
@Override
public void println(String s) throws IOException {
trackContentLength(s);
trackContentLengthLn();
this.delegate.println(s);
}
@Override
public void write(byte[] b) throws IOException {
trackContentLength(b);
this.delegate.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
checkContentLength(len);
this.delegate.write(b, off, len);
}
@Override
public String toString() {
return getClass().getName() + "[delegate=" + this.delegate.toString() + "]";
}
@Override
public boolean isReady() {
return this.delegate.isReady();
}
@Override
public void setWriteListener(WriteListener writeListener) {
this.delegate.setWriteListener(writeListener);
}
}
}
|
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\OnCommittedResponseWrapper.java
| 1
|
请完成以下Java代码
|
private static String createXoredCsrfToken(SecureRandom secureRandom, String token) {
byte[] tokenBytes = Utf8.encode(token);
byte[] randomBytes = new byte[tokenBytes.length];
secureRandom.nextBytes(randomBytes);
byte[] xoredBytes = xorCsrf(randomBytes, tokenBytes);
byte[] combinedBytes = new byte[tokenBytes.length + randomBytes.length];
System.arraycopy(randomBytes, 0, combinedBytes, 0, randomBytes.length);
System.arraycopy(xoredBytes, 0, combinedBytes, randomBytes.length, xoredBytes.length);
return Base64.getUrlEncoder().encodeToString(combinedBytes);
}
private static byte[] xorCsrf(byte[] randomBytes, byte[] csrfBytes) {
Assert.isTrue(randomBytes.length == csrfBytes.length, "arrays must be equal length");
int len = csrfBytes.length;
byte[] xoredCsrf = new byte[len];
System.arraycopy(csrfBytes, 0, xoredCsrf, 0, len);
for (int i = 0; i < len; i++) {
xoredCsrf[i] ^= randomBytes[i];
}
return xoredCsrf;
}
private static final class CachedCsrfTokenSupplier implements Supplier<CsrfToken> {
private final Supplier<CsrfToken> delegate;
private @Nullable CsrfToken csrfToken;
|
private CachedCsrfTokenSupplier(Supplier<CsrfToken> delegate) {
this.delegate = delegate;
}
@Override
public CsrfToken get() {
if (this.csrfToken == null) {
this.csrfToken = this.delegate.get();
}
return this.csrfToken;
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\XorCsrfTokenRequestAttributeHandler.java
| 1
|
请完成以下Java代码
|
protected void onInit(final IModelValidationEngine engine, final I_AD_Client client)
{
// nothing to do
}
@Override
public void onModelChange(final Object model, final ModelChangeType changeType) throws Exception
{
final boolean afterNewOrChange = changeType.isNewOrChange() && changeType.isAfter();
if (!afterNewOrChange)
{
// Note that currently we are not interested in splitting a partition if the only linking record gets deleted.
return; // Nothing to do.
}
final ImmutableSet<String> columnNames = ImmutableSet.of(ITableRecordReference.COLUMNNAME_AD_Table_ID, ITableRecordReference.COLUMNNAME_Record_ID);
if (!InterfaceWrapperHelper.isValueChanged(model, columnNames))
{
return;
}
final IPartitionerService partitionerService = Services.get(IPartitionerService.class);
final IDLMService dlmService = Services.get(IDLMService.class);
final PartitionConfig config = dlmService.loadDefaultPartitionConfig();
final ITableRecordReference recordReference = TableRecordReference.ofReferencedOrNull(model);
final Optional<PartitionerConfigLine> referencedLine = config.getLine(recordReference.getTableName());
if (!referencedLine.isPresent())
{
return; // the table we are referencing is not part of DLM; nothing to do
}
final String modelTableName = InterfaceWrapperHelper.getModelTableName(model);
|
final TableRecordIdDescriptor descriptor = TableRecordIdDescriptor.of(modelTableName, ITableRecordReference.COLUMNNAME_Record_ID, recordReference.getTableName());
final PartitionConfig augmentedConfig = partitionerService.augmentPartitionerConfig(config, Collections.singletonList(descriptor));
if (!augmentedConfig.isChanged())
{
return; // we are done
}
// now that the augmented config is stored, further changes will be handeled by AddToPartitionInterceptor.
dlmService.storePartitionConfig(augmentedConfig);
// however, for the current 'model', we need to enqueue it ourselves
final CreatePartitionAsyncRequest request = PartitionRequestFactory.asyncBuilder()
.setConfig(config)
.setRecordToAttach(TableRecordReference.ofOrNull(model))
.build();
final PInstanceId pinstanceId = null;
DLMPartitionerWorkpackageProcessor.schedule(request, pinstanceId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\model\interceptor\PartitionerInterceptor.java
| 1
|
请完成以下Java代码
|
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public org.compiere.model.I_GL_Journal getReversal()
{
return get_ValueAsPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_GL_Journal.class);
}
@Override
public void setReversal(final org.compiere.model.I_GL_Journal Reversal)
{
set_ValueFromPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_GL_Journal.class, Reversal);
}
@Override
public void setReversal_ID (final int Reversal_ID)
{
if (Reversal_ID < 1)
set_Value (COLUMNNAME_Reversal_ID, null);
else
set_Value (COLUMNNAME_Reversal_ID, Reversal_ID);
}
@Override
public int getReversal_ID()
{
return get_ValueAsInt(COLUMNNAME_Reversal_ID);
}
@Override
public void setSAP_GLJournal_ID (final int SAP_GLJournal_ID)
{
if (SAP_GLJournal_ID < 1)
set_ValueNoCheck (COLUMNNAME_SAP_GLJournal_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SAP_GLJournal_ID, SAP_GLJournal_ID);
|
}
@Override
public int getSAP_GLJournal_ID()
{
return get_ValueAsInt(COLUMNNAME_SAP_GLJournal_ID);
}
@Override
public void setTotalCr (final BigDecimal TotalCr)
{
set_ValueNoCheck (COLUMNNAME_TotalCr, TotalCr);
}
@Override
public BigDecimal getTotalCr()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalCr);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalDr (final BigDecimal TotalDr)
{
set_ValueNoCheck (COLUMNNAME_TotalDr, TotalDr);
}
@Override
public BigDecimal getTotalDr()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalDr);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_SAP_GLJournal.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setSUMUP_Config_ID (final int SUMUP_Config_ID)
{
if (SUMUP_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID);
}
@Override
public int getSUMUP_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID);
}
@Override
public void setSUMUP_LastSync_Error_ID (final int SUMUP_LastSync_Error_ID)
{
if (SUMUP_LastSync_Error_ID < 1)
set_Value (COLUMNNAME_SUMUP_LastSync_Error_ID, null);
else
set_Value (COLUMNNAME_SUMUP_LastSync_Error_ID, SUMUP_LastSync_Error_ID);
}
@Override
public int getSUMUP_LastSync_Error_ID()
{
return get_ValueAsInt(COLUMNNAME_SUMUP_LastSync_Error_ID);
}
/**
* SUMUP_LastSync_Status AD_Reference_ID=541901
* Reference name: SUMUP_LastSync_Status
*/
public static final int SUMUP_LASTSYNC_STATUS_AD_Reference_ID=541901;
/** OK = OK */
public static final String SUMUP_LASTSYNC_STATUS_OK = "OK";
/** Error = ERR */
public static final String SUMUP_LASTSYNC_STATUS_Error = "ERR";
@Override
public void setSUMUP_LastSync_Status (final @Nullable java.lang.String SUMUP_LastSync_Status)
{
set_Value (COLUMNNAME_SUMUP_LastSync_Status, SUMUP_LastSync_Status);
}
@Override
public java.lang.String getSUMUP_LastSync_Status()
{
return get_ValueAsString(COLUMNNAME_SUMUP_LastSync_Status);
}
@Override
public void setSUMUP_LastSync_Timestamp (final @Nullable java.sql.Timestamp SUMUP_LastSync_Timestamp)
|
{
set_Value (COLUMNNAME_SUMUP_LastSync_Timestamp, SUMUP_LastSync_Timestamp);
}
@Override
public java.sql.Timestamp getSUMUP_LastSync_Timestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_SUMUP_LastSync_Timestamp);
}
@Override
public void setSUMUP_merchant_code (final java.lang.String SUMUP_merchant_code)
{
set_Value (COLUMNNAME_SUMUP_merchant_code, SUMUP_merchant_code);
}
@Override
public java.lang.String getSUMUP_merchant_code()
{
return get_ValueAsString(COLUMNNAME_SUMUP_merchant_code);
}
@Override
public void setSUMUP_Transaction_ID (final int SUMUP_Transaction_ID)
{
if (SUMUP_Transaction_ID < 1)
set_ValueNoCheck (COLUMNNAME_SUMUP_Transaction_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SUMUP_Transaction_ID, SUMUP_Transaction_ID);
}
@Override
public int getSUMUP_Transaction_ID()
{
return get_ValueAsInt(COLUMNNAME_SUMUP_Transaction_ID);
}
@Override
public void setTimestamp (final java.sql.Timestamp Timestamp)
{
set_Value (COLUMNNAME_Timestamp, Timestamp);
}
@Override
public java.sql.Timestamp getTimestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_Timestamp);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_Transaction.java
| 2
|
请完成以下Java代码
|
public final <IT> List<IHUDocument> createHUDocuments(final Properties ctx, final Class<IT> modelClass, final Iterator<IT> records)
{
final HUDocumentsCollector documentsCollector = new HUDocumentsCollector();
createHUDocuments(documentsCollector, modelClass, records);
return documentsCollector.getHUDocuments();
}
protected <IT> void createHUDocuments(final HUDocumentsCollector documentsCollector, final Class<IT> modelClass, final Iterator<IT> records)
{
assumeTableName(InterfaceWrapperHelper.getTableName(modelClass));
while (records.hasNext())
{
final IT record = records.next();
final T model = InterfaceWrapperHelper.create(record, this.modelClass);
try
{
createHUDocumentsFromTypedModel(documentsCollector, model);
}
catch (final Exception e)
{
logger.warn("Error while creating source from " + model + ". Skipping.", e);
}
}
}
@Override
public final List<IHUDocument> createHUDocuments(final ProcessInfo pi)
{
final HUDocumentsCollector documentsCollector = new HUDocumentsCollector();
createHUDocuments(documentsCollector, pi);
return documentsCollector.getHUDocuments();
}
protected final void createHUDocuments(final HUDocumentsCollector documentsCollector, final ProcessInfo pi)
{
|
Check.assumeNotNull(pi, "process info not null");
final String tableName = pi.getTableNameOrNull();
assumeTableName(tableName);
final Iterator<T> models = retrieveModelsFromProcessInfo(pi);
createHUDocuments(documentsCollector, modelClass, models);
}
/**
* Method used to retrieve relevant models from given ProcessInfo.
*
* @param pi
* @return
*/
protected Iterator<T> retrieveModelsFromProcessInfo(final ProcessInfo pi)
{
final Properties ctx = pi.getCtx();
final int recordId = pi.getRecord_ID();
Check.assume(recordId > 0, "No Record_ID found in {}", pi);
final T model = InterfaceWrapperHelper.create(ctx, recordId, modelClass, ITrx.TRXNAME_None);
return new SingletonIterator<>(model);
}
@Override
public final List<IHUDocument> createHUDocumentsFromModel(final Object modelObj)
{
final HUDocumentsCollector documentsCollector = new HUDocumentsCollector();
final T model = InterfaceWrapperHelper.create(modelObj, modelClass);
createHUDocumentsFromTypedModel(documentsCollector, model);
return documentsCollector.getHUDocuments();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\AbstractHUDocumentFactory.java
| 1
|
请完成以下Java代码
|
public List<String> getCandidates() {
return this.candidates;
}
/**
* Loads the names of import candidates from the classpath. The names of the import
* candidates are stored in files named
* {@code META-INF/spring/full-qualified-annotation-name.imports} on the classpath.
* Every line contains the full qualified name of the candidate class. Comments are
* supported using the # character.
* @param annotation annotation to load
* @param classLoader class loader to use for loading
* @return list of names of annotated classes
*/
public static ImportCandidates load(Class<?> annotation, @Nullable ClassLoader classLoader) {
Assert.notNull(annotation, "'annotation' must not be null");
ClassLoader classLoaderToUse = decideClassloader(classLoader);
String location = String.format(LOCATION, annotation.getName());
Enumeration<URL> urls = findUrlsInClasspath(classLoaderToUse, location);
List<String> importCandidates = new ArrayList<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
importCandidates.addAll(readCandidateConfigurations(url));
}
return new ImportCandidates(importCandidates);
}
private static ClassLoader decideClassloader(@Nullable ClassLoader classLoader) {
if (classLoader == null) {
return ImportCandidates.class.getClassLoader();
}
return classLoader;
}
private static Enumeration<URL> findUrlsInClasspath(ClassLoader classLoader, String location) {
try {
return classLoader.getResources(location);
}
catch (IOException ex) {
throw new IllegalArgumentException("Failed to load configurations from location [" + location + "]", ex);
}
}
private static List<String> readCandidateConfigurations(URL url) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new UrlResource(url).getInputStream(), StandardCharsets.UTF_8))) {
List<String> candidates = new ArrayList<>();
String line;
|
while ((line = reader.readLine()) != null) {
line = stripComment(line);
line = line.trim();
if (line.isEmpty()) {
continue;
}
candidates.add(line);
}
return candidates;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load configurations from location [" + url + "]", ex);
}
}
private static String stripComment(String line) {
int commentStart = line.indexOf(COMMENT_START);
if (commentStart == -1) {
return line;
}
return line.substring(0, commentStart);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\annotation\ImportCandidates.java
| 1
|
请完成以下Java代码
|
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!getInvoiceRowsSelectedForAllocation().isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("No invoices shall be selected");
}
return creatPlan()
.resolve(plan -> ProcessPreconditionsResolution.accept().deriveWithCaptionOverride(computeCaption(plan.getAmountToWriteOff())),
ProcessPreconditionsResolution::rejectWithInternalReason);
}
private ExplainedOptional<Plan> creatPlan()
{
return createPlan(getPaymentRowsSelectedForAllocation());
}
private static ITranslatableString computeCaption(final Amount writeOffAmt)
{
return TranslatableStrings.builder()
.appendADElement("PaymentWriteOffAmt").append(": ").append(writeOffAmt)
.build();
}
@Override
protected String doIt()
{
final Plan plan = creatPlan().orElseThrow();
final PaymentAmtMultiplier amtMultiplier = plan.getAmtMultiplier();
final Amount amountToWriteOff = amtMultiplier.convertToRealValue(plan.getAmountToWriteOff());
paymentBL.paymentWriteOff(
plan.getPaymentId(),
amountToWriteOff.toMoney(moneyService::getCurrencyIdByCurrencyCode),
p_DateTrx.atStartOfDay(SystemTime.zoneId()).toInstant(),
null);
return MSG_OK;
}
//
//
//
private static ExplainedOptional<Plan> createPlan(@NonNull final ImmutableList<PaymentRow> paymentRows)
{
if (paymentRows.size() != 1)
{
return ExplainedOptional.emptyBecause("Only one payment row can be selected for write-off");
}
|
final PaymentRow paymentRow = CollectionUtils.singleElement(paymentRows);
final Amount openAmt = paymentRow.getOpenAmt();
if (openAmt.signum() == 0)
{
return ExplainedOptional.emptyBecause("Zero open amount. Nothing to write-off");
}
return ExplainedOptional.of(
Plan.builder()
.paymentId(paymentRow.getPaymentId())
.amtMultiplier(paymentRow.getPaymentAmtMultiplier())
.amountToWriteOff(openAmt)
.build());
}
@Value
@Builder
private static class Plan
{
@NonNull PaymentId paymentId;
@NonNull PaymentAmtMultiplier amtMultiplier;
@NonNull Amount amountToWriteOff;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentsView_PaymentWriteOff.java
| 1
|
请完成以下Java代码
|
public void setValue (Object value)
{
if (value == null)
m_oldText = "";
else
m_oldText = value.toString();
if (!m_setting)
setText (m_oldText);
} // setValue
/**
* Property Change Listener
* @param evt event
*/
public void propertyChange (PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
setValue(evt.getNewValue());
} // propertyChange
/**
* Return Editor value
* @return value
*/
public Object getValue()
{
return String.valueOf(getPassword());
} // getValue
/**
* Return Display Value
* @return value
*/
public String getDisplay()
{
return String.valueOf(getPassword());
} // getDisplay
/**************************************************************************
* Key Listener Interface
* @param e event
*/
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {}
/**
* Key Listener.
* @param e event
*/
public void keyReleased(KeyEvent e)
{
String newText = String.valueOf(getPassword());
m_setting = true;
try
|
{
fireVetoableChange(m_columnName, m_oldText, newText);
}
catch (PropertyVetoException pve) {}
m_setting = false;
} // keyReleased
/**
* Data Binding to MTable (via GridController) - Enter pressed
* @param e event
*/
public void actionPerformed(ActionEvent e)
{
String newText = String.valueOf(getPassword());
// Data Binding
try
{
fireVetoableChange(m_columnName, m_oldText, newText);
}
catch (PropertyVetoException pve) {}
} // actionPerformed
/**
* Set Field/WindowNo for ValuePreference
* @param mField field
*/
public void setField (GridField mField)
{
m_mField = mField;
} // setField
@Override
public GridField getField() {
return m_mField;
}
// metas: Ticket#2011062310000013
public boolean isAutoCommit()
{
return false;
}
} // VPassword
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VPassword.java
| 1
|
请完成以下Java代码
|
public List<I_C_Flatrate_Term> retrieveTerms(
@NonNull final BPartnerId bPartnerId,
@NonNull final OrgId orgId,
@NonNull final TypeConditions typeConditions)
{
return queryBL.createQueryBuilder(I_C_Flatrate_Term.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bPartnerId.getRepoId())
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Type_Conditions, typeConditions.getCode())
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_AD_Org_ID, orgId.getRepoId())
.create()
.list(I_C_Flatrate_Term.class);
}
@Override
public Set<FlatrateTermId> retrieveAllRunningSubscriptionIds(
@NonNull final BPartnerId bPartnerId,
@NonNull final Instant date,
@NonNull final OrgId orgId)
{
return existingSubscriptionsQueryBuilder(orgId, bPartnerId, date)
.create()
.idsAsSet(FlatrateTermId::ofRepoId);
}
private IQueryBuilder<I_C_Flatrate_Term> existingSubscriptionsQueryBuilder(@NonNull final OrgId orgId, @NonNull final BPartnerId bPartnerId, @NonNull final Instant date)
{
return queryBL.createQueryBuilder(I_C_Flatrate_Term.class)
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_AD_Org_ID, orgId)
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bPartnerId)
.addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Quit.getCode())
.addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Voided.getCode())
.addCompareFilter(I_C_Flatrate_Term.COLUMNNAME_EndDate, Operator.GREATER, date);
}
|
@Override
public boolean bpartnerHasExistingRunningTerms(@NonNull final I_C_Flatrate_Term flatrateTerm)
{
if (flatrateTerm.getC_Order_Term_ID() <= 0)
{
return true; // if this term has no C_Order_Term_ID, then it *is* one of those running terms
}
final Instant instant = TimeUtil.asInstant(flatrateTerm.getC_Order_Term().getDateOrdered());
final IQueryBuilder<I_C_Flatrate_Term> queryBuilder = //
existingSubscriptionsQueryBuilder(OrgId.ofRepoId(flatrateTerm.getAD_Org_ID()),
BPartnerId.ofRepoId(flatrateTerm.getBill_BPartner_ID()),
instant);
queryBuilder.addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_C_Order_Term_ID, flatrateTerm.getC_Order_Term_ID());
return queryBuilder.create()
.anyMatch();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\FlatrateDAO.java
| 1
|
请完成以下Java代码
|
protected List<ActivityImpl> findConditionalStartEventActivities(ProcessDefinitionEntity processDefinition) {
List<ActivityImpl> activities = new ArrayList<ActivityImpl>();
for (EventSubscriptionDeclaration declaration : ConditionalEventDefinition.getDeclarationsForScope(processDefinition).values()) {
if (isConditionStartEvent(declaration)) {
activities.add(((ConditionalEventDefinition) declaration).getConditionalActivity());
}
}
return activities;
}
protected boolean isConditionStartEvent(EventSubscriptionDeclaration declaration) {
return EventType.CONDITONAL.name().equals(declaration.getEventType()) && declaration.isStartEvent();
}
protected boolean evaluateCondition(ConditionSet conditionSet, ActivityImpl activity) {
|
ExecutionEntity temporaryExecution = new ExecutionEntity();
if (conditionSet.getVariables() != null) {
temporaryExecution.initializeVariableStore(conditionSet.getVariables());
}
temporaryExecution.setProcessDefinition(activity.getProcessDefinition());
ConditionalEventDefinition conditionalEventDefinition = activity.getProperties().get(BpmnProperties.CONDITIONAL_EVENT_DEFINITION);
if (conditionalEventDefinition.getVariableName() == null || conditionSet.getVariables().containsKey(conditionalEventDefinition.getVariableName())) {
return conditionalEventDefinition.tryEvaluate(temporaryExecution);
} else {
return false;
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\runtime\DefaultConditionHandler.java
| 1
|
请完成以下Java代码
|
public static String getStValidate(String url, String st, String service){
try {
url = url+"?service="+service+"&ticket="+st;
CloseableHttpClient httpclient = createHttpClientWithNoSsl();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
String res = readResponse(response);
return res == null ? null : (res == "" ? null : res);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 读取 response body 内容为字符串
*
* @param response
* @return
* @throws IOException
*/
private static String readResponse(HttpResponse response) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String result = new String();
String line;
while ((line = in.readLine()) != null) {
result += line;
}
return result;
}
/**
* 创建模拟客户端(针对 https 客户端禁用 SSL 验证)
*
* @param cookieStore 缓存的 Cookies 信息
|
* @return
* @throws Exception
*/
private static CloseableHttpClient createHttpClientWithNoSsl() throws Exception {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// don't check
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// don't check
}
}
};
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, trustAllCerts, null);
LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx);
return HttpClients.custom()
.setSSLSocketFactory(sslSocketFactory)
.build();
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\cas\util\CasServiceUtil.java
| 1
|
请完成以下Java代码
|
private DynamicTargetsMap retrieveDynamicTargetsMap()
{
final ImmutableListMultimap<GenericTargetWindowInfo, GenericTargetColumnInfo> map = DB.retrieveRows(
"SELECT * FROM dynamic_target_window_v",
ImmutableList.of(),
this::retrieveRowFrom_Dynamic_Target_Window_V)
.stream()
.filter(Objects::nonNull)
.collect(ImmutableListMultimap.toImmutableListMultimap(
TargetWindowAndColumn::getWindow,
TargetWindowAndColumn::getColumn));
return new DynamicTargetsMap(map);
}
@Nullable
private TargetWindowAndColumn retrieveRowFrom_Dynamic_Target_Window_V(@NonNull final ResultSet rs) throws SQLException
{
final GenericTargetWindowInfo targetWindow = extractWindowInfo(rs);
// SQL where clauses with context variables are not supported
if (targetWindow.getTabSqlWhereClause() != null && targetWindow.getTabSqlWhereClause().contains("@"))
{
logger.info("Excluding zoom to {}/{} because SQL where clause contains context variables which are not supported atm: {}", targetWindow.getTargetWindowId(), targetWindow.getName(), targetWindow.getTabSqlWhereClause());
return null;
|
}
final GenericTargetColumnInfo targetColumn = extractColumnInfo(rs).withDynamic(true);
return new TargetWindowAndColumn(targetWindow, targetColumn);
}
//
//
//
@Value
private static class DynamicTargetsMap
{
ImmutableListMultimap<GenericTargetWindowInfo, GenericTargetColumnInfo> multimap;
public ImmutableListMultimap<GenericTargetWindowInfo, GenericTargetColumnInfo> toMultimap() {return multimap;}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\generic\GenericRelatedDocumentDescriptorsRepository.java
| 1
|
请完成以下Java代码
|
public class VariableEventListenerExport extends AbstractPlanItemDefinitionExport<VariableEventListener> {
@Override
protected Class<? extends VariableEventListener> getExportablePlanItemDefinitionClass() {
return VariableEventListener.class;
}
@Override
protected String getPlanItemDefinitionXmlElementValue(VariableEventListener variableEventListener) {
return ELEMENT_GENERIC_EVENT_LISTENER;
}
@Override
protected void writePlanItemDefinitionSpecificAttributes(VariableEventListener variableEventListener, XMLStreamWriter xtw) throws Exception {
super.writePlanItemDefinitionSpecificAttributes(variableEventListener, xtw);
xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_TYPE, "variable");
if (StringUtils.isNotEmpty(variableEventListener.getVariableName())) {
|
xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_VARIABLE_NAME, variableEventListener.getVariableName());
}
if (StringUtils.isNotEmpty(variableEventListener.getVariableChangeType())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_VARIABLE_CHANGE_TYPE, variableEventListener.getVariableChangeType());
}
if (StringUtils.isNotEmpty(variableEventListener.getAvailableConditionExpression())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE,
CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_AVAILABLE_CONDITION,
variableEventListener.getAvailableConditionExpression());
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\VariableEventListenerExport.java
| 1
|
请完成以下Java代码
|
public final class DelegatingReactiveAuthorizationManager implements ReactiveAuthorizationManager<ServerWebExchange> {
private static final Log logger = LogFactory.getLog(DelegatingReactiveAuthorizationManager.class);
private final List<ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>>> mappings;
private DelegatingReactiveAuthorizationManager(
List<ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>>> mappings) {
this.mappings = mappings;
}
@Override
public Mono<AuthorizationResult> authorize(Mono<Authentication> authentication, ServerWebExchange exchange) {
return Flux.fromIterable(this.mappings)
.concatMap((mapping) -> mapping.getMatcher()
.matches(exchange)
.filter(MatchResult::isMatch)
.map(MatchResult::getVariables)
.flatMap((variables) -> {
logger.debug(LogMessage.of(() -> "Checking authorization on '"
+ exchange.getRequest().getPath().pathWithinApplication() + "' using "
+ mapping.getEntry()));
return mapping.getEntry().authorize(authentication, new AuthorizationContext(exchange, variables));
}))
.next()
.switchIfEmpty(Mono.fromCallable(() -> new AuthorizationDecision(false)));
}
|
public static DelegatingReactiveAuthorizationManager.Builder builder() {
return new DelegatingReactiveAuthorizationManager.Builder();
}
public static final class Builder {
private final List<ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>>> mappings = new ArrayList<>();
private Builder() {
}
public DelegatingReactiveAuthorizationManager.Builder add(
ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>> entry) {
this.mappings.add(entry);
return this;
}
public DelegatingReactiveAuthorizationManager build() {
return new DelegatingReactiveAuthorizationManager(this.mappings);
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authorization\DelegatingReactiveAuthorizationManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getResource() {
return resource;
}
@ApiModelProperty(example = "This is a case for testing purposes")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setDiagramResource(String diagramResource) {
this.diagramResource = diagramResource;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-repository/deployments/2/resources/testProcess.png", value = "Contains a graphical representation of the case, null when no diagram is available.")
public String getDiagramResource() {
|
return diagramResource;
}
public void setGraphicalNotationDefined(boolean graphicalNotationDefined) {
this.graphicalNotationDefined = graphicalNotationDefined;
}
@ApiModelProperty(value = "Indicates the case definition contains graphical information (CMMN DI).")
public boolean isGraphicalNotationDefined() {
return graphicalNotationDefined;
}
public void setStartFormDefined(boolean startFormDefined) {
this.startFormDefined = startFormDefined;
}
public boolean isStartFormDefined() {
return startFormDefined;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\CaseDefinitionResponse.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Comment {
@Id
private Long id;
private String text;
@ManyToOne
private User author;
@JsonBackReference
@ManyToOne
private Post post;
public Comment() {
}
public Long getId() {
return this.id;
}
public String getText() {
return this.text;
}
public User getAuthor() {
return this.author;
}
public Post getPost() {
return this.post;
}
public void setId(Long id) {
this.id = id;
}
public void setText(String text) {
this.text = text;
}
public void setAuthor(User author) {
this.author = author;
}
public void setPost(Post post) {
this.post = post;
|
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Comment comment = (Comment) o;
return Objects.equals(id, comment.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public String toString() {
return "Comment(id=" + this.getId() + ", text=" + this.getText() + ", author=" + this.getAuthor() + ", post=" + this.getPost()
+ ")";
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\listvsset\eager\list\fulldomain\Comment.java
| 2
|
请完成以下Java代码
|
public TimerEntity createStartTimerInstance(String deploymentId) {
return createTimer(deploymentId);
}
public TimerEntity createTimer(String deploymentId) {
TimerEntity timer = super.createJobInstance((ExecutionEntity) null);
timer.setDeploymentId(deploymentId);
scheduleTimer(timer);
return timer;
}
public TimerEntity createTimer(ExecutionEntity execution) {
TimerEntity timer = super.createJobInstance(execution);
scheduleTimer(timer);
return timer;
}
protected void scheduleTimer(TimerEntity timer) {
Context
.getCommandContext()
.getJobManager()
.schedule(timer);
}
protected ExecutionEntity resolveExecution(ExecutionEntity context) {
return context;
}
@Override
protected JobHandlerConfiguration resolveJobHandlerConfiguration(ExecutionEntity context) {
return resolveJobHandler().newConfiguration(rawJobHandlerConfiguration);
}
/**
* @return all timers declared in the given scope
*/
public static Map<String, TimerDeclarationImpl> getDeclarationsForScope(PvmScope scope) {
if (scope == null) {
return Collections.emptyMap();
}
Map<String, TimerDeclarationImpl> result = scope.getProperties().get(BpmnProperties.TIMER_DECLARATIONS);
if (result != null) {
|
return result;
}
else {
return Collections.emptyMap();
}
}
/**
* @return all timeout listeners declared in the given scope
*/
public static Map<String, Map<String, TimerDeclarationImpl>> getTimeoutListenerDeclarationsForScope(PvmScope scope) {
if (scope == null) {
return Collections.emptyMap();
}
Map<String, Map<String, TimerDeclarationImpl>> result = scope.getProperties().get(BpmnProperties.TIMEOUT_LISTENER_DECLARATIONS);
if (result != null) {
return result;
}
else {
return Collections.emptyMap();
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\TimerDeclarationImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public Embedded getEmbedded() {
return this.embedded;
}
public JmsPoolConnectionFactoryProperties getPool() {
return this.pool;
}
/**
* Configuration for an embedded Artemis server.
*/
public static class Embedded {
private static final AtomicInteger serverIdCounter = new AtomicInteger();
/**
* Server ID. By default, an auto-incremented counter is used.
*/
private int serverId = serverIdCounter.getAndIncrement();
/**
* Whether to enable embedded mode if the Artemis server APIs are available.
*/
private boolean enabled = true;
/**
* Whether to enable persistent store.
*/
private boolean persistent;
/**
* Journal file directory. Not necessary if persistence is turned off.
*/
private @Nullable String dataDirectory;
/**
* List of queues to create on startup.
*/
private String[] queues = new String[0];
/**
* List of topics to create on startup.
*/
private String[] topics = new String[0];
/**
* Cluster password. Randomly generated on startup by default.
*/
private String clusterPassword = UUID.randomUUID().toString();
private boolean defaultClusterPassword = true;
public int getServerId() {
return this.serverId;
}
public void setServerId(int serverId) {
this.serverId = serverId;
}
public boolean isEnabled() {
return this.enabled;
}
|
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isPersistent() {
return this.persistent;
}
public void setPersistent(boolean persistent) {
this.persistent = persistent;
}
public @Nullable String getDataDirectory() {
return this.dataDirectory;
}
public void setDataDirectory(@Nullable String dataDirectory) {
this.dataDirectory = dataDirectory;
}
public String[] getQueues() {
return this.queues;
}
public void setQueues(String[] queues) {
this.queues = queues;
}
public String[] getTopics() {
return this.topics;
}
public void setTopics(String[] topics) {
this.topics = topics;
}
public String getClusterPassword() {
return this.clusterPassword;
}
public void setClusterPassword(String clusterPassword) {
this.clusterPassword = clusterPassword;
this.defaultClusterPassword = false;
}
public boolean isDefaultClusterPassword() {
return this.defaultClusterPassword;
}
/**
* Creates the minimal transport parameters for an embedded transport
* configuration.
* @return the transport parameters
* @see TransportConstants#SERVER_ID_PROP_NAME
*/
public Map<String, Object> generateTransportParameters() {
Map<String, Object> parameters = new HashMap<>();
parameters.put(TransportConstants.SERVER_ID_PROP_NAME, getServerId());
return parameters;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "testuser")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@ApiModelProperty(example = "Fred")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@ApiModelProperty(example = "Smith")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@ApiModelProperty(example = "Fred Smith")
public String getDisplayName() {
return displayName;
|
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public String getPassword() {
return passWord;
}
public void setPassword(String passWord) {
this.passWord = passWord;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModelProperty(example = "companyTenantId")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "http://localhost:8182/identity/users/testuser/picture")
public String getPictureUrl() {
return pictureUrl;
}
public void setPictureUrl(String pictureUrl) {
this.pictureUrl = pictureUrl;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\identity\UserResponse.java
| 2
|
请完成以下Java代码
|
public ImmutableSet<String> getTableNames()
{
return tableNames;
}
public boolean containsTableName(final String tableName)
{
return tableNames.contains(tableName);
}
public ImmutableTableNamesGroupsIndex addingToDefaultGroup(@NonNull final String tableName)
{
return addingToDefaultGroup(ImmutableSet.of(tableName));
}
public ImmutableTableNamesGroupsIndex addingToDefaultGroup(@NonNull final Collection<String> tableNames)
{
if (tableNames.isEmpty())
{
return this;
}
final TableNamesGroup defaultGroupExisting = groupsById.get(DEFAULT_GROUP_ID);
final TableNamesGroup defaultGroupNew;
if (defaultGroupExisting != null)
{
defaultGroupNew = defaultGroupExisting.toBuilder()
.tableNames(tableNames)
.build();
}
else
{
defaultGroupNew = TableNamesGroup.builder()
.groupId(DEFAULT_GROUP_ID)
.tableNames(tableNames)
.build();
}
if (Objects.equals(defaultGroupExisting, defaultGroupNew))
{
return this;
}
return replacingGroup(defaultGroupNew);
}
public ImmutableTableNamesGroupsIndex replacingGroup(@NonNull final TableNamesGroup groupToAdd)
{
|
if (groupsById.isEmpty())
{
return new ImmutableTableNamesGroupsIndex(ImmutableList.of(groupToAdd));
}
final ArrayList<TableNamesGroup> newGroups = new ArrayList<>(groupsById.size() + 1);
boolean added = false;
for (final TableNamesGroup group : groupsById.values())
{
if (Objects.equals(group.getGroupId(), groupToAdd.getGroupId()))
{
newGroups.add(groupToAdd);
added = true;
}
else
{
newGroups.add(group);
}
}
if (!added)
{
newGroups.add(groupToAdd);
added = true;
}
return new ImmutableTableNamesGroupsIndex(newGroups);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\ImmutableTableNamesGroupsIndex.java
| 1
|
请完成以下Java代码
|
public void setPP_OrderLine_Candidate_ID (final int PP_OrderLine_Candidate_ID)
{
if (PP_OrderLine_Candidate_ID < 1)
set_Value (COLUMNNAME_PP_OrderLine_Candidate_ID, null);
else
set_Value (COLUMNNAME_PP_OrderLine_Candidate_ID, PP_OrderLine_Candidate_ID);
}
@Override
public int getPP_OrderLine_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_OrderLine_Candidate_ID);
}
@Override
public org.compiere.model.I_S_Resource getPP_Plant()
{
return get_ValueAsPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setPP_Plant(final org.compiere.model.I_S_Resource PP_Plant)
{
set_ValueFromPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class, PP_Plant);
}
@Override
public void setPP_Plant_ID (final int PP_Plant_ID)
{
if (PP_Plant_ID < 1)
set_Value (COLUMNNAME_PP_Plant_ID, null);
else
set_Value (COLUMNNAME_PP_Plant_ID, PP_Plant_ID);
}
@Override
public int getPP_Plant_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Plant_ID);
}
@Override
public org.eevolution.model.I_PP_Product_BOMLine getPP_Product_BOMLine()
{
return get_ValueAsPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class);
}
|
@Override
public void setPP_Product_BOMLine(final org.eevolution.model.I_PP_Product_BOMLine PP_Product_BOMLine)
{
set_ValueFromPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class, PP_Product_BOMLine);
}
@Override
public void setPP_Product_BOMLine_ID (final int PP_Product_BOMLine_ID)
{
if (PP_Product_BOMLine_ID < 1)
set_Value (COLUMNNAME_PP_Product_BOMLine_ID, null);
else
set_Value (COLUMNNAME_PP_Product_BOMLine_ID, PP_Product_BOMLine_ID);
}
@Override
public int getPP_Product_BOMLine_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Product_BOMLine_ID);
}
@Override
public void setPP_Product_Planning_ID (final int PP_Product_Planning_ID)
{
if (PP_Product_Planning_ID < 1)
set_Value (COLUMNNAME_PP_Product_Planning_ID, null);
else
set_Value (COLUMNNAME_PP_Product_Planning_ID, PP_Product_Planning_ID);
}
@Override
public int getPP_Product_Planning_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Product_Planning_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_Prod_Detail.java
| 1
|
请完成以下Java代码
|
public void afterPropertiesSet() {
Assert.hasLength(this.secureKeyword, "secureKeyword required");
Assert.notNull(this.entryPoint, "entryPoint required");
}
@Override
public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config)
throws IOException, ServletException {
Assert.isTrue((invocation != null) && (config != null), "Nulls cannot be provided");
for (ConfigAttribute attribute : config) {
if (supports(attribute)) {
if (!invocation.getHttpRequest().isSecure()) {
HttpServletResponse response = invocation.getResponse();
Assert.notNull(response, "HttpServletResponse is required");
this.entryPoint.commence(invocation.getRequest(), response);
}
}
}
}
public ChannelEntryPoint getEntryPoint() {
return this.entryPoint;
}
public String getSecureKeyword() {
return this.secureKeyword;
}
|
public void setEntryPoint(ChannelEntryPoint entryPoint) {
this.entryPoint = entryPoint;
}
public void setSecureKeyword(String secureKeyword) {
this.secureKeyword = secureKeyword;
}
@Override
public boolean supports(ConfigAttribute attribute) {
return (attribute != null) && (attribute.getAttribute() != null)
&& attribute.getAttribute().equals(getSecureKeyword());
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\channel\SecureChannelProcessor.java
| 1
|
请完成以下Java代码
|
public int viewToModel(float x, float y, Shape a, Position.Bias[] bias)
{
return m_view.viewToModel(x, y, a, bias);
}
/**
* Returns the document model underlying the view.
*
* @return the model
*/
public Document getDocument()
{
return m_view.getDocument();
}
/**
* Returns the starting offset into the model for this view.
*
* @return the starting offset
*/
public int getStartOffset()
{
return m_view.getStartOffset();
}
/**
* Returns the ending offset into the model for this view.
*
* @return the ending offset
*/
public int getEndOffset()
{
return m_view.getEndOffset();
}
/**
* Gets the element that this view is mapped to.
*
* @return the view
*/
public Element getElement()
{
return m_view.getElement();
}
/**
* Sets the view size.
*
|
* @param width the width
* @param height the height
*/
public void setSize(float width, float height)
{
this.m_width = (int) width;
m_view.setSize(width, height);
}
/**
* Fetches the factory to be used for building the
* various view fragments that make up the view that
* represents the model. This is what determines
* how the model will be represented. This is implemented
* to fetch the factory provided by the associated
* EditorKit.
*
* @return the factory
*/
public ViewFactory getViewFactory()
{
return m_factory;
}
} // HTMLRenderer
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\HTMLRenderer.java
| 1
|
请完成以下Java代码
|
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
return createNewDefaultParametersFiller().getDefaultValue(parameter);
}
@ProcessParamLookupValuesProvider(//
parameterName = WEBUI_M_HU_Pick_ParametersFiller.PARAM_M_ShipmentSchedule_ID, //
numericKey = true, //
lookupSource = DocumentLayoutElementFieldDescriptor.LookupSource.lookup)
private LookupValuesPage getShipmentScheduleValues(final LookupDataSourceContext context)
{
return createNewDefaultParametersFiller().getShipmentScheduleValues(context);
}
@Nullable
private OrderLineId getSalesOrderLineId()
{
if (getView() != null)
{
return getView().getSalesOrderLineId();
}
return null;
}
@ProcessParamLookupValuesProvider(//
parameterName = WEBUI_M_HU_Pick_ParametersFiller.PARAM_M_PickingSlot_ID, //
dependsOn = WEBUI_M_HU_Pick_ParametersFiller.PARAM_M_ShipmentSchedule_ID, //
numericKey = true, //
lookupSource = DocumentLayoutElementFieldDescriptor.LookupSource.lookup)
private LookupValuesList getPickingSlotValues(final LookupDataSourceContext context)
{
final WEBUI_M_HU_Pick_ParametersFiller filler = WEBUI_M_HU_Pick_ParametersFiller
|
.pickingSlotFillerBuilder()
.shipmentScheduleId(shipmentScheduleId)
.build();
return filler.getPickingSlotValues(context);
}
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
invalidateView();
}
private WEBUI_M_HU_Pick_ParametersFiller createNewDefaultParametersFiller()
{
final HURow row = WEBUI_PP_Order_ProcessHelper.getHURowsFromIncludedRows(getView()).get(0);
return WEBUI_M_HU_Pick_ParametersFiller.defaultFillerBuilder()
.huId(row.getHuId())
.salesOrderLineId(getSalesOrderLineId())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_Pick_ReceivedHUs.java
| 1
|
请完成以下Java代码
|
public long size() throws IOException {
assertNotClosed();
return this.size;
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
throw new NonWritableChannelException();
}
private void assertNotClosed() throws ClosedChannelException {
if (this.closed) {
throw new ClosedChannelException();
}
}
/**
* Resources used by the channel and suitable for registration with a {@link Cleaner}.
*/
static class Resources implements Runnable {
private final ZipContent zipContent;
private final CloseableDataBlock data;
Resources(Path path, String nestedEntryName) throws IOException {
this.zipContent = ZipContent.open(path, nestedEntryName);
this.data = this.zipContent.openRawZipData();
}
DataBlock getData() {
return this.data;
}
@Override
public void run() {
releaseAll();
}
|
private void releaseAll() {
IOException exception = null;
try {
this.data.close();
}
catch (IOException ex) {
exception = ex;
}
try {
this.zipContent.close();
}
catch (IOException ex) {
if (exception != null) {
ex.addSuppressed(exception);
}
exception = ex;
}
if (exception != null) {
throw new UncheckedIOException(exception);
}
}
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedByteChannel.java
| 1
|
请完成以下Java代码
|
public class LogWithChain {
public static void main(String[] args) throws Exception {
getLeave();
}
private static void getLeave() throws NoLeaveGrantedException {
try {
howIsTeamLead();
} catch (TeamLeadUpsetException e) {
throw new NoLeaveGrantedException("Leave not sanctioned.", e);
}
}
private static void howIsTeamLead() throws TeamLeadUpsetException {
try {
howIsManager();
|
} catch (ManagerUpsetException e) {
throw new TeamLeadUpsetException("Team lead is not in good mood", e);
}
}
private static void howIsManager() throws ManagerUpsetException {
try {
howIsGirlFriendOfManager();
} catch (GirlFriendOfManagerUpsetException e) {
throw new ManagerUpsetException("Manager is in bad mood", e);
}
}
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
}
}
|
repos\tutorials-master\core-java-modules\core-java-exceptions-5\src\main\java\com\baeldung\exceptions\chainedexception\LogWithChain.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.