instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
default <T extends RepoIdAware> T getParameterAsIdNotNull(@NonNull String parameterName, @NonNull Class<T> type)
{
final T id = getParameterAsId(parameterName, type);
if (id == null)
{
throw Check.mkEx("Parameter " + parameterName + " is not set");
}
return id;
}
/**
* @return boolean value or <code>false</code> if parameter is missing
*/
boolean getParameterAsBool(String parameterName);
@Nullable
Boolean getParameterAsBoolean(String parameterName, @Nullable Boolean defaultValue);
/**
* @return timestamp value or <code>null</code> if parameter is missing
*/
@Nullable
Timestamp getParameterAsTimestamp(String parameterName);
/**
* @return local date value or <code>null</code> if parameter is missing
*/
@Nullable
LocalDate getParameterAsLocalDate(String parameterName);
@Nullable
ZonedDateTime getParameterAsZonedDateTime(String parameterName);
@Nullable
Instant getParameterAsInstant(String parameterName);
/**
* @return {@link BigDecimal} value or <code>null</code> if parameter is missing or cannot be converted to {@link BigDecimal}
*/
BigDecimal getParameterAsBigDecimal(String parameterName);
|
default <T extends Enum<T>> Optional<T> getParameterAsEnum(final String parameterName, final Class<T> enumType)
{
final String value = getParameterAsString(parameterName);
return value != null
? Optional.of(ReferenceListAwareEnums.ofEnumCode(value, enumType))
: Optional.empty();
}
@Nullable
default Boolean getParameterAsBoolean(@NonNull final String parameterName)
{
final Object value = getParameterAsObject(parameterName);
if (value == null)
{
return null;
}
return StringUtils.toBoolean(value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\api\IParams.java
| 1
|
请完成以下Java代码
|
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public boolean isMarried() {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
|
public long getIncome() {
return income;
}
public void setIncome(long income) {
this.income = income;
}
@Override
public String toString() {
return "User [name=" + name + ", email=" + email + ", gender=" + gender + ", password=" + password
+ ", profession=" + profession + ", note=" + note + ", birthday=" + birthday + ", married=" + married
+ ", income=" + income + "]";
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-5 Spring Boot Web Application\SpringBootFormValidationJSP\src\main\java\spring\validation\model\User.java
| 1
|
请完成以下Java代码
|
public GatewayFilter apply() {
return apply((NameConfig) null);
}
@Override
public GatewayFilter apply(@Nullable NameConfig config) {
String defaultClientRegistrationId = (config == null) ? null : config.getName();
return (exchange, chain) -> exchange.getPrincipal()
// .log("token-relay-filter")
.filter(principal -> principal instanceof Authentication)
.cast(Authentication.class)
.flatMap(principal -> authorizationRequest(defaultClientRegistrationId, principal))
.flatMap(this::authorizedClient)
.map(OAuth2AuthorizedClient::getAccessToken)
.map(token -> withBearerAuth(exchange, token))
// TODO: adjustable behavior if empty
.defaultIfEmpty(exchange)
.flatMap(chain::filter);
}
private Mono<OAuth2AuthorizeRequest> authorizationRequest(@Nullable String defaultClientRegistrationId,
Authentication principal) {
String clientRegistrationId = defaultClientRegistrationId;
if (clientRegistrationId == null && principal instanceof OAuth2AuthenticationToken) {
clientRegistrationId = ((OAuth2AuthenticationToken) principal).getAuthorizedClientRegistrationId();
}
return Mono.justOrEmpty(clientRegistrationId)
.map(OAuth2AuthorizeRequest::withClientRegistrationId)
.map(builder -> builder.principal(principal).build());
}
|
private Mono<OAuth2AuthorizedClient> authorizedClient(OAuth2AuthorizeRequest request) {
ReactiveOAuth2AuthorizedClientManager clientManager = clientManagerProvider.getIfAvailable();
if (clientManager == null) {
return Mono.error(new IllegalStateException(
"No ReactiveOAuth2AuthorizedClientManager bean was found. Did you include the "
+ "org.springframework.boot:spring-boot-starter-oauth2-client dependency?"));
}
// TODO: use Mono.defer() for request above?
return clientManager.authorize(request);
}
private ServerWebExchange withBearerAuth(ServerWebExchange exchange, OAuth2AccessToken accessToken) {
return exchange.mutate()
.request(r -> r.headers(headers -> headers.setBearerAuth(accessToken.getTokenValue())))
.build();
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\TokenRelayGatewayFilterFactory.java
| 1
|
请完成以下Java代码
|
public void setOpaque (boolean isOpaque)
{
// JScrollPane & Viewport is always not Opaque
if (m_textArea == null) // during init of JScrollPane
super.setOpaque(isOpaque);
else
m_textArea.setOpaque(isOpaque);
} // setOpaque
/**
* Set Text Margin
* @param m insets
*/
public void setMargin (Insets m)
{
if (m_textArea != null)
m_textArea.setMargin(m);
} // setMargin
/**
* AddFocusListener
* @param l
*/
@Override
public void addFocusListener (FocusListener l)
{
if (m_textArea == null) // during init
super.addFocusListener(l);
else
m_textArea.addFocusListener(l);
}
/**
* Add Text Mouse Listener
* @param l
*/
@Override
public void addMouseListener (MouseListener l)
{
m_textArea.addMouseListener(l);
}
/**
* Add Text Key Listener
* @param l
*/
@Override
public void addKeyListener (KeyListener l)
{
m_textArea.addKeyListener(l);
}
/**
* Add Text Input Method Listener
* @param l
*/
@Override
public void addInputMethodListener (InputMethodListener l)
{
m_textArea.addInputMethodListener(l);
|
}
/**
* Get text Input Method Requests
* @return requests
*/
@Override
public InputMethodRequests getInputMethodRequests()
{
return m_textArea.getInputMethodRequests();
}
/**
* Set Text Input Verifier
* @param l
*/
@Override
public void setInputVerifier (InputVerifier l)
{
m_textArea.setInputVerifier(l);
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return copyPasteSupport;
}
} // CTextArea
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextArea.java
| 1
|
请完成以下Java代码
|
public void setStructureXML (String StructureXML)
{
set_Value (COLUMNNAME_StructureXML, StructureXML);
}
/** Get StructureXML.
@return Autogenerated Containerdefinition as XML Code
*/
public String getStructureXML ()
{
return (String)get_Value(COLUMNNAME_StructureXML);
}
/** Set Title.
@param Title
|
Name this entity is referred to as
*/
public void setTitle (String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
/** Get Title.
@return Name this entity is referred to as
*/
public String getTitle ()
{
return (String)get_Value(COLUMNNAME_Title);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Container.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int getVersion() {
return version;
}
public String getResource() {
return resource;
}
public String getDeploymentId() {
return deploymentId;
}
public String getDiagram() {
return diagram;
}
public boolean isSuspended() {
return suspended;
}
public String getTenantId() {
return tenantId;
}
public String getVersionTag() {
return versionTag;
}
public Integer getHistoryTimeToLive() {
return historyTimeToLive;
}
public boolean isStartableInTasklist() {
return isStartableInTasklist;
|
}
public static ProcessDefinitionDto fromProcessDefinition(ProcessDefinition definition) {
ProcessDefinitionDto dto = new ProcessDefinitionDto();
dto.id = definition.getId();
dto.key = definition.getKey();
dto.category = definition.getCategory();
dto.description = definition.getDescription();
dto.name = definition.getName();
dto.version = definition.getVersion();
dto.resource = definition.getResourceName();
dto.deploymentId = definition.getDeploymentId();
dto.diagram = definition.getDiagramResourceName();
dto.suspended = definition.isSuspended();
dto.tenantId = definition.getTenantId();
dto.versionTag = definition.getVersionTag();
dto.historyTimeToLive = definition.getHistoryTimeToLive();
dto.isStartableInTasklist = definition.isStartableInTasklist();
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\ProcessDefinitionDto.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class CommonRuntimeAutoConfiguration {
@Bean
public APIVariableInstanceConverter apiVariableInstanceConverter() {
return new APIVariableInstanceConverter();
}
@Bean
public VariableEventFilter variableEventFilter() {
return new VariableEventFilter();
}
@Bean
@ConditionalOnMissingBean
public EphemeralVariableResolver ephemeralVariableResolver(ProcessExtensionService processExtensionService) {
return new EphemeralVariableResolver(processExtensionService);
}
@Bean
public InitializingBean registerVariableCreatedListenerDelegate(
RuntimeService runtimeService,
@Autowired(required = false) List<VariableEventListener<VariableCreatedEvent>> listeners,
VariableEventFilter variableEventFilter,
EphemeralVariableResolver ephemeralVariableResolver
) {
return () ->
runtimeService.addEventListener(
new VariableCreatedListenerDelegate(
getInitializedListeners(listeners),
new ToVariableCreatedConverter(ephemeralVariableResolver),
variableEventFilter
),
ActivitiEventType.VARIABLE_CREATED
|
);
}
private <T> List<T> getInitializedListeners(List<T> eventListeners) {
return eventListeners != null ? eventListeners : emptyList();
}
@Bean
public InitializingBean registerVariableUpdatedListenerDelegate(
RuntimeService runtimeService,
@Autowired(required = false) List<VariableEventListener<VariableUpdatedEvent>> listeners,
VariableEventFilter variableEventFilter,
EphemeralVariableResolver ephemeralVariableResolver
) {
return () ->
runtimeService.addEventListener(
new VariableUpdatedListenerDelegate(
getInitializedListeners(listeners),
new ToVariableUpdatedConverter(ephemeralVariableResolver),
variableEventFilter
),
ActivitiEventType.VARIABLE_UPDATED
);
}
@Bean
public VariableNameValidator variableNameValidator() {
return new VariableNameValidator();
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-runtime-shared-impl\src\main\java\org\activiti\runtime\api\conf\CommonRuntimeAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public static void creatingJSONArray() {
JSONArray ja = new JSONArray();
ja.put(Boolean.TRUE);
ja.put("lorem ipsum");
// We can also put a JSONObject in JSONArray
JSONObject jo = new JSONObject();
jo.put("name", "jon doe");
jo.put("age", "22");
jo.put("city", "chicago");
ja.put(jo);
System.out.println(ja.toString());
}
public static void jsonArrayFromJSONString() {
|
JSONArray ja = new JSONArray("[true, \"lorem ipsum\", 215]");
System.out.println(ja);
}
public static void jsonArrayFromCollectionObj() {
List<String> list = new ArrayList<>();
list.add("California");
list.add("Texas");
list.add("Hawaii");
list.add("Alaska");
JSONArray ja = new JSONArray(list);
System.out.println(ja);
}
}
|
repos\tutorials-master\json-modules\json\src\main\java\com\baeldung\jsonjava\JSONArrayDemo.java
| 1
|
请完成以下Java代码
|
public OrderLineBuilder manualPrice(@Nullable final Money manualPrice)
{
return manualPrice(manualPrice != null ? manualPrice.toBigDecimal() : null);
}
public OrderLineBuilder manualDiscount(final BigDecimal manualDiscount)
{
assertNotBuilt();
this.manualDiscount = manualDiscount;
return this;
}
public OrderLineBuilder setDimension(final Dimension dimension)
{
assertNotBuilt();
this.dimension = dimension;
return this;
}
public boolean isProductAndUomMatching(@Nullable final ProductId productId, @Nullable final UomId uomId)
{
return ProductId.equals(getProductId(), productId)
&& UomId.equals(getUomId(), uomId);
}
public OrderLineBuilder description(@Nullable final String description)
{
this.description = description;
return this;
}
public OrderLineBuilder hideWhenPrinting(final boolean hideWhenPrinting)
{
this.hideWhenPrinting = hideWhenPrinting;
|
return this;
}
public OrderLineBuilder details(@NonNull final Collection<OrderLineDetailCreateRequest> details)
{
assertNotBuilt();
detailCreateRequests.addAll(details);
return this;
}
public OrderLineBuilder detail(@NonNull final OrderLineDetailCreateRequest detail)
{
assertNotBuilt();
detailCreateRequests.add(detail);
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderLineBuilder.java
| 1
|
请完成以下Java代码
|
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionVersionTag() {
return processDefinitionVersionTag;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public Integer getRetries() {
return retries;
}
public boolean isSuspended() {
return suspended;
}
public String getWorkerId() {
return workerId;
}
public String getTopicName() {
return topicName;
}
public String getTenantId() {
return tenantId;
}
public long getPriority() {
return priority;
}
|
public String getBusinessKey() {
return businessKey;
}
public static ExternalTaskDto fromExternalTask(ExternalTask task) {
ExternalTaskDto dto = new ExternalTaskDto();
dto.activityId = task.getActivityId();
dto.activityInstanceId = task.getActivityInstanceId();
dto.errorMessage = task.getErrorMessage();
dto.executionId = task.getExecutionId();
dto.id = task.getId();
dto.lockExpirationTime = task.getLockExpirationTime();
dto.createTime = task.getCreateTime();
dto.processDefinitionId = task.getProcessDefinitionId();
dto.processDefinitionKey = task.getProcessDefinitionKey();
dto.processDefinitionVersionTag = task.getProcessDefinitionVersionTag();
dto.processInstanceId = task.getProcessInstanceId();
dto.retries = task.getRetries();
dto.suspended = task.isSuspended();
dto.topicName = task.getTopicName();
dto.workerId = task.getWorkerId();
dto.tenantId = task.getTenantId();
dto.priority = task.getPriority();
dto.businessKey = task.getBusinessKey();
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\ExternalTaskDto.java
| 1
|
请完成以下Java代码
|
private EDIDesadvQuery buildEDIDesadvQuery(@NonNull final I_C_Order order)
{
final String poReference = Check.assumeNotNull(order.getPOReference(),
"In the DESADV-Context, POReference is mandatory; C_Order_ID={}",
order.getC_Order_ID());
final EDIDesadvQuery.EDIDesadvQueryBuilder ediDesadvQueryBuilder = EDIDesadvQuery.builder()
.poReference(poReference)
.ctxAware(InterfaceWrapperHelper.getContextAware(order));
if (isMatchUsingBPartnerId())
{
ediDesadvQueryBuilder.bPartnerId(BPartnerId.ofRepoId(order.getC_BPartner_ID()));
}
if (isMatchUsingOrderId(ClientId.ofRepoId(order.getAD_Client_ID())))
{
ediDesadvQueryBuilder.orderId(OrderId.ofRepoId(order.getC_Order_ID()));
}
return ediDesadvQueryBuilder
.build();
}
@NonNull
private EDIDesadvQuery buildEDIDesadvQuery(@NonNull final I_M_InOut inOut)
{
final String poReference = Check.assumeNotNull(inOut.getPOReference(),
"In the DESADV-Context, POReference is mandatory; M_InOut_ID={}",
inOut.getM_InOut_ID());
final EDIDesadvQuery.EDIDesadvQueryBuilder ediDesadvQueryBuilder = EDIDesadvQuery.builder()
.poReference(poReference)
.ctxAware(InterfaceWrapperHelper.getContextAware(inOut));
if (isMatchUsingBPartnerId())
{
ediDesadvQueryBuilder.bPartnerId(BPartnerId.ofRepoId(inOut.getC_BPartner_ID()));
}
|
return ediDesadvQueryBuilder
.build();
}
private boolean isMatchUsingBPartnerId()
{
return sysConfigBL.getBooleanValue(SYS_CONFIG_MATCH_USING_BPARTNER_ID, false);
}
private static void setExternalBPartnerInfo(@NonNull final I_EDI_DesadvLine newDesadvLine, @NonNull final I_C_OrderLine orderLineRecord)
{
newDesadvLine.setExternalSeqNo(orderLineRecord.getExternalSeqNo());
newDesadvLine.setC_UOM_BPartner_ID(orderLineRecord.getC_UOM_BPartner_ID());
newDesadvLine.setQtyEnteredInBPartnerUOM(ZERO);
newDesadvLine.setBPartner_QtyItemCapacity(orderLineRecord.getBPartner_QtyItemCapacity());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\DesadvBL.java
| 1
|
请完成以下Java代码
|
public void print() {
System.out.println("Signature is: print()");
}
/*
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
// The method signature is independent from return type
public int print() {
System.out.println("Signature is: print()");
return 0;
}
*/
/*
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
// The method signature is independent from modifiers
private final void print() {
System.out.println("Signature is: print()");
}
*/
/*
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
// The method signature is independent from thrown exception declaration
public void print() throws IllegalStateException {
System.out.println("Signature is: print()");
throw new IllegalStateException();
}
*/
public void print(int parameter) {
System.out.println("Signature is: print(int)");
}
/*
|
// Uncommenting this method will lead to a compilation error: java: method print(int) is already defined in class
// The method signature is independent from parameter names
public void print(int anotherParameter) {
System.out.println("Signature is: print(int)");
}
*/
public void printElement(T t) {
System.out.println("Signature is: printElement(T)");
}
/*
// Uncommenting this method will lead to a compilation error: java: name clash: printElement(java.io.Serializable) and printElement(T) have the same erasure
// Even though the signatures appear different, the compiler cannot statically bind the correct method after type erasure
public void printElement(Serializable o) {
System.out.println("Signature is: printElement(Serializable)");
}
*/
public void print(Object... parameter) {
System.out.println("Signature is: print(Object...)");
}
/*
// Uncommenting this method will lead to a compilation error: java cannot declare both sum(Object...) and sum(Object[])
// Even though the signatures appear different, after compilation they both resolve to sum(Object[])
public void print(Object[] parameter) {
System.out.println("Signature is: print(Object[])");
}
*/
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-methods-2\src\main\java\com\baeldung\signature\OverloadingErrors.java
| 1
|
请完成以下Java代码
|
public ReplacedElement createReplacedElement(LayoutContext lc, BlockBox box, UserAgentCallback uac, int cssWidth, int cssHeight) {
Element e = box.getElement();
String nodeName = e.getNodeName();
if (nodeName.equals("img")) {
String imagePath = e.getAttribute("src");
try {
InputStream input = new FileInputStream("src/main/resources/" + imagePath);
byte[] bytes = IOUtils.toByteArray(input);
Image image = Image.getInstance(bytes);
FSImage fsImage = new ITextFSImage(image);
if (cssWidth != -1 || cssHeight != -1) {
fsImage.scale(cssWidth, cssHeight);
} else {
fsImage.scale(2000, 1000);
}
return new ITextImageElement(fsImage);
} catch (Exception e1) {
e1.printStackTrace();
|
}
}
return null;
}
@Override
public void reset() {
}
@Override
public void remove(Element e) {
}
@Override
public void setFormSubmissionListener(FormSubmissionListener listener) {
}
}
|
repos\tutorials-master\text-processing-libraries-modules\pdf\src\main\java\com\baeldung\pdf\openpdf\CustomElementFactoryImpl.java
| 1
|
请完成以下Java代码
|
public static MaterialNeedsPlannerRow ofDocument(@NonNull final Document document)
{
final ProductId productId = document.getFieldView(I_M_Material_Needs_Planner_V.COLUMNNAME_M_Product_ID).getValueAsId(ProductId.class)
.orElseThrow(() -> new FillMandatoryException(I_M_Material_Needs_Planner_V.COLUMNNAME_M_Product_ID));
final WarehouseId warehouseId = document.getFieldView(I_M_Material_Needs_Planner_V.COLUMNNAME_M_Warehouse_ID).getValueAsId(WarehouseId.class)
.orElse(null);
final BigDecimal levelMin = document.getFieldView(I_M_Material_Needs_Planner_V.COLUMNNAME_Level_Min).getValueAsBigDecimal().orElse(BigDecimal.ZERO);
final BigDecimal levelMax = document.getFieldView(I_M_Material_Needs_Planner_V.COLUMNNAME_Level_Max).getValueAsBigDecimal().orElse(BigDecimal.ZERO);
return MaterialNeedsPlannerRow.builder()
.warehouseId(warehouseId)
.productId(productId)
.levelMin(levelMin)
.levelMax(levelMax)
.build();
}
public boolean isDemandFilled()
{
if (getWarehouseId() == null)
{
return false;
}
return getLevelMin().compareTo(BigDecimal.ZERO) > 0;
}
public ReplenishInfo toReplenishInfo()
{
|
if (warehouseId == null)
{
throw new FillMandatoryException(I_M_Material_Needs_Planner_V.COLUMNNAME_M_Warehouse_ID);
}
return ReplenishInfo.builder()
.identifier(ReplenishInfo.Identifier.builder()
.productId(productId)
.warehouseId(warehouseId)
.build())
.min(StockQtyAndUOMQtys.ofQtyInStockUOM(levelMin, productId))
.max(StockQtyAndUOMQtys.ofQtyInStockUOM(levelMax, productId))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\replenish\process\MaterialNeedsPlannerRow.java
| 1
|
请完成以下Java代码
|
/* package */class TrxItemProcessorContext implements ITrxItemProcessorContext
{
private final Properties ctx;
private ITrx trx = null;
private IParams params = null;
public TrxItemProcessorContext(final Properties ctx)
{
super();
this.ctx = ctx;
}
@Override
public TrxItemProcessorContext copy()
{
final TrxItemProcessorContext contextNew = new TrxItemProcessorContext(ctx);
contextNew.trx = trx;
contextNew.params = params;
return contextNew;
}
@Override
public Properties getCtx()
{
return ctx;
}
@Override
public String getTrxName()
{
if (trx == null)
{
return ITrx.TRXNAME_None;
}
return trx.getTrxName();
}
|
@Override
public void setTrx(final ITrx trx)
{
this.trx = trx;
}
@Override
public ITrx getTrx()
{
return trx;
}
@Override
public IParams getParams()
{
return params;
}
public void setParams(IParams params)
{
this.params = params;
}
@Override
public String toString()
{
return "TrxItemProcessorContext [trx=" + trx + ", params=" + params + "]";
}
/**
* Returning <code>false</code> to ensure that the trx which was set via {@link #setTrx(ITrx)} is actually used, even if it's <code>null</code>.
*/
@Override
public boolean isAllowThreadInherited()
{
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemProcessorContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Campaign {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "budget")
private BigDecimal budget;
@Column(name = "start_date")
private LocalDate startDate;
@Column(name = "end_date")
private LocalDate endDate;
public Campaign() {
}
public Campaign(String name, BigDecimal budget, LocalDate startDate, LocalDate endDate) {
this.name = name;
this.budget = budget;
this.startDate = startDate;
this.endDate = endDate;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getBudget() {
return budget;
}
|
public void setBudget(BigDecimal budget) {
this.budget = budget;
}
public LocalDate getStartDate() {
return startDate;
}
public void setStartDate(LocalDate startDate) {
this.startDate = startDate;
}
public LocalDate getEndDate() {
return endDate;
}
public void setEndDate(LocalDate endDate) {
this.endDate = endDate;
}
@Override
public String toString() {
return "Campaign{" + "id=" + id + ", name='" + name + '\'' + ", budget=" + budget + ", startDate=" + startDate + ", endDate=" + endDate + '}';
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-3-observation\src\main\java\com\baeldung\logging\model\Campaign.java
| 2
|
请完成以下Java代码
|
public boolean add(TermFrequency termFrequency)
{
TermFrequency tf = termFrequencyMap.get(termFrequency.getTerm());
if (tf == null)
{
termFrequencyMap.put(termFrequency.getKey(), termFrequency);
return true;
}
tf.increase(termFrequency.getFrequency());
return false;
}
@Override
public boolean remove(Object o)
{
return termFrequencyMap.remove(o) != null;
}
@Override
public boolean containsAll(Collection<?> c)
{
for (Object o : c)
{
if (!contains(o))
return false;
}
return true;
}
@Override
public boolean addAll(Collection<? extends TermFrequency> c)
{
for (TermFrequency termFrequency : c)
{
add(termFrequency);
}
return !c.isEmpty();
}
@Override
public boolean removeAll(Collection<?> c)
{
for (Object o : c)
{
if (!remove(o))
return false;
}
return true;
}
@Override
public boolean retainAll(Collection<?> c)
{
return termFrequencyMap.values().retainAll(c);
}
@Override
public void clear()
{
termFrequencyMap.clear();
}
/**
* 提取关键词(非线程安全)
*
* @param termList
* @param size
* @return
*/
@Override
|
public List<String> getKeywords(List<Term> termList, int size)
{
clear();
add(termList);
Collection<TermFrequency> topN = top(size);
List<String> r = new ArrayList<String>(topN.size());
for (TermFrequency termFrequency : topN)
{
r.add(termFrequency.getTerm());
}
return r;
}
/**
* 提取关键词(线程安全)
*
* @param document 文档内容
* @param size 希望提取几个关键词
* @return 一个列表
*/
public static List<String> getKeywordList(String document, int size)
{
return new TermFrequencyCounter().getKeywords(document, size);
}
@Override
public String toString()
{
final int max = 100;
return top(Math.min(max, size())).toString();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\TermFrequencyCounter.java
| 1
|
请完成以下Java代码
|
public class ExecutionsWithSameRootProcessInstanceIdMatcher implements CachedEntityMatcher<ExecutionEntity> {
@Override
public boolean isRetained(
Collection<ExecutionEntity> databaseEntities,
Collection<CachedEntity> cachedEntities,
ExecutionEntity entity,
Object param
) {
ExecutionEntity executionEntity = getMatchingExecution(databaseEntities, cachedEntities, (String) param);
return (
executionEntity.getRootProcessInstanceId() != null &&
executionEntity.getRootProcessInstanceId().equals(entity.getRootProcessInstanceId())
);
}
public ExecutionEntity getMatchingExecution(
Collection<ExecutionEntity> databaseEntities,
Collection<CachedEntity> cachedEntities,
String executionId
) {
// Doing some preprocessing here: we need to find the execution that matches the provided execution id,
|
// as we need to match the root process instance id later on.
if (cachedEntities != null) {
for (CachedEntity cachedEntity : cachedEntities) {
ExecutionEntity executionEntity = (ExecutionEntity) cachedEntity.getEntity();
if (executionId.equals(executionEntity.getId())) {
return executionEntity;
}
}
}
if (databaseEntities != null) {
for (ExecutionEntity databaseExecutionEntity : databaseEntities) {
if (executionId.equals(databaseExecutionEntity.getId())) {
return databaseExecutionEntity;
}
}
}
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\cachematcher\ExecutionsWithSameRootProcessInstanceIdMatcher.java
| 1
|
请完成以下Java代码
|
public class Person {
private String firstName;
private String lastName;
public Person() {
}
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
|
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
|
repos\tutorials-master\jackson-modules\jackson-exceptions\src\main\java\com\baeldung\mappingexception\Person.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setMessageConverter(@Nullable MessageConverter messageConverter) {
this.messageConverter = messageConverter;
}
/**
* Set the {@link StreamMessageConverter} to use or {@code null} if the out-of-the-box
* stream message converter should be used.
* @param streamMessageConverter the {@link StreamMessageConverter}
*/
public void setStreamMessageConverter(@Nullable StreamMessageConverter streamMessageConverter) {
this.streamMessageConverter = streamMessageConverter;
}
/**
* Set the {@link ProducerCustomizer} instances to use.
* @param producerCustomizer the producer customizer
*/
public void setProducerCustomizer(@Nullable ProducerCustomizer producerCustomizer) {
this.producerCustomizer = producerCustomizer;
}
|
/**
* Configure the specified {@link RabbitStreamTemplate}. The template can be further
* tuned and default settings can be overridden.
* @param template the {@link RabbitStreamTemplate} instance to configure
*/
public void configure(RabbitStreamTemplate template) {
if (this.messageConverter != null) {
template.setMessageConverter(this.messageConverter);
}
if (this.streamMessageConverter != null) {
template.setStreamConverter(this.streamMessageConverter);
}
if (this.producerCustomizer != null) {
template.setProducerCustomizer(this.producerCustomizer);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\RabbitStreamTemplateConfigurer.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public CommonResult getAuthCode(@RequestParam String telephone) {
String authCode = memberService.generateAuthCode(telephone);
return CommonResult.success(authCode,"获取验证码成功");
}
@ApiOperation("会员修改密码")
@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
@ResponseBody
public CommonResult updatePassword(@RequestParam String telephone,
@RequestParam String password,
@RequestParam String authCode) {
memberService.updatePassword(telephone,password,authCode);
return CommonResult.success(null,"密码修改成功");
}
|
@ApiOperation(value = "刷新token")
@RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
@ResponseBody
public CommonResult refreshToken(HttpServletRequest request) {
String token = request.getHeader(tokenHeader);
String refreshToken = memberService.refreshToken(token);
if (refreshToken == null) {
return CommonResult.failed("token已经过期!");
}
Map<String, String> tokenMap = new HashMap<>();
tokenMap.put("token", refreshToken);
tokenMap.put("tokenHead", tokenHead);
return CommonResult.success(tokenMap);
}
}
|
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\UmsMemberController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public at.erpel.schemas._1p0.documents.extensions.edifact.InvoiceRecipientExtensionType getInvoiceRecipientExtension() {
return invoiceRecipientExtension;
}
/**
* Sets the value of the invoiceRecipientExtension property.
*
* @param value
* allowed object is
* {@link at.erpel.schemas._1p0.documents.extensions.edifact.InvoiceRecipientExtensionType }
*
*/
public void setInvoiceRecipientExtension(at.erpel.schemas._1p0.documents.extensions.edifact.InvoiceRecipientExtensionType value) {
this.invoiceRecipientExtension = value;
}
/**
* Gets the value of the erpelInvoiceRecipientExtension property.
*
* @return
* possible object is
* {@link CustomType }
*
*/
public CustomType getErpelInvoiceRecipientExtension() {
|
return erpelInvoiceRecipientExtension;
}
/**
* Sets the value of the erpelInvoiceRecipientExtension property.
*
* @param value
* allowed object is
* {@link CustomType }
*
*/
public void setErpelInvoiceRecipientExtension(CustomType value) {
this.erpelInvoiceRecipientExtension = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\InvoiceRecipientExtensionType.java
| 2
|
请完成以下Java代码
|
public int getMaxResults() {
if (maxResults > DEFAULT_LIMIT_SELECT_INTERVAL) {
return DEFAULT_LIMIT_SELECT_INTERVAL;
}
return super.getMaxResults();
}
protected class MetricsQueryIntervalCmd implements Command<Object> {
protected MetricsQueryImpl metricsQuery;
public MetricsQueryIntervalCmd(MetricsQueryImpl metricsQuery) {
this.metricsQuery = metricsQuery;
}
@Override
public Object execute(CommandContext commandContext) {
return commandContext.getMeterLogManager()
.executeSelectInterval(metricsQuery);
}
}
|
protected class MetricsQuerySumCmd implements Command<Object> {
protected MetricsQueryImpl metricsQuery;
public MetricsQuerySumCmd(MetricsQueryImpl metricsQuery) {
this.metricsQuery = metricsQuery;
}
@Override
public Object execute(CommandContext commandContext) {
return commandContext.getMeterLogManager()
.executeSelectSum(metricsQuery);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\MetricsQueryImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Item {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "item")
private List<Characteristic> characteristics = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Characteristic> getCharacteristics() {
return characteristics;
}
public void setCharacteristics(List<Characteristic> characteristics) {
this.characteristics = characteristics;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-query-2\src\main\java\com\baeldung\entitygraph\model\Item.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
class CommentRestController {
private final CommentService commentService;
CommentRestController(CommentService commentService) {
this.commentService = commentService;
}
@PostMapping("/articles/{slug}/comments")
public CommentModel postComments(@AuthenticationPrincipal UserJWTPayload jwtPayload,
@PathVariable String slug, @Valid @RequestBody CommentPostRequestDTO dto) {
final var commentAdded = commentService.createComment(jwtPayload.getUserId(), slug, dto.getBody());
return CommentModel.fromComment(commentAdded);
}
@GetMapping("/articles/{slug}/comments")
|
public MultipleCommentModel getComments(@AuthenticationPrincipal UserJWTPayload jwtPayload,
@PathVariable String slug) {
final var comments = ofNullable(jwtPayload)
.map(JWTPayload::getUserId)
.map(userId -> commentService.getComments(userId, slug))
.orElseGet(() -> commentService.getComments(slug));
return MultipleCommentModel.fromComments(comments);
}
@DeleteMapping("/articles/{slug}/comments/{id}")
public void deleteComment(@AuthenticationPrincipal UserJWTPayload jwtPayload,
@PathVariable String slug, @PathVariable long id) {
commentService.deleteCommentById(jwtPayload.getUserId(), slug, id);
}
}
|
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\application\article\comment\CommentRestController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void updateAuthor(Author author) {
authorRepository.save(author);
System.out.println("\n\nPersistent Context after update the entity:");
briefOverviewOfPersistentContextContent();
}
private void briefOverviewOfPersistentContextContent() {
org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext();
int managedEntities = persistenceContext.getNumberOfManagedEntities();
Map collectionEntries = persistenceContext.getCollectionEntries();
System.out.println("\n-----------------------------------");
System.out.println("Total number of managed entities: " + managedEntities);
if (collectionEntries != null) {
System.out.println("Total number of collection entries: "
+ (collectionEntries.values().size()));
}
Map entities = persistenceContext.getEntitiesByKey();
entities.forEach((key, value) -> System.out.println(key + ":" + value));
|
entities.values().forEach(entry
-> {
EntityEntry ee = persistenceContext.getEntry(entry);
System.out.println(
"Entity name: " + ee.getEntityName()
+ " | Status: " + ee.getStatus()
+ " | State: " + Arrays.toString(ee.getLoadedState()));
});
System.out.println("\n-----------------------------------\n");
}
private org.hibernate.engine.spi.PersistenceContext getPersistenceContext() {
SharedSessionContractImplementor sharedSession = entityManager.unwrap(
SharedSessionContractImplementor.class
);
return sharedSession.getPersistenceContext();
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootReadOnlyQueries\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请完成以下Java代码
|
public void setIgnoreRegistrationFailure(boolean ignoreRegistrationFailure) {
this.ignoreRegistrationFailure = ignoreRegistrationFailure;
}
@Override
public void setBeanName(String name) {
this.beanName = name;
}
protected abstract @Nullable D addRegistration(String description, ServletContext servletContext);
protected void configure(D registration) {
registration.setAsyncSupported(this.asyncSupported);
if (!this.initParameters.isEmpty()) {
registration.setInitParameters(this.initParameters);
}
}
/**
|
* Deduces the name for this registration. Will return user specified name or fallback
* to the bean name. If the bean name is not available, convention based naming is
* used.
* @param value the object used for convention based names
* @return the deduced name
*/
protected final String getOrDeduceName(@Nullable Object value) {
if (this.name != null) {
return this.name;
}
if (this.beanName != null) {
return this.beanName;
}
if (value == null) {
return "null";
}
return Conventions.getVariableName(value);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\DynamicRegistrationBean.java
| 1
|
请完成以下Java代码
|
public class DirectoryMonitoringExample {
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
private static final int POLL_INTERVAL = 500;
public static void main(String[] args) throws Exception {
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
FileAlterationMonitor monitor = new FileAlterationMonitor(POLL_INTERVAL);
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
LOG.debug("File: " + file.getName() + " created");
}
@Override
|
public void onFileDelete(File file) {
LOG.debug("File: " + file.getName() + " deleted");
}
@Override
public void onFileChange(File file) {
LOG.debug("File: " + file.getName() + " changed");
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitor.start();
}
}
|
repos\tutorials-master\libraries-apache-commons\src\main\java\com\baeldung\dirmonitoring\DirectoryMonitoringExample.java
| 1
|
请完成以下Java代码
|
private final class ActionsContext implements IncludedDocumentsCollectionActionsContext
{
@Override
public boolean isParentDocumentProcessed()
{
return parentDocument.isProcessed();
}
@Override
public boolean isParentDocumentActive()
{
return parentDocument.isActive();
}
@Override
public boolean isParentDocumentNew()
{
return parentDocument.isNew();
}
@Override
public boolean isParentDocumentInvalid()
{
return !parentDocument.getValidStatus().isValid();
}
@Override
public Collection<Document> getIncludedDocuments()
{
return getChangedDocuments();
}
@Override
public Evaluatee toEvaluatee()
{
|
return parentDocument.asEvaluatee();
}
@Override
public void collectAllowNew(final DocumentPath parentDocumentPath, final DetailId detailId, final LogicExpressionResult allowNew)
{
parentDocument.getChangesCollector().collectAllowNew(parentDocumentPath, detailId, allowNew);
}
@Override
public void collectAllowDelete(final DocumentPath parentDocumentPath, final DetailId detailId, final LogicExpressionResult allowDelete)
{
parentDocument.getChangesCollector().collectAllowDelete(parentDocumentPath, detailId, allowDelete);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\HighVolumeReadWriteIncludedDocumentsCollection.java
| 1
|
请完成以下Java代码
|
public class Helpers {
// Write Files
public static Path fileOutAllPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.CSV_All).toURI();
return Paths.get(uri);
}
public static Path fileOutBeanPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.CSV_BEAN).toURI();
return Paths.get(uri);
}
public static Path fileOutOnePath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.CSV_ONE).toURI();
return Paths.get(uri);
}
// Read Files
public static Path twoColumnCsvPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.TWO_COLUMN_CSV).toURI();
return Paths.get(uri);
}
public static Path fourColumnCsvPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.FOUR_COLUMN_CSV).toURI();
return Paths.get(uri);
}
public static Path namedColumnCsvPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.NAMED_COLUMN_CSV).toURI();
|
return Paths.get(uri);
}
public static String readFile(Path path) throws IOException {
return IOUtils.toString(path.toUri());
}
// Dummy Data for Writing
public static List<String[]> twoColumnCsvString() {
List<String[]> list = new ArrayList<>();
list.add(new String[]{"ColA", "ColB"});
list.add(new String[]{"A", "B"});
return list;
}
public static List<String[]> fourColumnCsvString() {
List<String[]> list = new ArrayList<>();
list.add(new String[]{"ColA", "ColB", "ColC", "ColD"});
list.add(new String[]{"A", "B", "A", "B"});
list.add(new String[]{"BB", "AB", "AA", "B"});
return list;
}
}
|
repos\tutorials-master\libraries-data-io\src\main\java\com\baeldung\libraries\opencsv\helpers\Helpers.java
| 1
|
请完成以下Java代码
|
public NativeHistoricDetailQuery createNativeHistoricDetailQuery() {
return new NativeHistoricDetailQueryImpl(commandExecutor);
}
@Override
public HistoricVariableInstanceQuery createHistoricVariableInstanceQuery() {
return new HistoricVariableInstanceQueryImpl(commandExecutor);
}
@Override
public NativeHistoricVariableInstanceQuery createNativeHistoricVariableInstanceQuery() {
return new NativeHistoricVariableInstanceQueryImpl(commandExecutor);
}
@Override
public void deleteHistoricTaskInstance(String taskId) {
commandExecutor.execute(new DeleteHistoricTaskInstanceCmd(taskId));
}
@Override
public void deleteHistoricProcessInstance(String processInstanceId) {
commandExecutor.execute(new DeleteHistoricProcessInstanceCmd(processInstanceId));
}
@Override
public NativeHistoricProcessInstanceQuery createNativeHistoricProcessInstanceQuery() {
return new NativeHistoricProcessInstanceQueryImpl(commandExecutor);
}
@Override
|
public NativeHistoricTaskInstanceQuery createNativeHistoricTaskInstanceQuery() {
return new NativeHistoricTaskInstanceQueryImpl(commandExecutor);
}
@Override
public NativeHistoricActivityInstanceQuery createNativeHistoricActivityInstanceQuery() {
return new NativeHistoricActivityInstanceQueryImpl(commandExecutor);
}
@Override
public List<HistoricIdentityLink> getHistoricIdentityLinksForProcessInstance(String processInstanceId) {
return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(null, processInstanceId));
}
@Override
public List<HistoricIdentityLink> getHistoricIdentityLinksForTask(String taskId) {
return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(taskId, null));
}
@Override
public ProcessInstanceHistoryLogQuery createProcessInstanceHistoryLogQuery(String processInstanceId) {
return new ProcessInstanceHistoryLogQueryImpl(commandExecutor, processInstanceId);
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\HistoryServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ExternalReferenceTypes
{
private final ConcurrentHashMap<String, IExternalReferenceType> typesByCode = new ConcurrentHashMap<>();
public ExternalReferenceTypes()
{
registerType(NullExternalReferenceType.NULL);
registerType(BPartnerExternalReferenceType.BPARTNER);
registerType(BPLocationExternalReferenceType.BPARTNER_LOCATION);
registerType(BPartnerExternalReferenceType.BPARTNER_VALUE);
registerType(ProductExternalReferenceType.PRODUCT);
registerType(ProductCategoryExternalReferenceType.PRODUCT_CATEGORY);
registerType(ExternalUserReferenceType.USER_ID);
registerType(PriceListExternalReferenceType.PRICE_LIST);
registerType(PriceListVersionExternalReferenceType.PRICE_LIST_VERSION);
registerType(WarehouseExternalReferenceType.WAREHOUSE);
registerType(ProductPriceExternalReferenceType.PRODUCT_PRICE);
registerType(ShipperExternalReferenceType.SHIPPER);
}
public void registerType(@NonNull final IExternalReferenceType type)
{
|
typesByCode.put(type.getCode(), type);
}
@NonNull
public Optional<IExternalReferenceType> ofCode(@NonNull final String code)
{
final IExternalReferenceType externalReferenceType = typesByCode.get(code);
return Optional.ofNullable(externalReferenceType);
}
@NonNull
public IExternalReferenceType ofCodeNotNull(@NonNull final String code)
{
final IExternalReferenceType type = typesByCode.get(code);
if (type == null)
{
throw new AdempiereException("Unknown Type: " + code);
}
return type;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\ExternalReferenceTypes.java
| 2
|
请完成以下Java代码
|
public class InterceptorStatusToken {
private SecurityContext securityContext;
private Collection<ConfigAttribute> attr;
private Object secureObject;
private boolean contextHolderRefreshRequired;
public InterceptorStatusToken(SecurityContext securityContext, boolean contextHolderRefreshRequired,
Collection<ConfigAttribute> attributes, Object secureObject) {
this.securityContext = securityContext;
this.contextHolderRefreshRequired = contextHolderRefreshRequired;
this.attr = attributes;
this.secureObject = secureObject;
}
public Collection<ConfigAttribute> getAttributes() {
return this.attr;
|
}
public SecurityContext getSecurityContext() {
return this.securityContext;
}
public Object getSecureObject() {
return this.secureObject;
}
public boolean isContextHolderRefreshRequired() {
return this.contextHolderRefreshRequired;
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\InterceptorStatusToken.java
| 1
|
请完成以下Java代码
|
public String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public String getBusinessStatus() {
return businessStatus;
}
public String getProcessInstanceName() {
return processInstanceName;
}
public void setProcessInstanceName(String processInstanceName) {
this.processInstanceName = processInstanceName;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
public Map<String, Object> getTransientVariables() {
return transientVariables;
}
public void setTransientVariables(Map<String, Object> transientVariables) {
this.transientVariables = transientVariables;
}
|
public String getInitialActivityId() {
return initialActivityId;
}
public void setInitialActivityId(String initialActivityId) {
this.initialActivityId = initialActivityId;
}
public FlowElement getInitialFlowElement() {
return initialFlowElement;
}
public void setInitialFlowElement(FlowElement initialFlowElement) {
this.initialFlowElement = initialFlowElement;
}
public Process getProcess() {
return process;
}
public void setProcess(Process process) {
this.process = process;
}
public ProcessDefinition getProcessDefinition() {
return processDefinition;
}
public void setProcessDefinition(ProcessDefinition processDefinition) {
this.processDefinition = processDefinition;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\interceptor\AbstractStartProcessInstanceBeforeContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setExpressionHandler(MethodSecurityExpressionHandler expressionHandler) {
this.manager.setExpressionHandler(expressionHandler);
}
public void setObservationRegistry(ObservationRegistry registry) {
this.observationRegistry = registry;
}
}
public static final class PostAuthorizeAuthorizationMethodInterceptor
implements FactoryBean<AuthorizationManagerAfterMethodInterceptor> {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private ObservationRegistry observationRegistry = ObservationRegistry.NOOP;
private final PostAuthorizeAuthorizationManager manager = new PostAuthorizeAuthorizationManager();
@Override
public AuthorizationManagerAfterMethodInterceptor getObject() {
AuthorizationManager<MethodInvocationResult> manager = this.manager;
if (!this.observationRegistry.isNoop()) {
manager = new ObservationAuthorizationManager<>(this.observationRegistry, this.manager);
}
AuthorizationManagerAfterMethodInterceptor interceptor = AuthorizationManagerAfterMethodInterceptor
.postAuthorize(manager);
interceptor.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
return interceptor;
}
@Override
public Class<?> getObjectType() {
return AuthorizationManagerAfterMethodInterceptor.class;
}
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
public void setExpressionHandler(MethodSecurityExpressionHandler expressionHandler) {
this.manager.setExpressionHandler(expressionHandler);
|
}
public void setObservationRegistry(ObservationRegistry registry) {
this.observationRegistry = registry;
}
}
static class SecurityContextHolderStrategyFactory implements FactoryBean<SecurityContextHolderStrategy> {
@Override
public SecurityContextHolderStrategy getObject() throws Exception {
return SecurityContextHolder.getContextHolderStrategy();
}
@Override
public Class<?> getObjectType() {
return SecurityContextHolderStrategy.class;
}
}
static class ObservationRegistryFactory implements FactoryBean<ObservationRegistry> {
@Override
public ObservationRegistry getObject() throws Exception {
return ObservationRegistry.NOOP;
}
@Override
public Class<?> getObjectType() {
return ObservationRegistry.class;
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\MethodSecurityBeanDefinitionParser.java
| 2
|
请完成以下Java代码
|
private Optional<Date> handleAsDate(String value) {
try {
return Optional.ofNullable(dateFormatterProvider.parse(value));
} catch (DateTimeException e) {
// ignore exception and return empty: it's not a date so let's keep initial value
return Optional.empty();
}
}
private void checkNotValidCharactersInVariableName(String name, String errorMsg) {
if (!variableNameValidator.validate(name)) {
throw new IllegalStateException(errorMsg + (name != null ? name : "null"));
}
}
public CreateTaskVariablePayload handleCreateTaskVariablePayload(
CreateTaskVariablePayload createTaskVariablePayload
) {
checkNotValidCharactersInVariableName(createTaskVariablePayload.getName(), "Variable has not a valid name: ");
Object value = createTaskVariablePayload.getValue();
if (value instanceof String) {
handleAsDate((String) value).ifPresent(createTaskVariablePayload::setValue);
}
return createTaskVariablePayload;
}
public UpdateTaskVariablePayload handleUpdateTaskVariablePayload(
UpdateTaskVariablePayload updateTaskVariablePayload
) {
checkNotValidCharactersInVariableName(
updateTaskVariablePayload.getName(),
"You cannot update a variable with not a valid name: "
);
Object value = updateTaskVariablePayload.getValue();
if (value instanceof String) {
|
handleAsDate((String) value).ifPresent(updateTaskVariablePayload::setValue);
}
return updateTaskVariablePayload;
}
public Map<String, Object> handlePayloadVariables(Map<String, Object> variables) {
if (variables != null) {
Set<String> mismatchedVars = variableNameValidator.validateVariables(variables);
if (!mismatchedVars.isEmpty()) {
throw new IllegalStateException("Variables have not valid names: " + String.join(", ", mismatchedVars));
}
handleStringVariablesAsDates(variables);
}
return variables;
}
private void handleStringVariablesAsDates(Map<String, Object> variables) {
if (variables != null) {
variables
.entrySet()
.stream()
.filter(stringObjectEntry -> stringObjectEntry.getValue() instanceof String)
.forEach(stringObjectEntry ->
handleAsDate((String) stringObjectEntry.getValue()).ifPresent(stringObjectEntry::setValue)
);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\impl\TaskVariablesPayloadValidator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ProductServiceImpl implements ProductService {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private ProductDao productDao;
@Override
@DS(value = "product-ds")
@Transactional(propagation = Propagation.REQUIRES_NEW) // 开启新事物
public void reduceStock(Long productId, Integer amount) throws Exception {
logger.info("[reduceStock] 当前 XID: {}", RootContext.getXID());
// 检查库存
checkStock(productId, amount);
logger.info("[reduceStock] 开始扣减 {} 库存", productId);
// 扣减库存
int updateCount = productDao.reduceStock(productId, amount);
|
// 扣除成功
if (updateCount == 0) {
logger.warn("[reduceStock] 扣除 {} 库存失败", productId);
throw new Exception("库存不足");
}
// 扣除失败
logger.info("[reduceStock] 扣除 {} 库存成功", productId);
}
private void checkStock(Long productId, Integer requiredAmount) throws Exception {
logger.info("[checkStock] 检查 {} 库存", productId);
Integer stock = productDao.getStock(productId);
if (stock < requiredAmount) {
logger.warn("[checkStock] {} 库存不足,当前库存: {}", productId, stock);
throw new Exception("库存不足");
}
}
}
|
repos\SpringBoot-Labs-master\lab-52\lab-52-multiple-datasource\src\main\java\cn\iocoder\springboot\lab52\seatademo\service\impl\ProductServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public boolean matchesFilter(AlarmAssignmentTrigger trigger, AlarmAssignmentNotificationRuleTriggerConfig triggerConfig) {
Action action = trigger.getActionType() == ActionType.ALARM_ASSIGNED ? Action.ASSIGNED : Action.UNASSIGNED;
if (!triggerConfig.getNotifyOn().contains(action)) {
return false;
}
AlarmInfo alarmInfo = trigger.getAlarmInfo();
return emptyOrContains(triggerConfig.getAlarmTypes(), alarmInfo.getType()) &&
emptyOrContains(triggerConfig.getAlarmSeverities(), alarmInfo.getSeverity()) &&
(isEmpty(triggerConfig.getAlarmStatuses()) || AlarmStatusFilter.from(triggerConfig.getAlarmStatuses()).matches(alarmInfo));
}
@Override
public RuleOriginatedNotificationInfo constructNotificationInfo(AlarmAssignmentTrigger trigger) {
AlarmInfo alarmInfo = trigger.getAlarmInfo();
AlarmAssignee assignee = alarmInfo.getAssignee();
return AlarmAssignmentNotificationInfo.builder()
.action(trigger.getActionType() == ActionType.ALARM_ASSIGNED ? "assigned" : "unassigned")
.assigneeFirstName(assignee != null ? assignee.getFirstName() : null)
.assigneeLastName(assignee != null ? assignee.getLastName() : null)
.assigneeEmail(assignee != null ? assignee.getEmail() : null)
.assigneeId(assignee != null ? assignee.getId() : null)
.userEmail(trigger.getUser().getEmail())
.userFirstName(trigger.getUser().getFirstName())
.userLastName(trigger.getUser().getLastName())
.alarmId(alarmInfo.getUuidId())
.alarmType(alarmInfo.getType())
|
.alarmOriginator(alarmInfo.getOriginator())
.alarmOriginatorName(alarmInfo.getOriginatorName())
.alarmOriginatorLabel(alarmInfo.getOriginatorLabel())
.alarmSeverity(alarmInfo.getSeverity())
.alarmStatus(alarmInfo.getStatus())
.alarmCustomerId(alarmInfo.getCustomerId())
.dashboardId(alarmInfo.getDashboardId())
.build();
}
@Override
public NotificationRuleTriggerType getTriggerType() {
return NotificationRuleTriggerType.ALARM_ASSIGNMENT;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\rule\trigger\AlarmAssignmentTriggerProcessor.java
| 2
|
请完成以下Java代码
|
public class M_QualityNote
{
/**
* When a new M_QualityNote entry is created, also create an M_AttributeValue entry with the same Value, Name and IsActive values
*
* @param qualityNote
*/
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW })
public void createOnNew(final I_M_QualityNote qualityNote)
{
final IQualityNoteDAO qualityNoteDAO = Services.get(IQualityNoteDAO.class);
final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class);
attributesRepo.createAttributeValue(AttributeListValueCreateRequest.builder()
.attributeId(qualityNoteDAO.getQualityNoteAttributeId())
.value(qualityNote.getValue())
.name(qualityNote.getName())
.active(qualityNote.isActive())
.build());
}
/**
* When an M_QualityNote entry is deleted, also delete the linked M_AttributeValue entry
*
* @param qualityNote
*/
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE })
public void onDelete(final I_M_QualityNote qualityNote)
{
final IQualityNoteDAO qualityNoteDAO = Services.get(IQualityNoteDAO.class);
|
// Note: the check for null is not needed. The deletion will only happen if the M_AttributeValue entry exists, any way.
qualityNoteDAO.deleteAttribueValueForQualityNote(qualityNote);
}
/**
* Modify the linked M_AttributeValue entry each time an M_QualityNote entry has its IsActive or Name values modified.
*
* @param qualityNote
*/
@ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_M_QualityNote.COLUMNNAME_Name, I_M_QualityNote.COLUMNNAME_IsActive })
public void onChange(final I_M_QualityNote qualityNote)
{
final IQualityNoteDAO qualityNoteDAO = Services.get(IQualityNoteDAO.class);
qualityNoteDAO.modifyAttributeValueName(qualityNote);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\model\validator\M_QualityNote.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean matches(String className, @Nullable ClassLoader classLoader) {
return isPresent(className, classLoader);
}
},
MISSING {
@Override
public boolean matches(String className, @Nullable ClassLoader classLoader) {
return !isPresent(className, classLoader);
}
};
abstract boolean matches(String className, @Nullable ClassLoader classLoader);
|
private static boolean isPresent(String className, @Nullable ClassLoader classLoader) {
if (classLoader == null) {
classLoader = ClassUtils.getDefaultClassLoader();
}
try {
resolve(className, classLoader);
return true;
}
catch (Throwable ex) {
return false;
}
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\FilteringSpringBootCondition.java
| 2
|
请完成以下Java代码
|
public int getAD_NotificationGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_NotificationGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
|
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Interner Name.
@param InternalName
Generally used to give records a name that can be safely referenced from code.
*/
@Override
public void setInternalName (java.lang.String InternalName)
{
set_Value (COLUMNNAME_InternalName, InternalName);
}
/** Get Interner Name.
@return Generally used to give records a name that can be safely referenced from code.
*/
@Override
public java.lang.String getInternalName ()
{
return (java.lang.String)get_Value(COLUMNNAME_InternalName);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_NotificationGroup.java
| 1
|
请完成以下Java代码
|
public static void main(final String[] args)
{
new PrintingClientStandaloneService().run();
}
/**
* Thanks to http://stackoverflow.com/questions/3777055/reading-manifest-mf-file-from-jar-file-using-java
*/
private void logVersionInfo()
{
try
{
final Enumeration<URL> resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
while (resEnum.hasMoreElements())
{
try
{
final URL url = resEnum.nextElement();
final InputStream is = url.openStream();
if (is != null)
{
final Manifest manifest = new Manifest(is);
final Attributes mainAttribs = manifest.getMainAttributes();
final String version = mainAttribs.getValue("Implementation-Version");
if (version != null)
{
logger.info("Resource " + url + " has version " + version);
}
}
}
catch (final Exception e)
{
// Silently ignore wrong manifests on classpath?
}
}
}
catch (final IOException e1)
|
{
// Silently ignore wrong manifests on classpath?
}
}
private void run()
{
final Context context = Context.getContext();
context.addSource(new ConfigFileContext());
logVersionInfo();
//
// Start the client
final PrintingClient client = new PrintingClient();
client.start();
final Thread clientThread = client.getDaemonThread();
try
{
clientThread.join();
}
catch (final InterruptedException e)
{
logger.log(Level.INFO, "Interrupted. Exiting.", e);
client.stop();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\PrintingClientStandaloneService.java
| 1
|
请完成以下Java代码
|
public abstract class EDI_Export_JSON extends PostgRESTProcessExecutor
{
private final AttachmentEntryService attachmentEntryService = SpringContextHolder.instance.getBean(AttachmentEntryService.class);
protected abstract I_EDI_Document_Extension loadRecordOutOfTrx();
protected abstract void saveRecord(I_EDI_Document_Extension record);
/**
* Sets invoice's EDI_ExportStatus and tell metasfresh to store the result to disk, unless we are called via API.
*/
@Override
protected final CustomPostgRESTParameters beforePostgRESTCall()
{
final I_EDI_Document_Extension record = loadRecordOutOfTrx();
record.setEDI_ExportStatus(I_EDI_Document.EDI_EXPORTSTATUS_SendingStarted);
saveRecord(record);
final boolean calledViaAPI = isCalledViaAPI();
return CustomPostgRESTParameters.builder()
.storeJsonFile(!calledViaAPI)
.expectSingleResult(true) // because we export exactly one record, we don't want the JSON to be an array
.build();
}
@Override
protected final String afterPostgRESTCall()
{
final ReportResultData reportData = Check.assumeNotNull(getResult().getReportData(), "reportData shall not be null after successful invocation");
final I_EDI_Document_Extension record = loadRecordOutOfTrx();
// note that if it was called via API, then the result will also be in API_Response_Audit, but there it will be removed after some time
|
final TableRecordReference recordReference = TableRecordReference.of(record);
addLog("Attaching result with filename {} to the {}-record with ID {}",
reportData.getReportFilename(),
recordReference.getTableName(),
recordReference.getRecord_ID()
);
attachmentEntryService.createNewAttachment(
record,
reportData.getReportFilename(),
reportData.getReportDataByteArray());
// note that a possible C_Doc_Outbound_Log's status is updated via modelinterceptor
record.setEDI_ExportStatus(I_EDI_Document.EDI_EXPORTSTATUS_Sent);
saveRecord(record);
return MSG_OK;
}
@Override
protected Exception handleException(@NonNull final Exception e)
{
final I_EDI_Document_Extension record = loadRecordOutOfTrx();
record.setEDI_ExportStatus(I_EDI_Document.EDI_EXPORTSTATUS_Error);
record.setEDIErrorMsg(e.getLocalizedMessage());
saveRecord(record);
return AdempiereException.wrapIfNeeded(e);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\export\json\EDI_Export_JSON.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Bean
RoleHierarchy roleHierarchy() {
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
String hierarchy = "ROLE_dba > ROLE_admin ROLE_admin > ROLE_user";
roleHierarchy.setHierarchy(hierarchy);
return roleHierarchy;
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// The memory user is not configured, but the UserService just created is configured into the AuthenticationManagerBuilder.
auth.userDetailsService(userService);
}
@Order
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
/*.antMatchers("/admin/**").hasRole("ADMIN")//Indicates that the user accessing the URL in the "/admin/**" mode must have the role of ADMIN
.antMatchers("/user/**").access("hasAnyRole('ADMIN','USER')")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()//Indicates that in addition to the URL pattern defined previously, users must access other URLs after authentication (access after logging in) */
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O object) {
object.setSecurityMetadataSource(cfisms());
object.setAccessDecisionManager(cadm());
|
return object;
}
})
.and()
.formLogin()
.loginProcessingUrl("/login").permitAll()
.and()
.csrf().disable();
}
@Bean
CustomFilterInvocationSecurityMetadataSource cfisms() {
return new CustomFilterInvocationSecurityMetadataSource();
}
@Bean
CustomAccessDecisionManager cadm() {
return new CustomAccessDecisionManager();
}
}
|
repos\springboot-demo-master\security\src\main\java\com\et\security\config\WebSecurityConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class DmnDeploymentResponse {
protected String id;
protected String name;
@JsonSerialize(using = DateToStringSerializer.class, as = Date.class)
protected Date deploymentTime;
protected String category;
protected String url;
protected String parentDeploymentId;
protected String tenantId;
public DmnDeploymentResponse(DmnDeployment deployment, String url) {
setId(deployment.getId());
setName(deployment.getName());
setDeploymentTime(deployment.getDeploymentTime());
setCategory(deployment.getCategory());
setParentDeploymentId(deployment.getParentDeploymentId());
setTenantId(deployment.getTenantId());
setUrl(url);
}
@ApiModelProperty(example = "03ab310d-c1de-11e6-a4f4-62ce84ef239e")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@ApiModelProperty(example = "dmnTest")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ApiModelProperty(example = "2016-12-14T10:16:37.000+01:00")
public Date getDeploymentTime() {
return deploymentTime;
}
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
@ApiModelProperty(example = "dmnExamples")
public String getCategory() {
return category;
}
|
public void setCategory(String category) {
this.category = category;
}
@ApiModelProperty(example = "http://localhost:8080/flowable-rest/dmn-api/dmn-repository/deployments/03ab310d-c1de-11e6-a4f4-62ce84ef239e")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "17510")
public String getParentDeploymentId() {
return parentDeploymentId;
}
public void setParentDeploymentId(String parentDeploymentId) {
this.parentDeploymentId = parentDeploymentId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\repository\DmnDeploymentResponse.java
| 2
|
请完成以下Java代码
|
public InfoBuilder setKeyColumn(final String keyColumn)
{
_keyColumn = keyColumn;
return this;
}
private String getKeyColumn()
{
if (_keyColumn != null)
{
return _keyColumn;
}
return getTableName() + "_ID";
}
public InfoBuilder setSearchValue(final String value)
{
_searchValue = value;
return this;
}
public String getSearchValue()
{
return _searchValue;
}
public InfoBuilder setMultiSelection(final boolean multiSelection)
{
_multiSelection = multiSelection;
return this;
}
private boolean isMultiSelection()
{
return _multiSelection;
}
public InfoBuilder setWhereClause(final String whereClause)
{
_whereClause = whereClause;
return this;
}
public String getWhereClause()
{
return _whereClause;
}
public InfoBuilder setAttributes(final Map<String, Object> attributes)
{
_attributes = attributes;
return this;
}
private Map<String, Object> getAttributes()
{
return _attributes;
}
public InfoBuilder setInfoWindow(final I_AD_InfoWindow infoWindow)
{
_infoWindowDef = infoWindow;
if (infoWindow != null)
{
final String tableName = Services.get(IADInfoWindowBL.class).getTableName(infoWindow);
setTableName(tableName);
}
return this;
}
private I_AD_InfoWindow getInfoWindow()
{
if (_infoWindowDef != null)
{
return _infoWindowDef;
}
final String tableName = getTableName();
|
final I_AD_InfoWindow infoWindowFound = Services.get(IADInfoWindowDAO.class).retrieveInfoWindowByTableName(getCtx(), tableName);
if (infoWindowFound != null && infoWindowFound.isActive())
{
return infoWindowFound;
}
return null;
}
/**
* @param iconName icon name (without size and without file extension).
*/
public InfoBuilder setIconName(final String iconName)
{
if (Check.isEmpty(iconName, true))
{
return setIcon(null);
}
else
{
final Image icon = Images.getImage2(iconName + "16");
return setIcon(icon);
}
}
public InfoBuilder setIcon(final Image icon)
{
this._iconImage = icon;
return this;
}
private Image getIconImage()
{
return _iconImage;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\InfoBuilder.java
| 1
|
请完成以下Java代码
|
public void setC_Invoice_ID (int C_Invoice_ID)
{
if (C_Invoice_ID < 1)
set_Value (COLUMNNAME_C_Invoice_ID, null);
else
set_Value (COLUMNNAME_C_Invoice_ID, Integer.valueOf(C_Invoice_ID));
}
/** Get Rechnung.
@return Invoice Identifier
*/
@Override
public int getC_Invoice_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Recurrent Payment History.
@param C_RecurrentPaymentHistory_ID Recurrent Payment History */
@Override
public void setC_RecurrentPaymentHistory_ID (int C_RecurrentPaymentHistory_ID)
{
if (C_RecurrentPaymentHistory_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_RecurrentPaymentHistory_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_RecurrentPaymentHistory_ID, Integer.valueOf(C_RecurrentPaymentHistory_ID));
}
/** Get Recurrent Payment History.
@return Recurrent Payment History */
@Override
public int getC_RecurrentPaymentHistory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RecurrentPaymentHistory_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.banking.model.I_C_RecurrentPaymentLine getC_RecurrentPaymentLine() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_RecurrentPaymentLine_ID, de.metas.banking.model.I_C_RecurrentPaymentLine.class);
}
@Override
public void setC_RecurrentPaymentLine(de.metas.banking.model.I_C_RecurrentPaymentLine C_RecurrentPaymentLine)
{
set_ValueFromPO(COLUMNNAME_C_RecurrentPaymentLine_ID, de.metas.banking.model.I_C_RecurrentPaymentLine.class, C_RecurrentPaymentLine);
|
}
/** Set Recurrent Payment Line.
@param C_RecurrentPaymentLine_ID Recurrent Payment Line */
@Override
public void setC_RecurrentPaymentLine_ID (int C_RecurrentPaymentLine_ID)
{
if (C_RecurrentPaymentLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_RecurrentPaymentLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_RecurrentPaymentLine_ID, Integer.valueOf(C_RecurrentPaymentLine_ID));
}
/** Get Recurrent Payment Line.
@return Recurrent Payment Line */
@Override
public int getC_RecurrentPaymentLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RecurrentPaymentLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public org.compiere.util.KeyNamePair getKeyNamePair()
{
return new org.compiere.util.KeyNamePair(get_ID(), String.valueOf(getC_RecurrentPaymentLine_ID()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_RecurrentPaymentHistory.java
| 1
|
请完成以下Java代码
|
private Account getRevenueAccountFromCompensationSchema(@NonNull final AcctSchema as)
{
final ProductCategoryId productCategoryId = getProductCategoryForGroupTemplateId();
if (productCategoryId == null)
{
return null;
}
return getAccountProvider()
.getProductCategoryAccount(as.getId(), productCategoryId, ProductAcctType.P_Revenue_Acct)
.orElse(null);
}
@Nullable
private ProductCategoryId getProductCategoryForGroupTemplateId()
{
final I_C_InvoiceLine invoiceLine = getC_InvoiceLine();
final int orderLineRecordId = invoiceLine.getC_OrderLine_ID();
if (orderLineRecordId <= 0)
{
return null;
}
final I_C_OrderLine orderLineRecord = orderDAO.getOrderLineById(orderLineRecordId);
final GroupId groupId = OrderGroupRepository.extractGroupIdOrNull(orderLineRecord);
if (groupId == null)
{
return null;
}
final Group group = orderGroupRepo.retrieveGroupIfExists(groupId);
if (group == null)
{
return null;
|
}
final GroupTemplateId groupTemplateId = group.getGroupTemplateId();
if (groupTemplateId == null)
{
return null;
}
return productDAO.retrieveProductCategoryForGroupTemplateId(groupTemplateId);
}
@Override
protected OrderId getSalesOrderId()
{
final I_C_InvoiceLine invoiceLine = getC_InvoiceLine();
return OrderId.ofRepoIdOrNull(invoiceLine.getC_OrderSO_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine_Invoice.java
| 1
|
请完成以下Java代码
|
public void setDateInvoiced (java.sql.Timestamp DateInvoiced)
{
set_Value (COLUMNNAME_DateInvoiced, DateInvoiced);
}
/** Get Rechnungsdatum.
@return Datum auf der Rechnung
*/
@Override
public java.sql.Timestamp getDateInvoiced ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DateInvoiced);
}
/** Set Datum Fälligkeit.
@param DueDate
Datum, zu dem Zahlung fällig wird
*/
@Override
public void setDueDate (java.sql.Timestamp DueDate)
{
set_Value (COLUMNNAME_DueDate, DueDate);
}
/** Get Datum Fälligkeit.
@return Datum, zu dem Zahlung fällig wird
*/
@Override
public java.sql.Timestamp getDueDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DueDate);
}
/** Set Dunning Grace Date.
@param DunningGrace Dunning Grace Date */
@Override
public void setDunningGrace (java.sql.Timestamp DunningGrace)
{
set_Value (COLUMNNAME_DunningGrace, DunningGrace);
}
/** Get Dunning Grace Date.
@return Dunning Grace Date */
@Override
public java.sql.Timestamp getDunningGrace ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DunningGrace);
}
/** Set Summe Gesamt.
@param GrandTotal
Summe über Alles zu diesem Beleg
*/
@Override
public void setGrandTotal (java.math.BigDecimal GrandTotal)
{
set_Value (COLUMNNAME_GrandTotal, GrandTotal);
}
/** Get Summe Gesamt.
@return Summe über Alles zu diesem Beleg
*/
@Override
public java.math.BigDecimal getGrandTotal ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrandTotal);
if (bd == null)
|
return BigDecimal.ZERO;
return bd;
}
/** Set In Dispute.
@param IsInDispute
Document is in dispute
*/
@Override
public void setIsInDispute (boolean IsInDispute)
{
set_Value (COLUMNNAME_IsInDispute, Boolean.valueOf(IsInDispute));
}
/** Get In Dispute.
@return Document is in dispute
*/
@Override
public boolean isInDispute ()
{
Object oo = get_Value(COLUMNNAME_IsInDispute);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Offener Betrag.
@param OpenAmt Offener Betrag */
@Override
public void setOpenAmt (java.math.BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
/** Get Offener Betrag.
@return Offener Betrag */
@Override
public java.math.BigDecimal getOpenAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_Dunning_Candidate_Invoice_v1.java
| 1
|
请完成以下Java代码
|
public void parseLongestText(String text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor)
{
if (trie != null)
{
final int[] lengthArray = new int[text.length()];
final CoreDictionary.Attribute[] attributeArray = new CoreDictionary.Attribute[text.length()];
char[] charArray = text.toCharArray();
DoubleArrayTrie<CoreDictionary.Attribute>.Searcher searcher = dat.getSearcher(charArray, 0);
while (searcher.next())
{
lengthArray[searcher.begin] = searcher.length;
attributeArray[searcher.begin] = searcher.value;
}
trie.parseText(charArray, new AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute>()
{
@Override
public void hit(int begin, int end, CoreDictionary.Attribute value)
{
int length = end - begin;
if (length > lengthArray[begin])
{
lengthArray[begin] = length;
attributeArray[begin] = value;
}
}
});
for (int i = 0; i < charArray.length; )
{
if (lengthArray[i] == 0)
{
++i;
}
|
else
{
processor.hit(i, i + lengthArray[i], attributeArray[i]);
i += lengthArray[i];
}
}
}
else
dat.parseLongestText(text, processor);
}
/**
* 热更新(重新加载)<br>
* 集群环境(或其他IOAdapter)需要自行删除缓存文件(路径 = HanLP.Config.CustomDictionaryPath[0] + Predefine.BIN_EXT)
*
* @return 是否加载成功
*/
public boolean reload()
{
if (path == null || path.length == 0) return false;
IOUtil.deleteFile(path[0] + Predefine.BIN_EXT); // 删掉缓存
return loadMainDictionary(path[0], normalization);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\DynamicCustomDictionary.java
| 1
|
请完成以下Java代码
|
public int getM_Product_ID() {
Object o = fProduct.getValue();
return o == null ? 0 : ((Number) o).intValue();
}
public BigDecimal getQtyOrdered() {
Object value = fQtyOrdered.getValue();
if (value == null || value.toString().trim().length() == 0)
return Env.ZERO;
else if (value instanceof BigDecimal)
return (BigDecimal) value;
else if (value instanceof Integer)
return BigDecimal.valueOf(((Integer) value));
else
return new BigDecimal(value.toString());
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == fQtyOrdered) {
try {
setEnabled(false);
commit();
} catch (Exception ex) {
setInfo(ex.getLocalizedMessage(), true, fQtyOrdered);
} finally {
setEnabled(true);
}
}
}
@Override
public void vetoableChange(PropertyChangeEvent evt)
throws PropertyVetoException {
if (evt.getPropertyName().equals(I_C_OrderLine.COLUMNNAME_M_Product_ID)) {
reset(false);
fProduct.setValue(evt.getNewValue());
updateData(true, fProduct);
}
}
private void reset(boolean clearPrimaryField) {
fQtyOrdered.removeActionListener(this);
if (clearPrimaryField) {
fProduct.setValue(null);
}
fQtyOrdered.setValue(Env.ZERO);
fQtyOrdered.setReadWrite(false);
fProduct.requestFocus();
}
private void updateData(boolean requestFocus, Component source) {
if (requestFocus) {
SwingFieldsUtil.focusNextNotEmpty(source, m_editors);
}
fQtyOrdered.setReadWrite(true);
fQtyOrdered.addActionListener(this);
}
private void commit() {
int M_Product_ID = getM_Product_ID();
if (M_Product_ID <= 0)
throw new FillMandatoryException(
I_C_OrderLine.COLUMNNAME_M_Product_ID);
String productStr = fProduct.getDisplay();
if (productStr == null)
productStr = "";
|
BigDecimal qty = getQtyOrdered();
if (qty == null || qty.signum() == 0)
throw new FillMandatoryException(
I_C_OrderLine.COLUMNNAME_QtyOrdered);
//
MOrderLine line = new MOrderLine(order);
line.setM_Product_ID(getM_Product_ID(), true);
line.setQty(qty);
line.saveEx();
//
reset(true);
changed = true;
refreshIncludedTabs();
setInfo(Msg.parseTranslation(Env.getCtx(),
"@RecordSaved@ - @M_Product_ID@:" + productStr
+ ", @QtyOrdered@:" + qty), false, null);
}
public void showCenter() {
AEnv.showCenterWindow(getOwner(), this);
}
public boolean isChanged() {
return changed;
}
public void refreshIncludedTabs() {
for (GridTab includedTab : orderTab.getIncludedTabs()) {
includedTab.dataRefreshAll();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\form\swing\OrderLineCreate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ManufacturingJob execute()
{
trxManager.runInThreadInheritedTrx(this::execute0);
return job;
}
private void execute0()
{
job = job.withChangedRawMaterialsIssueStep(
request.getActivityId(),
request.getIssueScheduleId(),
(step) -> {
if (processed)
{
// shall not happen
logger.warn("Ignoring request because was already processed: request={}, step={}", request, step);
return step;
}
return issueToStep(step);
});
if (!processed)
{
throw new AdempiereException("Failed fulfilling issue request")
.setParameter("request", request)
.setParameter("job", job);
}
save();
|
}
private RawMaterialsIssueStep issueToStep(final RawMaterialsIssueStep step)
{
step.assertNotIssued();
final PPOrderIssueSchedule issueSchedule = ppOrderIssueScheduleService.issue(request);
this.processed = true;
return step.withIssued(issueSchedule.getIssued());
}
private void save()
{
newSaver().saveActivityStatuses(job);
}
@NonNull
private ManufacturingJobLoaderAndSaver newSaver() {return new ManufacturingJobLoaderAndSaver(loadingAndSavingSupportServices);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\issue\IssueRawMaterialsCommand.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public User findUserByUserName(String userName) {
Query query=new Query(Criteria.where("userName").is(userName));
User user = mongoTemplate.findOne(query , User.class);
return user;
}
/**
* 更新对象
* @param user
*/
@Override
public long updateUser(User user) {
Query query=new Query(Criteria.where("id").is(user.getId()));
Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord());
//更新查询返回结果集的第一条
UpdateResult result =mongoTemplate.updateFirst(query,update,User.class);
//更新查询返回结果集的所有
// mongoTemplate.updateMulti(query,update,UserEntity.class);
|
if(result!=null)
return result.getMatchedCount();
else
return 0;
}
/**
* 删除对象
* @param id
*/
@Override
public void deleteUserById(Long id) {
Query query=new Query(Criteria.where("id").is(id));
mongoTemplate.remove(query,User.class);
}
}
|
repos\spring-boot-leaning-master\2.x_42_courses\第 4-7 课:Spring Boot 简单集成 MongoDB\spring-boot-mongodb-template\src\main\java\com\neo\repository\impl\UserRepositoryImpl.java
| 2
|
请完成以下Java代码
|
protected AsyncResultSet executeRead(TenantId tenantId, Statement statement) {
return execute(tenantId, statement, defaultReadLevel, rateReadLimiter);
}
protected AsyncResultSet executeWrite(TenantId tenantId, Statement statement) {
return execute(tenantId, statement, defaultWriteLevel, rateWriteLimiter);
}
protected TbResultSetFuture executeAsyncRead(TenantId tenantId, Statement statement) {
return executeAsync(tenantId, statement, defaultReadLevel, rateReadLimiter);
}
protected TbResultSetFuture executeAsyncWrite(TenantId tenantId, Statement statement) {
return executeAsync(tenantId, statement, defaultWriteLevel, rateWriteLimiter);
}
private AsyncResultSet execute(TenantId tenantId, Statement statement, ConsistencyLevel level,
BufferedRateExecutor<CassandraStatementTask, TbResultSetFuture> rateExecutor) {
if (log.isDebugEnabled()) {
log.debug("Execute cassandra statement {}", statementToString(statement));
}
return executeAsync(tenantId, statement, level, rateExecutor).getUninterruptibly();
}
private TbResultSetFuture executeAsync(TenantId tenantId, Statement statement, ConsistencyLevel level,
|
BufferedRateExecutor<CassandraStatementTask, TbResultSetFuture> rateExecutor) {
if (log.isDebugEnabled()) {
log.debug("Execute cassandra async statement {}", statementToString(statement));
}
if (statement.getConsistencyLevel() == null) {
statement = statement.setConsistencyLevel(level);
}
return rateExecutor.submit(new CassandraStatementTask(tenantId, getSession(), statement));
}
private static String statementToString(Statement statement) {
if (statement instanceof BoundStatement) {
return ((BoundStatement) statement).getPreparedStatement().getQuery();
} else {
return statement.toString();
}
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\nosql\CassandraAbstractDao.java
| 1
|
请完成以下Java代码
|
public Mono<String> sleep() {
// System.out.println(Thread.currentThread().getName());
// return Mono.just("world").delayElement(Duration.ofMillis(100));
return Mono.defer(() -> {
// System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(100L);
} catch (InterruptedException ignored) {
}
return Mono.just("world");
}).subscribeOn(Schedulers.parallel());
}
private Map<String, Boolean> MAP = new ConcurrentHashMap<>();
@GetMapping("/sleep2")
|
public Mono<String> sleep2() {
return Mono.defer(() -> {
try {
// System.out.println(Thread.currentThread().getName());
if (!MAP.containsKey(Thread.currentThread().getName())) {
System.out.println(Thread.currentThread().getName());
MAP.put(Thread.currentThread().getName(), true);
}
Thread.sleep(100L);
} catch (InterruptedException ignored) {
}
return Mono.just("world");
}).subscribeOn(Schedulers.elastic());
}
}
|
repos\SpringBoot-Labs-master\lab-06\lab-06-webflux-tomcat\src\main\java\cn\iocoder\springboot\labs\lab06\webflux\Controller.java
| 1
|
请完成以下Java代码
|
public ProductWithDemandSupplyCollection getByProductIds(@NonNull final Collection<ProductId> productIds)
{
if (productIds.isEmpty())
{
return ProductWithDemandSupplyCollection.of(ImmutableMap.of());
}
final ArrayList<Object> sqlParams = new ArrayList<>();
final String sql = "SELECT * FROM getQtyDemandQtySupply( p_M_Product_IDs :=" + DB.TO_ARRAY(productIds, sqlParams) + ")";
return DB.retrieveRows(sql, sqlParams, QtyDemandSupplyRepository::ofResultSet)
.stream()
.collect(ProductWithDemandSupplyCollection.toProductsWithDemandSupply());
}
@NonNull
private static ProductWithDemandSupply ofResultSet(@NonNull final ResultSet rs) throws SQLException
{
return ProductWithDemandSupply.builder()
.warehouseId(WarehouseId.ofRepoIdOrNull(rs.getInt("M_Warehouse_ID")))
.attributesKey(AttributesKey.ofString(rs.getString("AttributesKey")))
.productId(ProductId.ofRepoId(rs.getInt("M_Product_ID")))
.uomId(UomId.ofRepoId(rs.getInt("C_UOM_ID")))
.qtyReserved(rs.getBigDecimal("QtyReserved"))
.qtyToMove(rs.getBigDecimal("QtyToMove"))
.build();
}
public QtyDemandQtySupply getById(@NonNull final QtyDemandQtySupplyId id)
{
final I_QtyDemand_QtySupply_V po = queryBL.createQueryBuilder(I_QtyDemand_QtySupply_V.class)
.addEqualsFilter(I_QtyDemand_QtySupply_V.COLUMNNAME_QtyDemand_QtySupply_V_ID, id)
.create()
|
.firstOnly(I_QtyDemand_QtySupply_V.class);
return fromPO(po);
}
private QtyDemandQtySupply fromPO(@NonNull final I_QtyDemand_QtySupply_V po)
{
final UomId uomId = UomId.ofRepoId(po.getC_UOM_ID());
return QtyDemandQtySupply.builder()
.id(QtyDemandQtySupplyId.ofRepoId(po.getQtyDemand_QtySupply_V_ID()))
.productId(ProductId.ofRepoId(po.getM_Product_ID()))
.warehouseId(WarehouseId.ofRepoId(po.getM_Warehouse_ID()))
.attributesKey(AttributesKey.ofString(po.getAttributesKey()))
.qtyToMove(Quantitys.of(po.getQtyToMove(), uomId))
.qtyReserved(Quantitys.of(po.getQtyReserved(), uomId))
.qtyForecasted(Quantitys.of(po.getQtyForecasted(), uomId))
.qtyToProduce(Quantitys.of(po.getQtyToProduce(), uomId))
.qtyStock(Quantitys.of(po.getQtyStock(), uomId))
.orgId(OrgId.ofRepoId(po.getAD_Org_ID()))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\QtyDemandSupplyRepository.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8081
spring:
graphql:
schema:
locations: classpath:error-handling/graphql/
datasource:
url: "jdbc:h2:mem:graphqldb"
driverClassName: "org.h2.Driver"
username: sa
password:
jpa:
show-sql: true
properties:
hibernate:
dialect: org.hibernate.dialect.H2Dialect
ddl-auto: none
global
|
ly_quoted_identifiers: true
defer-datasource-initialization: true
h2:
console.enabled: true
sql:
init:
platform: h2
mode: always
|
repos\tutorials-master\spring-boot-modules\spring-boot-graphql\src\main\resources\application-error-handling.yml
| 2
|
请完成以下Java代码
|
public HistoricDetailQueryImpl orderByProcessInstanceId() {
orderBy(HistoricDetailQueryProperty.PROCESS_INSTANCE_ID);
return this;
}
public HistoricDetailQueryImpl orderByTime() {
orderBy(HistoricDetailQueryProperty.TIME);
return this;
}
public HistoricDetailQueryImpl orderByVariableName() {
orderBy(HistoricDetailQueryProperty.VARIABLE_NAME);
return this;
}
public HistoricDetailQueryImpl orderByFormPropertyId() {
orderBy(HistoricDetailQueryProperty.VARIABLE_NAME);
return this;
}
public HistoricDetailQueryImpl orderByVariableRevision() {
orderBy(HistoricDetailQueryProperty.VARIABLE_REVISION);
return this;
}
public HistoricDetailQueryImpl orderByVariableType() {
orderBy(HistoricDetailQueryProperty.VARIABLE_TYPE);
return this;
}
// getters and setters
// //////////////////////////////////////////////////////
public String getId() {
return id;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getTaskId() {
return taskId;
|
}
public String getActivityId() {
return activityId;
}
public String getType() {
return type;
}
public boolean getExcludeTaskRelated() {
return excludeTaskRelated;
}
public String getExecutionId() {
return executionId;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricDetailQueryImpl.java
| 1
|
请完成以下Java代码
|
public boolean isLoaded()
{
return m_loaded;
}
/**
* Returns a list of parameters on which this lookup depends.
*
* Those parameters will be fetched from context on validation time.
*
* @return list of parameter names
*/
public Set<String> getParameters()
{
return ImmutableSet.of();
}
/**
*
* @return evaluation context
*/
public IValidationContext getValidationContext()
{
return IValidationContext.NULL;
}
/**
* Suggests a valid value for given value
*
* @param value
* @return equivalent valid value or same this value is valid; if there are no suggestions, null will be returned
*/
public NamePair suggestValidValue(final NamePair value)
{
|
return null;
}
/**
* Returns true if given <code>display</code> value was rendered for a not found item.
* To be used together with {@link #getDisplay} methods.
*
* @param display
* @return true if <code>display</code> contains not found markers
*/
public boolean isNotFoundDisplayValue(String display)
{
return false;
}
} // Lookup
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\Lookup.java
| 1
|
请完成以下Java代码
|
public boolean isPageBreak(final int row, final int col)
{
PrintDataElement pde = getPDE(row, col);
return pde != null ? pde.isPageBreak() : false;
}
@Override
public boolean isFunctionRow(final int row)
{
return m_printData.isFunctionRow(row);
}
@Override
protected void formatPage(final Sheet sheet)
{
super.formatPage(sheet);
MPrintPaper paper = MPrintPaper.get(this.m_printFormat.getAD_PrintPaper_ID());
//
// Set paper size:
short paperSize = -1;
MediaSizeName mediaSizeName = paper.getMediaSize().getMediaSizeName();
if (MediaSizeName.NA_LETTER.equals(mediaSizeName))
{
paperSize = PrintSetup.LETTER_PAPERSIZE;
}
else if (MediaSizeName.NA_LEGAL.equals(mediaSizeName))
{
paperSize = PrintSetup.LEGAL_PAPERSIZE;
}
else if (MediaSizeName.EXECUTIVE.equals(mediaSizeName))
{
paperSize = PrintSetup.EXECUTIVE_PAPERSIZE;
}
else if (MediaSizeName.ISO_A4.equals(mediaSizeName))
{
paperSize = PrintSetup.A4_PAPERSIZE;
}
else if (MediaSizeName.ISO_A5.equals(mediaSizeName))
{
paperSize = PrintSetup.A5_PAPERSIZE;
}
else if (MediaSizeName.NA_NUMBER_10_ENVELOPE.equals(mediaSizeName))
{
paperSize = PrintSetup.ENVELOPE_10_PAPERSIZE;
}
// else if (MediaSizeName..equals(mediaSizeName)) {
// paperSize = PrintSetup.ENVELOPE_DL_PAPERSIZE;
// }
// else if (MediaSizeName..equals(mediaSizeName)) {
|
// paperSize = PrintSetup.ENVELOPE_CS_PAPERSIZE;
// }
else if (MediaSizeName.MONARCH_ENVELOPE.equals(mediaSizeName))
{
paperSize = PrintSetup.ENVELOPE_MONARCH_PAPERSIZE;
}
if (paperSize != -1)
{
sheet.getPrintSetup().setPaperSize(paperSize);
}
//
// Set Landscape/Portrait:
sheet.getPrintSetup().setLandscape(paper.isLandscape());
//
// Set Paper Margin:
sheet.setMargin(Sheet.TopMargin, ((double)paper.getMarginTop()) / 72);
sheet.setMargin(Sheet.RightMargin, ((double)paper.getMarginRight()) / 72);
sheet.setMargin(Sheet.LeftMargin, ((double)paper.getMarginLeft()) / 72);
sheet.setMargin(Sheet.BottomMargin, ((double)paper.getMarginBottom()) / 72);
//
}
@Override
protected List<CellValue> getNextRow()
{
final ArrayList<CellValue> result = new ArrayList<>();
for (int i = 0; i < getColumnCount(); i++)
{
result.add(getValueAt(rowNumber, i));
}
rowNumber++;
return result;
}
@Override
protected boolean hasNextRow()
{
return rowNumber < getRowCount();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\print\export\PrintDataExcelExporter.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return toJson();
}
@JsonValue
public String toJson()
{
return json;
}
public int getProcessIdAsInt()
{
int processIdAsInt = this.processIdAsInt;
if (processIdAsInt <= 0)
{
final String processIdStr = getProcessId();
processIdAsInt = Integer.parseInt(processIdStr);
if (processIdAsInt <= 0)
{
throw new IllegalStateException("processId cannot be converted to int: " + processIdStr);
}
this.processIdAsInt = processIdAsInt;
}
return processIdAsInt;
}
public AdProcessId toAdProcessId()
{
final AdProcessId adProcessId = toAdProcessIdOrNull();
if (adProcessId == null)
{
|
throw new AdempiereException("Cannot convert " + this + " to " + AdProcessId.class.getSimpleName() + " because the processHanderType=" + processHandlerType + " is not supported");
}
return adProcessId;
}
/**
* Convenience method to get the {@link AdProcessId} for this instance if its {@code processIdAsInt} member is set and/or if {@link #getProcessHandlerType()} is {@link #PROCESSHANDLERTYPE_AD_Process}.
* {@code null} otherwise.
*/
public AdProcessId toAdProcessIdOrNull()
{
if (this.processIdAsInt > 0) // was set by the creator of this instance
{
return AdProcessId.ofRepoId(this.processIdAsInt);
}
else if (this.processHandlerType.isADProcess())
{
return AdProcessId.ofRepoId(getProcessIdAsInt());
}
else // nothing we can do here
{
return null;
}
}
public DocumentId toDocumentId()
{
return DocumentId.ofString(toJson());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\ProcessId.java
| 1
|
请完成以下Java代码
|
protected HistoryLevel getCaseDefinitionHistoryLevel(String caseDefinitionId) {
HistoryLevel caseDefinitionHistoryLevel = null;
try {
CaseDefinition caseDefinition = CaseDefinitionUtil.getCaseDefinition(caseDefinitionId);
CmmnModel cmmnModel = CaseDefinitionUtil.getCmmnModel(caseDefinitionId);
Case caze = cmmnModel.getCaseById(caseDefinition.getKey());
if (caze.getPlanModel().getExtensionElements().containsKey("historyLevel")) {
ExtensionElement historyLevelElement = caze.getPlanModel().getExtensionElements().get("historyLevel").iterator().next();
String historyLevelValue = historyLevelElement.getElementText();
if (StringUtils.isNotEmpty(historyLevelValue)) {
try {
caseDefinitionHistoryLevel = HistoryLevel.getHistoryLevelForKey(historyLevelValue);
} catch (Exception e) {}
}
}
if (caseDefinitionHistoryLevel == null) {
caseDefinitionHistoryLevel = this.cmmnEngineConfiguration.getHistoryLevel();
}
} catch (Exception e) {}
|
return caseDefinitionHistoryLevel;
}
protected boolean includePlanItemDefinitionInHistory(String caseDefinitionId, String activityId) {
boolean includeInHistory = false;
if (caseDefinitionId != null) {
CmmnModel cmmnModel = CaseDefinitionUtil.getCmmnModel(caseDefinitionId);
PlanItemDefinition planItemDefinition = cmmnModel.findPlanItemDefinition(activityId);
if (planItemDefinition == null) {
PlanItem planItem = cmmnModel.findPlanItem(activityId);
planItemDefinition = planItem.getPlanItemDefinition();
}
if (planItemDefinition.getExtensionElements().containsKey("includeInHistory")) {
ExtensionElement historyElement = planItemDefinition.getExtensionElements().get("includeInHistory").iterator().next();
String historyLevelValue = historyElement.getElementText();
includeInHistory = Boolean.valueOf(historyLevelValue);
}
}
return includeInHistory;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\DefaultCmmnHistoryConfigurationSettings.java
| 1
|
请完成以下Java代码
|
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setTextMsg (final java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
@Override
public java.lang.String getTextMsg()
{
return get_ValueAsString(COLUMNNAME_TextMsg);
}
@Override
public void setWF_Initial_User_ID (final int WF_Initial_User_ID)
{
if (WF_Initial_User_ID < 1)
set_Value (COLUMNNAME_WF_Initial_User_ID, null);
else
|
set_Value (COLUMNNAME_WF_Initial_User_ID, WF_Initial_User_ID);
}
@Override
public int getWF_Initial_User_ID()
{
return get_ValueAsInt(COLUMNNAME_WF_Initial_User_ID);
}
/**
* WFState AD_Reference_ID=305
* Reference name: WF_Instance State
*/
public static final int WFSTATE_AD_Reference_ID=305;
/** NotStarted = ON */
public static final String WFSTATE_NotStarted = "ON";
/** Running = OR */
public static final String WFSTATE_Running = "OR";
/** Suspended = OS */
public static final String WFSTATE_Suspended = "OS";
/** Completed = CC */
public static final String WFSTATE_Completed = "CC";
/** Aborted = CA */
public static final String WFSTATE_Aborted = "CA";
/** Terminated = CT */
public static final String WFSTATE_Terminated = "CT";
@Override
public void setWFState (final java.lang.String WFState)
{
set_Value (COLUMNNAME_WFState, WFState);
}
@Override
public java.lang.String getWFState()
{
return get_ValueAsString(COLUMNNAME_WFState);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Process.java
| 1
|
请完成以下Java代码
|
public void generate()
{
trxManager.run(ITrx.TRXNAME_ThreadInherited, new TrxRunnableAdapter()
{
@Override
public void run(final String localTrxName) throws Exception
{
generate0();
}
});
}
private void generate0()
{
final OrdersCollector ordersCollector = OrdersCollector.newInstance();
final OrdersAggregator aggregator = OrdersAggregator.newInstance(ordersCollector);
for (final Iterator<I_PMM_PurchaseCandidate> it = getCandidates(); it.hasNext();)
{
final I_PMM_PurchaseCandidate candidateModel = it.next();
final PurchaseCandidate candidate = PurchaseCandidate.of(candidateModel);
aggregator.add(candidate);
}
aggregator.closeAllGroups();
}
|
public OrdersGenerator setCandidates(final Iterator<I_PMM_PurchaseCandidate> candidates)
{
Check.assumeNotNull(candidates, "candidates not null");
this.candidates = candidates;
return this;
}
public OrdersGenerator setCandidates(final Iterable<I_PMM_PurchaseCandidate> candidates)
{
Check.assumeNotNull(candidates, "candidates not null");
setCandidates(candidates.iterator());
return this;
}
private Iterator<I_PMM_PurchaseCandidate> getCandidates()
{
return candidates;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\OrdersGenerator.java
| 1
|
请完成以下Java代码
|
final IUserQueryField findSearchFieldByColumnName(@Nullable final String columnName)
{
if (columnName == null || columnName.isEmpty())
{
return null;
}
for (final IUserQueryField searchField : getSearchFields())
{
if (searchField.matchesColumnName(columnName))
{
return searchField;
}
}
return null;
}
public static final class Builder
{
private Integer adTabId = null;
private Integer adTableId = null;
private Integer adUserId = null;
private Collection<IUserQueryField> searchFields;
private ColumnDisplayTypeProvider columnDisplayTypeProvider;
private Builder()
{
}
public UserQueryRepository build()
{
return new UserQueryRepository(this);
}
@SuppressWarnings("unchecked")
public Builder setSearchFields(final Collection<? extends IUserQueryField> searchFields)
{
this.searchFields = (Collection<IUserQueryField>)searchFields;
return this;
}
private Collection<IUserQueryField> getSearchFields()
{
Check.assumeNotNull(searchFields, "searchFields not null");
return searchFields;
}
public Builder setAD_Tab_ID(final int adTabId)
{
this.adTabId = adTabId;
return this;
}
private int getAD_Tab_ID()
{
Check.assumeNotNull(adTabId, "adTabId not null");
return adTabId;
}
public Builder setAD_Table_ID(final int adTableId)
|
{
this.adTableId = adTableId;
return this;
}
private int getAD_Table_ID()
{
Check.assumeNotNull(adTableId, "adTableId not null");
Check.assume(adTableId > 0, "adTableId > 0");
return adTableId;
}
public Builder setAD_User_ID(final int adUserId)
{
this.adUserId = adUserId;
return this;
}
public Builder setAD_User_ID_Any()
{
this.adUserId = -1;
return this;
}
private int getAD_User_ID()
{
Check.assumeNotNull(adUserId, "Parameter adUserId is not null");
return adUserId;
}
public Builder setColumnDisplayTypeProvider(@NonNull final ColumnDisplayTypeProvider columnDisplayTypeProvider)
{
this.columnDisplayTypeProvider = columnDisplayTypeProvider;
return this;
}
public ColumnDisplayTypeProvider getColumnDisplayTypeProvider()
{
return columnDisplayTypeProvider;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\apps\search\UserQueryRepository.java
| 1
|
请完成以下Java代码
|
static I_M_HU_PI_Item_Product extractPIItemProductOrNull(@NonNull final I_M_HU hu)
{
final HUPIItemProductId piItemProductId = HUPIItemProductId.ofRepoIdOrNull(hu.getM_HU_PI_Item_Product_ID());
return piItemProductId != null
? Services.get(IHUPIItemProductDAO.class).getRecordById(piItemProductId)
: null;
}
AttributesKey getAttributesKeyForInventory(@NonNull I_M_HU hu);
AttributesKey getAttributesKeyForInventory(@NonNull IAttributeSet attributeSet);
void setHUStatus(@NonNull Collection<I_M_HU> hus, @NonNull String huStatus);
void setHUStatus(@NonNull Collection<I_M_HU> hus, @NonNull IHUContext huContext, @NonNull String huStatus);
void setHUStatus(I_M_HU hu, IContextAware contextProvider, String huStatus);
void setHUStatus(@NonNull I_M_HU hu, @NonNull String huStatus);
|
boolean isEmptyStorage(I_M_HU hu);
boolean isDestroyedOrEmptyStorage(I_M_HU hu);
void setClearanceStatusRecursively(final HuId huId, final ClearanceStatusInfo statusInfo);
boolean isHUHierarchyCleared(@NonNull I_M_HU hu);
ITranslatableString getClearanceStatusCaption(ClearanceStatus clearanceStatus);
boolean isHUHierarchyCleared(@NonNull final HuId huId);
@NonNull
ImmutableSet<LocatorId> getLocatorIds(@NonNull Collection<HuId> huIds);
Set<HuPackingMaterialId> getHUPackingMaterialIds(HuId huId);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\IHandlingUnitsBL.java
| 1
|
请完成以下Java代码
|
public List<String> getFromActivityIds() {
return new ArrayList<>(fromActivityIds);
}
@Override
public List<String> getToActivityIds() {
ArrayList<String> list = new ArrayList<>();
list.add(toActivityId);
return list;
}
public String getToActivityId() {
return toActivityId;
}
@Override
public ManyToOneMapping inParentProcessOfCallActivityId(String fromCallActivityId) {
this.fromCallActivityId = fromCallActivityId;
this.toCallActivityId = null;
this.callActivityProcessDefinitionVersion = null;
return this;
}
@Override
public ManyToOneMapping inSubProcessOfCallActivityId(String toCallActivityId) {
this.toCallActivityId = toCallActivityId;
this.callActivityProcessDefinitionVersion = null;
this.fromCallActivityId = null;
return this;
}
@Override
public ManyToOneMapping inSubProcessOfCallActivityId(String toCallActivityId, int subProcessDefVersion) {
this.toCallActivityId = toCallActivityId;
this.callActivityProcessDefinitionVersion = subProcessDefVersion;
this.fromCallActivityId = null;
return this;
}
@Override
public ManyToOneMapping withNewAssignee(String newAssigneeId) {
this.withNewAssignee = newAssigneeId;
return this;
}
@Override
|
public String getWithNewAssignee() {
return withNewAssignee;
}
@Override
public ManyToOneMapping withNewOwner(String newOwner) {
this.withNewOwner = newOwner;
return this;
}
@Override
public String getWithNewOwner() {
return withNewOwner;
}
@Override
public ManyToOneMapping withLocalVariable(String variableName, Object variableValue) {
withLocalVariables.put(variableName, variableValue);
return this;
}
@Override
public ManyToOneMapping withLocalVariables(Map<String, Object> variables) {
withLocalVariables.putAll(variables);
return this;
}
@Override
public Map<String, Object> getActivityLocalVariables() {
return withLocalVariables;
}
@Override
public String toString() {
return "ManyToOneMapping{" + "fromActivityIds=" + fromActivityIds + ", toActivityId='" + toActivityId + '\'' + '}';
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\migration\ActivityMigrationMapping.java
| 1
|
请完成以下Java代码
|
public void updateProductFromBomVersions(final I_PP_Product_Planning planning)
{
final ProductBOMVersionsId bomVersionsId = ProductBOMVersionsId.ofRepoIdOrNull(planning.getPP_Product_BOMVersions_ID());
if (bomVersionsId == null)
{
return; // nothing to do
}
final I_PP_Product_BOMVersions bomVersions = bomVersionsDAO.getBOMVersions(bomVersionsId);
planning.setM_Product_ID(bomVersions.getM_Product_ID());
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = {
I_PP_Product_Planning.COLUMNNAME_PP_Product_BOMVersions_ID,
I_PP_Product_Planning.COLUMNNAME_IsAttributeDependant,
I_PP_Product_Planning.COLUMNNAME_M_AttributeSetInstance_ID,
})
public void validateProductBOMASI(@NonNull final I_PP_Product_Planning record)
{
final ProductPlanning productPlanning = ProductPlanningDAO.fromRecord(record);
|
if (!productPlanning.isAttributeDependant())
{
return;
}
if (productPlanning.getBomVersionsId() == null)
{
return;
}
final I_PP_Product_BOM bom = bomDAO.getLatestBOMRecordByVersionId(productPlanning.getBomVersionsId()).orElse(null);
if (bom == null)
{
return;
}
productBOMService.verifyBOMAssignment(productPlanning, bom);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\validator\PP_Product_Planning.java
| 1
|
请完成以下Java代码
|
public boolean add(E element) {
if (set.add(element)) {
list.add(element);
return true;
}
return false;
}
public boolean remove(E element) {
if (set.remove(element)) {
list.remove(element);
return true;
}
return false;
}
public int indexOf(E element) {
return list.indexOf(element);
}
public E get(int index) {
|
return list.get(index);
}
public boolean contains(E element) {
return set.contains(element);
}
public int size() {
return list.size();
}
public boolean isEmpty() {
return list.isEmpty();
}
public void clear() {
list.clear();
set.clear();
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-set-2\src\main\java\com\baeldung\linkedhashsetindexof\ListAndSetApproach.java
| 1
|
请完成以下Java代码
|
public static boolean startupEnvironment(boolean isSwingClient)
{
final Adempiere adempiere = instance;
final RunMode runMode = isSwingClient ? RunMode.SWING_CLIENT : RunMode.BACKEND;
adempiere.startup(runMode); // this emulates the old behavior of startupEnvironment
return adempiere.startupEnvironment(runMode);
}
private boolean startupEnvironment(final RunMode runMode)
{
final ADSystemInfo system = Services.get(ISystemBL.class).get(); // Initializes Base Context too
// Initialize main cached Singletons
ModelValidationEngine.get();
try
{
String className = null;
if (className == null || className.length() == 0)
{
className = System.getProperty(SecureInterface.METASFRESH_SECURE);
if (className != null && className.length() > 0
&& !className.equals(SecureInterface.METASFRESH_SECURE_DEFAULT))
{
SecureEngine.init(className); // test it
}
}
SecureEngine.init(className);
//
if (runMode == RunMode.SWING_CLIENT)
{
// Login Client loaded later
Services.get(IClientDAO.class).retriveClient(Env.getCtx(), IClientDAO.SYSTEM_CLIENT_ID);
}
else
{
// Load all clients (cache warm up)
Services.get(IClientDAO.class).retrieveAllClients(Env.getCtx());
}
}
catch (Exception e)
{
logger.warn("Environment problems", e);
}
// Start Workflow Document Manager (in other package) for PO
String className = null;
try
{
// Initialize Archive Engine
className = "org.compiere.print.ArchiveEngine";
Class.forName(className);
}
catch (Exception e)
{
logger.warn("Not started: {}", className, e);
}
return true;
} // startupEnvironment
// metas:
private static void startAddOns()
{
final IAddonStarter addonStarter = new AddonStarter();
addonStarter.startAddons();
}
/**
* If enabled, everything will run database decoupled. Supposed to be called before an interface like org.compiere.model.I_C_Order is to be used in a unit test.
*/
public static void enableUnitTestMode()
|
{
unitTestMode = true;
}
public static boolean isUnitTestMode()
{
return unitTestMode;
}
public static void assertUnitTestMode()
{
if (!isUnitTestMode())
{
throw new IllegalStateException("JUnit test mode shall be enabled");
}
}
private static boolean unitTestMode = false;
public static boolean isJVMDebugMode()
{
Boolean jvmDebugMode = Adempiere._jvmDebugMode;
if (jvmDebugMode == null)
{
jvmDebugMode = Adempiere._jvmDebugMode = computeJVMDebugMode();
}
return jvmDebugMode;
}
private static boolean computeJVMDebugMode()
{
return java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains("-agentlib:jdwp");
}
} // Adempiere
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\Adempiere.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BookDTO save(BookDTO bookDTO) {
log.debug("Request to save Book : {}", bookDTO);
Book book = bookMapper.toEntity(bookDTO);
book = bookRepository.save(book);
return bookMapper.toDto(book);
}
/**
* Get all the books.
*
* @return the list of entities
*/
@Override
@Transactional(readOnly = true)
public List<BookDTO> findAll() {
log.debug("Request to get all Books");
return bookRepository.findAll().stream()
.map(bookMapper::toDto)
.collect(Collectors.toCollection(LinkedList::new));
}
/**
* Get one book by id.
*
* @param id the id of the entity
* @return the entity
*/
@Override
@Transactional(readOnly = true)
public Optional<BookDTO> findOne(Long id) {
log.debug("Request to get Book : {}", id);
return bookRepository.findById(id)
.map(bookMapper::toDto);
|
}
/**
* Delete the book by id.
*
* @param id the id of the entity
*/
@Override
public void delete(Long id) {
log.debug("Request to delete Book : {}", id);
bookRepository.deleteById(id);
}
@Override
public Optional<BookDTO> purchase(Long id) {
Optional<BookDTO> bookDTO = findOne(id);
if(bookDTO.isPresent()) {
int quantity = bookDTO.get().getQuantity();
if(quantity > 0) {
bookDTO.get().setQuantity(quantity - 1);
Book book = bookMapper.toEntity(bookDTO.get());
book = bookRepository.save(book);
return bookDTO;
}
else {
throw new BadRequestAlertException("Book is not in stock", "book", "notinstock");
}
}
return Optional.empty();
}
}
|
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\impl\BookServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String filtering() {
// SomeBean someBean = new SomeBean("value1","value2", "value3");
var someBean = new SomeBean("value1","value2", "value3");
// MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(someBean);
// SimpleBeanPropertyFilter filter =
// SimpleBeanPropertyFilter.filterOutAllExcept("field1","field3");
var filter = SimpleBeanPropertyFilter.filterOutAllExcept("field1","field3");
// FilterProvider filters =
// new SimpleFilterProvider().addFilter("SomeBeanFilter", filter );
var filters = new SimpleFilterProvider().addFilter("SomeBeanFilter", filter);
var jsonMapper = JsonMapper.builder().build();
// mappingJacksonValue.setFilters(filters );
// return mappingJacksonValue
return jsonMapper.writer(filters).writeValueAsString(someBean);
}
@GetMapping("/filtering-list") //field2, field3
public String filteringList() {
List<SomeBean> list = Arrays.asList(new SomeBean("value1","value2", "value3"),
new SomeBean("value4","value5", "value6"));
|
// MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(list);
// SimpleBeanPropertyFilter filter =
// SimpleBeanPropertyFilter.filterOutAllExcept("field2","field3");
var filter = SimpleBeanPropertyFilter.filterOutAllExcept("field2", "field3");
// FilterProvider filters =
// new SimpleFilterProvider().addFilter("SomeBeanFilter", filter );
var filters = new SimpleFilterProvider().addFilter("SomeBeanFilter", filter);
// mappingJacksonValue.setFilters(filters );
var jsonMapper = JsonMapper.builder().build();
// return mappingJacksonValue;
return jsonMapper.writer(filters).writeValueAsString(list);
}
}
|
repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\filtering\FilteringController.java
| 2
|
请完成以下Java代码
|
public ValueGraph<Integer, Double> minSpanningTree(ValueGraph<Integer, Double> graph) {
return spanningTree(graph, true);
}
public ValueGraph<Integer, Double> maxSpanningTree(ValueGraph<Integer, Double> graph) {
return spanningTree(graph, false);
}
private ValueGraph<Integer, Double> spanningTree(ValueGraph<Integer, Double> graph, boolean minSpanningTree) {
Set<EndpointPair<Integer>> edges = graph.edges();
List<EndpointPair<Integer>> edgeList = new ArrayList<>(edges);
if (minSpanningTree) {
edgeList.sort(Comparator.comparing(e -> graph.edgeValue(e).get()));
} else {
edgeList.sort(Collections.reverseOrder(Comparator.comparing(e -> graph.edgeValue(e).get())));
}
int totalNodes = graph.nodes().size();
CycleDetector cycleDetector = new CycleDetector(totalNodes);
int edgeCount = 0;
|
MutableValueGraph<Integer, Double> spanningTree = ValueGraphBuilder.undirected().build();
for (EndpointPair<Integer> edge : edgeList) {
if (cycleDetector.detectCycle(edge.nodeU(), edge.nodeV())) {
continue;
}
spanningTree.putEdgeValue(edge.nodeU(), edge.nodeV(), graph.edgeValue(edge).get());
edgeCount++;
if (edgeCount == totalNodes - 1) {
break;
}
}
return spanningTree;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\kruskal\Kruskal.java
| 1
|
请完成以下Java代码
|
public <T> List<T> getSelectedModels(final Class<T> modelClass)
{
return _selectedModelsSupplier.apply(modelClass).getModels(modelClass);
}
@NonNull
@Override
public <T> Stream<T> streamSelectedModels(@NonNull final Class<T> modelClass)
{
return view.streamModelsByIds(getSelectedRowIds(), modelClass);
}
@Override
public SelectionSize getSelectionSize()
{
return getSelectedRowIds().toSelectionSize();
}
@Override
public boolean isNoSelection()
{
return getSelectedRowIds().isEmpty() && !getSelectedRowIds().isAll();
}
@Override
public boolean isMoreThanOneSelected()
{
return getSelectedRowIds().isMoreThanOneDocumentId();
}
private SelectedModelsList retrieveSelectedModels(final Class<?> modelClass)
{
final List<?> models = view.retrieveModelsByIds(getSelectedRowIds(), modelClass);
return SelectedModelsList.of(models, modelClass);
}
@Override
public <T> IQueryFilter<T> getQueryFilter(@NonNull final Class<T> recordClass)
{
final String tableName = InterfaceWrapperHelper.getTableName(recordClass);
final SqlViewRowsWhereClause sqlWhereClause = view.getSqlWhereClause(getSelectedRowIds(), SqlOptions.usingTableName(tableName));
return sqlWhereClause.toQueryFilter();
}
private static final class SelectedModelsList
{
private static SelectedModelsList of(final List<?> models, final Class<?> modelClass)
{
if (models == null || models.isEmpty())
{
return EMPTY;
}
return new SelectedModelsList(models, modelClass);
}
private static final SelectedModelsList EMPTY = new SelectedModelsList();
private final ImmutableList<?> models;
private final Class<?> modelClass;
/**
* empty constructor
*/
private SelectedModelsList()
{
models = ImmutableList.of();
modelClass = null;
}
private SelectedModelsList(final List<?> models, final Class<?> modelClass)
{
super();
this.models = ImmutableList.copyOf(models);
this.modelClass = modelClass;
}
|
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("modelClass", modelClass)
.add("models", models)
.toString();
}
public <T> List<T> getModels(final Class<T> modelClass)
{
// If loaded models list is empty, we can return an empty list directly
if (models.isEmpty())
{
return ImmutableList.of();
}
// If loaded models have the same model class as the requested one
// we can simple cast & return them
if (Objects.equals(modelClass, this.modelClass))
{
@SuppressWarnings("unchecked") final List<T> modelsCasted = (List<T>)models;
return modelsCasted;
}
// If not the same class, we have to wrap them fist.
else
{
return InterfaceWrapperHelper.wrapToImmutableList(models, modelClass);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\ViewAsPreconditionsContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Optional<BookDTO> findOne(Long id) {
log.debug("Request to get Book : {}", id);
return bookRepository.findById(id)
.map(bookMapper::toDto);
}
/**
* Delete the book by id.
*
* @param id the id of the entity
*/
@Override
public void delete(Long id) {
log.debug("Request to delete Book : {}", id);
bookRepository.deleteById(id);
}
|
@Override
public Optional<BookDTO> purchase(Long id) {
Optional<BookDTO> bookDTO = findOne(id);
if(bookDTO.isPresent()) {
int quantity = bookDTO.get().getQuantity();
if(quantity > 0) {
bookDTO.get().setQuantity(quantity - 1);
Book book = bookMapper.toEntity(bookDTO.get());
book = bookRepository.save(book);
return bookDTO;
}
else {
throw new BadRequestAlertException("Book is not in stock", "book", "notinstock");
}
}
return Optional.empty();
}
}
|
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\impl\BookServiceImpl.java
| 2
|
请完成以下Java代码
|
public String getProcess() {
return processRefAttribute.getValue(this);
}
public void setProcess(String process) {
processRefAttribute.setValue(this, process);
}
public ProcessRefExpression getProcessExpression() {
return processRefExpressionChild.getChild(this);
}
public void setProcessExpression(ProcessRefExpression processExpression) {
processRefExpressionChild.setChild(this, processExpression);
}
public Collection<ParameterMapping> getParameterMappings() {
return parameterMappingCollection.get(this);
}
public String getCamundaProcessBinding() {
return camundaProcessBindingAttribute.getValue(this);
}
public void setCamundaProcessBinding(String camundaProcessBinding) {
camundaProcessBindingAttribute.setValue(this, camundaProcessBinding);
}
public String getCamundaProcessVersion() {
return camundaProcessVersionAttribute.getValue(this);
}
public void setCamundaProcessVersion(String camundaProcessVersion) {
camundaProcessVersionAttribute.setValue(this, camundaProcessVersion);
}
public String getCamundaProcessTenantId() {
return camundaProcessTenantIdAttribute.getValue(this);
}
public void setCamundaProcessTenantId(String camundaProcessTenantId) {
camundaProcessTenantIdAttribute.setValue(this, camundaProcessTenantId);
}
public static void registerType(ModelBuilder modelBuilder) {
|
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ProcessTask.class, CMMN_ELEMENT_PROCESS_TASK)
.namespaceUri(CMMN11_NS)
.extendsType(Task.class)
.instanceProvider(new ModelTypeInstanceProvider<ProcessTask>() {
public ProcessTask newInstance(ModelTypeInstanceContext instanceContext) {
return new ProcessTaskImpl(instanceContext);
}
});
processRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_PROCESS_REF)
.build();
/** camunda extensions */
camundaProcessBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PROCESS_BINDING)
.namespace(CAMUNDA_NS)
.build();
camundaProcessVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PROCESS_VERSION)
.namespace(CAMUNDA_NS)
.build();
camundaProcessTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PROCESS_TENANT_ID)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class)
.build();
processRefExpressionChild = sequenceBuilder.element(ProcessRefExpression.class)
.minOccurs(0)
.maxOccurs(1)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ProcessTaskImpl.java
| 1
|
请完成以下Java代码
|
protected IDocumentLUTUConfigurationManager createReceiptLUTUConfigurationManager()
{
final I_PP_Order ppOrder = getPP_Order();
return huPPOrderBL.createReceiptLUTUConfigurationManager(ppOrder);
}
@Override
protected ReceiptCandidateRequestProducer newReceiptCandidateRequestProducer()
{
final I_PP_Order order = getPP_Order();
final PPOrderId orderId = PPOrderId.ofRepoId(order.getPP_Order_ID());
final OrgId orgId = OrgId.ofRepoId(order.getAD_Org_ID());
return ReceiptCandidateRequestProducer.builder()
.orderId(orderId)
.orgId(orgId)
.date(getMovementDate())
|
.locatorId(getLocatorId())
.pickingCandidateId(getPickingCandidateId())
.build();
}
@Override
protected void addAssignedHUs(final Collection<I_M_HU> hus)
{
final I_PP_Order ppOrder = getPP_Order();
huPPOrderBL.addAssignedHandlingUnits(ppOrder, hus);
}
@Override
public IPPOrderReceiptHUProducer withPPOrderLocatorId()
{
return locatorId(LocatorId.ofRepoId(ppOrder.getM_Warehouse_ID(), ppOrder.getM_Locator_ID()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\CostCollectorCandidateFinishedGoodsHUProducer.java
| 1
|
请完成以下Java代码
|
public String getTrackingURL(@NonNull final String shipperInternalName)
{
final I_M_Shipper shipper = shipperByInternalName.computeIfAbsent(shipperInternalName, this::loadShipper);
return shipper != null
? shipper.getTrackingURL()
: null;
}
@Nullable
private I_M_Shipper loadShipper(@NonNull final String shipperInternalName)
{
return shipperDAO.getByInternalName(ImmutableSet.of(shipperInternalName)).get(shipperInternalName);
}
public ProductId getProductId(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(shipmentScheduleId);
return ProductId.ofRepoId(shipmentSchedule.getM_Product_ID());
}
public ProductId getProductId(@NonNull final String productSearchKey, @NonNull final OrgId orgId)
{
final ProductQuery query = ProductQuery.builder()
.value(productSearchKey)
|
.orgId(orgId)
.includeAnyOrg(true) // include articles with org=*
.build();
return productIdsByQuery.computeIfAbsent(query, this::retrieveProductIdByQuery);
}
private ProductId retrieveProductIdByQuery(@NonNull final ProductQuery query)
{
final ProductId productId = productDAO.retrieveProductIdBy(query);
if (productId == null)
{
throw new AdempiereException("No product found for " + query);
}
return productId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShippingInfoCache.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
@ApiModelProperty(value = "The stage plan item instance id this process instance belongs to or null, if it is not part of a case at all or is not a child element of a stage")
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
public void setPropagatedStageInstanceId(String propagatedStageInstanceId) {
this.propagatedStageInstanceId = propagatedStageInstanceId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
|
}
@ApiModelProperty(example = "someTenantId")
public String getTenantId() {
return tenantId;
}
// Added by Ryan Johnston
public boolean isCompleted() {
return completed;
}
// Added by Ryan Johnston
public void setCompleted(boolean completed) {
this.completed = completed;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ProcessInstanceResponse.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class PaymentController {
@Autowired
private AlipayService alipayService;
@GetMapping("/")
public String index() {
return "index";
}
@PostMapping("/createOrder")
public String createOrder(@RequestParam String totalAmount, @RequestParam String subject, Model model) {
String outTradeNo = "ORDER_" + System.currentTimeMillis(); // 生成订单号
try {
String qrCodeUrl = alipayService.createOrder(outTradeNo, totalAmount, subject);
model.addAttribute("qrCodeUrl", qrCodeUrl);
model.addAttribute("totalAmount", totalAmount);
model.addAttribute("subject", subject);
|
model.addAttribute("outTradeNo", outTradeNo);
return "payment";
} catch (Exception e) {
model.addAttribute("error", "创建订单失败");
return "error";
}
}
@PostMapping("/queryPayment")
public String queryPayment(String outTradeNo) {
String TradeStatus=alipayService.queryPayment(outTradeNo);
if(TradeStatus.equals("TRADE_SUCCESS")||TradeStatus.equals("TRADE_FINISHED")){
return "success";
}else{
return "error";
}
}
}
|
repos\springboot-demo-master\Alipay-facetoface\src\main\java\com.et\controller\PaymentController.java
| 2
|
请完成以下Java代码
|
public ImpliedCurrencyAmountRangeChoice getAmt() {
return amt;
}
/**
* Sets the value of the amt property.
*
* @param value
* allowed object is
* {@link ImpliedCurrencyAmountRangeChoice }
*
*/
public void setAmt(ImpliedCurrencyAmountRangeChoice value) {
this.amt = value;
}
/**
* Gets the value of the cdtDbtInd property.
*
* @return
* possible object is
* {@link CreditDebitCode }
*
*/
public CreditDebitCode getCdtDbtInd() {
return cdtDbtInd;
}
/**
* Sets the value of the cdtDbtInd property.
*
* @param value
* allowed object is
* {@link CreditDebitCode }
*
*/
|
public void setCdtDbtInd(CreditDebitCode value) {
this.cdtDbtInd = value;
}
/**
* Gets the value of the ccy property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCcy() {
return ccy;
}
/**
* Sets the value of the ccy property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCcy(String value) {
this.ccy = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CurrencyAndAmountRange2.java
| 1
|
请完成以下Java代码
|
public String getCamundaProcessVersion() {
return camundaProcessVersionAttribute.getValue(this);
}
public void setCamundaProcessVersion(String camundaProcessVersion) {
camundaProcessVersionAttribute.setValue(this, camundaProcessVersion);
}
public String getCamundaProcessTenantId() {
return camundaProcessTenantIdAttribute.getValue(this);
}
public void setCamundaProcessTenantId(String camundaProcessTenantId) {
camundaProcessTenantIdAttribute.setValue(this, camundaProcessTenantId);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ProcessTask.class, CMMN_ELEMENT_PROCESS_TASK)
.namespaceUri(CMMN11_NS)
.extendsType(Task.class)
.instanceProvider(new ModelTypeInstanceProvider<ProcessTask>() {
public ProcessTask newInstance(ModelTypeInstanceContext instanceContext) {
return new ProcessTaskImpl(instanceContext);
}
});
processRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_PROCESS_REF)
.build();
/** camunda extensions */
camundaProcessBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PROCESS_BINDING)
.namespace(CAMUNDA_NS)
.build();
|
camundaProcessVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PROCESS_VERSION)
.namespace(CAMUNDA_NS)
.build();
camundaProcessTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PROCESS_TENANT_ID)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class)
.build();
processRefExpressionChild = sequenceBuilder.element(ProcessRefExpression.class)
.minOccurs(0)
.maxOccurs(1)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ProcessTaskImpl.java
| 1
|
请完成以下Java代码
|
public void onCancel() {
}
@Override
public void onReadyToSend() {
}
@Override
public void onConnecting() {
}
@Override
public void onDtlsRetransmission(int flight) {
}
@Override
public void onSent(boolean retransmission) {
}
@Override
public void onSendError(Throwable error) {
|
}
@Override
public void onResponseHandlingError(Throwable cause) {
}
@Override
public void onContextEstablished(EndpointContext endpointContext) {
}
@Override
public void onTransferComplete() {
}
}
|
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\TbCoapMessageObserver.java
| 1
|
请完成以下Java代码
|
public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class);
}
@Override
public void setAD_Window(org.compiere.model.I_AD_Window AD_Window)
{
set_ValueFromPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class, AD_Window);
}
/** Set Fenster.
@param AD_Window_ID
Eingabe- oder Anzeige-Fenster
*/
@Override
public void setAD_Window_ID (int AD_Window_ID)
{
if (AD_Window_ID < 1)
set_Value (COLUMNNAME_AD_Window_ID, null);
|
else
set_Value (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID));
}
/** Get Fenster.
@return Eingabe- oder Anzeige-Fenster
*/
@Override
public int getAD_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_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_AD_Element_Link.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CountryId implements RepoIdAware
{
public static final CountryId GERMANY = new CountryId(101);
public static final CountryId SWITZERLAND = new CountryId(107);
@JsonCreator
@NonNull
public static CountryId ofRepoId(final int repoId)
{
return new CountryId(repoId);
}
@Nullable
public static CountryId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new CountryId(repoId) : null;
}
public static int toRepoId(@Nullable final CountryId id)
{
return id != null ? id.getRepoId() : -1;
}
int repoId;
private CountryId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_Country_ID");
}
@Override
@JsonValue
|
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final CountryId countryId1, @Nullable final CountryId countryId2)
{
return Objects.equals(countryId1, countryId2);
}
public boolean equalsToRepoId(final int repoId)
{
return this.repoId == repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\CountryId.java
| 2
|
请完成以下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 void setT_Amount (final @Nullable BigDecimal T_Amount)
{
set_Value (COLUMNNAME_T_Amount, T_Amount);
}
@Override
public BigDecimal getT_Amount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Amount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setT_Date (final @Nullable java.sql.Timestamp T_Date)
{
set_Value (COLUMNNAME_T_Date, T_Date);
}
@Override
public java.sql.Timestamp getT_Date()
{
return get_ValueAsTimestamp(COLUMNNAME_T_Date);
}
@Override
public void setT_DateTime (final @Nullable java.sql.Timestamp T_DateTime)
{
set_Value (COLUMNNAME_T_DateTime, T_DateTime);
}
@Override
public java.sql.Timestamp getT_DateTime()
{
return get_ValueAsTimestamp(COLUMNNAME_T_DateTime);
}
@Override
public void setT_Integer (final int T_Integer)
{
set_Value (COLUMNNAME_T_Integer, T_Integer);
}
@Override
public int getT_Integer()
{
return get_ValueAsInt(COLUMNNAME_T_Integer);
}
@Override
public void setT_Number (final @Nullable BigDecimal T_Number)
{
set_Value (COLUMNNAME_T_Number, T_Number);
}
@Override
public BigDecimal getT_Number()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Number);
return bd != null ? bd : BigDecimal.ZERO;
}
|
@Override
public void setT_Qty (final @Nullable BigDecimal T_Qty)
{
set_Value (COLUMNNAME_T_Qty, T_Qty);
}
@Override
public BigDecimal getT_Qty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setT_Time (final @Nullable java.sql.Timestamp T_Time)
{
set_Value (COLUMNNAME_T_Time, T_Time);
}
@Override
public java.sql.Timestamp getT_Time()
{
return get_ValueAsTimestamp(COLUMNNAME_T_Time);
}
@Override
public void setTest_ID (final int Test_ID)
{
if (Test_ID < 1)
set_ValueNoCheck (COLUMNNAME_Test_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Test_ID, Test_ID);
}
@Override
public int getTest_ID()
{
return get_ValueAsInt(COLUMNNAME_Test_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Test.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private @Nullable String determineDatabaseName(R2dbcProperties properties) {
if (properties.isGenerateUniqueName()) {
return properties.determineUniqueName();
}
if (StringUtils.hasLength(properties.getName())) {
return properties.getName();
}
return null;
}
private String determineEmbeddedUsername(R2dbcProperties properties) {
String username = ifHasText(properties.getUsername());
return (username != null) ? username : "sa";
}
private ConnectionFactoryBeanCreationException connectionFactoryBeanCreationException(String message,
@Nullable String r2dbcUrl, EmbeddedDatabaseConnection embeddedDatabaseConnection) {
return new ConnectionFactoryBeanCreationException(message, r2dbcUrl, embeddedDatabaseConnection);
}
private @Nullable String ifHasText(@Nullable String candidate) {
return (StringUtils.hasText(candidate)) ? candidate : null;
}
static class ConnectionFactoryBeanCreationException extends BeanCreationException {
private final @Nullable String url;
private final EmbeddedDatabaseConnection embeddedDatabaseConnection;
ConnectionFactoryBeanCreationException(String message, @Nullable String url,
EmbeddedDatabaseConnection embeddedDatabaseConnection) {
super(message);
|
this.url = url;
this.embeddedDatabaseConnection = embeddedDatabaseConnection;
}
@Nullable String getUrl() {
return this.url;
}
EmbeddedDatabaseConnection getEmbeddedDatabaseConnection() {
return this.embeddedDatabaseConnection;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\autoconfigure\ConnectionFactoryOptionsInitializer.java
| 2
|
请完成以下Java代码
|
public final class MyUserPredicatesBuilder {
private final List<SearchCriteria> params;
public MyUserPredicatesBuilder() {
params = new ArrayList<>();
}
public MyUserPredicatesBuilder with(final String key, final String operation, final Object value) {
params.add(new SearchCriteria(key, operation, value));
return this;
}
public BooleanExpression build() {
if (params.size() == 0) {
return null;
}
final List<BooleanExpression> predicates = params.stream().map(param -> {
MyUserPredicate predicate = new MyUserPredicate(param);
return predicate.getPredicate();
}).filter(Objects::nonNull).collect(Collectors.toList());
BooleanExpression result = Expressions.asBoolean(true).isTrue();
for (BooleanExpression predicate : predicates) {
result = result.and(predicate);
|
}
return result;
}
static class BooleanExpressionWrapper {
private BooleanExpression result;
public BooleanExpressionWrapper(final BooleanExpression result) {
super();
this.result = result;
}
public BooleanExpression getResult() {
return result;
}
public void setResult(BooleanExpression result) {
this.result = result;
}
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\persistence\dao\MyUserPredicatesBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class ArtemisConnectionFactoryConfiguration {
@Configuration(proxyBeanMethods = false)
@ConditionalOnBooleanProperty(name = "spring.artemis.pool.enabled", havingValue = false, matchIfMissing = true)
static class SimpleConnectionFactoryConfiguration {
@Bean(name = "jmsConnectionFactory")
@ConditionalOnBooleanProperty(name = "spring.jms.cache.enabled", havingValue = false)
ActiveMQConnectionFactory jmsConnectionFactory(ArtemisProperties properties, ListableBeanFactory beanFactory,
ArtemisConnectionDetails connectionDetails) {
return createJmsConnectionFactory(properties, connectionDetails, beanFactory);
}
private static ActiveMQConnectionFactory createJmsConnectionFactory(ArtemisProperties properties,
ArtemisConnectionDetails connectionDetails, ListableBeanFactory beanFactory) {
return new ArtemisConnectionFactoryFactory(beanFactory, properties, connectionDetails)
.createConnectionFactory(ActiveMQConnectionFactory::new, ActiveMQConnectionFactory::new);
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(CachingConnectionFactory.class)
@ConditionalOnBooleanProperty(name = "spring.jms.cache.enabled", matchIfMissing = true)
static class CachingConnectionFactoryConfiguration {
@Bean(name = "jmsConnectionFactory")
CachingConnectionFactory cachingJmsConnectionFactory(JmsProperties jmsProperties,
ArtemisProperties properties, ArtemisConnectionDetails connectionDetails,
ListableBeanFactory beanFactory) {
JmsProperties.Cache cacheProperties = jmsProperties.getCache();
|
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(
createJmsConnectionFactory(properties, connectionDetails, beanFactory));
connectionFactory.setCacheConsumers(cacheProperties.isConsumers());
connectionFactory.setCacheProducers(cacheProperties.isProducers());
connectionFactory.setSessionCacheSize(cacheProperties.getSessionCacheSize());
return connectionFactory;
}
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ JmsPoolConnectionFactory.class, PooledObject.class })
@ConditionalOnBooleanProperty("spring.artemis.pool.enabled")
static class PooledConnectionFactoryConfiguration {
@Bean(destroyMethod = "stop")
JmsPoolConnectionFactory jmsConnectionFactory(ListableBeanFactory beanFactory, ArtemisProperties properties,
ArtemisConnectionDetails connectionDetails) {
ActiveMQConnectionFactory connectionFactory = new ArtemisConnectionFactoryFactory(beanFactory, properties,
connectionDetails)
.createConnectionFactory(ActiveMQConnectionFactory::new, ActiveMQConnectionFactory::new);
return new JmsPoolConnectionFactoryFactory(properties.getPool())
.createPooledConnectionFactory(connectionFactory);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisConnectionFactoryConfiguration.java
| 2
|
请完成以下Java代码
|
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 LinkURL.
@param LinkURL
Contains URL to a target
*/
public void setLinkURL (String LinkURL)
{
set_Value (COLUMNNAME_LinkURL, LinkURL);
}
/** Get LinkURL.
@return Contains URL to a target
*/
public String getLinkURL ()
{
return (String)get_Value(COLUMNNAME_LinkURL);
}
/** Set Publication Date.
@param PubDate
Date on which this article will / should get published
*/
public void setPubDate (Timestamp PubDate)
{
|
set_Value (COLUMNNAME_PubDate, PubDate);
}
/** Get Publication Date.
@return Date on which this article will / should get published
*/
public Timestamp getPubDate ()
{
return (Timestamp)get_Value(COLUMNNAME_PubDate);
}
/** Set Title.
@param Title
Name this entity is referred to as
*/
public void setTitle (String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
/** Get Title.
@return Name this entity is referred to as
*/
public String getTitle ()
{
return (String)get_Value(COLUMNNAME_Title);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_NewsItem.java
| 1
|
请完成以下Java代码
|
private void addWithEngineFactory(int x, int y) throws IllegalAccessException,
InstantiationException, javax.script.ScriptException, FileNotFoundException {
Class calcClass = (Class) engineFromFactory.eval(
new FileReader(new File("src/main/groovy/com/baeldung/", "CalcMath.groovy")));
GroovyObject calc = (GroovyObject) calcClass.newInstance();
Object result = calc.invokeMethod("calcSum", new Object[] { x, y });
LOG.info("Result of CalcMath.calcSum() method is {}", result);
}
private void addWithStaticCompiledClasses() {
LOG.info("Running the Groovy classes compiled statically...");
addWithCompiledClasses(5, 10);
}
private void addWithDynamicCompiledClasses() throws IOException, IllegalAccessException, InstantiationException,
ResourceException, ScriptException, javax.script.ScriptException {
LOG.info("Invocation of a dynamic groovy script...");
addWithGroovyShell(5, 10);
|
LOG.info("Invocation of the run method of a dynamic groovy script...");
addWithGroovyShellRun();
LOG.info("Invocation of a dynamic groovy class loaded with GroovyClassLoader...");
addWithGroovyClassLoader(10, 30);
LOG.info("Invocation of a dynamic groovy class loaded with GroovyScriptEngine...");
addWithGroovyScriptEngine(15, 0);
LOG.info("Invocation of a dynamic groovy class loaded with GroovyScriptEngine JSR223...");
addWithEngineFactory(5, 6);
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException,
ResourceException, ScriptException, IOException, javax.script.ScriptException {
MyJointCompilationApp myJointCompilationApp = new MyJointCompilationApp();
LOG.info("Example of addition operation via Groovy scripts integration with Java.");
myJointCompilationApp.addWithStaticCompiledClasses();
myJointCompilationApp.addWithDynamicCompiledClasses();
}
}
|
repos\tutorials-master\core-groovy-modules\core-groovy-2\src\main\java\com\baeldung\MyJointCompilationApp.java
| 1
|
请完成以下Java代码
|
public Builder append(final CtxName name)
{
append(new SingleParameterStringExpression(name.toStringWithMarkers(), name));
return this;
}
/**
* Wraps the entire content of this builder using given wrapper.
* After this method invocation the builder will contain only the wrapped expression.
*/
public Builder wrap(final IStringExpressionWrapper wrapper)
{
Check.assumeNotNull(wrapper, "Parameter wrapper is not null");
final IStringExpression expression = build();
final IStringExpression expressionWrapped = wrapper.wrap(expression);
expressions.clear();
append(expressionWrapped);
return this;
}
|
/**
* If the {@link Condition} is <code>true</code> then it wraps the entire content of this builder using given wrapper.
* After this method invocation the builder will contain only the wrapped expression.
*/
public Builder wrapIfTrue(final boolean condition, final IStringExpressionWrapper wrapper)
{
if (!condition)
{
return this;
}
return wrap(wrapper);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\CompositeStringExpression.java
| 1
|
请完成以下Java代码
|
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
Mono<?> principal = exchange.getPrincipal().cast(Object.class).defaultIfEmpty(NONE);
Mono<Object> session = exchange.getSession().cast(Object.class).defaultIfEmpty(NONE);
return Mono.zip(PrincipalAndSession::new, principal, session)
.flatMap((principalAndSession) -> filter(exchange, chain, principalAndSession));
}
private Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain,
PrincipalAndSession principalAndSession) {
return Mono.fromRunnable(() -> addExchangeOnCommit(exchange, principalAndSession)).and(chain.filter(exchange));
}
private void addExchangeOnCommit(ServerWebExchange exchange, PrincipalAndSession principalAndSession) {
RecordableServerHttpRequest sourceRequest = new RecordableServerHttpRequest(exchange.getRequest());
HttpExchange.Started startedHttpExchange = HttpExchange.start(sourceRequest);
exchange.getResponse().beforeCommit(() -> {
RecordableServerHttpResponse sourceResponse = new RecordableServerHttpResponse(exchange.getResponse());
HttpExchange finishedExchange = startedHttpExchange.finish(sourceResponse,
principalAndSession::getPrincipal, principalAndSession::getSessionId, this.includes);
this.repository.add(finishedExchange);
return Mono.empty();
});
}
/**
* A {@link Principal} and {@link WebSession}.
*/
private static class PrincipalAndSession {
private final @Nullable Principal principal;
private final @Nullable WebSession session;
|
PrincipalAndSession(Object[] zipped) {
this.principal = (zipped[0] != NONE) ? (Principal) zipped[0] : null;
this.session = (zipped[1] != NONE) ? (WebSession) zipped[1] : null;
}
@Nullable Principal getPrincipal() {
return this.principal;
}
@Nullable String getSessionId() {
return (this.session != null && this.session.isStarted()) ? this.session.getId() : null;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\actuate\web\exchanges\HttpExchangesWebFilter.java
| 1
|
请完成以下Java代码
|
public class VariableAggregationDefinitions {
protected Collection<VariableAggregationDefinition> aggregations = new ArrayList<>();
public Collection<VariableAggregationDefinition> getAggregations() {
return aggregations;
}
public Collection<VariableAggregationDefinition> getOverviewAggregations() {
return aggregations.stream()
// An aggregation is an overview aggregation when it is explicitly set and it is not stored as transient
.filter(agg -> agg.isCreateOverviewVariable() && !agg.isStoreAsTransientVariable())
.collect(Collectors.toList());
}
public void setAggregations(Collection<VariableAggregationDefinition> aggregations) {
this.aggregations = aggregations;
}
|
@Override
public VariableAggregationDefinitions clone() {
VariableAggregationDefinitions aggregations = new VariableAggregationDefinitions();
aggregations.setValues(this);
return aggregations;
}
public void setValues(VariableAggregationDefinitions otherAggregations) {
for (VariableAggregationDefinition otherAggregation : otherAggregations.getAggregations()) {
getAggregations().add(otherAggregation.clone());
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\VariableAggregationDefinitions.java
| 1
|
请完成以下Java代码
|
public class Student {
@Id
private String id;
private String name;
private Long age;
public Student(String id, String name, Long age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
|
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-mongodb-2\src\main\java\com\baeldung\projection\model\Student.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ImgWatermarkServiceImpl implements WatermarkService {
@Override
public String watermarkAdd( File imageFile, String imageFileName, String uploadPath, String realUploadPath ) {
String logoFileName = "watermark_" + imageFileName;
OutputStream os = null;
try {
Image image = ImageIO.read(imageFile);
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); // 创建图片缓存对象
Graphics2D g = bufferedImage.createGraphics(); // 创建绘绘图工具对象
g.drawImage(image, 0, 0, width,height,null); // 使用绘图工具将原图绘制到缓存图片对象
String logoPath = realUploadPath + "/" + Const.LOGO_FILE_NAME; // 水印图片地址
File logo = new File(logoPath); // 读取水印图片
Image imageLogo = ImageIO.read(logo);
int markWidth = imageLogo.getWidth(null); // 水印图片的宽度和高度
int markHeight = imageLogo.getHeight(null);
g.setComposite( AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, Const.ALPHA) ); // 设置水印透明度
g.rotate(Math.toRadians(-10), bufferedImage.getWidth()/2, bufferedImage.getHeight()/2); // 旋转图片
int x = Const.X;
int y = Const.Y;
int xInterval = Const.X_INTERVAL;
int yInterval = Const.Y_INTERVAL;
double count = 1.5;
|
while ( x < width*count ) { // 循环添加水印
y = -height / 2;
while( y < height*count ) {
g.drawImage(imageLogo, x, y, null); // 添加水印
y += markHeight + yInterval;
}
x += markWidth + xInterval;
}
g.dispose();
os = new FileOutputStream(realUploadPath + "/" + logoFileName);
JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
en.encode(bufferedImage);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return uploadPath + "/" + logoFileName;
}
}
|
repos\Spring-Boot-In-Action-master\springbt_watermark\src\main\java\cn\codesheep\springbt_watermark\service\impl\ImgWatermarkServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isCreditStopSales(@NonNull final BPartnerStats stat, @NonNull final BigDecimal grandTotal, @NonNull final Timestamp date)
{
final CalculateSOCreditStatusRequest request = CalculateSOCreditStatusRequest.builder()
.stat(stat)
.additionalAmt(grandTotal)
.date(date)
.build();
final String futureCreditStatus = calculateProjectedSOCreditStatus(request);
if (X_C_BPartner_Stats.SOCREDITSTATUS_CreditStop.equals(futureCreditStatus))
{
return true;
}
return false;
}
@Override
public BigDecimal getCreditWatchRatio(final BPartnerStats stats)
{
// bp group will be taken from the stats' bpartner
final I_C_BPartner partner = Services.get(IBPartnerDAO.class).getById(stats.getBpartnerId());
final I_C_BP_Group bpGroup = partner.getC_BP_Group();
final BigDecimal creditWatchPercent = bpGroup.getCreditWatchPercent();
if (creditWatchPercent.signum() == 0)
{
return new BigDecimal(0.90);
}
return creditWatchPercent.divide(Env.ONEHUNDRED, 2, BigDecimal.ROUND_HALF_UP);
|
}
@Override
public void resetCreditStatusFromBPGroup(@NonNull final I_C_BPartner bpartner)
{
final BPartnerStats bpartnerStats = Services.get(IBPartnerStatsDAO.class).getCreateBPartnerStats(bpartner);
final I_C_BP_Group bpGroup = bpartner.getC_BP_Group();
final String creditStatus = bpGroup.getSOCreditStatus();
if (Check.isEmpty(creditStatus, true))
{
return;
}
final I_C_BPartner_Stats stats = load(bpartnerStats.getRepoId(), I_C_BPartner_Stats.class);
stats.setSOCreditStatus(creditStatus);
save(stats);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPartnerStatsBL.java
| 2
|
请完成以下Java代码
|
public class MenuButton extends BaseModel {
private MenuType type;
private String name;
private String key;
private String url;
/**
* 菜单显示的永久素材的MaterialID,当MenuType值为media_id和view_limited时必需
*/
@JSONField(name = "media_id")
private String mediaId;
/**
* 二级菜单列表,每个一级菜单下最多5个
*/
@JSONField(name = "sub_button")
private List<MenuButton> subButton;
public MenuType getType() {
return type;
}
public void setType(MenuType type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getUrl() {
|
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public List<MenuButton> getSubButton() {
return subButton;
}
public void setSubButton(List<MenuButton> subButton) {
if (null == subButton || subButton.size() > 5) {
throw new WeixinException("子菜单最多只有5个");
}
this.subButton = subButton;
}
}
|
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\model\MenuButton.java
| 1
|
请完成以下Java代码
|
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
log.info("[preHandle][" + request + "]" + "[" + request.getMethod() + "]" + request.getRequestURI() + getParameters(request));
return true;
}
/**
* Executed before after handler is executed
**/
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception {
log.info("[postHandle][" + request + "]");
}
/**
* Executed after complete request is finished
**/
@Override
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception {
if (ex != null)
ex.printStackTrace();
log.info("[afterCompletion][" + request + "][exception: " + ex + "]");
}
private String getParameters(final HttpServletRequest request) {
final StringBuffer posted = new StringBuffer();
final Enumeration<?> e = request.getParameterNames();
if (e != null)
posted.append("?");
while (e != null && e.hasMoreElements()) {
if (posted.length() > 1)
posted.append("&");
final String curr = (String) e.nextElement();
posted.append(curr)
.append("=");
if (curr.contains("password") || curr.contains("answer") || curr.contains("pwd")) {
posted.append("*****");
|
} else {
posted.append(request.getParameter(curr));
}
}
final String ip = request.getHeader("X-FORWARDED-FOR");
final String ipAddr = (ip == null) ? getRemoteAddr(request) : ip;
if (!Strings.isNullOrEmpty(ipAddr))
posted.append("&_psip=" + ipAddr);
return posted.toString();
}
private String getRemoteAddr(final HttpServletRequest request) {
final String ipFromHeader = request.getHeader("X-FORWARDED-FOR");
if (ipFromHeader != null && ipFromHeader.length() > 0) {
log.debug("ip from proxy - X-FORWARDED-FOR : " + ipFromHeader);
return ipFromHeader;
}
return request.getRemoteAddr();
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-mvc-custom\src\main\java\com\baeldung\web\interceptor\LoggerInterceptor.java
| 1
|
请完成以下Java代码
|
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int read = (this.headerStream != null) ? this.headerStream.read(b, off, len) : -1;
if (read <= 0) {
return readRemainder(b, off, len);
}
this.position += read;
if (read < len) {
int remainderRead = readRemainder(b, off + read, len - read);
if (remainderRead > 0) {
read += remainderRead;
}
}
if (this.position >= this.headerLength) {
this.headerStream = null;
|
}
return read;
}
boolean hasZipHeader() {
return Arrays.equals(this.header, ZIP_HEADER);
}
private int readRemainder(byte[] b, int off, int len) throws IOException {
int read = super.read(b, off, len);
if (read > 0) {
this.position += read;
}
return read;
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\ZipHeaderPeekInputStream.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.