instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | private Runnable timeoutCallBack(String clientId) {
return () -> {
log.info("连接超时:{}", clientId);
removeUser(clientId);
};
}
/**
* 推送消息异常时,回调方法
*
* @param clientId 客户端ID
* @return java.util.function.Consumer<java.lang.Throwable>
* @author re
* @date 2021/12/14
**/
private Consumer<Throwable> errorCallBack(String clientId) {
return throwable -> {
log.error("SseEmitterServiceImpl[errorCallBack]:连接异常,客户端ID:{}", clientId);
// 推送消息失败后,每隔10s推送一次,推送5次
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(10000);
SseEmitter sseEmitter = sseCache.get(clientId);
if (sseEmitter == null) {
log.error("SseEmitterServiceImpl[errorCallBack]:第{}次消息重推失败,未获取到 {} 对应的长链接", i + 1, clientId);
continue;
}
sseEmitter.send("失败后重新推送");
} catch (Exception e) {
e.printStackTrace(); | }
}
};
}
/**
* 移除用户连接
*
* @param clientId 客户端ID
* @author re
* @date 2021/12/14
**/
private void removeUser(String clientId) {
sseCache.remove(clientId);
log.info("SseEmitterServiceImpl[removeUser]:移除用户:{}", clientId);
}
} | repos\spring-boot-quick-master\quick-sse\src\main\java\com\quick\service\SseEmitterServiceImpl.java | 2 |
请完成以下Java代码 | public class OrderStatusJAXBConvertersV1 implements OrderStatusServerJAXBConverters
{
public static final transient OrderStatusJAXBConvertersV1 instance = new OrderStatusJAXBConvertersV1();
private final OrderJAXBConvertersV1 orderConverters;
private final ObjectFactory jaxbObjectFactory;
private OrderStatusJAXBConvertersV1()
{
this.orderConverters = OrderJAXBConvertersV1.instance;
jaxbObjectFactory = orderConverters.getJaxbObjectFactory();
}
@Override
public Id getOrderIdFromClientRequest(final Object soapRequestObj)
{
final BestellstatusAbfragen soapRequest = castToRequestFromClient(soapRequestObj);
final Id orderId = Id.of(soapRequest.getBestellId());
return orderId;
}
@Override
public ClientSoftwareId getClientSoftwareIdFromClientRequest(final Object soapRequestObj)
{
final BestellstatusAbfragen soapRequest = castToRequestFromClient(soapRequestObj);
return ClientSoftwareId.of(soapRequest.getClientSoftwareKennung());
} | private static BestellstatusAbfragen castToRequestFromClient(final Object soapRequestObj)
{
final BestellstatusAbfragen soapRequest = (BestellstatusAbfragen)soapRequestObj;
return soapRequest;
}
@Override
public JAXBElement<BestellstatusAbfragenResponse> encodeResponseToClient(final OrderStatusResponse response)
{
return toJAXB(response);
}
private JAXBElement<BestellstatusAbfragenResponse> toJAXB(final OrderStatusResponse response)
{
final BestellstatusAntwort soapResponseContent = jaxbObjectFactory.createBestellstatusAntwort();
soapResponseContent.setId(response.getOrderId().getValueAsString());
soapResponseContent.setBestellSupportId(response.getSupportId().getValueAsInt());
soapResponseContent.setStatus(response.getOrderStatus().getV1SoapCode());
soapResponseContent.getAuftraege().addAll(response.getOrderPackages().stream()
.map(orderConverters::toJAXB)
.collect(ImmutableList.toImmutableList()));
final BestellstatusAbfragenResponse soapResponse = jaxbObjectFactory.createBestellstatusAbfragenResponse();
soapResponse.setReturn(soapResponseContent);
return jaxbObjectFactory.createBestellstatusAbfragenResponse(soapResponse);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\order\v1\OrderStatusJAXBConvertersV1.java | 1 |
请完成以下Java代码 | public class OrderMainLocationAdapter
implements IDocumentLocationAdapter, RecordBasedLocationAdapter<OrderMainLocationAdapter>
{
private final I_C_Order delegate;
OrderMainLocationAdapter(@NonNull final I_C_Order delegate)
{
this.delegate = delegate;
}
@Override
public int getC_BPartner_ID()
{
return delegate.getC_BPartner_ID();
}
@Override
public void setC_BPartner_ID(final int C_BPartner_ID)
{
delegate.setC_BPartner_ID(C_BPartner_ID);
}
@Override
public int getC_BPartner_Location_ID()
{
return delegate.getC_BPartner_Location_ID();
}
@Override
public void setC_BPartner_Location_ID(final int C_BPartner_Location_ID)
{
delegate.setC_BPartner_Location_ID(C_BPartner_Location_ID);
}
@Override
public int getC_BPartner_Location_Value_ID()
{
return delegate.getC_BPartner_Location_Value_ID();
}
@Override
public void setC_BPartner_Location_Value_ID(final int C_BPartner_Location_Value_ID)
{
delegate.setC_BPartner_Location_Value_ID(C_BPartner_Location_Value_ID);
}
@Override
public int getAD_User_ID()
{
return delegate.getAD_User_ID();
}
@Override
public void setAD_User_ID(final int AD_User_ID)
{
delegate.setAD_User_ID(AD_User_ID);
}
@Override
public String getBPartnerAddress()
{
return delegate.getBPartnerAddress(); | }
@Override
public void setBPartnerAddress(String address)
{
delegate.setBPartnerAddress(address);
}
@Override
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentLocationAdapter.super.setRenderedAddress(from);
}
public void setFrom(@NonNull final I_C_Order from)
{
setFrom(OrderDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation());
}
@Override
public I_C_Order getWrappedRecord()
{
return delegate;
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public OrderMainLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new OrderMainLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Order.class));
}
public void setLocationAndResetRenderedAddress(@Nullable final BPartnerLocationAndCaptureId from)
{
setC_BPartner_Location_ID(from != null ? from.getBPartnerLocationRepoId() : -1);
setC_BPartner_Location_Value_ID(from != null ? from.getLocationCaptureRepoId() : -1);
setBPartnerAddress(null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderMainLocationAdapter.java | 1 |
请完成以下Java代码 | public List<Customer> findCustomersByTenantIdAndIds(TenantId tenantId, List<CustomerId> customerIds) {
log.trace("Executing findCustomersByTenantIdAndIds, tenantId [{}], customerIds [{}]", tenantId, customerIds);
return customerDao.findCustomersByTenantIdAndIds(tenantId.getId(), customerIds.stream().map(CustomerId::getId).collect(Collectors.toList()));
}
@Override
public void deleteByTenantId(TenantId tenantId) {
deleteCustomersByTenantId(tenantId);
}
private final PaginatedRemover<TenantId, Customer> customersByTenantRemover =
new PaginatedRemover<>() {
@Override
protected PageData<Customer> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return customerDao.findCustomersByTenantId(id.getId(), pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, Customer entity) {
deleteCustomer(tenantId, new CustomerId(entity.getUuidId()));
}
}; | @Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findCustomerById(tenantId, new CustomerId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(findCustomerByIdAsync(tenantId, new CustomerId(entityId.getId())))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public long countByTenantId(TenantId tenantId) {
return customerDao.countByTenantId(tenantId);
}
@Override
public EntityType getEntityType() {
return EntityType.CUSTOMER;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\customer\CustomerServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private String getPubKey() {
// 如果本地没有密钥,就从授权服务器中获取
return StringUtils.isEmpty(resourceServerProperties.getJwt().getKeyValue()) ? getKeyFromAuthorizationServer() : resourceServerProperties.getJwt().getKeyValue();
}
/**
* 本地没有公钥的时候,从服务器上获取
* 需要进行 Basic 认证
*
* @return public key
*/
private String getKeyFromAuthorizationServer() {
ObjectMapper objectMapper = new ObjectMapper();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.AUTHORIZATION, encodeClient());
HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
String pubKey = new RestTemplate().getForObject(resourceServerProperties.getJwt().getKeyUri(), String.class, requestEntity);
try { | JSONObject body = objectMapper.readValue(pubKey, JSONObject.class);
log.info("Get Key From Authorization Server.");
return body.getStr("value");
} catch (IOException e) {
log.error("Get public key error: {}", e.getMessage());
}
return null;
}
/**
* 客户端信息
*
* @return basic
*/
private String encodeClient() {
return "Basic " + Base64.getEncoder().encodeToString((resourceServerProperties.getClientId() + ":" + resourceServerProperties.getClientSecret()).getBytes());
}
} | repos\spring-boot-demo-master\demo-oauth\oauth-resource-server\src\main\java\com\xkcoding\oauth\config\OauthResourceTokenConfig.java | 2 |
请完成以下Java代码 | protected ContextSource getContextSource() {
return this.contextSource;
}
public String[] getUserAttributes() {
return this.userAttributes;
}
/**
* Builds list of possible DNs for the user, worked out from the
* <tt>userDnPatterns</tt> property.
* @param username the user's login name
* @return the list of possible DN matches, empty if <tt>userDnPatterns</tt> wasn't
* set.
*/
protected List<String> getUserDns(String username) {
if (this.userDnFormat == null) {
return Collections.emptyList();
}
List<String> userDns = new ArrayList<>(this.userDnFormat.length);
String[] args = new String[] { LdapEncoder.nameEncode(username) };
synchronized (this.mutex) {
for (MessageFormat formatter : this.userDnFormat) {
userDns.add(formatter.format(args));
}
}
return userDns;
}
protected LdapUserSearch getUserSearch() {
return this.userSearch;
}
@Override
public void setMessageSource(@NonNull MessageSource messageSource) {
Assert.notNull(messageSource, "Message source must not be null");
this.messages = new MessageSourceAccessor(messageSource);
}
/**
* Sets the user attributes which will be retrieved from the directory.
* @param userAttributes the set of user attributes to retrieve
*/
public void setUserAttributes(String[] userAttributes) { | Assert.notNull(userAttributes, "The userAttributes property cannot be set to null");
this.userAttributes = userAttributes;
}
/**
* Sets the pattern which will be used to supply a DN for the user. The pattern should
* be the name relative to the root DN. The pattern argument {0} will contain the
* username. An example would be "cn={0},ou=people".
* @param dnPattern the array of patterns which will be tried when converting a
* username to a DN.
*/
public void setUserDnPatterns(String[] dnPattern) {
Assert.notNull(dnPattern, "The array of DN patterns cannot be set to null");
// this.userDnPattern = dnPattern;
this.userDnFormat = new MessageFormat[dnPattern.length];
for (int i = 0; i < dnPattern.length; i++) {
this.userDnFormat[i] = new MessageFormat(dnPattern[i]);
}
}
public void setUserSearch(LdapUserSearch userSearch) {
Assert.notNull(userSearch, "The userSearch cannot be set to null");
this.userSearch = userSearch;
}
} | repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\authentication\AbstractLdapAuthenticator.java | 1 |
请完成以下Java代码 | public List benchmarkStringIndexOf() {
int pos = 0, end;
while ((end = longString.indexOf(' ', pos)) >= 0) {
stringSplit.add(longString.substring(pos, end));
pos = end + 1;
}
//Add last token of string
stringSplit.add(longString.substring(pos));
return stringSplit;
}
@Benchmark
public String benchmarkIntegerToString() {
return Integer.toString(sampleNumber);
}
@Benchmark
public String benchmarkStringValueOf() {
return String.valueOf(sampleNumber);
}
@Benchmark
public String benchmarkStringConvertPlus() {
return sampleNumber + "";
}
@Benchmark
public String benchmarkStringFormat_d() {
return String.format(formatDigit, sampleNumber);
}
@Benchmark
public boolean benchmarkStringEquals() {
return longString.equals(baeldung);
}
@Benchmark
public boolean benchmarkStringEqualsIgnoreCase() {
return longString.equalsIgnoreCase(baeldung);
} | @Benchmark
public boolean benchmarkStringMatches() {
return longString.matches(baeldung);
}
@Benchmark
public boolean benchmarkPrecompiledMatches() {
return longPattern.matcher(baeldung).matches();
}
@Benchmark
public int benchmarkStringCompareTo() {
return longString.compareTo(baeldung);
}
@Benchmark
public boolean benchmarkStringIsEmpty() {
return longString.isEmpty();
}
@Benchmark
public boolean benchmarkStringLengthZero() {
return longString.length() == 0;
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(StringPerformance.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
} | repos\tutorials-master\core-java-modules\core-java-strings\src\main\java\com\baeldung\stringperformance\StringPerformance.java | 1 |
请完成以下Java代码 | private static AccountId setValuesAndSave(
@NonNull final I_C_ValidCombination vc,
@NonNull final AccountDimension dimension)
{
vc.setAD_Org_ID(dimension.getAD_Org_ID());
vc.setC_AcctSchema_ID(AcctSchemaId.toRepoId(dimension.getAcctSchemaId()));
vc.setAccount_ID(dimension.getC_ElementValue_ID());
vc.setC_SubAcct_ID(dimension.getC_SubAcct_ID());
vc.setM_Product_ID(dimension.getM_Product_ID());
vc.setC_BPartner_ID(dimension.getC_BPartner_ID());
vc.setAD_OrgTrx_ID(dimension.getAD_OrgTrx_ID());
vc.setC_LocFrom_ID(dimension.getC_LocFrom_ID());
vc.setC_LocTo_ID(dimension.getC_LocTo_ID());
vc.setC_SalesRegion_ID(dimension.getC_SalesRegion_ID());
vc.setC_Project_ID(dimension.getC_Project_ID());
vc.setC_Campaign_ID(dimension.getC_Campaign_ID()); | vc.setC_Activity_ID(dimension.getC_Activity_ID());
vc.setUser1_ID(dimension.getUser1_ID());
vc.setUser2_ID(dimension.getUser2_ID());
vc.setUserElement1_ID(dimension.getUserElement1_ID());
vc.setUserElement2_ID(dimension.getUserElement2_ID());
vc.setUserElementString1(dimension.getUserElementString1());
vc.setUserElementString2(dimension.getUserElementString2());
vc.setUserElementString3(dimension.getUserElementString3());
vc.setUserElementString4(dimension.getUserElementString4());
vc.setUserElementString5(dimension.getUserElementString5());
vc.setUserElementString6(dimension.getUserElementString6());
vc.setUserElementString7(dimension.getUserElementString7());
InterfaceWrapperHelper.save(vc);
return AccountId.ofRepoId(vc.getC_ValidCombination_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\impl\AccountDAO.java | 1 |
请完成以下Spring Boot application配置 | spring.datasource.url=jdbc:mysql://localhost:3306/springjdbc
spring.datasource.username=guest_user
spring.datasource.password=guest_password
spring.jp | a.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect | repos\tutorials-master\persistence-modules\spring-persistence-simple\src\main\resources\com\baeldung\spring\jdbc\template\guide\application-mysql.properties | 2 |
请完成以下Java代码 | public Object getPersistentState() {
// details are not updatable so we always provide the same object as the state
return HistoricDetailEntity.class;
}
public void delete() {
DbSqlSession dbSqlSession = Context
.getCommandContext()
.getDbSqlSession();
dbSqlSession.delete(this);
}
// getters and setters //////////////////////////////////////////////////////
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@Override
public String getActivityInstanceId() {
return activityInstanceId;
}
public void setActivityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
} | @Override
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@Override
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getDetailType() {
return detailType;
}
public void setDetailType(String detailType) {
this.detailType = detailType;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricDetailEntity.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* DefaultAuthenticationMethod AD_Reference_ID=541848
* Reference name: MobileAuthenticationMethod
*/
public static final int DEFAULTAUTHENTICATIONMETHOD_AD_Reference_ID=541848;
/** QR Code = QR_Code */
public static final String DEFAULTAUTHENTICATIONMETHOD_QRCode = "QR_Code";
/** User & Pass = UserPass */
public static final String DEFAULTAUTHENTICATIONMETHOD_UserPass = "UserPass";
@Override
public void setDefaultAuthenticationMethod (final java.lang.String DefaultAuthenticationMethod)
{
set_Value (COLUMNNAME_DefaultAuthenticationMethod, DefaultAuthenticationMethod);
}
@Override | public java.lang.String getDefaultAuthenticationMethod()
{
return get_ValueAsString(COLUMNNAME_DefaultAuthenticationMethod);
}
@Override
public void setMobileConfiguration_ID (final int MobileConfiguration_ID)
{
if (MobileConfiguration_ID < 1)
set_ValueNoCheck (COLUMNNAME_MobileConfiguration_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MobileConfiguration_ID, MobileConfiguration_ID);
}
@Override
public int getMobileConfiguration_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileConfiguration_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileConfiguration.java | 1 |
请完成以下Java代码 | public String getInfoName()
{
return infoName;
} // getInfoName
public Operator getOperator()
{
return operator;
}
/**
* Get Info Operator
*
* @return info Operator
*/
public String getInfoOperator()
{
return operator == null ? null : operator.getCaption();
} // getInfoOperator
/**
* Get Display with optional To
*
* @return info display
*/
public String getInfoDisplayAll()
{
if (infoDisplayTo == null)
{
return infoDisplay;
} | StringBuilder sb = new StringBuilder(infoDisplay);
sb.append(" - ").append(infoDisplayTo);
return sb.toString();
} // getInfoDisplay
public Object getCode()
{
return code;
}
public String getInfoDisplay()
{
return infoDisplay;
}
public Object getCodeTo()
{
return codeTo;
}
public String getInfoDisplayTo()
{
return infoDisplayTo;
}
} // Restriction | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MQuery.java | 1 |
请完成以下Java代码 | private static int findPlaceholderEndIndex(CharSequence buf, int startIndex) {
int index = startIndex + PLACEHOLDER_PREFIX.length();
int withinNestedPlaceholder = 0;
while (index < buf.length()) {
if (substringMatch(buf, index, PLACEHOLDER_SUFFIX)) {
if (withinNestedPlaceholder > 0) {
withinNestedPlaceholder--;
index = index + PLACEHOLDER_SUFFIX.length();
}
else {
return index;
}
}
else if (substringMatch(buf, index, SIMPLE_PREFIX)) {
withinNestedPlaceholder++;
index = index + SIMPLE_PREFIX.length();
}
else { | index++;
}
}
return -1;
}
private static boolean substringMatch(CharSequence str, int index, CharSequence substring) {
for (int j = 0; j < substring.length(); j++) {
int i = index + j;
if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {
return false;
}
}
return true;
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\SystemPropertyUtils.java | 1 |
请完成以下Java代码 | void sendRequests() {
// prepare the response callback
final StreamObserver<HelloWorldResponse> responseObserver = new StreamObserver<HelloWorldResponse>() {
@Override
public void onNext(HelloWorldResponse helloWorldResponse) {
log.info("Hello World Response: {}", helloWorldResponse.getGreeting());
}
@Override
public void onError(Throwable throwable) {
log.error("Error occured", throwable);
}
@Override
public void onCompleted() {
log.info("Hello World request finished");
} | };
// connect to the server
final StreamObserver<HelloWorldRequest> request = stub.sayHello(responseObserver);
// send multiple requests (streaming)
Stream.of("Tom", "Julia", "Baeldung", "", "Ralf")
.map(HelloWorldRequest.newBuilder()::setName)
.map(HelloWorldRequest.Builder::build)
.forEach(request::onNext);
request.onCompleted();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-3-grpc\helloworld-grpc-consumer\src\main\java\com\baeldung\helloworld\consumer\HelloWorldClient.java | 1 |
请完成以下Java代码 | public String getLastName() {
return lastName;
}
@Override
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String getEmail() {
return email;
}
@Override
public void setEmail(String email) {
this.email = email;
}
@Override
public String getPassword() {
return password != null ? password : id; | }
@Override
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("id=" + id)
.add("firstName=" + firstName)
.add("lastName=" + lastName)
.add("email=" + email)
.add("password=******") // sensitive for logging
.toString();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\AdminUserProperty.java | 1 |
请完成以下Java代码 | private void setASI(final int recordId, final KeyNamePair asi)
{
if (isValidASI(asi))
{
recordId2asi.put(recordId, asi.getKey());
}
else
{
recordId2asi.remove(recordId);
}
}
private boolean isValidASI(final KeyNamePair asi)
{
if (asi == null)
{
return false;
}
if (asi.getKey() <= 0)
{
return false;
}
return true;
}
@Override
public List<String> getDependsOnColumnNames()
{
return Collections.emptyList();
}
@Override
public Set<String> getValuePropagationKeyColumnNames(final Info_Column infoColumn)
{
return Collections.singleton(InfoProductQtyController.COLUMNNAME_M_Product_ID);
}
@Override
public Object gridConvertAfterLoad(final Info_Column infoColumn, final int rowIndexModel, final int rowRecordId, final Object data)
{
return data;
}
@Override
public int getParameterCount()
{
return 0;
}
@Override
public String getLabel(final int index)
{
return null;
}
@Override
public Object getParameterComponent(final int index)
{
return null;
}
@Override
public Object getParameterToComponent(final int index)
{
return null;
} | @Override
public Object getParameterValue(final int index, final boolean returnValueTo)
{
return null;
}
@Override
public String[] getWhereClauses(final List<Object> params)
{
return new String[0];
}
@Override
public String getText()
{
return null;
}
@Override
public void save(final Properties ctx, final int windowNo, final IInfoWindowGridRowBuilders builders)
{
for (final Map.Entry<Integer, Integer> e : recordId2asi.entrySet())
{
final Integer recordId = e.getKey();
if (recordId == null || recordId <= 0)
{
continue;
}
final Integer asiId = e.getValue();
if (asiId == null || asiId <= 0)
{
continue;
}
final OrderLineProductASIGridRowBuilder productQtyBuilder = new OrderLineProductASIGridRowBuilder();
productQtyBuilder.setSource(recordId, asiId);
builders.addGridTabRowBuilder(recordId, productQtyBuilder);
}
}
@Override
public void prepareEditor(final CEditor editor, final Object value, final int rowIndexModel, final int columnIndexModel)
{
final VPAttributeContext attributeContext = new VPAttributeContext(rowIndexModel);
editor.putClientProperty(IVPAttributeContext.ATTR_NAME, attributeContext);
// nothing
}
@Override
public String getProductCombinations()
{
// nothing to do
return null;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\InfoProductASIController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public LocalDateTime convert(Instant source) {
return LocalDateTime.ofInstant(source, ZoneOffset.UTC);
}
}
@ReadingConverter
public enum InstantReadConverter implements Converter<LocalDateTime, Instant> {
INSTANCE;
@Override
public Instant convert(LocalDateTime localDateTime) {
return localDateTime.toInstant(ZoneOffset.UTC);
}
}
@ReadingConverter
public enum BitSetReadConverter implements Converter<BitSet, Boolean> {
INSTANCE;
@Override
public Boolean convert(BitSet bitSet) {
return bitSet.get(0);
}
}
@ReadingConverter
public enum ZonedDateTimeReadConverter implements Converter<LocalDateTime, ZonedDateTime> {
INSTANCE;
@Override
public ZonedDateTime convert(LocalDateTime localDateTime) {
// Be aware - we are using the UTC timezone
return ZonedDateTime.of(localDateTime, ZoneOffset.UTC); | }
}
@WritingConverter
public enum ZonedDateTimeWriteConverter implements Converter<ZonedDateTime, LocalDateTime> {
INSTANCE;
@Override
public LocalDateTime convert(ZonedDateTime zonedDateTime) {
return zonedDateTime.toLocalDateTime();
}
}
@WritingConverter
public enum DurationWriteConverter implements Converter<Duration, Long> {
INSTANCE;
@Override
public Long convert(Duration source) {
return source != null ? source.toMillis() : null;
}
}
@ReadingConverter
public enum DurationReadConverter implements Converter<Long, Duration> {
INSTANCE;
@Override
public Duration convert(Long source) {
return source != null ? Duration.ofMillis(source) : null;
}
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\config\DatabaseConfiguration.java | 2 |
请完成以下Java代码 | public void setMaxValue (int MaxValue)
{
set_Value (COLUMNNAME_MaxValue, Integer.valueOf(MaxValue));
}
/** Get Max Value.
@return Max Value */
public int getMaxValue ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MaxValue);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Min Value.
@param MinValue Min Value */
public void setMinValue (int MinValue)
{
set_Value (COLUMNNAME_MinValue, Integer.valueOf(MinValue));
}
/** Get Min Value.
@return Min Value */
public int getMinValue ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MinValue);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Service date.
@param ServiceDate
Date service was provided
*/
public void setServiceDate (Timestamp ServiceDate)
{
set_Value (COLUMNNAME_ServiceDate, ServiceDate);
} | /** Get Service date.
@return Date service was provided
*/
public Timestamp getServiceDate ()
{
return (Timestamp)get_Value(COLUMNNAME_ServiceDate);
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Attribute.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Filter addMissingHeadersFilter()
{
return new Filter()
{
@Override
public void init(final FilterConfig filterConfig)
{
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException
{
try
{
chain.doFilter(request, response);
}
finally
{
if (response instanceof HttpServletResponse)
{
final HttpServletResponse httpResponse = (HttpServletResponse)response;
// | // If the Cache-Control is not set then set it to no-cache.
// In this way we precisely tell to browser that it shall not cache our REST calls.
// The Cache-Control is usually defined by features like ETag
if (!httpResponse.containsHeader("Cache-Control"))
{
httpResponse.setHeader("Cache-Control", "no-cache");
}
}
}
}
@Override
public void destroy()
{
}
};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\config\WebConfig.java | 2 |
请完成以下Java代码 | private GenericZoomIntoTableInfo retrieveTableInfo(@NonNull final TableInfoCacheKey key)
{
return tableInfoRepository.retrieveTableInfo(key.getTableName(), key.isIgnoreExcludeFromZoomTargetsFlag())
.withCustomizedWindowIds(customizedWindowInfoMapRepository.get());
}
private SOTrx getRecordSOTrxEffective()
{
if (_recordSOTrx_Effective == null)
{
_recordSOTrx_Effective = computeRecordSOTrxEffective();
}
return _recordSOTrx_Effective;
}
private SOTrx computeRecordSOTrxEffective()
{
final String tableName = getTableInfo().getTableName();
final String sqlWhereClause = getRecordWhereClause(); // might be null
if (sqlWhereClause == null || Check.isBlank(sqlWhereClause))
{
return SOTrx.SALES;
}
return DB.retrieveRecordSOTrx(tableName, sqlWhereClause).orElse(SOTrx.SALES);
}
private Optional<TableRecordReference> retrieveParentRecordRef()
{
final GenericZoomIntoTableInfo tableInfo = getTableInfo();
if (tableInfo.getParentTableName() == null
|| tableInfo.getParentLinkColumnName() == null)
{
return Optional.empty();
}
final String sqlWhereClause = getRecordWhereClause(); // might be null
if (sqlWhereClause == null || Check.isBlank(sqlWhereClause))
{
return Optional.empty();
}
final String sql = "SELECT " + tableInfo.getParentLinkColumnName()
+ " FROM " + tableInfo.getTableName()
+ " WHERE " + sqlWhereClause;
try
{
final int parentRecordId = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql);
if (parentRecordId < InterfaceWrapperHelper.getFirstValidIdByColumnName(tableInfo.getParentTableName() + "_ID"))
{
return Optional.empty();
}
final TableRecordReference parentRecordRef = TableRecordReference.of(tableInfo.getParentTableName(), parentRecordId); | return Optional.of(parentRecordRef);
}
catch (final Exception ex)
{
logger.warn("Failed retrieving parent record ID from current record. Returning empty. \n\tthis={} \n\tSQL: {}", this, sql, ex);
return Optional.empty();
}
}
@NonNull
private static CustomizedWindowInfoMapRepository getCustomizedWindowInfoMapRepository()
{
return !Adempiere.isUnitTestMode()
? SpringContextHolder.instance.getBean(CustomizedWindowInfoMapRepository.class)
: NullCustomizedWindowInfoMapRepository.instance;
}
@Value
@Builder
private static class TableInfoCacheKey
{
@NonNull String tableName;
boolean ignoreExcludeFromZoomTargetsFlag;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\zoom_into\RecordWindowFinder.java | 1 |
请完成以下Java代码 | public EventDefinitionEntity findEventDefinitionByKeyAndVersionAndTenantId(String eventDefinitionKey, Integer eventVersion, String tenantId) {
Map<String, Object> params = new HashMap<>();
params.put("eventDefinitionKey", eventDefinitionKey);
params.put("eventVersion", eventVersion);
params.put("tenantId", tenantId);
List<EventDefinitionEntity> results = getDbSqlSession().selectList("selectEventDefinitionsByKeyAndVersionAndTenantId", params);
if (results.size() == 1) {
return results.get(0);
} else if (results.size() > 1) {
throw new FlowableException("There are " + results.size() + " event definitions with key = '" + eventDefinitionKey + "' and version = '" + eventVersion + "' in tenant = '" + tenantId + "'.");
}
return null;
}
@Override
@SuppressWarnings("unchecked")
public List<EventDefinition> findEventDefinitionsByNativeQuery(Map<String, Object> parameterMap) {
return getDbSqlSession().selectListWithRawParameter("selectEventDefinitionByNativeQuery", parameterMap);
} | @Override
public long findEventDefinitionCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectEventDefinitionCountByNativeQuery", parameterMap);
}
@Override
public void updateEventDefinitionTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().directUpdate("updateEventDefinitionTenantIdForDeploymentId", params);
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\data\impl\MybatisEventDefinitionDataManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
public Boolean getWithoutScopeId() {
return withoutScopeId;
}
public void setWithoutScopeId(Boolean withoutScopeId) {
this.withoutScopeId = withoutScopeId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
public void setPropagatedStageInstanceId(String propagatedStageInstanceId) {
this.propagatedStageInstanceId = propagatedStageInstanceId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Boolean getWithoutDeleteReason() {
return withoutDeleteReason;
}
public void setWithoutDeleteReason(Boolean withoutDeleteReason) {
this.withoutDeleteReason = withoutDeleteReason;
}
public String getTaskCandidateGroup() {
return taskCandidateGroup;
}
public void setTaskCandidateGroup(String taskCandidateGroup) {
this.taskCandidateGroup = taskCandidateGroup; | }
public boolean isIgnoreTaskAssignee() {
return ignoreTaskAssignee;
}
public void setIgnoreTaskAssignee(boolean ignoreTaskAssignee) {
this.ignoreTaskAssignee = ignoreTaskAssignee;
}
public String getRootScopeId() {
return rootScopeId;
}
public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
}
public void setParentScopeId(String parentScopeId) {
this.parentScopeId = parentScopeId;
}
public Set<String> getScopeIds() {
return scopeIds;
}
public void setScopeIds(Set<String> scopeIds) {
this.scopeIds = scopeIds;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceQueryRequest.java | 2 |
请完成以下Java代码 | private DeliveryOrder updateDeliveryOrder(final @NonNull DeliveryOrder deliveryOrder, @NonNull final JsonDeliveryResponse response)
{
final ImmutableMap<String, JsonDeliveryResponseItem> lineIdToResponseMap = response.getItems().stream()
.collect(ImmutableMap.toImmutableMap(JsonDeliveryResponseItem::getLineId, Function.identity()));
final ImmutableList<DeliveryOrderParcel> updatedDeliveryOrderParcels = deliveryOrder.getDeliveryOrderParcels()
.stream()
.map(line -> updateDeliveryOrderLine(line, lineIdToResponseMap.get(String.valueOf(line.getId().getRepoId()))))
.collect(ImmutableList.toImmutableList());
return deliveryOrder.withDeliveryOrderParcels(updatedDeliveryOrderParcels);
}
private DeliveryOrderParcel updateDeliveryOrderLine(@NonNull final DeliveryOrderParcel line, @NonNull final JsonDeliveryResponseItem jsonDeliveryResponseItem)
{
final String awb = jsonDeliveryResponseItem.getAwb();
final byte[] labelData = Base64.getDecoder().decode(jsonDeliveryResponseItem.getLabelPdfBase64());
final String trackingUrl = jsonDeliveryResponseItem.getTrackingUrl();
return line.toBuilder()
.awb(awb)
.trackingUrl(trackingUrl)
.labelPdfBase64(labelData)
.build();
}
@NonNull
@Override
public List<PackageLabels> getPackageLabelsList(@NonNull final DeliveryOrder deliveryOrder) throws ShipperGatewayException
{
final String orderIdAsString = String.valueOf(deliveryOrder.getId());
return deliveryOrder.getDeliveryOrderParcels()
.stream() | .map(line -> createPackageLabel(line.getLabelPdfBase64(), line.getAwb(), orderIdAsString))
.collect(Collectors.toList());
}
@Override
public @NonNull JsonDeliveryAdvisorResponse adviseShipment(final @NonNull JsonDeliveryAdvisorRequest request)
{
return shipAdvisorService.advise(request);
}
@NonNull
private static PackageLabels createPackageLabel(final byte[] labelData, @NonNull final String awb, @NonNull final String deliveryOrderIdAsString)
{
return PackageLabels.builder()
.orderId(OrderId.of(NShiftConstants.SHIPPER_GATEWAY_ID, deliveryOrderIdAsString))
.defaultLabelType(NShiftPackageLabelType.DEFAULT)
.label(PackageLabel.builder()
.type(NShiftPackageLabelType.DEFAULT)
.labelData(labelData)
.contentType(PackageLabel.CONTENTTYPE_PDF)
.fileName(awb)
.build())
.build();
}
public JsonShipperConfig getJsonShipperConfig()
{
return jsonConverter.toJsonShipperConfig(shipperConfig);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.nshift\src\main\java\de\metas\shipper\gateway\nshift\client\NShiftShipperGatewayClient.java | 1 |
请完成以下Java代码 | public void setMessageConverter(MessageConverter messageConverter) {
super.setMessageConverter(messageConverter);
this.messageConverter = messageConverter;
}
@Override
public void setValidator(Validator validator) {
super.setValidator(validator);
this.validator = validator;
}
@Override
protected List<HandlerMethodArgumentResolver> initArgumentResolvers() {
List<HandlerMethodArgumentResolver> resolvers = super.initArgumentResolvers();
if (KotlinDetector.isKotlinPresent()) {
// Insert before PayloadMethodArgumentResolver
resolvers.add(resolvers.size() - 1, new ContinuationHandlerMethodArgumentResolver()); | }
// Has to be at the end - look at PayloadMethodArgumentResolver documentation
resolvers.add(resolvers.size() - 1, new KafkaNullAwarePayloadArgumentResolver(this.messageConverter, this.validator));
this.argumentResolvers.addResolvers(resolvers);
return resolvers;
}
@Override
public InvocableHandlerMethod createInvocableHandlerMethod(Object bean, Method method) {
InvocableHandlerMethod handlerMethod = new KotlinAwareInvocableHandlerMethod(bean, method);
handlerMethod.setMessageMethodArgumentResolvers(this.argumentResolvers);
return handlerMethod;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\adapter\KafkaMessageHandlerMethodFactory.java | 1 |
请完成以下Java代码 | public boolean isExclusive() {
return exclusive;
}
public void setExclusive(boolean exclusive) {
this.exclusive = exclusive;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
public String getConcurrency() {
return concurrency;
}
public void setConcurrency(String concurrency) { | this.concurrency = concurrency;
}
public String getExecutor() {
return executor;
}
public void setExecutor(String executor) {
this.executor = executor;
}
public String getAckMode() {
return ackMode;
}
public void setAckMode(String ackMode) {
this.ackMode = ackMode;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\RabbitInboundChannelModel.java | 1 |
请完成以下Java代码 | public void setM_PackagingTreeItemSched_ID(int M_PackagingTreeItemSched_ID)
{
if (M_PackagingTreeItemSched_ID < 1)
set_ValueNoCheck(COLUMNNAME_M_PackagingTreeItemSched_ID, null);
else
set_ValueNoCheck(COLUMNNAME_M_PackagingTreeItemSched_ID, Integer.valueOf(M_PackagingTreeItemSched_ID));
}
/**
* Get Packaging Tree Item Schedule.
*
* @return Packaging Tree Item Schedule
*/
public int getM_PackagingTreeItemSched_ID()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PackagingTreeItemSched_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_PackagingTreeItem getM_PackagingTreeItem() throws RuntimeException
{
return (I_M_PackagingTreeItem)MTable.get(getCtx(), I_M_PackagingTreeItem.Table_Name)
.getPO(getM_PackagingTreeItem_ID(), get_TrxName());
}
/**
* Set Packaging Tree Item.
*
* @param M_PackagingTreeItem_ID
* Packaging Tree Item
*/
public void setM_PackagingTreeItem_ID(int M_PackagingTreeItem_ID)
{
if (M_PackagingTreeItem_ID < 1)
set_Value(COLUMNNAME_M_PackagingTreeItem_ID, null);
else
set_Value(COLUMNNAME_M_PackagingTreeItem_ID, Integer.valueOf(M_PackagingTreeItem_ID));
}
/**
* Get Packaging Tree Item.
*
* @return Packaging Tree Item
*/
public int getM_PackagingTreeItem_ID()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PackagingTreeItem_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public I_M_ShipmentSchedule getM_ShipmentSchedule() throws RuntimeException
{
return (I_M_ShipmentSchedule)MTable.get(getCtx(), I_M_ShipmentSchedule.Table_Name)
.getPO(getM_ShipmentSchedule_ID(), get_TrxName());
} | @Override
public int getM_ShipmentSchedule_ID()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ShipmentSchedule_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public void setM_ShipmentSchedule_ID(int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_Value(COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_Value(COLUMNNAME_M_ShipmentSchedule_ID, Integer.valueOf(M_ShipmentSchedule_ID));
}
/**
* Set Menge.
*
* @param Qty
* Menge
*/
public void setQty(BigDecimal Qty)
{
set_Value(COLUMNNAME_Qty, Qty);
}
/**
* Get Menge.
*
* @return Menge
*/
public BigDecimal getQty()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PackagingTreeItemSched.java | 1 |
请完成以下Java代码 | default <ST> RT addNotInSubQueryFilter(final String columnName, final String subQueryColumnName, final IQuery<ST> subQuery)
{
final IQueryFilter<T> filter = InSubQueryFilter.<T>builder()
.tableName(getModelTableName())
.subQuery(subQuery)
.matchingColumnNames(columnName, subQueryColumnName)
.build();
final IQueryFilter<T> notFilter = NotQueryFilter.of(filter);
return addFilter(notFilter);
}
/**
* @param column the key column from the "main" query
* @param subQueryColumn the key column from the "sub" query
* @param subQuery the actual sub query
* @return this
*/
default <ST> RT addInSubQueryFilter(final ModelColumn<T, ?> column, final ModelColumn<ST, ?> subQueryColumn, final IQuery<ST> subQuery)
{
return addFilter(InSubQueryFilter.<T>builder()
.tableName(getModelTableName())
.subQuery(subQuery)
.matchingColumnNames(column.getColumnName(), subQueryColumn.getColumnName())
.build());
}
default <ST> RT addNotInSubQueryFilter(final ModelColumn<T, ?> column, final ModelColumn<ST, ?> subQueryColumn, final IQuery<ST> subQuery)
{
final IQueryFilter<T> filter = InSubQueryFilter.<T>builder()
.tableName(getModelTableName())
.subQuery(subQuery)
.matchingColumnNames(column.getColumnName(), subQueryColumn.getColumnName())
.build();
final IQueryFilter<T> notFilter = NotQueryFilter.of(filter);
return addFilter(notFilter); | }
default RT addIntervalIntersection(
@NonNull final String lowerBoundColumnName,
@NonNull final String upperBoundColumnName,
@Nullable final ZonedDateTime lowerBoundValue,
@Nullable final ZonedDateTime upperBoundValue)
{
addIntervalIntersection(
lowerBoundColumnName,
upperBoundColumnName,
lowerBoundValue != null ? lowerBoundValue.toInstant() : null,
upperBoundValue != null ? upperBoundValue.toInstant() : null);
return self();
}
default RT addIntervalIntersection(
@NonNull final String lowerBoundColumnName,
@NonNull final String upperBoundColumnName,
@Nullable final Instant lowerBoundValue,
@Nullable final Instant upperBoundValue)
{
addFilter(new DateIntervalIntersectionQueryFilter<>(
ModelColumnNameValue.forColumnName(lowerBoundColumnName),
ModelColumnNameValue.forColumnName(upperBoundColumnName),
lowerBoundValue,
upperBoundValue));
return self();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\ICompositeQueryFilterProxy.java | 1 |
请完成以下Java代码 | public static String sentenceCase(List<String> words) {
List<String> capitalized = new ArrayList<>();
for (int i = 0; i < words.size(); i++) {
String currentWord = words.get(i);
if (i == 0) {
capitalized.add(capitalizeFirst(currentWord));
} else {
capitalized.add(currentWord.toLowerCase());
}
}
return String.join(" ", capitalized) + ".";
}
public static String capitalizeMyTitle(List<String> words) {
List<String> capitalized = new ArrayList<>(); | for (int i = 0; i < words.size(); i++) {
String currentWord = words.get(i);
if (i == 0 || !STOP_WORDS.contains(currentWord.toLowerCase())) {
capitalized.add(capitalizeFirst(currentWord));
} else {
capitalized.add(currentWord.toLowerCase());
}
}
return String.join(" ", capitalized);
}
private static String capitalizeFirst(String word) {
return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
}
} | repos\tutorials-master\core-java-modules\core-java-regex-2\src\main\java\com\baeldung\regex\camelcasetowords\Recapitalize.java | 1 |
请完成以下Java代码 | public boolean deleteByIdAndRecipientId(TenantId tenantId, UserId recipientId, NotificationId notificationId) {
return notificationRepository.deleteByIdAndRecipientId(notificationId.getId(), recipientId.getId()) != 0;
}
@Override
public int updateStatusByDeliveryMethodAndRecipientId(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId, NotificationStatus status) {
return notificationRepository.updateStatusByDeliveryMethodAndRecipientIdAndStatusNot(deliveryMethod, recipientId.getId(), status);
}
@Override
public void deleteByRequestId(TenantId tenantId, NotificationRequestId requestId) {
notificationRepository.deleteByRequestId(requestId.getId());
}
@Override
public void deleteByRecipientId(TenantId tenantId, UserId recipientId) {
notificationRepository.deleteByRecipientId(recipientId.getId());
}
@Override
public void createPartition(NotificationEntity entity) {
partitioningRepository.createPartitionIfNotExists(ModelConstants.NOTIFICATION_TABLE_NAME,
entity.getCreatedTime(), TimeUnit.HOURS.toMillis(partitionSizeInHours));
} | @Override
protected Class<NotificationEntity> getEntityClass() {
return NotificationEntity.class;
}
@Override
protected JpaRepository<NotificationEntity, UUID> getRepository() {
return notificationRepository;
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationDao.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ErpelDocumentExtensionType {
@XmlElement(name = "Attachments")
protected AttachmentsType attachments;
/**
* Gets the value of the attachments property.
*
* @return
* possible object is
* {@link AttachmentsType }
*
*/
public AttachmentsType getAttachments() {
return attachments; | }
/**
* Sets the value of the attachments property.
*
* @param value
* allowed object is
* {@link AttachmentsType }
*
*/
public void setAttachments(AttachmentsType value) {
this.attachments = 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\ErpelDocumentExtensionType.java | 2 |
请完成以下Java代码 | public List<Employee> getAllEmployeesUsingWrapperClass() {
RestTemplate restTemplate = new RestTemplate();
EmployeeList response =
restTemplate.getForObject(
"http://localhost:8080/spring-rest/employees/v2",
EmployeeList.class);
List<Employee> employees = response.getEmployees();
employees.forEach(System.out::println);
return employees;
}
public void createEmployeesUsingLists() {
RestTemplate restTemplate = new RestTemplate();
List<Employee> newEmployees = new ArrayList<>();
newEmployees.add(new Employee(3, "Intern"));
newEmployees.add(new Employee(4, "CEO"));
restTemplate.postForObject( | "http://localhost:8080/spring-rest/employees/",
newEmployees,
ResponseEntity.class);
}
public void createEmployeesUsingWrapperClass() {
RestTemplate restTemplate = new RestTemplate();
List<Employee> newEmployees = new ArrayList<>();
newEmployees.add(new Employee(3, "Intern"));
newEmployees.add(new Employee(4, "CEO"));
restTemplate.postForObject(
"http://localhost:8080/spring-rest/employees/v2",
new EmployeeList(newEmployees),
ResponseEntity.class);
}
} | repos\tutorials-master\spring-web-modules\spring-resttemplate-1\src\main\java\com\baeldung\resttemplate\lists\client\EmployeeClient.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getRefundStatus()
{
return refundStatus;
}
public void setRefundStatus(String refundStatus)
{
this.refundStatus = refundStatus;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
OrderRefund orderRefund = (OrderRefund)o;
return Objects.equals(this.amount, orderRefund.amount) &&
Objects.equals(this.refundDate, orderRefund.refundDate) &&
Objects.equals(this.refundId, orderRefund.refundId) &&
Objects.equals(this.refundReferenceId, orderRefund.refundReferenceId) &&
Objects.equals(this.refundStatus, orderRefund.refundStatus);
}
@Override
public int hashCode()
{ | return Objects.hash(amount, refundDate, refundId, refundReferenceId, refundStatus);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class OrderRefund {\n");
sb.append(" amount: ").append(toIndentedString(amount)).append("\n");
sb.append(" refundDate: ").append(toIndentedString(refundDate)).append("\n");
sb.append(" refundId: ").append(toIndentedString(refundId)).append("\n");
sb.append(" refundReferenceId: ").append(toIndentedString(refundReferenceId)).append("\n");
sb.append(" refundStatus: ").append(toIndentedString(refundStatus)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\OrderRefund.java | 2 |
请完成以下Java代码 | public static void bulkDeleteHistoricCaseInstances(Collection<String> caseInstanceIds, CmmnEngineConfiguration cmmnEngineConfiguration) {
HistoricCaseInstanceEntityManager historicCaseInstanceEntityManager = cmmnEngineConfiguration.getHistoricCaseInstanceEntityManager();
HistoricMilestoneInstanceEntityManager historicMilestoneInstanceEntityManager = cmmnEngineConfiguration.getHistoricMilestoneInstanceEntityManager();
historicMilestoneInstanceEntityManager.bulkDeleteHistoricMilestoneInstancesForCaseInstanceIds(caseInstanceIds);
HistoricPlanItemInstanceEntityManager historicPlanItemInstanceEntityManager = cmmnEngineConfiguration.getHistoricPlanItemInstanceEntityManager();
historicPlanItemInstanceEntityManager.bulkDeleteHistoricPlanItemInstancesForCaseInstanceIds(caseInstanceIds);
HistoricIdentityLinkService historicIdentityLinkService = cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getHistoricIdentityLinkService();
historicIdentityLinkService.bulkDeleteHistoricIdentityLinksByScopeIdsAndScopeType(caseInstanceIds, ScopeTypes.CMMN);
historicIdentityLinkService.bulkDeleteHistoricIdentityLinksByScopeIdsAndScopeType(caseInstanceIds, ScopeTypes.PLAN_ITEM);
if (cmmnEngineConfiguration.isEnableEntityLinks()) {
cmmnEngineConfiguration.getEntityLinkServiceConfiguration().getHistoricEntityLinkService()
.bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(ScopeTypes.CMMN, caseInstanceIds);
}
HistoricVariableInstanceEntityManager historicVariableInstanceEntityManager = cmmnEngineConfiguration.getVariableServiceConfiguration().getHistoricVariableInstanceEntityManager(); | historicVariableInstanceEntityManager.bulkDeleteHistoricVariableInstancesByScopeIdsAndScopeType(caseInstanceIds, ScopeTypes.CMMN);
TaskHelper.bulkDeleteHistoricTaskInstancesByCaseInstanceIds(caseInstanceIds, cmmnEngineConfiguration);
historicCaseInstanceEntityManager.bulkDeleteHistoricCaseInstances(caseInstanceIds);
// Also delete any sub cases that may be active
List<String> subCaseInstanceIds = historicCaseInstanceEntityManager.findHistoricCaseInstanceIdsByParentIds(caseInstanceIds);
if (subCaseInstanceIds != null && !subCaseInstanceIds.isEmpty()) {
List<List<String>> partitionedSubCaseInstanceIds = CollectionUtil.partition(subCaseInstanceIds, MAX_SUB_CASE_INSTANCES);
for (List<String> batchSubCaseInstanceIds : partitionedSubCaseInstanceIds) {
cmmnEngineConfiguration.getCmmnHistoryManager().recordBulkDeleteHistoricCaseInstances(batchSubCaseInstanceIds);
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\CmmnHistoryHelper.java | 1 |
请完成以下Java代码 | private static final ArrayKey buildCacheKey(final Properties ctx)
{
return new ArrayKey(
Env.getAD_Client_ID(ctx),
Env.getAD_Role_ID(ctx),
Env.getAD_User_ID(ctx),
Env.getAD_Language(ctx));
}
/**
* Method used to compare if to contexts are considered to be equal from caching perspective.
* Equality from caching perspective means that the following is equal:
* <ul>
* <li>AD_Client_ID
* <li>AD_Role_ID
* <li>AD_User_ID
* <li>AD_Language
* </ul>
*
* @param ctx1
* @param ctx2 | * @return true if given contexts shall be considered equal from caching perspective
*/
public static final boolean isSameCtx(final Properties ctx1, final Properties ctx2)
{
if (ctx1 == ctx2)
{
return true;
}
if (ctx1 == null || ctx2 == null)
{
return false;
}
return buildCacheKey(ctx1).equals(buildCacheKey(ctx2));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CacheCtxParamDescriptor.java | 1 |
请完成以下Java代码 | public Class<? extends BaseElement> getHandledType() {
return IntermediateCatchEvent.class;
}
@Override
protected void executeParse(BpmnParse bpmnParse, IntermediateCatchEvent event) {
ActivityImpl nestedActivity = null;
EventDefinition eventDefinition = null;
if (!event.getEventDefinitions().isEmpty()) {
eventDefinition = event.getEventDefinitions().get(0);
}
if (eventDefinition == null) {
nestedActivity = createActivityOnCurrentScope(bpmnParse, event, BpmnXMLConstants.ELEMENT_EVENT_CATCH);
nestedActivity.setAsync(event.isAsynchronous());
nestedActivity.setExclusive(!event.isNotExclusive());
} else {
ScopeImpl scope = bpmnParse.getCurrentScope();
String eventBasedGatewayId = getPrecedingEventBasedGateway(bpmnParse, event);
if (eventBasedGatewayId != null) {
ActivityImpl gatewayActivity = scope.findActivity(eventBasedGatewayId);
nestedActivity = createActivityOnScope(bpmnParse, event, BpmnXMLConstants.ELEMENT_EVENT_CATCH, gatewayActivity);
} else {
nestedActivity = createActivityOnScope(bpmnParse, event, BpmnXMLConstants.ELEMENT_EVENT_CATCH, scope);
} | nestedActivity.setAsync(event.isAsynchronous());
nestedActivity.setExclusive(!event.isNotExclusive());
// Catch event behavior is the same for all types
nestedActivity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createIntermediateCatchEventActivityBehavior(event));
if (eventDefinition instanceof TimerEventDefinition
|| eventDefinition instanceof SignalEventDefinition
|| eventDefinition instanceof MessageEventDefinition) {
bpmnParse.getBpmnParserHandlers().parseElement(bpmnParse, eventDefinition);
} else {
LOGGER.warn("Unsupported intermediate catch event type for event {}", event.getId());
}
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\IntermediateCatchEventParseHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | 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 static ImmutableAttributeSet extractAttributeSet(@NonNull HUQRCode huQRCode)
{
final ImmutableList<HUQRCodeAttribute> huQRCodeAttributes = huQRCode.getAttributes();
if (huQRCodeAttributes.isEmpty())
{
return ImmutableAttributeSet.EMPTY;
}
final ImmutableAttributeSet.Builder builder = ImmutableAttributeSet.builder();
for (final HUQRCodeAttribute huQRCodeAttribute : huQRCodeAttributes)
{
builder.attributeValue(huQRCodeAttribute.getCode(), huQRCodeAttribute.getValue());
}
return builder.build();
}
@NonNull
private IHUProductStorage getSingleStorage(final I_M_HU hu)
{
final IHUStorage huStorage = handlingUnitsBL
.getStorageFactory()
.getStorage(hu);
final List<IHUProductStorage> huProductStorages = huStorage.getProductStorages();
if (huProductStorages.isEmpty())
{
throw new AdempiereException("Empty HU is not handled");
}
else if (huProductStorages.size() == 1) | {
return huProductStorages.get(0);
}
else
{
throw new AdempiereException("Multi product storage is not handled");
}
}
private DocTypeId getInventoryDocTypeId(@NonNull final ClientAndOrgId clientAndOrgId)
{
return docTypeDAO.getDocTypeId(DocTypeQuery.builder()
.docBaseType(DocBaseType.MaterialPhysicalInventory)
.docSubType(DocSubType.SingleHUInventory)
.adClientId(clientAndOrgId.getClientId().getRepoId())
.adOrgId(clientAndOrgId.getOrgId().getRepoId())
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUQtyService.java | 1 |
请完成以下Java代码 | protected void checkInvalidDefinitionId(String definitionId) {
ensureNotNull("Invalid case definition id", "caseDefinitionId", definitionId);
}
@Override
protected void checkDefinitionFound(String definitionId, CaseDefinitionEntity definition) {
ensureNotNull(CaseDefinitionNotFoundException.class, "no deployed case definition found with id '" + definitionId + "'", "caseDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKey(String definitionKey, CaseDefinitionEntity definition) {
ensureNotNull(CaseDefinitionNotFoundException.class, "no case definition deployed with key '" + definitionKey + "'", "caseDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKeyAndTenantId(String definitionKey, String tenantId, CaseDefinitionEntity definition) {
ensureNotNull(CaseDefinitionNotFoundException.class, "no case definition deployed with key '" + definitionKey + "' and tenant-id '" + tenantId + "'", "caseDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId, CaseDefinitionEntity definition) { | ensureNotNull(CaseDefinitionNotFoundException.class, "no case definition deployed with key = '" + definitionKey + "', version = '" + definitionVersion + "'"
+ " and tenant-id = '" + tenantId + "'", "caseDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId, CaseDefinitionEntity definition) {
throw new UnsupportedOperationException("Version tag is not implemented in case definition."); }
@Override
protected void checkInvalidDefinitionByDeploymentAndKey(String deploymentId, String definitionKey, CaseDefinitionEntity definition) {
ensureNotNull(CaseDefinitionNotFoundException.class, "no case definition deployed with key = '" + definitionKey + "' in deployment = '" + deploymentId + "'", "caseDefinition", definition);
}
@Override
protected void checkInvalidDefinitionWasCached(String deploymentId, String definitionId, CaseDefinitionEntity definition) {
ensureNotNull("deployment '" + deploymentId + "' didn't put case definition '" + definitionId + "' in the cache", "cachedCaseDefinition", definition);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\CaseDefinitionCache.java | 1 |
请完成以下Java代码 | public void logout(HttpServletRequest request, HttpServletResponse response,
@Nullable Authentication authentication) {
super.logout(request, response, authentication);
if (authentication != null) {
this.tokenRepository.removeUserTokens(authentication.getName());
}
}
protected String generateSeriesData() {
byte[] newSeries = new byte[this.seriesLength];
this.random.nextBytes(newSeries);
return new String(Base64.getEncoder().encode(newSeries));
}
protected String generateTokenData() {
byte[] newToken = new byte[this.tokenLength];
this.random.nextBytes(newToken);
return new String(Base64.getEncoder().encode(newToken));
}
private void addCookie(PersistentRememberMeToken token, HttpServletRequest request, HttpServletResponse response) {
setCookie(new String[] { token.getSeries(), token.getTokenValue() }, getTokenValiditySeconds(), request, | response);
}
public void setSeriesLength(int seriesLength) {
this.seriesLength = seriesLength;
}
public void setTokenLength(int tokenLength) {
this.tokenLength = tokenLength;
}
@Override
public void setTokenValiditySeconds(int tokenValiditySeconds) {
Assert.isTrue(tokenValiditySeconds > 0, "tokenValiditySeconds must be positive for this implementation");
super.setTokenValiditySeconds(tokenValiditySeconds);
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\rememberme\PersistentTokenBasedRememberMeServices.java | 1 |
请完成以下Java代码 | public void setHU_BestBeforeDate (final @Nullable java.sql.Timestamp HU_BestBeforeDate)
{
set_ValueNoCheck (COLUMNNAME_HU_BestBeforeDate, HU_BestBeforeDate);
}
@Override
public java.sql.Timestamp getHU_BestBeforeDate()
{
return get_ValueAsTimestamp(COLUMNNAME_HU_BestBeforeDate);
}
@Override
public void setHU_Expired (final @Nullable java.lang.String HU_Expired)
{
set_ValueNoCheck (COLUMNNAME_HU_Expired, HU_Expired);
}
@Override
public java.lang.String getHU_Expired()
{
return get_ValueAsString(COLUMNNAME_HU_Expired);
}
@Override
public void setHU_ExpiredWarnDate (final @Nullable java.sql.Timestamp HU_ExpiredWarnDate)
{
set_ValueNoCheck (COLUMNNAME_HU_ExpiredWarnDate, HU_ExpiredWarnDate);
} | @Override
public java.sql.Timestamp getHU_ExpiredWarnDate()
{
return get_ValueAsTimestamp(COLUMNNAME_HU_ExpiredWarnDate);
}
@Override
public void setM_HU_ID (final int M_HU_ID)
{
if (M_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID);
}
@Override
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_BestBefore_V.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class TemplateEngineConfigurations {
@Configuration(proxyBeanMethods = false)
static class DefaultTemplateEngineConfiguration {
@Bean
@ConditionalOnMissingBean(ISpringTemplateEngine.class)
SpringTemplateEngine templateEngine(ThymeleafProperties properties,
ObjectProvider<ITemplateResolver> templateResolvers, ObjectProvider<IDialect> dialects) {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(properties.isEnableSpringElCompiler());
engine.setRenderHiddenMarkersBeforeCheckboxes(properties.isRenderHiddenMarkersBeforeCheckboxes());
templateResolvers.orderedStream().forEach(engine::addTemplateResolver);
dialects.orderedStream().forEach(engine::addDialect);
return engine;
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.REACTIVE)
static class ReactiveTemplateEngineConfiguration { | @Bean
@ConditionalOnMissingBean(ISpringWebFluxTemplateEngine.class)
SpringWebFluxTemplateEngine templateEngine(ThymeleafProperties properties,
ObjectProvider<ITemplateResolver> templateResolvers, ObjectProvider<IDialect> dialects) {
SpringWebFluxTemplateEngine engine = new SpringWebFluxTemplateEngine();
engine.setEnableSpringELCompiler(properties.isEnableSpringElCompiler());
engine.setRenderHiddenMarkersBeforeCheckboxes(properties.isRenderHiddenMarkersBeforeCheckboxes());
templateResolvers.orderedStream().forEach(engine::addTemplateResolver);
dialects.orderedStream().forEach(engine::addDialect);
return engine;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-thymeleaf\src\main\java\org\springframework\boot\thymeleaf\autoconfigure\TemplateEngineConfigurations.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static class LU
{
@NonNull @Getter(AccessLevel.NONE) I_M_HU hu;
@NonNull TUsList tus;
boolean isPreExistingLU;
public static LU of(@NonNull final I_M_HU lu, @NonNull final TU... tus)
{
return builder().hu(lu).tus(TUsList.of(tus)).build();
}
public static LU of(@NonNull final I_M_HU lu, @NonNull final List<TU> tus)
{
return builder().hu(lu).tus(TUsList.of(tus)).build();
}
public static LU of(@NonNull final I_M_HU lu, @NonNull final TUsList tus)
{
return builder().hu(lu).tus(tus).build();
}
public LU markedAsPreExistingLU()
{
return this.isPreExistingLU ? this : toBuilder().isPreExistingLU(true).build();
}
public HuId getId() {return HuId.ofRepoId(hu.getM_HU_ID());}
public I_M_HU toHU() {return hu;}
public Stream<I_M_HU> streamAllLUAndTURecords()
{
return Stream.concat(Stream.of(hu), tus.streamHURecords());
}
public Stream<TU> streamTUs() {return tus.stream();}
public QtyTU getQtyTU() {return tus.getQtyTU();}
public LU mergeWith(@NonNull final LU other)
{
if (this.hu.getM_HU_ID() != other.hu.getM_HU_ID())
{
throw new AdempiereException("Cannot merge " + this + " with " + other + " because they don't have the same HU");
}
return builder()
.hu(this.hu)
.isPreExistingLU(this.isPreExistingLU && other.isPreExistingLU)
.tus(this.tus.mergeWith(other.tus))
.build();
}
private static List<LU> mergeLists(final List<LU> list1, final List<LU> list2)
{
if (list2.isEmpty())
{ | return list1;
}
if (list1.isEmpty())
{
return list2;
}
else
{
final HashMap<HuId, LU> lusNew = new HashMap<>();
list1.forEach(lu -> lusNew.put(lu.getId(), lu));
list2.forEach(lu -> lusNew.compute(lu.getId(), (luId, existingLU) -> existingLU == null ? lu : existingLU.mergeWith(lu)));
return ImmutableList.copyOf(lusNew.values());
}
}
public boolean containsAnyOfHUIds(final Collection<HuId> huIds)
{
if (huIds.isEmpty()) {return false;}
return huIds.contains(getId()) // LU matches
|| tus.containsAnyOfHUIds(huIds); // any of the TU matches
}
public void forEachAffectedHU(@NonNull final LUTUCUConsumer consumer)
{
tus.forEachAffectedHU(this, consumer);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\LUTUResult.java | 2 |
请完成以下Java代码 | public ImmutableList<I_PP_OrderCandidate_PP_Order> getPPOrderAllocations(@NonNull final PPOrderId ppOrderId)
{
return queryBL
.createQueryBuilder(I_PP_OrderCandidate_PP_Order.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_PP_OrderCandidate_PP_Order.COLUMNNAME_PP_Order_ID, ppOrderId.getRepoId())
.create()
.listImmutable(I_PP_OrderCandidate_PP_Order.class);
}
@NonNull
public ImmutableList<I_PP_Order> getByProductBOMId(@NonNull final ProductBOMId productBOMId)
{
return queryBL
.createQueryBuilder(I_PP_Order.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_PP_Order.COLUMNNAME_PP_Product_BOM_ID, productBOMId.getRepoId())
.create()
.listImmutable(I_PP_Order.class);
}
@NonNull
public Stream<I_PP_Order> streamDraftedPPOrdersFor(@NonNull final ProductBOMVersionsId bomVersionsId)
{ | final ManufacturingOrderQuery query = ManufacturingOrderQuery.builder()
.bomVersionsId(bomVersionsId)
.onlyDrafted(true)
.build();
final IQueryBuilder<I_PP_Order> ppOrderQueryBuilder = toSqlQueryBuilder(query);
//dev-note: make sure there are no material transactions already created
final IQuery<I_PP_Cost_Collector> withMaterialTransactionsQuery = queryBL.createQueryBuilder(I_PP_Cost_Collector.class)
.addInSubQueryFilter(I_PP_Cost_Collector.COLUMNNAME_PP_Order_ID, I_PP_Order.COLUMNNAME_PP_Order_ID, ppOrderQueryBuilder.create())
.create();
return ppOrderQueryBuilder
.addNotInSubQueryFilter(I_PP_Order.COLUMNNAME_PP_Order_ID, I_PP_Cost_Collector.COLUMNNAME_PP_Order_ID, withMaterialTransactionsQuery)
.create()
.iterateAndStream();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\impl\PPOrderDAO.java | 1 |
请完成以下Java代码 | public Set<DocumentPath> getReferencingDocumentPaths()
{
return ImmutableSet.of();
}
/**
* Always returns {@link I_M_PickingSlot#Table_Name}
*/
@Override
public String getTableNameOrNull(@Nullable final DocumentId ignored)
{
return I_M_PickingSlot.Table_Name;
}
@Override
public ViewId getParentViewId()
{
return parentViewId;
}
@Override
public DocumentId getParentRowId()
{
return parentRowId;
}
@Override
public long size()
{
return rows.size();
}
@Override
public int getQueryLimit()
{
return -1;
}
@Override
public boolean isQueryLimitHit()
{
return false;
}
@Override
public ViewResult getPage(
final int firstRow,
final int pageLength,
@NonNull final ViewRowsOrderBy orderBys)
{
final List<PickingSlotRow> pageRows = rows.getPage(firstRow, pageLength);
return ViewResult.ofViewAndPage(this, firstRow, pageLength, orderBys.toDocumentQueryOrderByList(), pageRows);
}
@Override
public PickingSlotRow getById(@NonNull final DocumentId id) throws EntityNotFoundException
{
return rows.getById(id);
}
@Override
public LookupValuesPage getFilterParameterDropdown(final String filterId, final String filterParameterName, final ViewFilterParameterLookupEvaluationCtx ctx)
{
throw new UnsupportedOperationException();
}
@Override
public LookupValuesPage getFilterParameterTypeahead(final String filterId, final String filterParameterName, final String query, final ViewFilterParameterLookupEvaluationCtx ctx)
{
throw new UnsupportedOperationException();
}
@Override
public DocumentFilterList getStickyFilters()
{
return DocumentFilterList.EMPTY;
}
@Override
public DocumentFilterList getFilters()
{
return filters;
}
@Override
public DocumentQueryOrderByList getDefaultOrderBys()
{
return DocumentQueryOrderByList.EMPTY;
} | @Override
public SqlViewRowsWhereClause getSqlWhereClause(final DocumentIdsSelection rowIds, final SqlOptions sqlOpts)
{
// TODO Auto-generated method stub
return null;
}
@Override
public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass)
{
throw new UnsupportedOperationException();
}
@Override
public Stream<? extends IViewRow> streamByIds(final DocumentIdsSelection rowIds)
{
return rows.streamByIds(rowIds);
}
@Override
public void notifyRecordsChanged(
@NonNull final TableRecordReferenceSet recordRefs,
final boolean watchedByFrontend)
{
// TODO Auto-generated method stub
}
@Override
public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors()
{
return additionalRelatedProcessDescriptors;
}
/**
* @return the {@code M_ShipmentSchedule_ID} of the packageable line that is currently selected within the {@link PackageableView}.
*/
@NonNull
public ShipmentScheduleId getCurrentShipmentScheduleId()
{
return currentShipmentScheduleId;
}
@Override
public void invalidateAll()
{
rows.invalidateAll();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotView.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers().antMatchers("/me")
.and()
.authorizeRequests()
.antMatchers("/me").access("#oauth2.hasScope('read')");
// @formatter:on
}
/**
* Id of the resource that you are letting the client have access to.
* Supposing you have another api ("say api2"), then you can customize the
* access within resource server to define what api is for what resource id.
* <br>
* <br> | *
* So suppose you have 2 APIs, then you can define 2 resource servers.
* <ol>
* <li>Client 1 has been configured for access to resourceid1, so he can
* only access "api1" if the resource server configures the resourceid to
* "api1".</li>
* <li>Client 1 can't access resource server 2 since it has configured the
* resource id to "api2"
* </li>
* </ol>
*
*/
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("apis");
}
} | repos\spring-boot-microservices-master\auth-server\src\main\java\com\rohitghatol\microservice\auth\config\ResourceServerConfiguration.java | 2 |
请完成以下Java代码 | public void setDD_OrderLine(final org.eevolution.model.I_DD_OrderLine DD_OrderLine)
{
set_ValueFromPO(COLUMNNAME_DD_OrderLine_ID, org.eevolution.model.I_DD_OrderLine.class, DD_OrderLine);
}
@Override
public void setDD_OrderLine_ID (final int DD_OrderLine_ID)
{
if (DD_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_DD_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DD_OrderLine_ID, DD_OrderLine_ID);
}
@Override
public int getDD_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_DD_OrderLine_ID);
}
@Override
public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance()
{
return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class);
}
@Override
public void setM_AttributeSetInstance(final org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance);
}
@Override
public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID)
{
if (M_AttributeSetInstance_ID < 0)
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null);
else
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID);
}
@Override
public int getM_AttributeSetInstance_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
} | @Override
public void setQtyDelivered (final BigDecimal QtyDelivered)
{
set_Value (COLUMNNAME_QtyDelivered, QtyDelivered);
}
@Override
public BigDecimal getQtyDelivered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDelivered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyInTransit (final BigDecimal QtyInTransit)
{
set_Value (COLUMNNAME_QtyInTransit, QtyInTransit);
}
@Override
public BigDecimal getQtyInTransit()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInTransit);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOrdered (final BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_OrderLine_Alternative.java | 1 |
请完成以下Java代码 | public int getM_HU_PI_Item_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_ID);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); | return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSnapshot_UUID (final java.lang.String Snapshot_UUID)
{
set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID);
}
@Override
public java.lang.String getSnapshot_UUID()
{
return get_ValueAsString(COLUMNNAME_Snapshot_UUID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item_Snapshot.java | 1 |
请完成以下Java代码 | public void setEventType (java.lang.String EventType)
{
set_Value (COLUMNNAME_EventType, EventType);
}
/** Get Ereignisart.
@return Ereignisart */
@Override
public java.lang.String getEventType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EventType);
}
/** Set Kommentar/Hilfe.
@param Help
Comment or Hint
*/
@Override
public void setHelp (java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Kommentar/Hilfe.
@return Comment or Hint
*/
@Override
public java.lang.String getHelp ()
{
return (java.lang.String)get_Value(COLUMNNAME_Help);
}
/** 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);
}
/**
* RuleType AD_Reference_ID=53235
* Reference name: AD_Rule_RuleType
*/
public static final int RULETYPE_AD_Reference_ID=53235;
/** AspectOrientProgram = A */
public static final String RULETYPE_AspectOrientProgram = "A";
/** JSR223ScriptingAPIs = S */
public static final String RULETYPE_JSR223ScriptingAPIs = "S";
/** JSR94RuleEngineAPI = R */
public static final String RULETYPE_JSR94RuleEngineAPI = "R";
/** SQL = Q */ | public static final String RULETYPE_SQL = "Q";
/** Set Rule Type.
@param RuleType Rule Type */
@Override
public void setRuleType (java.lang.String RuleType)
{
set_Value (COLUMNNAME_RuleType, RuleType);
}
/** Get Rule Type.
@return Rule Type */
@Override
public java.lang.String getRuleType ()
{
return (java.lang.String)get_Value(COLUMNNAME_RuleType);
}
/** Set Skript.
@param Script
Dynamic Java Language Script to calculate result
*/
@Override
public void setScript (java.lang.String Script)
{
set_Value (COLUMNNAME_Script, Script);
}
/** Get Skript.
@return Dynamic Java Language Script to calculate result
*/
@Override
public java.lang.String getScript ()
{
return (java.lang.String)get_Value(COLUMNNAME_Script);
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Rule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
//因为使用JWT,所以不需要HttpSession
.sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
//OPTIONS请求全部放行
.antMatchers( HttpMethod.OPTIONS, "/**").permitAll()
//登录接口放行
.antMatchers("/auth/login").permitAll()
//其他接口全部接受验证
.anyRequest().authenticated();
//使用自定义的 Token过滤器 验证请求的Token是否合法
http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
http.headers().cacheControl(); | }
@Bean
public JwtTokenFilter authenticationTokenFilterBean() throws Exception {
return new JwtTokenFilter();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
} | repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\config\SecurityConfig.java | 2 |
请完成以下Java代码 | public BigDecimal getQtyTU()
{
return Quantitys.toBigDecimalOrNull(olCandEffectiveValuesBL.getQtyItemCapacity_Effective(olCand));
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
values.setQtyTU(qtyPacks);
}
@Override
public int getC_BPartner_ID()
{
final BPartnerId bpartnerId = olCandEffectiveValuesBL.getBPartnerEffectiveId(olCand);
return BPartnerId.toRepoId(bpartnerId);
}
@Override
public void setC_BPartner_ID(final int partnerId) | {
olCand.setC_BPartner_Override_ID(partnerId);
values.setBpartnerId(BPartnerId.ofRepoIdOrNull(partnerId));
}
@Override
public boolean isInDispute()
{
// order line has no IsInDispute flag
return values.isInDispute();
}
@Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OLCandHUPackingAware.java | 1 |
请完成以下Java代码 | public boolean isNoCache()
{
final Boolean noCache = noCacheRef.get();
return noCache != null && noCache;
}
@NonNull
public IAutoCloseable temporaryDisableCache()
{
final Boolean noCachePrev = noCacheRef.get();
noCacheRef.set(Boolean.TRUE);
return new IAutoCloseable()
{
boolean closed = false;
@Override
public void close()
{
if (closed)
{
return;
}
closed = true;
noCacheRef.set(noCachePrev);
}
};
}
private static boolean isApplicationDictionaryCache(@NonNull final String cacheName, @NonNull final ImmutableSet<CacheLabel> labels)
{ | final boolean anyApplicationDictionaryTableNames = labels.stream().anyMatch(CacheLabel::isApplicationDictionaryTableName);
if (!anyApplicationDictionaryTableNames)
{
return false;
}
final boolean anyNonApplicationDictionaryTableNames = labels.stream().anyMatch(label -> isNonApplicationDictionaryTableName(label, cacheName));
return !anyNonApplicationDictionaryTableNames;
}
private static boolean isNonApplicationDictionaryTableName(@NonNull final CacheLabel label, @NonNull final String cacheName)
{
return !label.equalsByName(cacheName) //ignore the label created from this.cacheName as it's not necessary a table name
&& !label.containsNoTableNameMarker()
&& !label.isApplicationDictionaryTableName();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\ThreadLocalCacheController.java | 1 |
请完成以下Java代码 | public boolean isInheritable()
{
return false;
}
/**
* @return preference type (see X_AD_Role.PREFERENCETYPE_*)
*/
public String getPreferenceType()
{
return preferenceType;
}
/**
* Show (Value) Preference Menu
*
* @return true if preference type is not {@link #NONE}.
*/
public boolean isShowPreference()
{
return !isNone();
}
public boolean isNone()
{
return this == NONE;
}
public boolean isClient()
{
return this == CLIENT;
}
public boolean isOrganization()
{ | return this == ORGANIZATION;
}
public boolean isUser()
{
return this == USER;
}
/**
*
* @return true if this level allows user to view table record change log (i.e. this level is {@link #CLIENT})
*/
public boolean canViewRecordChangeLog()
{
return isClient();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\UserPreferenceLevelConstraint.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getTaskUrl() { | return taskUrl;
}
public void setTaskUrl(String taskUrl) {
this.taskUrl = taskUrl;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
public List<String> getMessage() {
return message;
}
public void setMessage(List<String> message) {
this.message = message;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\engine\EventResponse.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void saveImage(Long bookId, File image) {
try (InputStream imageInStream = new FileInputStream(image)) {
jdbcTemplate.execute(
"INSERT INTO book_image (book_id, filename, blob_image) VALUES (?, ?, ?)",
new AbstractLobCreatingPreparedStatementCallback(lobHandler) {
protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {
ps.setLong(1, 1L);
ps.setString(2, image.getName());
lobCreator.setBlobAsBinaryStream(ps, 3, imageInStream, (int) image.length());
}
}
);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public List<Map<String, InputStream>> findImageByBookId(Long bookId) {
List<Map<String, InputStream>> result = jdbcTemplate.query(
"select id, book_id, filename, blob_image from book_image where book_id = ?",
new Object[]{bookId},
new RowMapper<Map<String, InputStream>>() {
public Map<String, InputStream> mapRow(ResultSet rs, int i) throws SQLException {
String fileName = rs.getString("filename"); | InputStream blob_image_stream = lobHandler.getBlobAsBinaryStream(rs, "blob_image");
// byte array
//Map<String, Object> results = new HashMap<>();
//byte[] blobBytes = lobHandler.getBlobAsBytes(rs, "blob_image");
//results.put("BLOB", blobBytes);
Map<String, InputStream> results = new HashMap<>();
results.put(fileName, blob_image_stream);
return results;
}
});
return result;
}
} | repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\repository\JdbcBookRepository.java | 2 |
请完成以下Java代码 | public Boolean getIsUseCommonJWorkManager() {
return isUseCommonJWorkManager;
}
public void setIsUseCommonJWorkManager(Boolean isUseCommonJWorkManager) {
this.isUseCommonJWorkManager = isUseCommonJWorkManager;
}
public String getCommonJWorkManagerName() {
return commonJWorkManagerName;
}
public void setCommonJWorkManagerName(String commonJWorkManagerName) {
this.commonJWorkManagerName = commonJWorkManagerName;
}
// misc //////////////////////////////////////////////////////////////////
@Override
public int hashCode() {
return 17; | }
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (other == this) {
return true;
}
if (!(other instanceof JcaExecutorServiceConnector)) {
return false;
}
return true;
}
} | repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\JcaExecutorServiceConnector.java | 1 |
请完成以下Java代码 | public String getState() {
return state;
}
public Date getCreateTime() {
return createTime;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public static HistoricVariableInstanceDto fromHistoricVariableInstance(HistoricVariableInstance historicVariableInstance) {
HistoricVariableInstanceDto dto = new HistoricVariableInstanceDto();
dto.id = historicVariableInstance.getId();
dto.name = historicVariableInstance.getName();
dto.processDefinitionKey = historicVariableInstance.getProcessDefinitionKey();
dto.processDefinitionId = historicVariableInstance.getProcessDefinitionId();
dto.processInstanceId = historicVariableInstance.getProcessInstanceId();
dto.executionId = historicVariableInstance.getExecutionId();
dto.activityInstanceId = historicVariableInstance.getActivityInstanceId();
dto.caseDefinitionKey = historicVariableInstance.getCaseDefinitionKey();
dto.caseDefinitionId = historicVariableInstance.getCaseDefinitionId();
dto.caseInstanceId = historicVariableInstance.getCaseInstanceId();
dto.caseExecutionId = historicVariableInstance.getCaseExecutionId(); | dto.taskId = historicVariableInstance.getTaskId();
dto.tenantId = historicVariableInstance.getTenantId();
dto.state = historicVariableInstance.getState();
dto.createTime = historicVariableInstance.getCreateTime();
dto.removalTime = historicVariableInstance.getRemovalTime();
dto.rootProcessInstanceId = historicVariableInstance.getRootProcessInstanceId();
if(historicVariableInstance.getErrorMessage() == null) {
VariableValueDto.fromTypedValue(dto, historicVariableInstance.getTypedValue());
}
else {
dto.errorMessage = historicVariableInstance.getErrorMessage();
dto.type = VariableValueDto.toRestApiTypeName(historicVariableInstance.getTypeName());
}
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricVariableInstanceDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Book implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
private String title;
private String isbn;
private String genre;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn; | }
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title
+ ", isbn=" + isbn + ", genre=" + genre + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootAvoidEntityInDtoViaConstructor\src\main\java\com\bookstore\entity\Book.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ACLContext {
@Autowired
DataSource dataSource;
@Bean
public SpringCacheBasedAclCache aclCache() {
final ConcurrentMapCache aclCache = new ConcurrentMapCache("acl_cache");
return new SpringCacheBasedAclCache(aclCache, permissionGrantingStrategy(), aclAuthorizationStrategy());
}
@Bean
public PermissionGrantingStrategy permissionGrantingStrategy() {
return new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger());
}
@Bean
public AclAuthorizationStrategy aclAuthorizationStrategy() {
return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ADMIN"));
} | @Bean
public MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler() {
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
AclPermissionEvaluator permissionEvaluator = new AclPermissionEvaluator(aclService());
expressionHandler.setPermissionEvaluator(permissionEvaluator);
expressionHandler.setPermissionCacheOptimizer(new AclPermissionCacheOptimizer(aclService()));
return expressionHandler;
}
@Bean
public LookupStrategy lookupStrategy() {
return new BasicLookupStrategy(dataSource, aclCache(), aclAuthorizationStrategy(), new ConsoleAuditLogger());
}
@Bean
public JdbcMutableAclService aclService() {
return new JdbcMutableAclService(dataSource, lookupStrategy(), aclCache());
}
} | repos\tutorials-master\spring-security-modules\spring-security-acl\src\main\java\com\baeldung\acl\config\ACLContext.java | 2 |
请完成以下Java代码 | protected static DefaultDecisionRequirementsDiagramCanvas initDecisionRequirementsDiagramCanvas(DmnDefinition dmnDefinition, String imageType,
String activityFontName, String labelFontName, String annotationFontName, ClassLoader customClassLoader) {
// We need to calculate maximum values to know how big the image will be in its entirety
double minX = Double.MAX_VALUE;
double maxX = 0;
double minY = Double.MAX_VALUE;
double maxY = 0;
for (DecisionService decisionService : dmnDefinition.getDecisionServices()) {
GraphicInfo decisionServiceInfo = dmnDefinition.getGraphicInfo(decisionService.getId());
if (decisionServiceInfo == null) {
throw new FlowableImageException("Could not find graphic info for decision service: " + decisionService.getId());
}
// width
if (decisionServiceInfo.getX() + decisionServiceInfo.getWidth() > maxX) {
maxX = decisionServiceInfo.getX() + decisionServiceInfo.getWidth();
}
if (decisionServiceInfo.getX() < minX) {
minX = decisionServiceInfo.getX();
}
// height
if (decisionServiceInfo.getY() + decisionServiceInfo.getHeight() > maxY) {
maxY = decisionServiceInfo.getY() + decisionServiceInfo.getHeight();
}
if (decisionServiceInfo.getY() < minY) {
minY = decisionServiceInfo.getY();
}
}
return new DefaultDecisionRequirementsDiagramCanvas((int) maxX + 10, (int) maxY + 10, (int) minX, (int) minY,
imageType, activityFontName, labelFontName, annotationFontName, customClassLoader); | }
public Map<Class<? extends NamedElement>, ActivityDrawInstruction> getElementDrawInstructions() {
return elementDrawInstructions;
}
public void setElementDrawInstructions(
Map<Class<? extends NamedElement>, ActivityDrawInstruction> elementDrawInstructions) {
this.elementDrawInstructions = elementDrawInstructions;
}
protected interface ActivityDrawInstruction {
void draw(DefaultDecisionRequirementsDiagramCanvas decisionRequirementsDiagramCanvas, DmnDefinition dmnDefinition, NamedElement NamedElement);
}
} | repos\flowable-engine-main\modules\flowable-dmn-image-generator\src\main\java\org\flowable\dmn\image\impl\DefaultDecisionRequirementsDiagramGenerator.java | 1 |
请完成以下Java代码 | private HttpMessageConverter<Object> createXmlHttpMessageConverter() {
final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
xmlConverter.setMarshaller(xstreamMarshaller);
xmlConverter.setUnmarshaller(xstreamMarshaller);
return xmlConverter;
}
// Etags
// If we're not using Spring Boot we can make use of
// AbstractAnnotationConfigDispatcherServletInitializer#getServletFilters
@Bean | public FilterRegistrationBean<ShallowEtagHeaderFilter> shallowEtagHeaderFilter() {
FilterRegistrationBean<ShallowEtagHeaderFilter> filterRegistrationBean =
new FilterRegistrationBean<>(new ShallowEtagHeaderFilter());
filterRegistrationBean.addUrlPatterns("/foos/*");
filterRegistrationBean.setName("etagFilter");
return filterRegistrationBean;
}
// We can also just declare the filter directly
// @Bean
// public ShallowEtagHeaderFilter shallowEtagHeaderFilter() {
// return new ShallowEtagHeaderFilter();
// }
} | repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\spring\WebConfig.java | 1 |
请完成以下Java代码 | public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if(obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final IdBook other = (IdBook) obj; | if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 3;
hash = 89 * hash + Objects.hashCode(this.id);
return hash;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootLombokEqualsAndHashCode\src\main\java\com\app\IdBook.java | 1 |
请完成以下Java代码 | private long invalidateForRecordNoFail(final TableRecordReference recordRef)
{
return streamCaches()
.mapToLong(cache -> invalidateNoFail(cache, recordRef))
.sum();
}
private static long invalidateNoFail(@Nullable final CacheInterface cacheInstance)
{
try (final IAutoCloseable ignored = CacheMDC.putCache(cacheInstance))
{
if (cacheInstance == null)
{
return 0;
}
return cacheInstance.reset();
}
catch (final Exception ex)
{
// log but don't fail
logger.warn("Error while resetting {}. Ignored.", cacheInstance, ex);
return 0;
} | }
private static long invalidateNoFail(final CacheInterface cacheInstance, final TableRecordReference recordRef)
{
try (final IAutoCloseable ignored = CacheMDC.putCache(cacheInstance))
{
return cacheInstance.resetForRecordId(recordRef);
}
catch (final Exception ex)
{
// log but don't fail
logger.warn("Error while resetting {} for {}. Ignored.", cacheInstance, recordRef, ex);
return 0;
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CacheMgt.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SpringBootAdminWarApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(SpringBootAdminWarApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application;
}
@Profile("insecure")
@Configuration(proxyBeanMethods = false)
public static class SecurityPermitAllConfig {
private final AdminServerProperties adminServer;
public SecurityPermitAllConfig(AdminServerProperties adminServer) {
this.adminServer = adminServer;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests.anyRequest().permitAll())
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
PathPatternRequestMatcher.withDefaults().matcher(POST, this.adminServer.path("/instances")),
PathPatternRequestMatcher.withDefaults()
.matcher(DELETE, this.adminServer.path("/instances/*")),
PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/actuator/**"))));
return http.build();
}
}
@Profile("secure")
@Configuration(proxyBeanMethods = false)
public static class SecuritySecureConfig { | private final AdminServerProperties adminServer;
public SecuritySecureConfig(AdminServerProperties adminServer) {
this.adminServer = adminServer;
}
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(this.adminServer.path("/"));
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests
.requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/assets/**")))
.permitAll()
.requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/login")))
.permitAll()
.anyRequest()
.authenticated())
.formLogin((formLogin) -> formLogin.loginPage(this.adminServer.path("/login"))
.successHandler(successHandler))
.logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout")))
.httpBasic(Customizer.withDefaults())
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
PathPatternRequestMatcher.withDefaults().matcher(POST, this.adminServer.path("/instances")),
PathPatternRequestMatcher.withDefaults()
.matcher(DELETE, this.adminServer.path("/instances/*")),
PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/actuator/**"))));
return http.build();
}
}
} | repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-war\src\main\java\de\codecentric\boot\admin\sample\SpringBootAdminWarApplication.java | 2 |
请完成以下Java代码 | private long benchMarkMergeMethod() {
long startTime = System.nanoTime();
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingMerge(getString());
long endTime = System.nanoTime();
return endTime - startTime;
}
private long benchMarkGetOrDefaultMethod() {
long startTime = System.nanoTime();
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingGetOrDefault(getString());
long endTime = System.nanoTime();
return endTime - startTime;
} | private String getString() {
return
"Once upon a time in a quaint village nestled between rolling hills and whispering forests, there lived a solitary storyteller named Elias. Elias was known for spinning tales that transported listeners to magical realms and awakened forgotten dreams.\n"
+ "\n"
+ "His favorite spot was beneath an ancient oak tree, its sprawling branches offering shade to those who sought refuge from the bustle of daily life. Villagers of all ages would gather around Elias, their faces illuminated by the warmth of his stories.\n"
+ "\n" + "One evening, as dusk painted the sky in hues of orange and purple, a curious young girl named Lily approached Elias. Her eyes sparkled with wonder as she asked for a tale unlike any other.\n" + "\n"
+ "Elias smiled, sensing her thirst for adventure, and began a story about a forgotten kingdom veiled by mist, guarded by mystical creatures and enchanted by ancient spells. With each word, the air grew thick with anticipation, and the listeners were transported into a world where magic danced on the edges of reality.\n"
+ "\n" + "As Elias weaved the story, Lily's imagination took flight. She envisioned herself as a brave warrior, wielding a shimmering sword against dark forces, her heart fueled by courage and kindness.\n" + "\n"
+ "The night wore on, but the spell of the tale held everyone captive. The villagers laughed, gasped, and held their breaths, journeying alongside the characters through trials and triumphs.\n" + "\n"
+ "As the final words lingered in the air, a sense of enchantment settled upon the listeners. They thanked Elias for the gift of his storytelling, each carrying a piece of the magical kingdom within their hearts.\n" + "\n"
+ "Lily, inspired by the story, vowed to cherish the spirit of adventure and kindness in her own life. With a newfound spark in her eyes, she bid Elias goodnight, already dreaming of the countless adventures awaiting her.\n" + "\n"
+ "Under the star-studded sky, Elias remained beneath the ancient oak, his heart aglow with the joy of sharing tales that ignited imagination and inspired dreams. And as the night embraced the village, whispers of the enchanted kingdom lingered in the breeze, promising endless possibilities to those who dared to believe.";
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps-7\src\main\java\com\baeldung\map\incrementmapkey\BenchmarkMapMethods.java | 1 |
请完成以下Java代码 | public void setCompany(CompanyType value) {
this.company = value;
}
/**
* Gets the value of the person property.
*
* @return
* possible object is
* {@link PersonType }
*
*/
public PersonType getPerson() {
return person;
}
/**
* Sets the value of the person property.
*
* @param value
* allowed object is
* {@link PersonType }
*
*/
public void setPerson(PersonType value) {
this.person = value;
}
/**
* Gets the value of the eanParty property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEanParty() {
return eanParty;
}
/**
* Sets the value of the eanParty property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEanParty(String value) {
this.eanParty = value;
}
/**
* Gets the value of the zsr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getZsr() {
return zsr;
}
/**
* Sets the value of the zsr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setZsr(String value) {
this.zsr = value;
}
/**
* Gets the value of the specialty property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSpecialty() { | return specialty;
}
/**
* Sets the value of the specialty property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSpecialty(String value) {
this.specialty = value;
}
/**
* Gets the value of the uidNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUidNumber() {
return uidNumber;
}
/**
* Sets the value of the uidNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUidNumber(String value) {
this.uidNumber = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\BillerAddressType.java | 1 |
请完成以下Java代码 | public void setRetryListeners(RetryListener... listeners) {
Assert.noNullElements(listeners, "'listeners' cannot have null elements");
this.retryListeners.clear();
this.retryListeners.addAll(Arrays.asList(listeners));
}
@Override
public boolean isAckAfterHandle() {
return this.ackAfterHandle;
}
@Override
public void setAckAfterHandle(boolean ackAfterHandle) {
this.ackAfterHandle = ackAfterHandle;
}
/**
* True to reclassify the exception if different from the previous failure. If
* classified as retryable, the existing back off sequence is used; a new sequence is
* not started.
* @return the reclassifyOnExceptionChange
* @since 2.9.7
*/
protected boolean isReclassifyOnExceptionChange() {
return this.reclassifyOnExceptionChange;
}
/**
* Set to false to not reclassify the exception if different from the previous
* failure. If the changed exception is classified as retryable, the existing back off
* sequence is used; a new sequence is not started. Default true.
* @param reclassifyOnExceptionChange false to not reclassify.
* @since 2.9.7
*/
public void setReclassifyOnExceptionChange(boolean reclassifyOnExceptionChange) {
this.reclassifyOnExceptionChange = reclassifyOnExceptionChange;
}
@Override
public void handleBatch(Exception thrownException, @Nullable ConsumerRecords<?, ?> records,
Consumer<?, ?> consumer, MessageListenerContainer container, Runnable invokeListener) {
if (records == null || records.count() == 0) {
this.logger.error(thrownException, "Called with no records; consumer exception");
return;
}
this.retrying.put(Thread.currentThread(), true);
try {
ErrorHandlingUtils.retryBatch(thrownException, records, consumer, container, invokeListener, this.backOff,
this.seeker, this.recoverer, this.logger, getLogLevel(), this.retryListeners, getExceptionMatcher(),
this.reclassifyOnExceptionChange);
}
finally {
this.retrying.remove(Thread.currentThread());
} | }
@Override
public void onPartitionsAssigned(Consumer<?, ?> consumer, Collection<TopicPartition> partitions,
Runnable publishPause) {
if (Boolean.TRUE.equals(this.retrying.get(Thread.currentThread()))) {
consumer.pause(consumer.assignment());
publishPause.run();
}
}
private final class SeekAfterRecoverFailsOrInterrupted implements CommonErrorHandler {
SeekAfterRecoverFailsOrInterrupted() {
}
@Override
public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer,
MessageListenerContainer container, Runnable invokeListener) {
data.partitions()
.stream()
.collect(
Collectors.toMap(tp -> tp,
tp -> data.records(tp).get(0).offset(), (u, v) -> v, LinkedHashMap::new))
.forEach(consumer::seek);
throw new KafkaException("Seek to current after exception", getLogLevel(), thrownException);
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\FallbackBatchErrorHandler.java | 1 |
请完成以下Java代码 | protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept()
.withCaptionMapper(getCaptionMapper());
}
private ProcessPreconditionsResolution.ProcessCaptionMapper getCaptionMapper()
{
return processCaptionMapperHelper.getProcessCaptionMapperForNetAmountsFromQuery(retrieveQuery(false));
}
@Override
@RunOutOfTrx
protected String doIt() throws Exception
{
final IQuery<I_C_Invoice_Candidate> query = retrieveQuery(true);
//
// Fail if there is nothing to update
final int countToUpdate = query.count();
if (countToUpdate <= 0)
{
throw new AdempiereException("@NoSelection@");
}
final boolean flagToSet = isApproveForInvoicing();
//
// Update selected invoice candidates
countUpdated = query.update(ic -> {
ic.setApprovalForInvoicing(flagToSet);
return IQueryUpdater.MODEL_UPDATED;
});
return MSG_OK;
}
protected IQueryFilter<I_C_Invoice_Candidate> getSelectionFilter()
{
final SqlViewRowsWhereClause viewSqlWhereClause = getViewSqlWhereClause(getSelectedRowIds());
return viewSqlWhereClause.toQueryFilter(); | }
private SqlViewRowsWhereClause getViewSqlWhereClause(@NonNull final DocumentIdsSelection rowIds)
{
final String invoiceCandidateTableName = I_C_Invoice_Candidate.Table_Name;
return getView().getSqlWhereClause(rowIds, SqlOptions.usingTableName(invoiceCandidateTableName));
}
protected abstract boolean isApproveForInvoicing();
protected abstract IQuery<I_C_Invoice_Candidate> retrieveQuery(final boolean includeProcessInfoFilters);
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
//
// Notify frontend that the view shall be refreshed because we changed some candidates
if (countUpdated > 0)
{
invalidateView();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoicecandidate\process\C_Invoice_Candidate_ProcessHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class StudentVersioningController {
@GetMapping("v1/student")
public StudentV1 studentV1() {
return new StudentV1("Bob Charlie");
}
@GetMapping("v2/student")
public StudentV2 studentV2() {
return new StudentV2(new Name("Bob", "Charlie"));
}
@GetMapping(value = "/student/param", params = "version=1")
public StudentV1 paramV1() {
return new StudentV1("Bob Charlie");
}
@GetMapping(value = "/student/param", params = "version=2")
public StudentV2 paramV2() {
return new StudentV2(new Name("Bob", "Charlie"));
}
@GetMapping(value = "/student/header", headers = "X-API-VERSION=1")
public StudentV1 headerV1() { | return new StudentV1("Bob Charlie");
}
@GetMapping(value = "/student/header", headers = "X-API-VERSION=2")
public StudentV2 headerV2() {
return new StudentV2(new Name("Bob", "Charlie"));
}
@GetMapping(value = "/student/produces", produces = "application/vnd.company.app-v1+json")
public StudentV1 producesV1() {
return new StudentV1("Bob Charlie");
}
@GetMapping(value = "/student/produces", produces = "application/vnd.company.app-v2+json")
public StudentV2 producesV2() {
return new StudentV2(new Name("Bob", "Charlie"));
}
} | repos\spring-boot-examples-master\spring-boot-2-rest-service-versioning\src\main\java\com\in28minutes\springboot\rest\example\versioning\StudentVersioningController.java | 2 |
请完成以下Java代码 | public de.metas.dataentry.model.I_DataEntry_Section getDataEntry_Section() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DataEntry_Section_ID, de.metas.dataentry.model.I_DataEntry_Section.class);
}
@Override
public void setDataEntry_Section(de.metas.dataentry.model.I_DataEntry_Section DataEntry_Section)
{
set_ValueFromPO(COLUMNNAME_DataEntry_Section_ID, de.metas.dataentry.model.I_DataEntry_Section.class, DataEntry_Section);
}
/** Set Sektion.
@param DataEntry_Section_ID Sektion */
@Override
public void setDataEntry_Section_ID (int DataEntry_Section_ID)
{
if (DataEntry_Section_ID < 1)
set_ValueNoCheck (COLUMNNAME_DataEntry_Section_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DataEntry_Section_ID, Integer.valueOf(DataEntry_Section_ID));
}
/** Get Sektion.
@return Sektion */
@Override
public int getDataEntry_Section_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Section_ID);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Line.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ApplicationRunner runner1(ApplicationContext applicationContext) {
return args -> {
// tag::getBeans[]
applicationContext.getBean(MyPojo.class, "one", "topic2");
applicationContext.getBean(MyPojo.class, "two", "topic3");
// end::getBeans[]
};
}
// tag::create[]
private ConcurrentMessageListenerContainer<String, String> createContainer(
ConcurrentKafkaListenerContainerFactory<String, String> factory, String topic, String group) {
ConcurrentMessageListenerContainer<String, String> container = factory.createContainer(topic);
container.getContainerProperties().setMessageListener(new MyListener());
container.getContainerProperties().setGroupId(group);
container.setBeanName(group);
container.start();
return container;
}
// end::create[]
@Bean
public KafkaAdmin.NewTopics topics() {
return new KafkaAdmin.NewTopics(
TopicBuilder.name("topic1")
.partitions(10) | .replicas(1)
.build(),
TopicBuilder.name("topic2")
.partitions(10)
.replicas(1)
.build(),
TopicBuilder.name("topic3")
.partitions(10)
.replicas(1)
.build());
}
// tag::pojoBean[]
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
MyPojo pojo(String id, String topic) {
return new MyPojo(id, topic);
}
//end::pojoBean[]
} | repos\spring-kafka-main\spring-kafka-docs\src\main\java\org\springframework\kafka\jdocs\dynamic\Application.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JsonRemittanceAdvice
{
@ApiModelProperty(dataType = "java.lang.String",
value = "This translates to AD_Org_ID")
@Nullable
String orgCode;
@ApiModelProperty(required = true,
dataType = "java.lang.String",
value = "This translates to Source_BPartner_ID")
@NonNull
String senderId;
@ApiModelProperty(required = true,
dataType = "java.lang.String",
value = "This translates to Destintion_BPartner_ID")
@NonNull
String recipientId;
@ApiModelProperty(dataType = "java.lang.String",
value = "This translates to ExternalDocumentNo")
@NonNull
String documentNumber;
@ApiModelProperty(dataType = "java.lang.String",
value = "This translates to SendAt, using DateTimeFormatter ISO_INSTANT e.g.2017-11-22T00:00:00Z")
@Nullable
String sendDate;
@ApiModelProperty(dataType = "java.lang.String",
value = "This translates to DateDoc, using DateTimeFormatter ISO_INSTANT. "
+ "If not provided current date is taken ")
@Nullable
String documentDate;
@ApiModelProperty(required = true,
dataType = "RemittanceAdviceType as INBOUND/OUTBOUND",
value = "This translates to C_DocType_ID")
@NonNull
RemittanceAdviceType remittanceAdviceType; | @ApiModelProperty(required = true,
dataType = "java.math.BigDecimal",
value = "This translates as RemittanceAmt")
@NonNull
BigDecimal remittedAmountSum;
@ApiModelProperty(required = true,
dataType = "java.math.BigDecimal",
value = "This translates as RemittanceAmt_Currency_ID")
@NonNull
String remittanceAmountCurrencyISO;
@ApiModelProperty(dataType = "java.math.BigDecimal",
value = "This translates as ServiceFeeAmount")
BigDecimal serviceFeeAmount;
@ApiModelProperty(dataType = "java.lang.String",
value = "This translates as ServiceFeeAmount_Currency_ID")
@Nullable
String serviceFeeCurrencyISO;
@ApiModelProperty(dataType = "java.math.BigDecimal",
value = "This translates as PaymentDiscountAmountSum")
@Nullable
BigDecimal paymentDiscountAmountSum;
@ApiModelProperty(dataType = "java.lang.String",
value = "This translates as AdditionalNotes")
@Nullable
String additionalNotes;
@ApiModelProperty(dataType = "List<JsonRemittanceAdviceLine>",
value = "This translates as each entry in RemittanceAdviceLine table for a remittanceAdvice document")
@NonNull
List<JsonRemittanceAdviceLine> lines;
@JsonIgnoreProperties(ignoreUnknown = true) // the annotation to ignore properties should be set on the deserializer method (on the builder), and not on the base class
@JsonPOJOBuilder(withPrefix = "")
public static class JsonRemittanceAdviceBuilder
{
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v1\remittanceadvice\JsonRemittanceAdvice.java | 2 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.add("lookupValues", lookupValues)
.toString();
}
@Override
public LookupSource getLookupSourceType()
{
return lookupSourceType;
}
@Override
public boolean isNumericKey()
{
return numericKey;
}
@Override
public Set<String> getDependsOnFieldNames()
{
return dependsOnFieldNames;
}
@Override
public Optional<String> getLookupTableName()
{
return lookupTableName;
}
@Override
public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx)
{
final LookupValuesPage page = lookupValues.apply(evalCtx);
return page.getValues().getById(evalCtx.getSingleIdToFilterAsObject());
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
return lookupValues.apply(evalCtx);
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
//
//
//
//
//
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static class Builder
{
private LookupSource lookupSourceType = LookupSource.list;
private boolean numericKey;
private Function<LookupDataSourceContext, LookupValuesPage> lookupValues;
private Set<String> dependsOnFieldNames;
private Optional<String> lookupTableName = Optional.empty(); | private Builder()
{
}
public ListLookupDescriptor build()
{
return new ListLookupDescriptor(this);
}
public Builder setLookupSourceType(@NonNull final LookupSource lookupSourceType)
{
this.lookupSourceType = lookupSourceType;
return this;
}
public Builder setLookupValues(final boolean numericKey, final Function<LookupDataSourceContext, LookupValuesPage> lookupValues)
{
this.numericKey = numericKey;
this.lookupValues = lookupValues;
return this;
}
public Builder setIntegerLookupValues(final Function<LookupDataSourceContext, LookupValuesPage> lookupValues)
{
setLookupValues(true, lookupValues);
return this;
}
public Builder setDependsOnFieldNames(final String[] dependsOnFieldNames)
{
this.dependsOnFieldNames = ImmutableSet.copyOf(dependsOnFieldNames);
return this;
}
public Builder setLookupTableName(final String lookupTableName)
{
this.lookupTableName = Check.isEmpty(lookupTableName, true) ? Optional.empty() : Optional.of(lookupTableName);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\ListLookupDescriptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ForkingComponent extends RecursiveAction {
@Value("${jdbc.batch.size}")
private int batchSize;
@Autowired
private JoiningComponent joiningComponent;
@Autowired
private ApplicationContext applicationContext;
private final List<String> jsonList;
public ForkingComponent(List<String> jsonList) {
this.jsonList = jsonList;
}
@Override
public void compute() {
if (jsonList.size() > batchSize) {
ForkJoinTask.invokeAll(createSubtasks());
} else {
joiningComponent.executeBatch(jsonList);
} | }
private List<ForkingComponent> createSubtasks() {
List<ForkingComponent> subtasks = new ArrayList<>();
int size = jsonList.size();
List<String> jsonListOne = jsonList.subList(0, (size + 1) / 2);
List<String> jsonListTwo = jsonList.subList((size + 1) / 2, size);
subtasks.add(applicationContext.getBean(ForkingComponent.class, new ArrayList<>(jsonListOne)));
subtasks.add(applicationContext.getBean(ForkingComponent.class, new ArrayList<>(jsonListTwo)));
return subtasks;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchJsonFileForkJoin\src\main\java\com\citylots\forkjoin\ForkingComponent.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("admin").password("{noop}password").roles("USER", "ADMIN");
}
// Secure the endpoins with HTTP Basic authentication
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//HTTP Basic authentication
.httpBasic()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/books/**").hasRole("USER")
.antMatchers(HttpMethod.POST, "/books").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT, "/books/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PATCH, "/books/**").hasRole("ADMIN")
.antMatchers(HttpMethod.DELETE, "/books/**").hasRole("ADMIN") | .and()
.csrf().disable()
.formLogin().disable();
}
/*@Bean
public UserDetailsService userDetailsService() {
//ok for demo
User.UserBuilder users = User.withDefaultPasswordEncoder();
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(users.username("user").password("password").roles("USER").build());
manager.createUser(users.username("admin").password("password").roles("USER", "ADMIN").build());
return manager;
}*/
} | repos\spring-boot-master\spring-rest-security\src\main\java\com\mkyong\config\SpringSecurityConfig.java | 2 |
请完成以下Java代码 | public org.compiere.model.I_C_Country getC_Country()
{
return get_ValueAsPO(COLUMNNAME_C_Country_ID, org.compiere.model.I_C_Country.class);
}
@Override
public void setC_Country(final org.compiere.model.I_C_Country C_Country)
{
set_ValueFromPO(COLUMNNAME_C_Country_ID, org.compiere.model.I_C_Country.class, C_Country);
}
@Override
public void setC_Country_ID (final int C_Country_ID)
{
if (C_Country_ID < 1)
set_Value (COLUMNNAME_C_Country_ID, null);
else
set_Value (COLUMNNAME_C_Country_ID, C_Country_ID);
}
@Override
public int getC_Country_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Country_ID);
}
@Override
public void setC_TaxCategory_ID (final int C_TaxCategory_ID)
{
if (C_TaxCategory_ID < 1)
set_Value (COLUMNNAME_C_TaxCategory_ID, null);
else
set_Value (COLUMNNAME_C_TaxCategory_ID, C_TaxCategory_ID);
}
@Override
public int getC_TaxCategory_ID()
{
return get_ValueAsInt(COLUMNNAME_C_TaxCategory_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else | set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setM_Product_TaxCategory_ID (final int M_Product_TaxCategory_ID)
{
if (M_Product_TaxCategory_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_TaxCategory_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_TaxCategory_ID, M_Product_TaxCategory_ID);
}
@Override
public int getM_Product_TaxCategory_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_TaxCategory_ID);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_TaxCategory.java | 1 |
请完成以下Java代码 | public String getDatabaseType() {
return databaseType;
}
public Map<String, String> getStatementMappings() {
return statementMappings;
}
public void setStatementMappings(Map<String, String> statementMappings) {
this.statementMappings = statementMappings;
}
public Map<Class< ? >, String> getInsertStatements() {
return insertStatements;
}
public void setInsertStatements(Map<Class< ? >, String> insertStatements) {
this.insertStatements = insertStatements;
}
public Map<Class< ? >, String> getUpdateStatements() {
return updateStatements;
}
public void setUpdateStatements(Map<Class< ? >, String> updateStatements) {
this.updateStatements = updateStatements;
}
public Map<Class< ? >, String> getDeleteStatements() {
return deleteStatements;
}
public void setDeleteStatements(Map<Class< ? >, String> deleteStatements) {
this.deleteStatements = deleteStatements;
}
public Map<Class< ? >, String> getSelectStatements() {
return selectStatements;
}
public void setSelectStatements(Map<Class< ? >, String> selectStatements) {
this.selectStatements = selectStatements;
}
public boolean isDbIdentityUsed() {
return isDbIdentityUsed;
}
public void setDbIdentityUsed(boolean isDbIdentityUsed) {
this.isDbIdentityUsed = isDbIdentityUsed;
}
public boolean isDbHistoryUsed() {
return isDbHistoryUsed;
} | public void setDbHistoryUsed(boolean isDbHistoryUsed) {
this.isDbHistoryUsed = isDbHistoryUsed;
}
public boolean isCmmnEnabled() {
return cmmnEnabled;
}
public void setCmmnEnabled(boolean cmmnEnabled) {
this.cmmnEnabled = cmmnEnabled;
}
public boolean isDmnEnabled() {
return dmnEnabled;
}
public void setDmnEnabled(boolean dmnEnabled) {
this.dmnEnabled = dmnEnabled;
}
public void setDatabaseTablePrefix(String databaseTablePrefix) {
this.databaseTablePrefix = databaseTablePrefix;
}
public String getDatabaseTablePrefix() {
return databaseTablePrefix;
}
public String getDatabaseSchema() {
return databaseSchema;
}
public void setDatabaseSchema(String databaseSchema) {
this.databaseSchema = databaseSchema;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\sql\DbSqlSessionFactory.java | 1 |
请完成以下Java代码 | private TableCellEditor createTableCellEditor(final TableColumnInfo columnMetaInfo)
{
if (columnMetaInfo.isSelectionColumn())
{
return new SelectionColumnCellEditor();
}
return new AnnotatedTableCellEditor(columnMetaInfo);
}
/**
* Synchronize changes from {@link TableColumnInfo} to {@link TableColumnExt}.
*
* @author tsa
*
*/
private static final class TableColumnInfo2TableColumnExtSynchronizer implements PropertyChangeListener
{
private final WeakReference<TableColumnExt> columnExtRef;
private boolean running = false;
public TableColumnInfo2TableColumnExtSynchronizer(final TableColumnExt columnExt)
{
super();
columnExtRef = new WeakReference<>(columnExt);
}
private TableColumnExt getTableColumnExt()
{
return columnExtRef.getValue();
}
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
// Avoid recursion
if (running)
{ | return;
}
running = true;
try
{
final TableColumnInfo columnMetaInfo = (TableColumnInfo)evt.getSource();
final TableColumnExt columnExt = getTableColumnExt();
if (columnExt == null)
{
// ColumnExt reference expired:
// * remove this listener because there is no point to have this listener invoked in future
// * exit quickly because there is nothing to do
columnMetaInfo.removePropertyChangeListener(this);
return;
}
updateColumnExtFromMetaInfo(columnExt, columnMetaInfo);
}
finally
{
running = false;
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableColumnFactory.java | 1 |
请完成以下Java代码 | public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public Date getCreateTime() {
return createTime;
}
public Date getEndTime() {
return endTime;
}
public Date getRemovalTime() {
return removalTime;
}
public String getIncidentType() {
return incidentType;
}
public String getActivityId() {
return activityId;
}
public String getFailedActivityId() {
return failedActivityId;
}
public String getCauseIncidentId() {
return causeIncidentId;
}
public String getRootCauseIncidentId() {
return rootCauseIncidentId;
}
public String getConfiguration() {
return configuration;
}
public String getHistoryConfiguration() {
return historyConfiguration;
}
public String getIncidentMessage() {
return incidentMessage;
}
public String getTenantId() {
return tenantId;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public Boolean isOpen() {
return open;
}
public Boolean isDeleted() {
return deleted;
}
public Boolean isResolved() {
return resolved;
} | public String getAnnotation() {
return annotation;
}
public static HistoricIncidentDto fromHistoricIncident(HistoricIncident historicIncident) {
HistoricIncidentDto dto = new HistoricIncidentDto();
dto.id = historicIncident.getId();
dto.processDefinitionKey = historicIncident.getProcessDefinitionKey();
dto.processDefinitionId = historicIncident.getProcessDefinitionId();
dto.processInstanceId = historicIncident.getProcessInstanceId();
dto.executionId = historicIncident.getExecutionId();
dto.createTime = historicIncident.getCreateTime();
dto.endTime = historicIncident.getEndTime();
dto.incidentType = historicIncident.getIncidentType();
dto.failedActivityId = historicIncident.getFailedActivityId();
dto.activityId = historicIncident.getActivityId();
dto.causeIncidentId = historicIncident.getCauseIncidentId();
dto.rootCauseIncidentId = historicIncident.getRootCauseIncidentId();
dto.configuration = historicIncident.getConfiguration();
dto.historyConfiguration = historicIncident.getHistoryConfiguration();
dto.incidentMessage = historicIncident.getIncidentMessage();
dto.open = historicIncident.isOpen();
dto.deleted = historicIncident.isDeleted();
dto.resolved = historicIncident.isResolved();
dto.tenantId = historicIncident.getTenantId();
dto.jobDefinitionId = historicIncident.getJobDefinitionId();
dto.removalTime = historicIncident.getRemovalTime();
dto.rootProcessInstanceId = historicIncident.getRootProcessInstanceId();
dto.annotation = historicIncident.getAnnotation();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIncidentDto.java | 1 |
请完成以下Java代码 | public void setRemote_Addr (String Remote_Addr)
{
set_ValueNoCheck (COLUMNNAME_Remote_Addr, Remote_Addr);
}
/** Get Remote Addr.
@return Remote Address
*/
public String getRemote_Addr ()
{
return (String)get_Value(COLUMNNAME_Remote_Addr);
}
/** Set Remote Host.
@param Remote_Host
Remote host Info
*/
public void setRemote_Host (String Remote_Host)
{
set_ValueNoCheck (COLUMNNAME_Remote_Host, Remote_Host);
}
/** Get Remote Host.
@return Remote host Info
*/
public String getRemote_Host ()
{
return (String)get_Value(COLUMNNAME_Remote_Host);
}
/** Set Sales Volume in 1.000.
@param SalesVolume
Total Volume of Sales in Thousands of Currency
*/
public void setSalesVolume (int SalesVolume)
{
set_Value (COLUMNNAME_SalesVolume, Integer.valueOf(SalesVolume));
} | /** Get Sales Volume in 1.000.
@return Total Volume of Sales in Thousands of Currency
*/
public int getSalesVolume ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesVolume);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start Implementation/Production.
@param StartProductionDate
The day you started the implementation (if implementing) - or production (went life) with Adempiere
*/
public void setStartProductionDate (Timestamp StartProductionDate)
{
set_Value (COLUMNNAME_StartProductionDate, StartProductionDate);
}
/** Get Start Implementation/Production.
@return The day you started the implementation (if implementing) - or production (went life) with Adempiere
*/
public Timestamp getStartProductionDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartProductionDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Registration.java | 1 |
请完成以下Java代码 | public static boolean isStaffLevel(String name) {
PositionLevelEnum position = getByName(name);
return position != null && position.getType() == PositionType.STAFF;
}
/**
* 根据职级名称判断是否为领导层级
* @param name 职级名称
* @return true-领导层级,false-非领导层级
*/
public static boolean isLeaderLevel(String name) {
PositionLevelEnum position = getByName(name);
return position != null && position.getType() == PositionType.LEADER;
}
/**
* 比较两个职级的等级高低
* @param name1 职级名称1
* @param name2 职级名称2
* @return 正数表示name1等级更高,负数表示name2等级更高,0表示等级相同
*/
public static int compareLevel(String name1, String name2) {
PositionLevelEnum pos1 = getByName(name1);
PositionLevelEnum pos2 = getByName(name2);
if (pos1 == null || pos2 == null) {
return 0;
}
// 等级数字越小代表职级越高
return pos2.getLevel() - pos1.getLevel();
}
/**
* 判断是否为更高等级
* @param currentName 当前职级名称
* @param targetName 目标职级名称
* @return true-目标职级更高,false-目标职级不高于当前职级
*/
public static boolean isHigherLevel(String currentName, String targetName) {
return compareLevel(targetName, currentName) > 0;
}
/**
* 获取所有职员层级名称
* @return 职员层级名称列表
*/
public static List<String> getStaffLevelNames() {
return Arrays.asList(MINISTER.getName(), VICE_MINISTER.getName(), STAFF.getName()); | }
/**
* 获取所有领导层级名称
* @return 领导层级名称列表
*/
public static List<String> getLeaderLevelNames() {
return Arrays.asList(CHAIRMAN.getName(), GENERAL_MANAGER.getName(), VICE_GENERAL_MANAGER.getName());
}
/**
* 获取所有职级名称(按等级排序)
* @return 所有职级名称列表
*/
public static List<String> getAllPositionNames() {
return Arrays.asList(
CHAIRMAN.getName(), GENERAL_MANAGER.getName(), VICE_GENERAL_MANAGER.getName(),
MINISTER.getName(), VICE_MINISTER.getName(), STAFF.getName()
);
}
/**
* 获取指定等级范围的职级
* @param minLevel 最小等级
* @param maxLevel 最大等级
* @return 职级名称列表
*/
public static List<String> getPositionsByLevelRange(int minLevel, int maxLevel) {
return Arrays.stream(values())
.filter(p -> p.getLevel() >= minLevel && p.getLevel() <= maxLevel)
.map(PositionLevelEnum::getName)
.collect(java.util.stream.Collectors.toList());
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\PositionLevelEnum.java | 1 |
请完成以下Java代码 | public class DunningDocDocumentHandler implements DocumentHandler
{
@Override
public String getSummary(@NonNull final DocumentTableFields docFields)
{
return extractDunningDoc(docFields).getDocumentNo();
}
@Override
public String getDocumentInfo(@NonNull final DocumentTableFields docFields)
{
return getSummary(docFields);
}
@Override
public int getDoc_User_ID(@NonNull final DocumentTableFields docFields)
{
return extractDunningDoc(docFields).getCreatedBy();
}
@Override
public LocalDate getDocumentDate(@NonNull final DocumentTableFields docFields)
{
return TimeUtil.asLocalDate(extractDunningDoc(docFields).getDunningDate());
}
/**
* Sets the <code>Processed</code> flag of the given <code>dunningDoc</code> and sets the <code>IsDunningDocProcessed</code> flag of the dunning candidates that are the sources of dunning doc's
* lines.
* <p>
* Assumes that the given doc is not yet processed.
*/
@Override
public String completeIt(@NonNull final DocumentTableFields docFields)
{
final I_C_DunningDoc dunningDocRecord = extractDunningDoc(docFields);
dunningDocRecord.setDocAction(IDocument.ACTION_ReActivate);
if (dunningDocRecord.isProcessed())
{
throw new DunningException("@Processed@=@Y@");
}
final IDunningDAO dunningDao = Services.get(IDunningDAO.class);
final List<I_C_DunningDoc_Line> lines = dunningDao.retrieveDunningDocLines(dunningDocRecord);
final IDunningBL dunningBL = Services.get(IDunningBL.class);
for (final I_C_DunningDoc_Line line : lines)
{
for (final I_C_DunningDoc_Line_Source source : dunningDao.retrieveDunningDocLineSources(line))
{
dunningBL.processSourceAndItsCandidates(dunningDocRecord, source);
} | line.setProcessed(true);
InterfaceWrapperHelper.save(line);
}
//
// Delivery stop (https://github.com/metasfresh/metasfresh/issues/2499)
dunningBL.makeDeliveryStopIfNeeded(dunningDocRecord);
dunningDocRecord.setProcessed(true);
return IDocument.STATUS_Completed;
}
@Override
public void reactivateIt(@NonNull final DocumentTableFields docFields)
{
final I_C_DunningDoc dunningDocRecord = extractDunningDoc(docFields);
dunningDocRecord.setProcessed(false);
dunningDocRecord.setDocAction(IDocument.ACTION_Complete);
}
private static I_C_DunningDoc extractDunningDoc(@NonNull final DocumentTableFields docFields)
{
return InterfaceWrapperHelper.create(docFields, I_C_DunningDoc.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\DunningDocDocumentHandler.java | 1 |
请完成以下Java代码 | public static final class SourceDocumentLine
{
@Nullable
OrderLineId orderLineId;
@NonNull
SOTrx soTrx;
@NonNull
BPartnerId bpartnerId;
@NonNull
ProductId productId;
@NonNull
ProductCategoryId productCategoryId;
@NonNull
Money priceEntered;
@lombok.Builder.Default
@NonNull
Percent discount = Percent.ZERO;
@Nullable
PaymentTermId paymentTermId;
@Nullable
PricingConditionsBreakId pricingConditionsBreakId;
}
@lombok.Value
@lombok.Builder
private static final class LastInOutDateRequest
{
@NonNull
BPartnerId bpartnerId;
@NonNull | ProductId productId;
@NonNull
SOTrx soTrx;
}
//
//
//
//
//
public static class PricingConditionsRowsLoaderBuilder
{
public PricingConditionsRowData load()
{
return build().load();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRowsLoader.java | 1 |
请完成以下Java代码 | public Builder registrationAccessToken(String registrationAccessToken) {
return claim(OidcClientMetadataClaimNames.REGISTRATION_ACCESS_TOKEN, registrationAccessToken);
}
/**
* Sets the {@code URL} of the Client Configuration Endpoint where the
* Registration Access Token can be used, OPTIONAL.
* @param registrationClientUrl the {@code URL} of the Client Configuration
* Endpoint where the Registration Access Token can be used
* @return the {@link Builder} for further configuration
*/
public Builder registrationClientUrl(String registrationClientUrl) {
return claim(OidcClientMetadataClaimNames.REGISTRATION_CLIENT_URI, registrationClientUrl);
}
/**
* Validate the claims and build the {@link OidcClientRegistration}.
* <p>
* The following claims are REQUIRED: {@code client_id}, {@code redirect_uris}.
* @return the {@link OidcClientRegistration}
*/
@Override
public OidcClientRegistration build() {
validate();
return new OidcClientRegistration(getClaims());
}
@Override
protected void validate() {
super.validate();
Assert.notNull(getClaims().get(OidcClientMetadataClaimNames.REDIRECT_URIS), "redirect_uris cannot be null");
Assert.isInstanceOf(List.class, getClaims().get(OidcClientMetadataClaimNames.REDIRECT_URIS),
"redirect_uris must be of type List");
Assert.notEmpty((List<?>) getClaims().get(OidcClientMetadataClaimNames.REDIRECT_URIS),
"redirect_uris cannot be empty");
if (getClaims().get(OidcClientMetadataClaimNames.POST_LOGOUT_REDIRECT_URIS) != null) {
Assert.isInstanceOf(List.class, getClaims().get(OidcClientMetadataClaimNames.POST_LOGOUT_REDIRECT_URIS),
"post_logout_redirect_uris must be of type List");
Assert.notEmpty((List<?>) getClaims().get(OidcClientMetadataClaimNames.POST_LOGOUT_REDIRECT_URIS),
"post_logout_redirect_uris cannot be empty");
}
} | @SuppressWarnings("unchecked")
private void addClaimToClaimList(String name, String value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
getClaims().computeIfAbsent(name, (k) -> new LinkedList<String>());
((List<String>) getClaims().get(name)).add(value);
}
@SuppressWarnings("unchecked")
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
getClaims().computeIfAbsent(name, (k) -> new LinkedList<String>());
List<String> values = (List<String>) getClaims().get(name);
valuesConsumer.accept(values);
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\OidcClientRegistration.java | 1 |
请完成以下Java代码 | public class ProcessDocumentsBySelection extends AbstractProcessDocumentsTemplate implements IProcessPrecondition
{
// services
private final IQueryBL queryBL = Services.get(IQueryBL.class);
public static final String PARAM_DocStatus = "DocStatus";
@Param(parameterName = PARAM_DocStatus)
private DocStatus p_DocStatus;
public static final String PARAM_DocAction = "DocAction";
@Param(parameterName = PARAM_DocAction, mandatory = true)
private String p_DocAction;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@NonNull
protected Iterator<GenericPO> retrieveDocumentsToProcess()
{ | final String tableName = Check.assumeNotNull(getTableName(), "The process must be associated with a table!");
final IQueryBuilder<Object> queryBuilder = queryBL.createQueryBuilder(tableName)
.addOnlyActiveRecordsFilter()
.filter(getProcessInfo().getQueryFilterOrElseFalse());
if (p_DocStatus != null)
{
queryBuilder.addEqualsFilter(PARAM_DocStatus, p_DocStatus);
}
return queryBuilder.create().iterate(GenericPO.class);
}
@Override
protected String getDocAction() {return p_DocAction;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\process\ProcessDocumentsBySelection.java | 1 |
请完成以下Java代码 | private void processBlock(LineIterator iterator, CQLSSTableWriter writer, File outDir, Function<List<String>, List<Object>> function) {
String currentLine;
long linesProcessed = 0;
while(iterator.hasNext()) {
logLinesProcessed(linesProcessed++);
currentLine = iterator.nextLine();
if(isBlockFinished(currentLine)) {
return;
}
try {
List<String> raw = Arrays.stream(currentLine.trim().split("\t"))
.map(String::trim)
.collect(Collectors.toList());
List<Object> values = function.apply(raw);
if (this.currentWriterCount == 0) {
System.out.println(new Date() + " close writer " + new Date());
writer.close();
writer = WriterBuilder.getLatestWriter(outDir);
}
if (this.castStringIfPossible) {
writer.addRow(castToNumericIfPossible(values));
} else {
writer.addRow(values);
}
currentWriterCount++;
if (currentWriterCount >= rowPerFile) {
currentWriterCount = 0;
}
} catch (Exception ex) {
System.out.println(ex.getMessage() + " -> " + currentLine);
}
}
}
private List<Object> castToNumericIfPossible(List<Object> values) {
try {
if (values.get(6) != null && NumberUtils.isNumber(values.get(6).toString())) {
Double casted = NumberUtils.createDouble(values.get(6).toString());
List<Object> numeric = Lists.newArrayList();
numeric.addAll(values); | numeric.set(6, null);
numeric.set(8, casted);
castedOk++;
return numeric;
}
} catch (Throwable th) {
castErrors++;
}
processPartitions(values);
return values;
}
private boolean isBlockFinished(String line) {
return StringUtils.isBlank(line) || line.equals("\\.");
}
private boolean isBlockTsStarted(String line) {
return line.startsWith("COPY public.ts_kv (");
}
private boolean isBlockLatestStarted(String line) {
return line.startsWith("COPY public.ts_kv_latest (");
}
} | repos\thingsboard-master\tools\src\main\java\org\thingsboard\client\tools\migrator\PgCaMigrator.java | 1 |
请完成以下Java代码 | public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCnname() {
return cnname;
}
public void setCnname(String cnname) {
this.cnname = cnname;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getWechatId() {
return wechatId;
}
public void setWechatId(String wechatId) {
this.wechatId = wechatId;
} | public String getSkill() {
return skill;
}
public void setSkill(String skill) {
this.skill = skill;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
public Integer getLoginCount() {
return loginCount;
}
public void setLoginCount(Integer loginCount) {
this.loginCount = loginCount;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", cnname=" + cnname +
", username=" + username +
", password=" + password +
", email=" + email +
", telephone=" + telephone +
", mobilePhone=" + mobilePhone +
", wechatId=" + wechatId +
", skill=" + skill +
", departmentId=" + departmentId +
", loginCount=" + loginCount +
'}';
}
} | repos\springBoot-master\springboot-shiro\src\main\java\com\us\bean\User.java | 1 |
请完成以下Java代码 | private static void transformIntoStream() {
int[] anArray = new int[] {1, 2, 3, 4, 5};
IntStream aStream = Arrays.stream(anArray);
Integer[] anotherArray = new Integer[] {1, 2, 3, 4, 5};
Stream<Integer> anotherStream = Arrays.stream(anotherArray, 2, 4);
}
private static void sort() {
int[] anArray = new int[] {5, 2, 1, 4, 8};
Arrays.sort(anArray); // anArray is now {1, 2, 4, 5, 8}
Integer[] anotherArray = new Integer[] {5, 2, 1, 4, 8};
Arrays.sort(anotherArray); // anArray is now {1, 2, 4, 5, 8}
String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"};
Arrays.sort(yetAnotherArray, 1, 3, Comparator.comparing(String::toString).reversed()); // yetAnotherArray is now {"A", "Z", "E", "B", "C"}
}
private static void search() {
int[] anArray = new int[] {5, 2, 1, 4, 8};
for (int i = 0; i < anArray.length; i++) {
if (anArray[i] == 4) {
System.out.println("Found at index " + i);
break;
}
} | Arrays.sort(anArray);
int index = Arrays.binarySearch(anArray, 4);
System.out.println("Found at index " + index);
}
private static void merge() {
int[] anArray = new int[] {5, 2, 1, 4, 8};
int[] anotherArray = new int[] {10, 4, 9, 11, 2};
int[] resultArray = new int[anArray.length + anotherArray.length];
for (int i = 0; i < resultArray.length; i++) {
resultArray[i] = (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]);
}
for (int element : resultArray) {
System.out.println(element);
}
Arrays.setAll(resultArray, i -> (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]));
for (int element : resultArray) {
System.out.println(element);
}
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-guides\src\main\java\com\baeldung\array\ArrayReferenceGuide.java | 1 |
请完成以下Java代码 | public @Nullable String getBeanName(Class<?> beanClass) {
return (this.beanNameGenerator != null) ? this.beanNameGenerator.apply(beanClass) : null;
}
/**
* Return the classes from all the specified configurations in the order that they
* would be registered.
* @param configurations the source configuration
* @return configuration classes in registration order
*/
public static Class<?>[] getClasses(Configurations... configurations) {
return getClasses(Arrays.asList(configurations));
}
/**
* Return the classes from all the specified configurations in the order that they
* would be registered.
* @param configurations the source configuration
* @return configuration classes in registration order
*/
public static Class<?>[] getClasses(Collection<Configurations> configurations) {
List<Configurations> collated = collate(configurations);
LinkedHashSet<Class<?>> classes = collated.stream()
.flatMap(Configurations::streamClasses)
.collect(Collectors.toCollection(LinkedHashSet::new));
return ClassUtils.toClassArray(classes);
}
/**
* Collate the given configuration by sorting and merging them. | * @param configurations the source configuration
* @return the collated configurations
* @since 3.4.0
*/
public static List<Configurations> collate(Collection<Configurations> configurations) {
LinkedList<Configurations> collated = new LinkedList<>();
for (Configurations configuration : sortConfigurations(configurations)) {
if (collated.isEmpty() || collated.getLast().getClass() != configuration.getClass()) {
collated.add(configuration);
}
else {
collated.set(collated.size() - 1, collated.getLast().merge(configuration));
}
}
return collated;
}
private static List<Configurations> sortConfigurations(Collection<Configurations> configurations) {
List<Configurations> sorted = new ArrayList<>(configurations);
sorted.sort(COMPARATOR);
return sorted;
}
private static Stream<Class<?>> streamClasses(Configurations configurations) {
return configurations.getClasses().stream();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\annotation\Configurations.java | 1 |
请完成以下Java代码 | public static HistoricTaskInstanceDto fromHistoricTaskInstance(HistoricTaskInstance taskInstance) {
HistoricTaskInstanceDto dto = new HistoricTaskInstanceDto();
dto.id = taskInstance.getId();
dto.processDefinitionKey = taskInstance.getProcessDefinitionKey();
dto.processDefinitionId = taskInstance.getProcessDefinitionId();
dto.processInstanceId = taskInstance.getProcessInstanceId();
dto.executionId = taskInstance.getExecutionId();
dto.caseDefinitionKey = taskInstance.getCaseDefinitionKey();
dto.caseDefinitionId = taskInstance.getCaseDefinitionId();
dto.caseInstanceId = taskInstance.getCaseInstanceId();
dto.caseExecutionId = taskInstance.getCaseExecutionId();
dto.activityInstanceId = taskInstance.getActivityInstanceId();
dto.name = taskInstance.getName();
dto.description = taskInstance.getDescription();
dto.deleteReason = taskInstance.getDeleteReason();
dto.owner = taskInstance.getOwner();
dto.assignee = taskInstance.getAssignee();
dto.startTime = taskInstance.getStartTime();
dto.endTime = taskInstance.getEndTime(); | dto.duration = taskInstance.getDurationInMillis();
dto.taskDefinitionKey = taskInstance.getTaskDefinitionKey();
dto.priority = taskInstance.getPriority();
dto.due = taskInstance.getDueDate();
dto.parentTaskId = taskInstance.getParentTaskId();
dto.followUp = taskInstance.getFollowUpDate();
dto.tenantId = taskInstance.getTenantId();
dto.removalTime = taskInstance.getRemovalTime();
dto.rootProcessInstanceId = taskInstance.getRootProcessInstanceId();
dto.taskState = taskInstance.getTaskState();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricTaskInstanceDto.java | 1 |
请完成以下Java代码 | public int hashCode() {
int result = ObjectUtils.nullSafeHashCode(this.name);
result = 31 * result + ObjectUtils.nullSafeHashCode(this.value);
return result;
}
@Override
public String toString() {
return new ToStringCreator(this).append("name", this.name)
.append("value", this.value)
.append("origin", this.origin)
.toString();
}
@Override
public int compareTo(ConfigurationProperty other) {
return this.name.compareTo(other.name);
}
@Contract("_, !null -> !null") | static @Nullable ConfigurationProperty of(ConfigurationPropertyName name, @Nullable OriginTrackedValue value) {
if (value == null) {
return null;
}
return new ConfigurationProperty(name, value.getValue(), value.getOrigin());
}
@Contract("_, _, !null, _ -> !null")
static @Nullable ConfigurationProperty of(@Nullable ConfigurationPropertySource source,
ConfigurationPropertyName name, @Nullable Object value, @Nullable Origin origin) {
if (value == null) {
return null;
}
return new ConfigurationProperty(source, name, value, origin);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\ConfigurationProperty.java | 1 |
请完成以下Java代码 | public Optional<BPartnerLocation> extractShipToLocation()
{
final Predicate<BPartnerLocation> predicate = l -> l.getLocationType().getIsShipToOr(false);
return createFilteredLocationStream(predicate).min(Comparator.comparing(l -> !l.getLocationType().getIsShipToDefaultOr(false)));
}
public Optional<BPartnerLocation> extractLocationByHandle(@NonNull final String handle)
{
return extractLocation(bpLocation -> bpLocation.containsHandle(handle));
}
public Optional<BPartnerLocation> extractLocation(@NonNull final Predicate<BPartnerLocation> filter)
{
return createFilteredLocationStream(filter).findAny();
}
private Stream<BPartnerLocation> createFilteredLocationStream(@NonNull final Predicate<BPartnerLocation> filter)
{
return getLocations()
.stream()
.filter(filter);
}
public void addBankAccount(@NonNull final BPartnerBankAccount bankAccount)
{
bankAccounts.add(bankAccount);
} | public Optional<BPartnerBankAccount> getBankAccountByIBAN(@NonNull final String iban)
{
Check.assumeNotEmpty(iban, "iban is not empty");
return bankAccounts.stream()
.filter(bankAccount -> iban.equals(bankAccount.getIban()))
.findFirst();
}
public void addCreditLimit(@NonNull final BPartnerCreditLimit creditLimit)
{
creditLimits.add(creditLimit);
}
@NonNull
public Stream<BPartnerContactId> streamContactIds()
{
return this.getContacts().stream().map(BPartnerContact::getId);
}
@NonNull
public Stream<BPartnerLocationId> streamBPartnerLocationIds()
{
return this.getLocations().stream().map(BPartnerLocation::getId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerComposite.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setAuthenticationRequestRepository(
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) {
Assert.notNull(authenticationRequestRepository, "authenticationRequestRepository cannot be null");
this.authenticationRequestRepository = authenticationRequestRepository;
}
/**
* Use the given {@code shouldConvertGetRequests} to convert {@code GET} requests.
* Default is {@code true}.
* @param shouldConvertGetRequests the {@code shouldConvertGetRequests} to use
* @since 7.0
*/
public void setShouldConvertGetRequests(boolean shouldConvertGetRequests) {
this.shouldConvertGetRequests = shouldConvertGetRequests;
}
private String decode(HttpServletRequest request) {
String encoded = request.getParameter(Saml2ParameterNames.SAML_RESPONSE); | if (encoded == null) {
return null;
}
boolean isGet = HttpMethod.GET.matches(request.getMethod());
if (!this.shouldConvertGetRequests && isGet) {
return null;
}
Saml2Utils.DecodingConfigurer decoding = Saml2Utils.withEncoded(encoded).requireBase64(true).inflate(isGet);
try {
return decoding.decode();
}
catch (Exception ex) {
throw new Saml2AuthenticationException(Saml2Error.invalidResponse(ex.getMessage()), ex);
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\Saml2AuthenticationTokenConverter.java | 2 |
请完成以下Java代码 | private synchronized Path getFilePathOrNull() {return _path;}
public static Path getMigrationScriptDirectory()
{
final Path migrationScriptsDirectory = _migrationScriptsDirectory;
return migrationScriptsDirectory != null ? migrationScriptsDirectory : getDefaultMigrationScriptDirectory();
}
private static Path getDefaultMigrationScriptDirectory()
{
return Paths.get(Ini.getMetasfreshHome(), "migration_scripts");
}
public static void setMigrationScriptDirectory(@NonNull final Path path)
{
_migrationScriptsDirectory = path;
logger.info("Set migration scripts directory: {}", path);
}
/**
* Appends given SQL statement.
* <p>
* If this method is called within a database transaction then the SQL statement will not be written to file directly,
* but it will be collected and written when the transaction is committed.
*/
public synchronized void appendSqlStatement(@NonNull final Sql sqlStatement)
{
collectorFactory.collect(sqlStatement);
}
public synchronized void appendSqlStatements(@NonNull final SqlBatch sqlBatch)
{
sqlBatch.streamSqls().forEach(collectorFactory::collect);
}
private synchronized void appendNow(final String sqlStatements) | {
if (sqlStatements == null || sqlStatements.isEmpty())
{
return;
}
try
{
final Path path = getCreateFilePath();
FileUtil.writeString(path, sqlStatements, CHARSET, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
catch (final IOException ex)
{
logger.error("Failed writing to {}:\n {}", this, sqlStatements, ex);
close(); // better to close the file ... so, next time a new one will be created
}
}
/**
* Close underling file.
* <p>
* Next time, {@link #appendSqlStatement(Sql)} will be called, a new file will be created, so it's safe to call this method as many times as needed.
*/
public synchronized void close()
{
watcher.addLog("Closed migration script: " + _path);
_path = null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\MigrationScriptFileLogger.java | 1 |
请完成以下Java代码 | public URL transform(URL artifact) throws Exception {
try {
return new URL("bar", null, artifact.toString());
} catch (Exception e) {
LOGGER.error("Unable to build bar bundle", e);
return null;
}
}
@Override
public boolean canHandle(File artifact) {
JarFile jar = null;
try {
if (!artifact.getName().endsWith(".bar")) {
return false;
}
jar = new JarFile(artifact);
// Only handle non OSGi bundles
Manifest m = jar.getManifest(); | if (m != null && m.getMainAttributes().getValue(new Attributes.Name(BUNDLE_SYMBOLICNAME)) != null && m.getMainAttributes().getValue(new Attributes.Name(BUNDLE_VERSION)) != null) {
return false;
}
return true;
} catch (Exception e) {
return false;
} finally {
if (jar != null) {
try {
jar.close();
} catch (IOException e) {
LOGGER.error("Unable to close jar", e);
}
}
}
}
} | repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\BarDeploymentListener.java | 1 |
请完成以下Java代码 | public I_M_InOutLine getM_InOutLine()
{
return get_ValueAsPO(COLUMNNAME_M_InOutLine_ID, I_M_InOutLine.class);
}
@Override
public void setM_InOutLine(final I_M_InOutLine M_InOutLine)
{
set_ValueFromPO(COLUMNNAME_M_InOutLine_ID, I_M_InOutLine.class, M_InOutLine);
}
@Override
public void setM_InOutLine_ID (final int M_InOutLine_ID)
{
if (M_InOutLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID);
}
@Override
public int getM_InOutLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public I_M_InOut_Cost getReversal()
{
return get_ValueAsPO(COLUMNNAME_Reversal_ID, I_M_InOut_Cost.class);
} | @Override
public void setReversal(final I_M_InOut_Cost Reversal)
{
set_ValueFromPO(COLUMNNAME_Reversal_ID, I_M_InOut_Cost.class, Reversal);
}
@Override
public void setReversal_ID (final int Reversal_ID)
{
if (Reversal_ID < 1)
set_Value (COLUMNNAME_Reversal_ID, null);
else
set_Value (COLUMNNAME_Reversal_ID, Reversal_ID);
}
@Override
public int getReversal_ID()
{
return get_ValueAsInt(COLUMNNAME_Reversal_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOut_Cost.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ConnectionString getConnectionString() {
// protocol://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database.collection][?options]]
if (this.properties.getUri() != null) {
return new ConnectionString(this.properties.getUri());
}
StringBuilder builder = new StringBuilder(getProtocol()).append("://");
if (this.properties.getUsername() != null) {
builder.append(encode(this.properties.getUsername()));
builder.append(":");
if (this.properties.getPassword() != null) {
builder.append(encode(this.properties.getPassword()));
}
builder.append("@");
}
builder.append((this.properties.getHost() != null) ? this.properties.getHost() : "localhost");
if (this.properties.getPort() != null) {
builder.append(":");
builder.append(this.properties.getPort());
}
if (this.properties.getAdditionalHosts() != null) {
builder.append(",");
builder.append(String.join(",", this.properties.getAdditionalHosts()));
}
builder.append("/");
builder.append(this.properties.getMongoClientDatabase());
List<String> options = getOptions();
if (!options.isEmpty()) {
builder.append("?");
builder.append(String.join("&", options));
}
return new ConnectionString(builder.toString());
}
private String getProtocol() {
String protocol = this.properties.getProtocol();
if (StringUtils.hasText(protocol)) {
return protocol;
}
return "mongodb";
}
private String encode(String input) {
return URLEncoder.encode(input, StandardCharsets.UTF_8);
}
private char[] encode(char[] input) {
return URLEncoder.encode(new String(input), StandardCharsets.UTF_8).toCharArray(); | }
@Override
public @Nullable SslBundle getSslBundle() {
Ssl ssl = this.properties.getSsl();
if (!ssl.isEnabled()) {
return null;
}
if (StringUtils.hasLength(ssl.getBundle())) {
Assert.notNull(this.sslBundles, "SSL bundle name has been set but no SSL bundles found in context");
return this.sslBundles.getBundle(ssl.getBundle());
}
return SslBundle.systemDefault();
}
private List<String> getOptions() {
List<String> options = new ArrayList<>();
if (StringUtils.hasText(this.properties.getReplicaSetName())) {
options.add("replicaSet=" + this.properties.getReplicaSetName());
}
if (this.properties.getUsername() != null && this.properties.getAuthenticationDatabase() != null) {
options.add("authSource=" + this.properties.getAuthenticationDatabase());
}
return options;
}
} | repos\spring-boot-4.0.1\module\spring-boot-mongodb\src\main\java\org\springframework\boot\mongodb\autoconfigure\PropertiesMongoConnectionDetails.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected CmmnExecution newCaseInstance() {
CaseExecutionEntity caseInstance = new CaseExecutionEntity();
if (tenantId != null) {
caseInstance.setTenantId(tenantId);
}
Context
.getCommandContext()
.getCaseExecutionManager()
.insertCaseExecution(caseInstance);
return caseInstance;
}
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("historyTimeToLive", this.historyTimeToLive);
return persistentState;
}
@Override | public String toString() {
return "CaseDefinitionEntity["+id+"]";
}
/**
* Updates all modifiable fields from another case definition entity.
* @param updatingCaseDefinition
*/
@Override
public void updateModifiableFieldsFromEntity(CaseDefinitionEntity updatingCaseDefinition) {
if (this.key.equals(updatingCaseDefinition.key) && this.deploymentId.equals(updatingCaseDefinition.deploymentId)) {
this.revision = updatingCaseDefinition.revision;
this.historyTimeToLive = updatingCaseDefinition.historyTimeToLive;
}
else {
LOG.logUpdateUnrelatedCaseDefinitionEntity(this.key, updatingCaseDefinition.key, this.deploymentId, updatingCaseDefinition.deploymentId);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\repository\CaseDefinitionEntity.java | 2 |
请完成以下Java代码 | public void logMethodCallBeforeExecution(JoinPoint joinPoint) {
logger.info("Before Aspect - {} is called with arguments: {}"
, joinPoint, joinPoint.getArgs());//WHAT
}
@After("com.in28minutes.learnspringaop.aopexample.aspects.CommonPointcutConfig.businessPackageConfig()")
public void logMethodCallAfterExecution(JoinPoint joinPoint) {
logger.info("After Aspect - {} has executed", joinPoint);
}
@AfterThrowing(
pointcut = "com.in28minutes.learnspringaop.aopexample.aspects.CommonPointcutConfig.businessAndDataPackageConfig()",
throwing = "exception"
)
public void logMethodCallAfterException(JoinPoint joinPoint, Exception exception) { | logger.info("AfterThrowing Aspect - {} has thrown an exception {}"
, joinPoint, exception);
}
@AfterReturning(
pointcut = "com.in28minutes.learnspringaop.aopexample.aspects.CommonPointcutConfig.dataPackageConfig()",
returning = "resultValue"
)
public void logMethodCallAfterSuccessfulExecution(JoinPoint joinPoint,
Object resultValue) {
logger.info("AfterReturning Aspect - {} has returned {}"
, joinPoint, resultValue);
}
} | repos\master-spring-and-spring-boot-main\73-spring-aop\src\main\java\com\in28minutes\learnspringaop\aopexample\aspects\LoggingAspect.java | 1 |
请完成以下Java代码 | public void setStatecode(String value) {
this.statecode = value;
}
/**
* Gets the value of the countrycode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCountrycode() {
if (countrycode == null) {
return "CH";
} else {
return countrycode; | }
}
/**
* Sets the value of the countrycode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCountrycode(String value) {
this.countrycode = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ZipType.java | 1 |
请完成以下Java代码 | private ProcessPreconditionsResolution.ProcessCaptionMapper getCaptionMapper()
{
return processCaptionMapperHelper.getProcessCaptionMapperForNetAmountsFromQuery(retrieveQuery(false));
}
@Override
@RunOutOfTrx
protected String doIt() throws Exception
{
final IQuery<I_C_Invoice_Candidate> query = retrieveQuery(true);
//
// Fail if there is nothing to update
final int countToUpdate = query.count();
if (countToUpdate <= 0)
{
throw new AdempiereException("@NoSelection@");
}
final boolean flagToSet = isApproveForInvoicing();
//
// Update selected invoice candidates
countUpdated = query.update(ic -> {
ic.setApprovalForInvoicing(flagToSet);
return IQueryUpdater.MODEL_UPDATED;
});
return MSG_OK;
}
protected IQueryFilter<I_C_Invoice_Candidate> getSelectionFilter()
{
final SqlViewRowsWhereClause viewSqlWhereClause = getViewSqlWhereClause(getSelectedRowIds());
return viewSqlWhereClause.toQueryFilter();
} | private SqlViewRowsWhereClause getViewSqlWhereClause(@NonNull final DocumentIdsSelection rowIds)
{
final String invoiceCandidateTableName = I_C_Invoice_Candidate.Table_Name;
return getView().getSqlWhereClause(rowIds, SqlOptions.usingTableName(invoiceCandidateTableName));
}
protected abstract boolean isApproveForInvoicing();
protected abstract IQuery<I_C_Invoice_Candidate> retrieveQuery(final boolean includeProcessInfoFilters);
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
//
// Notify frontend that the view shall be refreshed because we changed some candidates
if (countUpdated > 0)
{
invalidateView();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoicecandidate\process\C_Invoice_Candidate_ProcessHelper.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.