instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public boolean requestFocus(final GridTab gridTab)
{
final I_C_Order order = InterfaceWrapperHelper.create(gridTab, I_C_Order.class);
final Integer productId = order.getM_Product_ID();
if (productId <= 0
&& gridTab.getField(I_C_Order.COLUMNNAME_M_Product_ID).isDisplayed())
{
gridTab.getField(I_C_Order.COLUMNNAME_M_Product_ID).requestFocus();
return true;
}
final BigDecimal qty = order.getQty_FastInput();
if (qty == null || qty.signum() <= 0
&& gridTab.getField(I_C_Order.COLUMNNAME_Qty_FastInput).isDisplayed())
{
|
// product has been set, but qty hasn't
gridTab.getField(I_C_Order.COLUMNNAME_Qty_FastInput).requestFocus();
return true;
}
// no focus was requested
return false;
}
@Override
public IGridTabRowBuilder createLineBuilderFromHeader(final Object model)
{
final OrderLineProductQtyGridRowBuilder builder = new OrderLineProductQtyGridRowBuilder();
builder.setSource(model);
return builder;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\callout\ProductQtyOrderFastInputHandler.java
| 1
|
请完成以下Java代码
|
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
|
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public List<Role> getRoles()
{
return roles;
}
public void setRoles(List<Role> roles)
{
this.roles = roles;
}
}
|
repos\Spring-Boot-Advanced-Projects-main\springboot-thymeleaf-security-demo\src\main\java\net\alanbinu\springbootsecurity\entities\User.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected void validateDataImpl(TenantId tenantId, TbResource resource) {
validateString("Resource title", resource.getTitle());
if (resource.getTenantId() == null) {
resource.setTenantId(TenantId.SYS_TENANT_ID);
}
if (!resource.getTenantId().isSysTenantId()) {
if (!tenantService.tenantExists(resource.getTenantId())) {
throw new DataValidationException("Resource is referencing to non-existent tenant!");
}
}
if (resource.getResourceType() == null) {
throw new DataValidationException("Resource type should be specified!");
}
if (resource.getData() != null) {
validateResourceSize(resource.getTenantId(), resource.getId(), resource.getData().length);
}
if (StringUtils.isEmpty(resource.getFileName())) {
throw new DataValidationException("Resource file name should be specified!");
}
if (Strings.CS.containsAny(resource.getFileName(), "/", "\\")) {
throw new DataValidationException("File name contains forbidden symbols");
}
|
if (StringUtils.isEmpty(resource.getResourceKey())) {
throw new DataValidationException("Resource key should be specified!");
}
}
public void validateResourceSize(TenantId tenantId, TbResourceId resourceId, long dataSize) {
if (!tenantId.isSysTenantId()) {
DefaultTenantProfileConfiguration profileConfiguration = tenantProfileCache.get(tenantId).getDefaultProfileConfiguration();
long maxResourceSize = profileConfiguration.getMaxResourceSize();
if (maxResourceSize > 0 && dataSize > maxResourceSize) {
throw new IllegalArgumentException("Resource exceeds the maximum size of " + FileUtils.byteCountToDisplaySize(maxResourceSize));
}
long maxSumResourcesDataInBytes = profileConfiguration.getMaxResourcesInBytes();
if (resourceId != null) {
long prevSize = resourceDao.getResourceSize(tenantId, resourceId);
dataSize -= prevSize;
}
validateMaxSumDataSizePerTenant(tenantId, resourceDao, maxSumResourcesDataInBytes, dataSize, TB_RESOURCE);
}
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\ResourceDataValidator.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setAuthoritiesExtractor(AuthoritiesExtractor authoritiesExtractor) {
this.authoritiesExtractor = authoritiesExtractor;
}
@Override
public OAuth2Authentication loadAuthentication(String accessToken)
throws AuthenticationException, InvalidTokenException {
Map<String, Object> map = getMap(this.userInfoEndpointUrl, accessToken);
if (map.containsKey("error")) {
this.logger.debug("userinfo returned error: " + map.get("error"));
throw new InvalidTokenException(accessToken);
}
return extractAuthentication(map);
}
private OAuth2Authentication extractAuthentication(Map<String, Object> map) {
Object principal = getPrincipal(map);
OAuth2Request request = getRequest(map);
List<GrantedAuthority> authorities = this.authoritiesExtractor
.extractAuthorities(map);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
principal, "N/A", authorities);
token.setDetails(map);
return new OAuth2Authentication(request, token);
}
private Object getPrincipal(Map<String, Object> map) {
for (String key : PRINCIPAL_KEYS) {
if (map.containsKey(key)) {
return map.get(key);
}
}
return "unknown";
}
@SuppressWarnings({ "unchecked" })
private OAuth2Request getRequest(Map<String, Object> map) {
Map<String, Object> request = (Map<String, Object>) map.get("oauth2Request");
String clientId = (String) request.get("clientId");
Set<String> scope = new LinkedHashSet<>(request.containsKey("scope") ?
(Collection<String>) request.get("scope") : Collections.<String>emptySet());
return new OAuth2Request(null, clientId, null, true, new HashSet<>(scope),
null, null, null, null);
}
@Override
public OAuth2AccessToken readAccessToken(String accessToken) {
throw new UnsupportedOperationException("Not supported: read access token");
|
}
@SuppressWarnings({ "unchecked" })
private Map<String, Object> getMap(String path, String accessToken) {
this.logger.debug("Getting user info from: " + path);
try {
OAuth2RestOperations restTemplate = this.restTemplate;
if (restTemplate == null) {
BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails();
resource.setClientId(this.clientId);
restTemplate = new OAuth2RestTemplate(resource);
}
OAuth2AccessToken existingToken = restTemplate.getOAuth2ClientContext()
.getAccessToken();
if (existingToken == null || !accessToken.equals(existingToken.getValue())) {
DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(
accessToken);
token.setTokenType(this.tokenType);
restTemplate.getOAuth2ClientContext().setAccessToken(token);
}
return restTemplate.getForEntity(path, Map.class).getBody();
}
catch (Exception ex) {
this.logger.info("Could not fetch user details: " + ex.getClass() + ", "
+ ex.getMessage());
return Collections.<String, Object>singletonMap("error",
"Could not fetch user details");
}
}
}
|
repos\piggymetrics-master\account-service\src\main\java\com\piggymetrics\account\service\security\CustomUserInfoTokenServices.java
| 2
|
请完成以下Java代码
|
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOutputName() {
return outputName;
}
public void setOutputName(String outputName) {
this.outputName = outputName;
}
public TypedValue getValue() {
return value;
}
public void setValue(TypedValue value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DmnEvaluatedOutputImpl that = (DmnEvaluatedOutputImpl) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (outputName != null ? !outputName.equals(that.outputName) : that.outputName != null) return false;
return !(value != null ? !value.equals(that.value) : that.value != null);
}
|
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (outputName != null ? outputName.hashCode() : 0);
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "DmnEvaluatedOutputImpl{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", outputName='" + outputName + '\'' +
", value=" + value +
'}';
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\delegate\DmnEvaluatedOutputImpl.java
| 1
|
请完成以下Java代码
|
private Set<String> determineImports(GroovyCompilationUnit compilationUnit) {
List<String> imports = new ArrayList<>();
for (GroovyTypeDeclaration typeDeclaration : compilationUnit.getTypeDeclarations()) {
imports.add(typeDeclaration.getExtends());
imports.addAll(typeDeclaration.getImplements());
imports.addAll(appendImports(typeDeclaration.annotations().values(), Annotation::getImports));
for (GroovyFieldDeclaration fieldDeclaration : typeDeclaration.getFieldDeclarations()) {
imports.add(fieldDeclaration.getReturnType());
imports.addAll(appendImports(fieldDeclaration.annotations().values(), Annotation::getImports));
}
for (GroovyMethodDeclaration methodDeclaration : typeDeclaration.getMethodDeclarations()) {
imports.add(methodDeclaration.getReturnType());
imports.addAll(appendImports(methodDeclaration.annotations().values(), Annotation::getImports));
for (Parameter parameter : methodDeclaration.getParameters()) {
imports.add(parameter.getType());
imports.addAll(appendImports(parameter.annotations().values(), Annotation::getImports));
}
imports.addAll(methodDeclaration.getCode().getImports());
}
}
return imports.stream()
.filter((candidate) -> isImportCandidate(compilationUnit, candidate))
.sorted()
.collect(Collectors.toCollection(LinkedHashSet::new));
}
private <T> List<String> appendImports(Stream<T> candidates, Function<T, Collection<String>> mapping) {
return candidates.map(mapping).flatMap(Collection::stream).collect(Collectors.toList());
}
private String getUnqualifiedName(String name) {
if (!name.contains(".")) {
return name;
|
}
return name.substring(name.lastIndexOf(".") + 1);
}
private boolean isImportCandidate(CompilationUnit<?> compilationUnit, String name) {
if (name == null || !name.contains(".")) {
return false;
}
String packageName = name.substring(0, name.lastIndexOf('.'));
return !"java.lang".equals(packageName) && !compilationUnit.getPackageName().equals(packageName);
}
static class GroovyFormattingOptions implements FormattingOptions {
@Override
public String statementSeparator() {
return "";
}
@Override
public CodeBlock arrayOf(CodeBlock... values) {
return CodeBlock.of("[ $L ]", CodeBlock.join(Arrays.asList(values), ", "));
}
@Override
public CodeBlock classReference(ClassName className) {
return CodeBlock.of("$T", className);
}
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\groovy\GroovySourceCodeWriter.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
|
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
|
repos\tutorials-master\persistence-modules\java-jpa-4\src\main\java\com\baeldung\jpa\undeterminejdbctype\EmployeeWithAnnotation.java
| 1
|
请完成以下Java代码
|
protected void applySortBy(HistoricJobLogQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_TIMESTAMP)) {
query.orderByTimestamp();
} else if (sortBy.equals(SORT_BY_JOB_ID)) {
query.orderByJobId();
} else if (sortBy.equals(SORT_BY_JOB_DUE_DATE)) {
query.orderByJobDueDate();
} else if (sortBy.equals(SORT_BY_JOB_RETRIES)) {
query.orderByJobRetries();
} else if (sortBy.equals(SORT_BY_JOB_PRIORITY)) {
query.orderByJobPriority();
} else if (sortBy.equals(SORT_BY_JOB_DEFINITION_ID)) {
query.orderByJobDefinitionId();
} else if (sortBy.equals(SORT_BY_ACTIVITY_ID)) {
query.orderByActivityId();
} else if (sortBy.equals(SORT_BY_EXECUTION_ID)) {
query.orderByExecutionId();
} else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID)) {
query.orderByProcessInstanceId();
|
} else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) {
query.orderByProcessDefinitionId();
} else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) {
query.orderByProcessDefinitionKey();
} else if (sortBy.equals(SORT_BY_DEPLOYMENT_ID)) {
query.orderByDeploymentId();
} else if (sortBy.equals(SORT_PARTIALLY_BY_OCCURRENCE)) {
query.orderPartiallyByOccurrence();
} else if (sortBy.equals(SORT_BY_TENANT_ID)) {
query.orderByTenantId();
} else if (sortBy.equals(SORT_BY_HOSTNAME)) {
query.orderByHostname();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricJobLogQueryDto.java
| 1
|
请完成以下Java代码
|
public String getDescribed() {
return described;
}
public void setDescribed(String described) {
this.described = described;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* 根据值获取名称
*
* @param value
* @return
*/
public static String getNameByValue(String value){
if (oConvertUtils.isEmpty(value)) {
return null;
}
for (DepartCategoryEnum val : values()) {
|
if (val.getValue().equals(value)) {
return val.getName();
}
}
return value;
}
/**
* 根据名称获取值
*
* @param name
* @return
*/
public static String getValueByName(String name){
if (oConvertUtils.isEmpty(name)) {
return null;
}
for (DepartCategoryEnum val : values()) {
if (val.getName().equals(name)) {
return val.getValue();
}
}
return name;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\DepartCategoryEnum.java
| 1
|
请完成以下Java代码
|
public Boolean getComplete() {
return complete;
}
public void setComplete(Boolean complete) {
this.complete = complete;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order order = (Order) o;
return Objects.equals(this.id, order.id) &&
Objects.equals(this.petId, order.petId) &&
Objects.equals(this.quantity, order.quantity) &&
Objects.equals(this.shipDate, order.shipDate) &&
Objects.equals(this.status, order.status) &&
Objects.equals(this.complete, order.complete);
}
@Override
public int hashCode() {
return Objects.hash(id, petId, quantity, shipDate, status, complete);
|
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Order {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" petId: ").append(toIndentedString(petId)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" complete: ").append(toIndentedString(complete)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\Order.java
| 1
|
请完成以下Java代码
|
private ProcessPreconditionsResolution checkPreconditions(final IView view, final DocumentIdsSelection selectedDocumentIds)
{
try
{
return getPreconditionsInstance().matches(view, selectedDocumentIds);
}
catch (final InstantiationException | IllegalAccessException ex)
{
throw AdempiereException.wrapIfNeeded(ex);
}
}
private Precondition getPreconditionsInstance() throws InstantiationException, IllegalAccessException
{
if (preconditionSharedInstance != null)
{
return preconditionSharedInstance;
}
return preconditionClass.newInstance();
}
@NonNull public Method getViewActionMethod()
{
return viewActionMethod;
}
public ProcessInstanceResult.ResultAction convertReturnType(final Object returnValue)
{
|
return viewActionReturnTypeConverter.convert(returnValue);
}
@NonNull public Object[] extractMethodArguments(final IView view, final Document processParameters, final DocumentIdsSelection selectedDocumentIds)
{
return viewActionParamDescriptors.stream()
.map(paramDesc -> paramDesc.extractArgument(view, processParameters, selectedDocumentIds))
.toArray();
}
@FunctionalInterface
public interface ViewActionMethodReturnTypeConverter
{
ProcessInstanceResult.ResultAction convert(Object returnValue);
}
@FunctionalInterface
public interface ViewActionMethodArgumentExtractor
{
Object extractArgument(IView view, Document processParameters, DocumentIdsSelection selectedDocumentIds);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\view\ViewActionDescriptor.java
| 1
|
请完成以下Java代码
|
public String getErrorMessage() {
return errorMessage;
}
public Date getCreateTime() {
return createTime;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public static HistoricDecisionInputInstanceDto fromHistoricDecisionInputInstance(HistoricDecisionInputInstance historicDecisionInputInstance) {
HistoricDecisionInputInstanceDto dto = new HistoricDecisionInputInstanceDto();
dto.id = historicDecisionInputInstance.getId();
dto.decisionInstanceId = historicDecisionInputInstance.getDecisionInstanceId();
dto.clauseId = historicDecisionInputInstance.getClauseId();
dto.clauseName = historicDecisionInputInstance.getClauseName();
dto.createTime = historicDecisionInputInstance.getCreateTime();
|
dto.removalTime = historicDecisionInputInstance.getRemovalTime();
dto.rootProcessInstanceId = historicDecisionInputInstance.getRootProcessInstanceId();
if(historicDecisionInputInstance.getErrorMessage() == null) {
VariableValueDto.fromTypedValue(dto, historicDecisionInputInstance.getTypedValue());
}
else {
dto.errorMessage = historicDecisionInputInstance.getErrorMessage();
dto.type = VariableValueDto.toRestApiTypeName(historicDecisionInputInstance.getTypeName());
}
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricDecisionInputInstanceDto.java
| 1
|
请完成以下Java代码
|
public void setM_Warehouse_Type_ID (int M_Warehouse_Type_ID)
{
if (M_Warehouse_Type_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_Type_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_Type_ID, Integer.valueOf(M_Warehouse_Type_ID));
}
/** Get Warehouse Type.
@return Warehouse Type */
@Override
public int getM_Warehouse_Type_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_Type_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
|
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse_Type.java
| 1
|
请完成以下Java代码
|
public List<HttpExchange> findAll(String query) {
List<HttpExchange> allTrace = super.findAll();
if (null != allTrace && !allTrace.isEmpty()) {
Stream<HttpExchange> stream = allTrace.stream();
String[] params = query.split(",");
stream = filter(params, stream);
stream = sort(params, stream);
allTrace = stream.collect(Collectors.toList());
}
return allTrace;
}
private Stream<HttpExchange> sort(String[] params, Stream<HttpExchange> stream) {
if (params.length < 2) {
return stream;
}
String sortBy = params[1];
String order;
if (params.length > 2) {
order = params[2];
} else {
order = "desc";
}
return stream.sorted((o1, o2) -> {
int i = 0;
if("timeTaken".equalsIgnoreCase(sortBy)) {
i = o1.getTimeTaken().compareTo(o2.getTimeTaken());
}else if("timestamp".equalsIgnoreCase(sortBy)){
i = o1.getTimestamp().compareTo(o2.getTimestamp());
}
if("desc".equalsIgnoreCase(order)){
i *=-1;
}
return i;
});
}
private static Stream<HttpExchange> filter(String[] params, Stream<HttpExchange> stream) {
if (params.length == 0) {
return stream;
}
String statusQuery = params[0];
if (null != statusQuery && !statusQuery.isEmpty()) {
statusQuery = statusQuery.toLowerCase().trim();
switch (statusQuery) {
case "error":
stream = stream.filter(httpTrace -> {
int status = httpTrace.getResponse().getStatus();
return status >= 404 && status < 501;
});
|
break;
case "warn":
stream = stream.filter(httpTrace -> {
int status = httpTrace.getResponse().getStatus();
return status >= 201 && status < 404;
});
break;
case "success":
stream = stream.filter(httpTrace -> {
int status = httpTrace.getResponse().getStatus();
return status == 200;
});
break;
case "all":
default:
break;
}
return stream;
}
return stream;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\monitor\actuator\httptrace\CustomInMemoryHttpTraceRepository.java
| 1
|
请完成以下Java代码
|
public File checkDirectory(@NonNull final String name, @NonNull final String dir)
{
return checkDirectory(name, new File(dir));
}
public File checkDirectory(@NonNull final String name, @NonNull final File dir)
{
if (!dir.exists())
{
throw new IllegalArgumentException(name + " '" + dir + "' does not exist");
}
final File dirAbs;
try
{
dirAbs = dir.getCanonicalFile();
}
|
catch (final IOException e)
{
throw new IllegalArgumentException(name + " '" + dir + "' is not accessible", e);
}
if (!dirAbs.isDirectory())
{
throw new IllegalArgumentException(name + " '" + dirAbs + "' is not a directory");
}
if (!dirAbs.canRead())
{
throw new IllegalArgumentException(name + " '" + dirAbs + "' is not readable");
}
return dirAbs;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\DirectoryChecker.java
| 1
|
请完成以下Java代码
|
public Builder refreshToken(String refreshToken) {
this.refreshToken = refreshToken;
return this;
}
/**
* Sets the additional parameters returned in the response.
* @param additionalParameters the additional parameters returned in the response
* @return the {@link Builder}
*/
public Builder additionalParameters(Map<String, Object> additionalParameters) {
this.additionalParameters = additionalParameters;
return this;
}
/**
* Builds a new {@link OAuth2AccessTokenResponse}.
* @return a {@link OAuth2AccessTokenResponse}
*/
public OAuth2AccessTokenResponse build() {
Instant issuedAt = getIssuedAt();
Instant expiresAt = getExpiresAt();
OAuth2AccessTokenResponse accessTokenResponse = new OAuth2AccessTokenResponse();
accessTokenResponse.accessToken = new OAuth2AccessToken(this.tokenType, this.tokenValue, issuedAt,
expiresAt, this.scopes);
if (StringUtils.hasText(this.refreshToken)) {
accessTokenResponse.refreshToken = new OAuth2RefreshToken(this.refreshToken, issuedAt);
}
accessTokenResponse.additionalParameters = Collections
.unmodifiableMap(CollectionUtils.isEmpty(this.additionalParameters) ? Collections.emptyMap()
: this.additionalParameters);
return accessTokenResponse;
}
private Instant getIssuedAt() {
|
if (this.issuedAt == null) {
this.issuedAt = Instant.now();
}
return this.issuedAt;
}
/**
* expires_in is RECOMMENDED, as per spec
* https://tools.ietf.org/html/rfc6749#section-5.1 Therefore, expires_in may not
* be returned in the Access Token response which would result in the default
* value of 0. For these instances, default the expiresAt to +1 second from
* issuedAt time.
* @return
*/
private Instant getExpiresAt() {
if (this.expiresAt == null) {
Instant issuedAt = getIssuedAt();
this.expiresAt = (this.expiresIn > 0) ? issuedAt.plusSeconds(this.expiresIn) : issuedAt.plusSeconds(1);
}
return this.expiresAt;
}
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2AccessTokenResponse.java
| 1
|
请完成以下Java代码
|
protected final boolean processKeyBinding(final KeyStroke ks, final KeyEvent e, final int condition, final boolean pressed)
{
// Forward all key events on this component to the text field.
// We have to do this for the case when we are embedding this editor in a JTable and the JTable is forwarding the key strokes to editing component.
// Effect of NOT doing this: when in JTable, user presses a key (e.g. a digit) to start editing but the first key he pressed gets lost here.
if (m_text != null && condition == WHEN_FOCUSED)
{
// Usually the text component does not have focus yet but it was requested, so, considering that:
// * we are requesting the focus just to make sure
// * we select all text (once) => as an effect, on first key pressed the editor content (which is selected) will be deleted and replaced with the new typing
// * make sure that in the focus event which will come, the text is not selected again, else, if user is typing fast, the editor content will be only what he typed last.
if(!m_text.hasFocus())
{
skipNextSelectAllOnFocusGained = true;
m_text.requestFocus();
if (m_text.getDocument().getLength() > 0)
{
|
m_text.selectAll();
}
}
if (m_text.processKeyBinding(ks, e, condition, pressed))
{
return true;
}
}
//
// Fallback to super
return super.processKeyBinding(ks, e, condition, pressed);
}
} // VNumber
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VNumber.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Optional<MaterialDispoGroupId> getEffectiveGroupId() {return Optional.ofNullable(candidate.getEffectiveGroupId());}
public Optional<MaterialDispoGroupId> getGroupId() {return Optional.ofNullable(candidate.getGroupId());}
public BigDecimal getQtyDelta()
{
BigDecimal qtyDelta = candidate.getQuantity();
if (previousQty != null)
{
qtyDelta = qtyDelta.subtract(previousQty);
}
return qtyDelta;
}
/**
* @return {@code true} if before the save, there already was a record with a different date.
*/
public boolean isDateMoved()
{
if (previousTime == null)
{
return false;
}
return !DateAndSeqNo.equals(previousTime, DateAndSeqNo.ofCandidate(candidate));
}
public boolean isDateMovedForwards()
{
if (previousTime == null)
{
return false;
}
return previousTime.isBefore(DateAndSeqNo.ofCandidate(candidate));
}
/**
* @return {@code true} there was no record before the save, or the record's date was changed.
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isDateChanged()
{
if (previousTime == null)
{
return true;
}
return !DateAndSeqNo.equals(previousTime, DateAndSeqNo.ofCandidate(candidate));
}
|
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isQtyChanged()
{
return getQtyDelta().signum() != 0;
}
// TODO figure out if we really need this
public Candidate toCandidateWithQtyDelta()
{
return candidate.withQuantity(getQtyDelta());
}
/**
* Convenience method that returns a new instance whose included {@link Candidate} has the given id.
*/
public CandidateSaveResult withCandidateId(@Nullable final CandidateId candidateId)
{
return toBuilder()
.candidate(candidate.withId(candidateId))
.build();
}
/**
* Convenience method that returns a new instance with negated candidate quantity and previousQty
*/
public CandidateSaveResult withNegatedQuantity()
{
return toBuilder()
.candidate(candidate.withNegatedQuantity())
.previousQty(previousQty == null ? null : previousQty.negate())
.build();
}
public CandidateSaveResult withParentId(@Nullable final CandidateId parentId)
{
return toBuilder()
.candidate(candidate.withParentId(parentId))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\CandidateSaveResult.java
| 2
|
请完成以下Java代码
|
public static ColorValue ofHexString(final String hexString)
{
return interner.intern(new ColorValue(hexString));
}
private static Interner<ColorValue> interner = Interners.newStrongInterner();
static
{
interner.intern(RED);
interner.intern(GREEN);
}
String hexString;
private ColorValue(final String hexString)
{
this.hexString = normalizeHexString(hexString);
}
private static String normalizeHexString(@NonNull final String hexString)
{
try
{
final int i = Integer.decode(hexString);
final int red = i >> 16 & 0xFF;
final int green = i >> 8 & 0xFF;
final int blue = i & 0xFF;
|
return toHexString(red, green, blue);
}
catch (final Exception ex)
{
throw new AdempiereException("Invalid color hex string: " + hexString, ex);
}
}
public static String toHexString(final int red, final int green, final int blue)
{
return MFColor.toHexString(red, green, blue);
}
@JsonValue
public String toJson()
{
return hexString;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\ColorValue.java
| 1
|
请完成以下Java代码
|
private void setValidStatus(final JSONDocumentValidStatus validStatus)
{
this.validStatus = validStatus;
}
private void setSaveStatus(final JSONDocumentSaveStatus saveStatus)
{
this.saveStatus = saveStatus;
}
public void addIncludedTabInfo(final JSONIncludedTabInfo tabInfo)
{
if (includedTabsInfo == null)
{
includedTabsInfo = new HashMap<>();
}
includedTabsInfo.put(tabInfo.getTabId().toJson(), tabInfo);
}
|
@JsonIgnore
public Collection<JSONIncludedTabInfo> getIncludedTabsInfos()
{
if (includedTabsInfo == null || includedTabsInfo.isEmpty())
{
return ImmutableSet.of();
}
return includedTabsInfo.values();
}
private void setStandardActions(final Set<DocumentStandardAction> standardActions)
{
this.standardActions = standardActions;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocument.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void registerDefaultLogoutSuccessHandler(B http, RequestMatcher preferredMatcher) {
LogoutConfigurer<B> logout = http.getConfigurer(LogoutConfigurer.class);
if (logout == null) {
return;
}
LogoutConfigurer<B> handler = logout.defaultLogoutSuccessHandlerFor(
postProcess(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.NO_CONTENT)), preferredMatcher);
}
@Override
public void configure(B http) {
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
BasicAuthenticationFilter basicAuthenticationFilter = new BasicAuthenticationFilter(authenticationManager,
this.authenticationEntryPoint);
if (this.authenticationDetailsSource != null) {
|
basicAuthenticationFilter.setAuthenticationDetailsSource(this.authenticationDetailsSource);
}
if (this.securityContextRepository != null) {
basicAuthenticationFilter.setSecurityContextRepository(this.securityContextRepository);
}
RememberMeServices rememberMeServices = http.getSharedObject(RememberMeServices.class);
if (rememberMeServices != null) {
basicAuthenticationFilter.setRememberMeServices(rememberMeServices);
}
basicAuthenticationFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy());
basicAuthenticationFilter = postProcess(basicAuthenticationFilter);
http.addFilter(basicAuthenticationFilter);
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\HttpBasicConfigurer.java
| 2
|
请完成以下Java代码
|
public UserDO setUsername(String username) {
this.username = username;
return this;
}
public String getPassword() {
return password;
}
public UserDO setPassword(String password) {
this.password = password;
return this;
}
public Date getCreateTime() {
return createTime;
|
}
public UserDO setCreateTime(Date createTime) {
this.createTime = createTime;
return this;
}
@Override
public String toString() {
return "UserDO{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", createTime=" + createTime +
'}';
}
}
|
repos\SpringBoot-Labs-master\lab-14-spring-jdbc-template\lab-14-jdbctemplate\src\main\java\cn\iocoder\springboot\lab14\jdbctemplate\dataobject\UserDO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class X_AD_ChangeLog_Config extends org.compiere.model.PO implements I_AD_ChangeLog_Config, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 850578821L;
/** Standard Constructor */
public X_AD_ChangeLog_Config (final Properties ctx, final int AD_ChangeLog_Config_ID, @Nullable final String trxName)
{
super (ctx, AD_ChangeLog_Config_ID, trxName);
}
/** Load Constructor */
public X_AD_ChangeLog_Config (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_ChangeLog_Config_ID (final int AD_ChangeLog_Config_ID)
{
if (AD_ChangeLog_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_ChangeLog_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_ChangeLog_Config_ID, AD_ChangeLog_Config_ID);
}
|
@Override
public int getAD_ChangeLog_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_ChangeLog_Config_ID);
}
@Override
public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID);
}
@Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public void setKeepChangeLogsDays (final int KeepChangeLogsDays)
{
set_Value (COLUMNNAME_KeepChangeLogsDays, KeepChangeLogsDays);
}
@Override
public int getKeepChangeLogsDays()
{
return get_ValueAsInt(COLUMNNAME_KeepChangeLogsDays);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ChangeLog_Config.java
| 2
|
请完成以下Java代码
|
protected void writeUserOperationLog(CommandContext commandContext, int instancesCount) {
List<PropertyChange> propChanges = new ArrayList<>();
int variablesCount = variables.size();
propChanges.add(new PropertyChange("nrOfInstances", null, instancesCount));
propChanges.add(new PropertyChange("nrOfVariables", null, variablesCount));
propChanges.add(new PropertyChange("async", null, true));
commandContext.getOperationLogManager()
.logProcessInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_SET_VARIABLES, propChanges);
}
public BatchConfiguration getConfiguration(BatchElementConfiguration elementConfiguration) {
DeploymentMappings mappings = elementConfiguration.getMappings();
List<String> ids = elementConfiguration.getIds();
return new BatchConfiguration(ids, mappings);
}
protected BatchElementConfiguration collectProcessInstanceIds(CommandContext commandContext) {
BatchElementConfiguration elementConfiguration = new BatchElementConfiguration();
if (!CollectionUtil.isEmpty(processInstanceIds)) {
ProcessInstanceQueryImpl query = new ProcessInstanceQueryImpl();
query.processInstanceIds(new HashSet<>(processInstanceIds));
List<ImmutablePair<String, String>> mappings =
commandContext.runWithoutAuthorization(query::listDeploymentIdMappings);
elementConfiguration.addDeploymentMappings(mappings);
}
|
ProcessInstanceQueryImpl processInstanceQuery =
(ProcessInstanceQueryImpl) this.processInstanceQuery;
if (processInstanceQuery != null) {
List<ImmutablePair<String, String>> mappings =
processInstanceQuery.listDeploymentIdMappings();
elementConfiguration.addDeploymentMappings(mappings);
}
HistoricProcessInstanceQueryImpl historicProcessInstanceQuery =
(HistoricProcessInstanceQueryImpl) this.historicProcessInstanceQuery;
if (historicProcessInstanceQuery != null) {
historicProcessInstanceQuery.unfinished();
List<ImmutablePair<String, String>> mappings =
historicProcessInstanceQuery.listDeploymentIdMappings();
elementConfiguration.addDeploymentMappings(mappings);
}
return elementConfiguration;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\batch\variables\SetVariablesToProcessInstancesBatchCmd.java
| 1
|
请完成以下Java代码
|
public static int toOrderRepoId(@Nullable final OrderAndLineId orderAndLineId)
{
return getOrderRepoIdOr(orderAndLineId, -1);
}
public static int getOrderRepoIdOr(@Nullable final OrderAndLineId orderAndLineId, final int defaultValue)
{
return orderAndLineId != null ? orderAndLineId.getOrderRepoId() : defaultValue;
}
public static int toOrderLineRepoId(@Nullable final OrderAndLineId orderAndLineId)
{
return getOrderLineRepoIdOr(orderAndLineId, -1);
}
public static int getOrderLineRepoIdOr(@Nullable final OrderAndLineId orderAndLineId, final int defaultValue)
{
return orderAndLineId != null ? orderAndLineId.getOrderLineRepoId() : defaultValue;
}
public static Set<Integer> getOrderLineRepoIds(final Collection<OrderAndLineId> orderAndLineIds)
{
return orderAndLineIds.stream().map(OrderAndLineId::getOrderLineRepoId).collect(ImmutableSet.toImmutableSet());
}
public static Set<OrderId> getOrderIds(final Collection<OrderAndLineId> orderAndLineIds)
{
return orderAndLineIds.stream().map(OrderAndLineId::getOrderId).collect(ImmutableSet.toImmutableSet());
}
public static Set<OrderLineId> getOrderLineIds(final Collection<OrderAndLineId> orderAndLineIds)
{
return orderAndLineIds.stream().map(OrderAndLineId::getOrderLineId).collect(ImmutableSet.toImmutableSet());
}
OrderId orderId;
OrderLineId orderLineId;
private OrderAndLineId(@NonNull final OrderId orderId, @NonNull final OrderLineId orderLineId)
{
this.orderId = orderId;
this.orderLineId = orderLineId;
}
public int getOrderRepoId()
{
return orderId.getRepoId();
}
public int getOrderLineRepoId()
|
{
return orderLineId.getRepoId();
}
public static boolean equals(@Nullable final OrderAndLineId o1, @Nullable final OrderAndLineId o2)
{
return Objects.equals(o1, o2);
}
@JsonValue
public String toJson()
{
return orderId.getRepoId() + "_" + orderLineId.getRepoId();
}
@JsonCreator
public static OrderAndLineId ofJson(@NonNull String json)
{
try
{
final int idx = json.indexOf("_");
return ofRepoIds(Integer.parseInt(json.substring(0, idx)), Integer.parseInt(json.substring(idx + 1)));
}
catch (Exception ex)
{
throw new AdempiereException("Invalid JSON: " + json, ex);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderAndLineId.java
| 1
|
请完成以下Java代码
|
public class WordNatureDependencyParser extends MinimumSpanningTreeParser
{
private WordNatureDependencyModel model;
public WordNatureDependencyParser(WordNatureDependencyModel model)
{
this.model = model;
}
public WordNatureDependencyParser(String modelPath)
{
model = GlobalObjectPool.get(modelPath);
if (model != null) return;
model = new WordNatureDependencyModel(modelPath);
GlobalObjectPool.put(modelPath, model);
}
public WordNatureDependencyParser()
{
this(HanLP.Config.WordNatureModelPath);
}
/**
* 分析句子的依存句法
*
* @param termList 句子,可以是任何具有词性标注功能的分词器的分词结果
* @return CoNLL格式的依存句法树
*/
public static CoNLLSentence compute(List<Term> termList)
{
return new WordNatureDependencyParser().parse(termList);
}
|
/**
* 分析句子的依存句法
*
* @param sentence 句子
* @return CoNLL格式的依存句法树
*/
public static CoNLLSentence compute(String sentence)
{
return new WordNatureDependencyParser().parse(sentence);
}
@Override
protected Edge makeEdge(Node[] nodeArray, int from, int to)
{
return model.getEdge(nodeArray[from], nodeArray[to]);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\WordNatureDependencyParser.java
| 1
|
请完成以下Java代码
|
public class CommentGenerator extends DefaultCommentGenerator {
private boolean addRemarkComments = false;
private static final String EXAMPLE_SUFFIX="Example";
private static final String MAPPER_SUFFIX="Mapper";
private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.annotations.ApiModelProperty";
/**
* 设置用户配置的参数
*/
@Override
public void addConfigurationProperties(Properties properties) {
super.addConfigurationProperties(properties);
this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
}
/**
* 给字段添加注释
*/
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
String remarks = introspectedColumn.getRemarks();
//根据参数和备注信息判断是否添加swagger注解信息
if(addRemarkComments&&StringUtility.stringHasValue(remarks)){
// addFieldJavaDoc(field, remarks);
//数据库中特殊字符需要转义
if(remarks.contains("\"")){
remarks = remarks.replace("\"","'");
}
//给model的字段添加swagger注解
field.addJavaDocLine("@ApiModelProperty(value = \""+remarks+"\")");
}
}
/**
* 给model的字段添加注释
*/
private void addFieldJavaDoc(Field field, String remarks) {
//文档注释开始
|
field.addJavaDocLine("/**");
//获取数据库字段的备注信息
String[] remarkLines = remarks.split(System.getProperty("line.separator"));
for(String remarkLine:remarkLines){
field.addJavaDocLine(" * "+remarkLine);
}
addJavadocTag(field, false);
field.addJavaDocLine(" */");
}
@Override
public void addJavaFileComment(CompilationUnit compilationUnit) {
super.addJavaFileComment(compilationUnit);
//只在model中添加swagger注解类的导入
if(!compilationUnit.getType().getFullyQualifiedName().contains(MAPPER_SUFFIX)&&!compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)){
compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
}
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\CommentGenerator.java
| 1
|
请完成以下Java代码
|
public String getDecisionKey() {
return decisionKey;
}
public void setDecisionKey(String decisionKey) {
this.decisionKey = decisionKey;
}
@Override
public String getDecisionName() {
return decisionName;
}
public void setDecisionName(String decisionName) {
this.decisionName = decisionName;
}
|
@Override
public String getDecisionVersion() {
return decisionVersion;
}
public void setDecisionVersion(String decisionVersion) {
this.decisionVersion = decisionVersion;
}
@Override
public String toString() {
return "HistoricDecisionExecutionEntity[" + id + "]";
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\HistoricDecisionExecutionEntityImpl.java
| 1
|
请完成以下Java代码
|
public void setCostAmountReceived (final BigDecimal CostAmountReceived)
{
set_Value (COLUMNNAME_CostAmountReceived, CostAmountReceived);
}
@Override
public BigDecimal getCostAmountReceived()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CostAmountReceived);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setLineNetAmt (final BigDecimal LineNetAmt)
{
set_Value (COLUMNNAME_LineNetAmt, LineNetAmt);
}
@Override
public BigDecimal getLineNetAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_LineNetAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
|
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@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;
}
@Override
public void setQtyReceived (final BigDecimal QtyReceived)
{
set_Value (COLUMNNAME_QtyReceived, QtyReceived);
}
@Override
public BigDecimal getQtyReceived()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReceived);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_Cost_Detail.java
| 1
|
请完成以下Java代码
|
public String[] getChannelNames() { return channelNames; }
@Override
public String[] getModeNames() { return modeNames; }
@Override
public ATN getATN() { return _ATN; }
public static final String _serializedATN =
"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\r=\b\1\4\2\t\2\4"+
"\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t"+
"\13\4\f\t\f\3\2\3\2\3\3\3\3\3\4\3\4\3\5\3\5\3\6\3\6\3\7\3\7\3\b\3\b\3"+
"\t\6\t)\n\t\r\t\16\t*\3\n\6\n.\n\n\r\n\16\n/\3\13\5\13\63\n\13\3\13\3"+
"\13\3\f\6\f8\n\f\r\f\16\f9\3\f\3\f\2\2\r\3\3\5\4\7\5\t\6\13\7\r\b\17\t"+
"\21\n\23\13\25\f\27\r\3\2\5\4\2C\\c|\3\2\62;\4\2\13\13\"\"\2@\2\3\3\2"+
"\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17"+
"\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\3\31\3\2"+
"\2\2\5\33\3\2\2\2\7\35\3\2\2\2\t\37\3\2\2\2\13!\3\2\2\2\r#\3\2\2\2\17"+
"%\3\2\2\2\21(\3\2\2\2\23-\3\2\2\2\25\62\3\2\2\2\27\67\3\2\2\2\31\32\7"+
|
"?\2\2\32\4\3\2\2\2\33\34\7*\2\2\34\6\3\2\2\2\35\36\7+\2\2\36\b\3\2\2\2"+
"\37 \7,\2\2 \n\3\2\2\2!\"\7\61\2\2\"\f\3\2\2\2#$\7-\2\2$\16\3\2\2\2%&"+
"\7/\2\2&\20\3\2\2\2\')\t\2\2\2(\'\3\2\2\2)*\3\2\2\2*(\3\2\2\2*+\3\2\2"+
"\2+\22\3\2\2\2,.\t\3\2\2-,\3\2\2\2./\3\2\2\2/-\3\2\2\2/\60\3\2\2\2\60"+
"\24\3\2\2\2\61\63\7\17\2\2\62\61\3\2\2\2\62\63\3\2\2\2\63\64\3\2\2\2\64"+
"\65\7\f\2\2\65\26\3\2\2\2\668\t\4\2\2\67\66\3\2\2\289\3\2\2\29\67\3\2"+
"\2\29:\3\2\2\2:;\3\2\2\2;<\b\f\2\2<\30\3\2\2\2\7\2*/\629\3\b\2\2";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
}
|
repos\springboot-demo-master\ANTLR\src\main\java\com\et\antlr\LabeledExprLexer.java
| 1
|
请完成以下Java代码
|
public static boolean isNonAlphanumericAnyLangScript(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return true;
}
}
return false;
}
/**
* checks for special characters,returns false if any character
* found other than the script argument
* @param str - String to check for special characters
* @param script - Language script
* @return true if special character found else false
*/
public static boolean isNonAlphanumericInLangScript(String str, String script) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// script e.g., Character.UnicodeScript.of(c).toString().equalsIgnoreCase(Character.UnicodeScript.LATIN.toString())
|
if (!Character.UnicodeScript.of(c).toString().equalsIgnoreCase(script)
&& !Character.isDigit(c)) {
return true;
}
}
return false;
}
/**
* checks for special characters in any lang
* @param str - String to check for special characters
* @return true if special character found else false
*/
public static boolean isNonAlphanumericAnyLangScriptV2(String str) {
return !StringUtils.isAlphanumeric(str);
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-operations-6\src\main\java\com\baeldung\nonalphanumeric\NonAlphaNumericChecker.java
| 1
|
请完成以下Java代码
|
private I_C_Mail toMailRecord(final InboundEMail email)
{
final I_C_Mail mailRecord = InterfaceWrapperHelper.newInstance(I_C_Mail.class);
mailRecord.setIsInboundEMail(true);
mailRecord.setEMail_From(email.getFrom());
mailRecord.setEMail_To(Joiner.on(", ").join(email.getTo()));
mailRecord.setEMail_Cc(Joiner.on(", ").join(email.getCc()));
mailRecord.setEMail_Bcc(Joiner.on(", ").join(email.getBcc()));
mailRecord.setSubject(email.getSubject());
mailRecord.setContentText(email.getContent());
mailRecord.setContentType(email.getContentType());
mailRecord.setDateReceived(TimeUtil.asTimestamp(email.getReceivedDate()));
mailRecord.setMessageID(email.getMessageId());
mailRecord.setInitialMessageID(email.getInitialMessageId());
mailRecord.setEMailHeadersJSON(toJson(email.getHeaders()));
mailRecord.setR_Request_ID(RequestId.toRepoId(email.getRequestId()));
final ClientId adClientId = ClientId.ofRepoId(mailRecord.getAD_Client_ID());
final IUserDAO usersRepo = Services.get(IUserDAO.class);
final UserId fromUserId = usersRepo.retrieveUserIdByEMail(email.getFrom(), adClientId);
if (fromUserId != null)
{
mailRecord.setFrom_User_ID(fromUserId.getRepoId());
}
return mailRecord;
}
private String toJson(final Map<String, Object> map)
{
try
{
return jsonObjectMapper.writeValueAsString(map);
}
catch (final JsonProcessingException ex)
{
throw AdempiereException.wrapIfNeeded(ex)
.setParameter("map", map);
}
}
public RequestId getRequestIdForMessageId(@NonNull final String messageId)
{
final List<Integer> requestIds = Services.get(IQueryBL.class).createQueryBuilder(I_C_Mail.class)
.addEqualsFilter(I_C_Mail.COLUMN_InitialMessageID, messageId)
.addNotNull(I_C_Mail.COLUMN_R_Request_ID)
.orderBy(I_C_Mail.COLUMN_R_Request_ID)
|
.create()
.listDistinct(I_C_Mail.COLUMNNAME_R_Request_ID, Integer.class);
if (requestIds.isEmpty())
{
return null;
}
return RequestId.ofRepoId(requestIds.get(0));
}
private static final class InboundEMailAttachmentDataSource implements DataSource
{
private InboundEMailAttachment attachment;
private InboundEMailAttachmentDataSource(@NonNull final InboundEMailAttachment attachment)
{
this.attachment = attachment;
}
@Override
public String getName()
{
return attachment.getFilename();
}
@Override
public String getContentType()
{
return attachment.getContentType();
}
@Override
public InputStream getInputStream() throws IOException
{
return Files.newInputStream(attachment.getTempFile());
}
@Override
public OutputStream getOutputStream() throws IOException
{
throw new UnsupportedOperationException();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java\de\metas\inbound\mail\InboundEMailRepository.java
| 1
|
请完成以下Java代码
|
public class SomeData {
private String id;
private String type;
private String status;
private Instant timestamp;
public SomeData() {
}
public SomeData(String id, String type, String status, Instant timestamp) {
this.id = id;
this.type = type;
this.status = status;
this.timestamp = timestamp;
}
public String getId() {
|
return id;
}
public String getType() {
return type;
}
public String getStatus() {
return status;
}
public Instant getTimestamp() {
return timestamp;
}
}
|
repos\tutorials-master\spring-kafka-3\src\main\java\com\baeldung\spring\kafka\trusted\packages\SomeData.java
| 1
|
请完成以下Java代码
|
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 setName (final @Nullable java.lang.String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPlannedAmt (final BigDecimal PlannedAmt)
{
set_ValueNoCheck (COLUMNNAME_PlannedAmt, PlannedAmt);
}
@Override
public BigDecimal getPlannedAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPlannedMarginAmt (final BigDecimal PlannedMarginAmt)
{
set_ValueNoCheck (COLUMNNAME_PlannedMarginAmt, PlannedMarginAmt);
}
@Override
public BigDecimal getPlannedMarginAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedMarginAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPlannedPrice (final BigDecimal PlannedPrice)
{
set_ValueNoCheck (COLUMNNAME_PlannedPrice, PlannedPrice);
}
@Override
public BigDecimal getPlannedPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedPrice);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPlannedQty (final BigDecimal PlannedQty)
{
set_ValueNoCheck (COLUMNNAME_PlannedQty, PlannedQty);
}
|
@Override
public BigDecimal getPlannedQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setProductValue (final @Nullable java.lang.String ProductValue)
{
set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue);
}
@Override
public java.lang.String getProductValue()
{
return get_ValueAsString(COLUMNNAME_ProductValue);
}
@Override
public void setSKU (final @Nullable java.lang.String SKU)
{
set_ValueNoCheck (COLUMNNAME_SKU, SKU);
}
@Override
public java.lang.String getSKU()
{
return get_ValueAsString(COLUMNNAME_SKU);
}
@Override
public void setUPC (final @Nullable java.lang.String UPC)
{
set_ValueNoCheck (COLUMNNAME_UPC, UPC);
}
@Override
public java.lang.String getUPC()
{
return get_ValueAsString(COLUMNNAME_UPC);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Details_v.java
| 1
|
请完成以下Java代码
|
public AuthorizationManager<HttpServletRequest> getAuthorizationManager() {
return this.authorizationManager;
}
public boolean isObserveOncePerRequest() {
return this.observeOncePerRequest;
}
/**
* Sets whether this filter apply only once per request. By default, this is
* <code>false</code>, meaning the filter will execute on every request. Sometimes
* users may wish it to execute more than once per request, such as when JSP forwards
* are being used and filter security is desired on each included fragment of the HTTP
* request.
* @param observeOncePerRequest whether the filter should only be applied once per
* request
*/
public void setObserveOncePerRequest(boolean observeOncePerRequest) {
this.observeOncePerRequest = observeOncePerRequest;
}
/**
* If set to true, the filter will be applied to error dispatcher. Defaults to
* {@code true}.
* @param filterErrorDispatch whether the filter should be applied to error dispatcher
*/
public void setFilterErrorDispatch(boolean filterErrorDispatch) {
this.filterErrorDispatch = filterErrorDispatch;
}
/**
* If set to true, the filter will be applied to the async dispatcher. Defaults to
* {@code true}.
|
* @param filterAsyncDispatch whether the filter should be applied to async dispatch
*/
public void setFilterAsyncDispatch(boolean filterAsyncDispatch) {
this.filterAsyncDispatch = filterAsyncDispatch;
}
private static class NoopAuthorizationEventPublisher implements AuthorizationEventPublisher {
@Override
public <T> void publishAuthorizationEvent(Supplier<Authentication> authentication, T object,
@Nullable AuthorizationResult result) {
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\intercept\AuthorizationFilter.java
| 1
|
请完成以下Java代码
|
public class Record {
/**
* The record description. For example, this can be the artist name for the famous musician
* example.
*/
private final String description;
/**
* Encapsulates all attributes and their corresponding values, i.e. features.
*/
private final Map<String, Double> features;
public Record(String description, Map<String, Double> features) {
this.description = description;
this.features = features;
}
public Record(Map<String, Double> features) {
this("", features);
}
public String getDescription() {
return description;
}
public Map<String, Double> getFeatures() {
return features;
}
@Override
public String toString() {
String prefix = description == null || description
|
.trim()
.isEmpty() ? "Record" : description;
return prefix + ": " + features;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Record record = (Record) o;
return Objects.equals(getDescription(), record.getDescription()) && Objects.equals(getFeatures(), record.getFeatures());
}
@Override
public int hashCode() {
return Objects.hash(getDescription(), getFeatures());
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-3\src\main\java\com\baeldung\algorithms\kmeans\Record.java
| 1
|
请完成以下Java代码
|
public TechnicalInputChannel1Choice getTechInptChanl() {
return techInptChanl;
}
/**
* Sets the value of the techInptChanl property.
*
* @param value
* allowed object is
* {@link TechnicalInputChannel1Choice }
*
*/
public void setTechInptChanl(TechnicalInputChannel1Choice value) {
this.techInptChanl = value;
}
/**
* Gets the value of the intrst property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the intrst property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getIntrst().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TransactionInterest2 }
*
*
*/
public List<TransactionInterest2> getIntrst() {
if (intrst == null) {
intrst = new ArrayList<TransactionInterest2>();
}
return this.intrst;
}
/**
* Gets the value of the ntryDtls property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the ntryDtls property.
*
|
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNtryDtls().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link EntryDetails1 }
*
*
*/
public List<EntryDetails1> getNtryDtls() {
if (ntryDtls == null) {
ntryDtls = new ArrayList<EntryDetails1>();
}
return this.ntryDtls;
}
/**
* Gets the value of the addtlNtryInf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlNtryInf() {
return addtlNtryInf;
}
/**
* Sets the value of the addtlNtryInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlNtryInf(String value) {
this.addtlNtryInf = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ReportEntry2.java
| 1
|
请完成以下Java代码
|
public abstract class BaseChildElementParser implements BpmnXMLConstants {
protected static final Logger LOGGER = LoggerFactory.getLogger(BaseChildElementParser.class);
public abstract String getElementName();
public abstract void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model)
throws Exception;
protected void parseChildElements(
XMLStreamReader xtr,
BaseElement parentElement,
BpmnModel model,
BaseChildElementParser parser
) throws Exception {
boolean readyWithChildElements = false;
while (!readyWithChildElements && xtr.hasNext()) {
xtr.next();
if (xtr.isStartElement()) {
if (parser.getElementName().equals(xtr.getLocalName())) {
parser.parseChildElement(xtr, parentElement, model);
}
} else if (xtr.isEndElement() && getElementName().equalsIgnoreCase(xtr.getLocalName())) {
readyWithChildElements = true;
}
}
}
public boolean accepts(BaseElement element) {
|
return element != null;
}
protected List<ExtensionAttribute> parseExtensionAttributes(
XMLStreamReader xtr,
BaseElement parentElement,
BpmnModel model
) {
List<ExtensionAttribute> attributes = new LinkedList<>();
for (int i = 0; i < xtr.getAttributeCount(); i++) {
if (ACTIVITI_EXTENSIONS_NAMESPACE.equals(xtr.getAttributeNamespace(i))) {
ExtensionAttribute attr = new ExtensionAttribute(
ACTIVITI_EXTENSIONS_NAMESPACE,
xtr.getAttributeLocalName(i)
);
attr.setValue(xtr.getAttributeValue(i));
attributes.add(attr);
}
}
return unmodifiableList(attributes);
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\child\BaseChildElementParser.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void addToStarred(UserDashboardsInfo stored, DashboardId dashboardId) {
UUID id = dashboardId.getId();
long ts = System.currentTimeMillis();
var opt = stored.getStarred().stream().filter(filterById(id)).findFirst();
if (opt.isPresent()) {
opt.get().setStarredAt(ts);
} else {
var newInfo = new StarredDashboardInfo();
newInfo.setId(id);
newInfo.setStarredAt(System.currentTimeMillis());
stored.getStarred().add(newInfo);
}
stored.getStarred().sort(Comparator.comparing(StarredDashboardInfo::getStarredAt).reversed());
if (stored.getStarred().size() > MAX_DASHBOARD_INFO_LIST_SIZE) {
stored.setStarred(stored.getStarred().stream().limit(MAX_DASHBOARD_INFO_LIST_SIZE).collect(Collectors.toList()));
}
Set<UUID> starredMap =
stored.getStarred().stream().map(AbstractUserDashboardInfo::getId).collect(Collectors.toSet());
stored.getLast().forEach(d -> d.setStarred(starredMap.contains(d.getId())));
}
private Predicate<AbstractUserDashboardInfo> filterById(UUID id) {
return d -> id.equals(d.getId());
}
private UserDashboardsInfo refreshDashboardTitles(TenantId tenantId, UserDashboardsInfo stored) {
if (stored == null) {
return UserDashboardsInfo.EMPTY;
}
stored.getLast().forEach(i -> i.setTitle(null));
stored.getStarred().forEach(i -> i.setTitle(null));
Set<UUID> uniqueIds = new HashSet<>();
stored.getLast().stream().map(AbstractUserDashboardInfo::getId).forEach(uniqueIds::add);
stored.getStarred().stream().map(AbstractUserDashboardInfo::getId).forEach(uniqueIds::add);
|
Map<UUID, String> dashboardTitles = new HashMap<>();
uniqueIds.forEach(id -> {
var title = dashboardService.findDashboardTitleById(tenantId, new DashboardId(id));
if (StringUtils.isNotEmpty(title)) {
dashboardTitles.put(id, title);
}
}
);
stored.getLast().forEach(i -> i.setTitle(dashboardTitles.get(i.getId())));
stored.getLast().removeIf(EMPTY_TITLE);
stored.getStarred().forEach(i -> i.setTitle(dashboardTitles.get(i.getId())));
stored.getStarred().removeIf(EMPTY_TITLE);
return stored;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\user\DefaultTbUserSettingsService.java
| 2
|
请完成以下Java代码
|
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isCompleted() {
return completed;
|
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
@Override
public String toString() {
return "ToDoItem{"
+ "userId=" + userId
+ ", id=" + id
+ ", title='" + title + '\''
+ ", completed=" + completed +
'}';
}
}
|
repos\tutorials-master\aws-modules\aws-lambda-modules\todo-reminder-lambda\ToDoFunction\src\main\java\com\baeldung\lambda\todo\api\ToDoItem.java
| 1
|
请完成以下Java代码
|
public String getDecisionDefinitionId() {
return decisionDefinitionId;
}
@Override
public void setDecisionDefinitionId(String decisionDefinitionId) {
this.decisionDefinitionId = decisionDefinitionId;
}
@Override
public String getDeploymentId() {
return deploymentId;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public Date getStartTime() {
return startTime;
}
@Override
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
@Override
public Date getEndTime() {
return endTime;
}
@Override
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
@Override
public String getInstanceId() {
return instanceId;
}
@Override
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@Override
public String getActivityId() {
return activityId;
}
@Override
public void setActivityId(String activityId) {
this.activityId = activityId;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public boolean isFailed() {
return failed;
}
@Override
public void setFailed(boolean failed) {
|
this.failed = failed;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getExecutionJson() {
return executionJson;
}
@Override
public void setExecutionJson(String executionJson) {
this.executionJson = executionJson;
}
@Override
public String getDecisionKey() {
return decisionKey;
}
public void setDecisionKey(String decisionKey) {
this.decisionKey = decisionKey;
}
@Override
public String getDecisionName() {
return decisionName;
}
public void setDecisionName(String decisionName) {
this.decisionName = decisionName;
}
@Override
public String getDecisionVersion() {
return decisionVersion;
}
public void setDecisionVersion(String decisionVersion) {
this.decisionVersion = decisionVersion;
}
@Override
public String toString() {
return "HistoricDecisionExecutionEntity[" + id + "]";
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\HistoricDecisionExecutionEntityImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public final class ActiveMQAutoConfiguration {
@Bean
@ConditionalOnMissingBean
ActiveMQConnectionDetails activemqConnectionDetails(ActiveMQProperties properties) {
return new PropertiesActiveMQConnectionDetails(properties);
}
/**
* Adapts {@link ActiveMQProperties} to {@link ActiveMQConnectionDetails}.
*/
static class PropertiesActiveMQConnectionDetails implements ActiveMQConnectionDetails {
private final ActiveMQProperties properties;
PropertiesActiveMQConnectionDetails(ActiveMQProperties properties) {
this.properties = properties;
}
|
@Override
public String getBrokerUrl() {
return this.properties.determineBrokerUrl();
}
@Override
public @Nullable String getUser() {
return this.properties.getUser();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public void setAD_Scheduler(final org.compiere.model.I_AD_Scheduler AD_Scheduler)
{
set_ValueFromPO(COLUMNNAME_AD_Scheduler_ID, org.compiere.model.I_AD_Scheduler.class, AD_Scheduler);
}
@Override
public void setAD_Scheduler_ID (final int AD_Scheduler_ID)
{
if (AD_Scheduler_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Scheduler_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Scheduler_ID, AD_Scheduler_ID);
}
@Override
public int getAD_Scheduler_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Scheduler_ID);
}
@Override
public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID);
}
@Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public void setAD_User_ID (final int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, AD_User_ID);
}
@Override
public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
@Override
public org.compiere.model.I_AD_Window getAD_Window()
{
return get_ValueAsPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class);
}
@Override
public void setAD_Window(final org.compiere.model.I_AD_Window AD_Window)
{
set_ValueFromPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class, AD_Window);
}
@Override
public void setAD_Window_ID (final int AD_Window_ID)
{
if (AD_Window_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Window_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Window_ID, AD_Window_ID);
}
@Override
public int getAD_Window_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Window_ID);
}
@Override
public void setErrorMsg (final @Nullable java.lang.String ErrorMsg)
{
set_Value (COLUMNNAME_ErrorMsg, ErrorMsg);
}
@Override
public java.lang.String getErrorMsg()
{
return get_ValueAsString(COLUMNNAME_ErrorMsg);
}
@Override
public void setIsProcessing (final boolean IsProcessing)
|
{
set_Value (COLUMNNAME_IsProcessing, IsProcessing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_IsProcessing);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setResult (final int Result)
{
set_Value (COLUMNNAME_Result, Result);
}
@Override
public int getResult()
{
return get_ValueAsInt(COLUMNNAME_Result);
}
@Override
public void setWhereClause (final @Nullable java.lang.String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
@Override
public java.lang.String getWhereClause()
{
return get_ValueAsString(COLUMNNAME_WhereClause);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void startEmbeddedJms() {
for (String embeddedJmsClass : EMBEDDED_JMS_CLASSES) {
if (ClassUtils.isPresent(embeddedJmsClass, null)) {
try {
this.beanFactory.getBeansOfType(Class.forName(embeddedJmsClass));
}
catch (Exception ex) {
// Ignore
}
}
}
}
private <T extends ActiveMQConnectionFactory> T doCreateConnectionFactory(Function<String, T> nativeFactoryCreator,
Function<ServerLocator, T> embeddedFactoryCreator) throws Exception {
ArtemisMode mode = this.connectionDetails.getMode();
if (mode == null) {
mode = deduceMode();
}
if (mode == ArtemisMode.EMBEDDED) {
return createEmbeddedConnectionFactory(embeddedFactoryCreator);
}
return createNativeConnectionFactory(nativeFactoryCreator);
}
/**
* Deduce the {@link ArtemisMode} to use if none has been set.
* @return the mode
*/
private ArtemisMode deduceMode() {
if (this.properties.getEmbedded().isEnabled() && isEmbeddedJmsClassPresent()) {
return ArtemisMode.EMBEDDED;
}
return ArtemisMode.NATIVE;
}
private boolean isEmbeddedJmsClassPresent() {
for (String embeddedJmsClass : EMBEDDED_JMS_CLASSES) {
if (ClassUtils.isPresent(embeddedJmsClass, null)) {
return true;
|
}
}
return false;
}
private <T extends ActiveMQConnectionFactory> T createEmbeddedConnectionFactory(
Function<ServerLocator, T> factoryCreator) throws Exception {
try {
TransportConfiguration transportConfiguration = new TransportConfiguration(
InVMConnectorFactory.class.getName(), this.properties.getEmbedded().generateTransportParameters());
ServerLocator serverLocator = ActiveMQClient.createServerLocatorWithoutHA(transportConfiguration);
return factoryCreator.apply(serverLocator);
}
catch (NoClassDefFoundError ex) {
throw new IllegalStateException("Unable to create InVM "
+ "Artemis connection, ensure that artemis-jms-server.jar is in the classpath", ex);
}
}
private <T extends ActiveMQConnectionFactory> T createNativeConnectionFactory(Function<String, T> factoryCreator) {
T connectionFactory = newNativeConnectionFactory(factoryCreator);
String user = this.connectionDetails.getUser();
if (StringUtils.hasText(user)) {
connectionFactory.setUser(user);
connectionFactory.setPassword(this.connectionDetails.getPassword());
}
return connectionFactory;
}
private <T extends ActiveMQConnectionFactory> T newNativeConnectionFactory(Function<String, T> factoryCreator) {
String brokerUrl = StringUtils.hasText(this.connectionDetails.getBrokerUrl())
? this.connectionDetails.getBrokerUrl() : DEFAULT_BROKER_URL;
return factoryCreator.apply(brokerUrl);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisConnectionFactoryFactory.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Set<TenantId> remove(TenantProfileId profileId) {
Set<TenantId> tenants = tenantProfileIds.remove(profileId);
if (tenants != null) {
tenants.forEach(tenantIds::remove);
}
profiles.remove(profileId);
return tenants;
}
private TenantProfile getTenantProfile(TenantId tenantId) {
TenantProfile profile = null;
TenantProfileId tenantProfileId = tenantIds.get(tenantId);
if (tenantProfileId != null) {
profile = profiles.get(tenantProfileId);
}
if (profile == null) {
tenantProfileFetchLock.lock();
try {
tenantProfileId = tenantIds.get(tenantId);
if (tenantProfileId != null) {
profile = profiles.get(tenantProfileId);
}
if (profile == null) {
TransportProtos.GetEntityProfileRequestMsg msg = TransportProtos.GetEntityProfileRequestMsg.newBuilder()
.setEntityType(EntityType.TENANT.name())
.setEntityIdMSB(tenantId.getId().getMostSignificantBits())
.setEntityIdLSB(tenantId.getId().getLeastSignificantBits())
.build();
TransportProtos.GetEntityProfileResponseMsg entityProfileMsg = transportService.getEntityProfile(msg);
profile = ProtoUtils.fromProto(entityProfileMsg.getTenantProfile());
TenantProfile existingProfile = profiles.get(profile.getId());
if (existingProfile != null) {
profile = existingProfile;
|
} else {
profiles.put(profile.getId(), profile);
}
tenantProfileIds.computeIfAbsent(profile.getId(), id -> ConcurrentHashMap.newKeySet()).add(tenantId);
tenantIds.put(tenantId, profile.getId());
ApiUsageState apiUsageState = ProtoUtils.fromProto(entityProfileMsg.getApiState());
rateLimitService.update(tenantId, apiUsageState.isTransportEnabled());
}
} finally {
tenantProfileFetchLock.unlock();
}
}
return profile;
}
}
|
repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\service\DefaultTransportTenantProfileCache.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/","/login").permitAll()//根路径和/login路径不拦截
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login") //2登陆页面路径为/login
.defaultSuccessUrl("/chat") //3登陆成功转向chat页面
.permitAll()
.and()
.logout()
.permitAll();
}
|
//4在内存中配置两个用户 wyf 和 wisely ,密码和用户名一致,角色是 USER
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("admin").roles("USER")
.and()
.withUser("abel").password("abel").roles("USER");
}
//5忽略静态资源的拦截
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/static/**");
}
}
|
repos\springBoot-master\springWebSocket\src\main\java\com\us\example\config\WebSecurityConfig.java
| 2
|
请完成以下Java代码
|
protected final I_C_BankStatement getSelectedBankStatement()
{
final BankStatementId bankStatementId = getSelectedBankStatementId();
return bankStatementBL.getById(bankStatementId);
}
@NonNull
protected final BankStatementId getSelectedBankStatementId()
{
return BankStatementId.ofRepoId(getRecord_ID());
}
protected final I_C_BankStatementLine getSingleSelectedBankStatementLine()
{
final BankStatementLineId lineId = getSingleSelectedBankStatementLineId();
return bankStatementBL.getLineById(lineId);
}
protected final BankStatementLineId getSingleSelectedBankStatementLineId()
{
final Set<Integer> bankStatementLineRepoIds = getSelectedIncludedRecordIds(I_C_BankStatementLine.class);
if (bankStatementLineRepoIds.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
else if (bankStatementLineRepoIds.size() == 1)
{
return BankStatementLineId.ofRepoId(bankStatementLineRepoIds.iterator().next());
}
else
{
throw new AdempiereException("More than one bank statement line selected: " + bankStatementLineRepoIds);
|
}
}
protected final void openBankStatementReconciliationView(@NonNull final Collection<PaymentId> paymentIds)
{
if (paymentIds.isEmpty())
{
throw new AdempiereException("@NoPayments@");
}
final BankStatementReconciliationView view = bankStatementReconciliationViewFactory.createView(BanksStatementReconciliationViewCreateRequest.builder()
.bankStatementLineId(getSingleSelectedBankStatementLineId())
.paymentIds(paymentIds)
.build());
final ViewId viewId = view.getViewId();
getResult().setWebuiViewToOpen(WebuiViewToOpen.builder()
.viewId(viewId.toJson())
.target(ViewOpenTarget.ModalOverlay)
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\banking\process\BankStatementBasedProcess.java
| 1
|
请完成以下Java代码
|
public boolean requestFocus(final GridTab gridTab)
{
final I_C_Order order = InterfaceWrapperHelper.create(gridTab, I_C_Order.class);
final Integer productId = order.getM_Product_ID();
if (productId <= 0
&& gridTab.getField(de.metas.adempiere.model.I_C_Order.COLUMNNAME_M_Product_ID).isDisplayed())
{
gridTab.getField(de.metas.adempiere.model.I_C_Order.COLUMNNAME_M_Product_ID).requestFocus();
return true;
}
// task 06300: focus shall go from product to TU-qty (not CU-qty)
final BigDecimal qtyTU = order.getQty_FastInput_TU();
final BigDecimal qtyCU = order.getQty_FastInput();
final boolean hasTUs = Services.get(IHUOrderBL.class).hasTUs(order);
if (!hasTUs || null != qtyCU && qtyCU.signum() > 0)
{
// the product is not assigned to a TU, so we return false and leave it to the default handler which will probably request the focus for the "CU Qty" field
// 06730: Also, we leave it for the default handler if we have a TU quantity with no HU.
return false;
}
if ((qtyTU == null || qtyTU.signum() <= 0)
&& gridTab.getField(I_C_Order.COLUMNNAME_Qty_FastInput_TU).isDisplayed())
{
// product has been set, but qty hasn't
gridTab.getField(I_C_Order.COLUMNNAME_Qty_FastInput_TU).requestFocus();
return true;
}
final int huPIPId = order.getM_HU_PI_Item_Product_ID();
if (huPIPId <= 0
|
&& gridTab.getField(I_C_Order.COLUMNNAME_M_HU_PI_Item_Product_ID).isDisplayed())
{
gridTab.getField(I_C_Order.COLUMNNAME_M_HU_PI_Item_Product_ID).requestFocus();
return true;
}
// no focus was requested
return false;
}
@Override
public IGridTabRowBuilder createLineBuilderFromHeader(final Object model)
{
return new OrderLineHUPackingGridRowBuilder();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\HUOrderFastInputHandler.java
| 1
|
请完成以下Java代码
|
public final class BearerTokenAuthenticationExtractor implements AuthenticationExtractor {
/** Default key to access Authorization value in {@code connection_init} payload. */
public static final String AUTHORIZATION_KEY = "Authorization";
private static final Pattern authorizationPattern =
Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-._~+/]+=*)$", Pattern.CASE_INSENSITIVE);
private final String authorizationKey;
/**
* Constructor that defaults to {@link #AUTHORIZATION_KEY} for the payload key.
*/
public BearerTokenAuthenticationExtractor() {
this(AUTHORIZATION_KEY);
}
/**
* Constructor with the key for the authorization value.
* @param authorizationKey the key under which to look up the authorization
* value in the {@code "connection_init"} payload.
*/
public BearerTokenAuthenticationExtractor(String authorizationKey) {
this.authorizationKey = authorizationKey;
}
@Override
public Mono<Authentication> getAuthentication(Map<String, Object> payload) {
String authorizationValue = getAuthorizationValue(payload);
if (authorizationValue == null) {
return Mono.empty();
}
if (!StringUtils.startsWithIgnoreCase(authorizationValue, "bearer")) {
|
BearerTokenError error = BearerTokenErrors.invalidRequest("Not a bearer token");
return Mono.error(new OAuth2AuthenticationException(error));
}
Matcher matcher = authorizationPattern.matcher(authorizationValue);
if (!matcher.matches()) {
BearerTokenError error = BearerTokenErrors.invalidToken("Bearer token is malformed");
return Mono.error(new OAuth2AuthenticationException(error));
}
String token = matcher.group("token");
return Mono.just(new BearerTokenAuthenticationToken(token));
}
private @Nullable String getAuthorizationValue(Map<String, Object> payload) {
String value = (String) payload.get(this.authorizationKey);
if (value != null) {
return value;
}
for (String key : payload.keySet()) {
if (key.equalsIgnoreCase(this.authorizationKey)) {
return (String) payload.get(key);
}
}
return null;
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\support\BearerTokenAuthenticationExtractor.java
| 1
|
请完成以下Java代码
|
private static boolean updateProductFromExpenseType(final I_M_Product product, final I_S_ExpenseType parent)
{
boolean changed = false;
if (!X_M_Product.PRODUCTTYPE_ExpenseType.equals(product.getProductType()))
{
product.setProductType(X_M_Product.PRODUCTTYPE_ExpenseType);
changed = true;
}
if (parent.getS_ExpenseType_ID() != product.getS_ExpenseType_ID())
{
product.setS_ExpenseType_ID(parent.getS_ExpenseType_ID());
changed = true;
}
if (parent.isActive() != product.isActive())
{
product.setIsActive(parent.isActive());
changed = true;
}
//
if (!parent.getValue().equals(product.getValue()))
{
product.setValue(parent.getValue());
changed = true;
}
if (!parent.getName().equals(product.getName()))
{
product.setName(parent.getName());
changed = true;
}
if ((parent.getDescription() == null && product.getDescription() != null)
|| (parent.getDescription() != null && !parent.getDescription().equals(product.getDescription())))
{
product.setDescription(parent.getDescription());
changed = true;
|
}
if (parent.getC_UOM_ID() != product.getC_UOM_ID())
{
product.setC_UOM_ID(parent.getC_UOM_ID());
changed = true;
}
if (parent.getM_Product_Category_ID() != product.getM_Product_Category_ID())
{
product.setM_Product_Category_ID(parent.getM_Product_Category_ID());
changed = true;
}
// metas 05129 end
return changed;
}
} // MExpenseType
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MExpenseType.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return ObjectUtils.toString(this);
}
@Override
public String getTableName()
{
return I_C_Invoice_Candidate.Table_Name;
}
@Override
public List<String> getDependsOnColumnNames()
{
return columnNames;
}
@Override
public AggregationKey buildAggregationKey(I_C_Invoice_Candidate model)
{
final List<Object> keyValues = extractKeyValues(model);
final ArrayKey key = Util.mkKey(keyValues.toArray());
|
final AggregationId aggregationId = null;
return new AggregationKey(key, aggregationId);
}
private final List<Object> extractKeyValues(final I_C_Invoice_Candidate ic)
{
final List<Object> values = new ArrayList<>();
final de.metas.materialtracking.model.I_C_Invoice_Candidate icExt = InterfaceWrapperHelper.create(ic, de.metas.materialtracking.model.I_C_Invoice_Candidate.class);
//
// Bind the Material Tracking ID for the reference of the Invoice Candidate
values.add(icExt.getM_Material_Tracking_ID());
return values;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\agg\key\impl\MaterialTrackingICHeaderAggregationKeyBuilder_OLD.java
| 1
|
请完成以下Java代码
|
default void afterLoad(IHUContext huContext, List<IAllocationResult> loadResults)
{
// nothing
}
/**
* This default implementation does nothing.
*
* @param hu handling unit (never null)
* @param parentHUItemOld (might be null)
*/
// TODO: we shall have a proper transaction for this case
default void huParentChanged(final I_M_HU hu, final I_M_HU_Item parentHUItemOld)
{
// nothing
}
/**
* Called by {@link HULoader} each time a single unload/load transaction was performed. This default implementation does nothing.
*
* @param huContext
* @param unloadTrx
* @param loadTrx
|
*/
default void onUnloadLoadTransaction(IHUContext huContext, IHUTransactionCandidate unloadTrx, IHUTransactionCandidate loadTrx)
{
// nothing
}
/**
* Called when a split is performed. This default implementation does nothing.
*
* @param huContext
* @param unloadTrx transaction on source HU
* @param loadTrx transaction on destination HU
*/
default void onSplitTransaction(IHUContext huContext, IHUTransactionCandidate unloadTrx, IHUTransactionCandidate loadTrx)
{
// nothing
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\IHUTrxListener.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the year
*/
public Integer getYear() {
return year;
}
/**
* @param year the year to set
*/
public void setYear(Integer year) {
this.year = year;
}
/**
* @return the sku
*/
public String getSku() {
return sku;
}
/**
* @param sku the sku to set
*/
public void setSku(String sku) {
this.sku = sku;
}
/**
* @return the maker
*/
public CarMaker getMaker() {
return maker;
}
/**
* @param maker the maker to set
*/
public void setMaker(CarMaker maker) {
this.maker = maker;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((maker == null) ? 0 : maker.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sku == null) ? 0 : sku.hashCode());
result = prime * result + ((year == null) ? 0 : year.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
|
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CarModel other = (CarModel) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (maker == null) {
if (other.maker != null)
return false;
} else if (!maker.equals(other.maker))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (sku == null) {
if (other.sku != null)
return false;
} else if (!sku.equals(other.sku))
return false;
if (year == null) {
if (other.year != null)
return false;
} else if (!year.equals(other.year))
return false;
return true;
}
}
|
repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\domain\CarModel.java
| 1
|
请完成以下Java代码
|
public class EventPayloadKafkaPartitionProvider implements KafkaPartitionProvider {
protected final String eventField;
public EventPayloadKafkaPartitionProvider(String eventField) {
this.eventField = eventField;
}
@Override
public Integer determinePartition(OutboundEvent<?> outboundEvent) {
for (EventPayloadInstance payloadInstance : outboundEvent.getEventInstance()
.getPayloadInstances()) {
if (eventField.equals(payloadInstance.getDefinitionName())) {
return parseValue(payloadInstance.getValue());
}
}
|
return null;
}
protected Integer parseValue(Object value) {
if (value instanceof Number) {
return ((Number) value).intValue();
} else if (value instanceof String) {
return Integer.parseInt(value.toString());
} else if (value != null) {
throw new IllegalStateException(
"The [" + eventField + "] must resolve to an Number or a String that can be parsed as an Integer. "
+ "Resolved to [" + value.getClass() + "] for [" + value + "]");
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\kafka\EventPayloadKafkaPartitionProvider.java
| 1
|
请完成以下Java代码
|
public int getHeaderAggregationKeyBuilder_ID()
{
return get_ValueAsInt(COLUMNNAME_HeaderAggregationKeyBuilder_ID);
}
@Override
public void setInvoicingGroupNo (final int InvoicingGroupNo)
{
set_ValueNoCheck (COLUMNNAME_InvoicingGroupNo, InvoicingGroupNo);
}
@Override
public int getInvoicingGroupNo()
{
return get_ValueAsInt(COLUMNNAME_InvoicingGroupNo);
}
@Override
public void setIsSOTrx (final boolean IsSOTrx)
{
|
set_ValueNoCheck (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public boolean isSOTrx()
{
return get_ValueAsBoolean(COLUMNNAME_IsSOTrx);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_Invoice_Candidate_HeaderAggregation.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class MessagingAdviceConfiguration {
@Bean
MessagingAdviceRSocketMessageHandlerCustomizer messagingAdviceRSocketMessageHandlerCustomizer(
ApplicationContext applicationContext) {
return new MessagingAdviceRSocketMessageHandlerCustomizer(applicationContext);
}
}
static final class MessagingAdviceRSocketMessageHandlerCustomizer implements RSocketMessageHandlerCustomizer {
private final ApplicationContext applicationContext;
MessagingAdviceRSocketMessageHandlerCustomizer(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public void customize(RSocketMessageHandler messageHandler) {
ControllerAdviceBean.findAnnotatedBeans(this.applicationContext)
.forEach((controllerAdviceBean) -> messageHandler
.registerMessagingAdvice(new ControllerAdviceBeanWrapper(controllerAdviceBean)));
}
}
private static final class ControllerAdviceBeanWrapper implements MessagingAdviceBean {
private final ControllerAdviceBean adviceBean;
private ControllerAdviceBeanWrapper(ControllerAdviceBean adviceBean) {
this.adviceBean = adviceBean;
}
|
@Override
public @Nullable Class<?> getBeanType() {
return this.adviceBean.getBeanType();
}
@Override
public Object resolveBean() {
return this.adviceBean.resolveBean();
}
@Override
public boolean isApplicableToBeanType(Class<?> beanType) {
return this.adviceBean.isApplicableToBeanType(beanType);
}
@Override
public int getOrder() {
return this.adviceBean.getOrder();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketMessagingAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public void evaluateRuleValidity(int ruleNumber, ELExecutionContext executionContext) {
//TODO: not on audit container
for (Map.Entry<Integer, RuleExecutionAuditContainer> entry : executionContext.getAuditContainer().getRuleExecutions().entrySet()) {
if (entry.getKey().equals(ruleNumber) == false && entry.getValue().isValid()) {
String hitPolicyViolatedMessage = String.format("HitPolicy %s violated; at least rule %d and rule %d are valid.", getHitPolicyName(), ruleNumber, entry.getKey());
if (CommandContextUtil.getDmnEngineConfiguration().isStrictMode()) {
executionContext.getAuditContainer().getRuleExecutions().get(ruleNumber).setExceptionMessage(hitPolicyViolatedMessage);
executionContext.getAuditContainer().getRuleExecutions().get(entry.getKey()).setExceptionMessage(hitPolicyViolatedMessage);
throw new FlowableException("HitPolicy UNIQUE violated.");
} else {
executionContext.getAuditContainer().getRuleExecutions().get(ruleNumber).setValidationMessage(hitPolicyViolatedMessage);
executionContext.getAuditContainer().getRuleExecutions().get(entry.getKey()).setValidationMessage(hitPolicyViolatedMessage);
break;
}
}
}
}
@Override
public void composeDecisionResults(ELExecutionContext executionContext) {
List<Map<String, Object>> ruleResults = new ArrayList<>(executionContext.getRuleResults().values());
List<Map<String, Object>> decisionResults;
|
if (ruleResults.size() > 1 && CommandContextUtil.getDmnEngineConfiguration().isStrictMode() == false) {
Map<String, Object> lastResult = new HashMap<>();
for (Map<String, Object> ruleResult : ruleResults) {
for (Map.Entry<String, Object> entry : ruleResult.entrySet()) {
if (entry.getValue() != null) {
lastResult.put(entry.getKey(), entry.getValue());
}
}
}
executionContext.getAuditContainer().setValidationMessage(String.format("HitPolicy %s violated; multiple valid rules. Setting last valid rule result as final result.", getHitPolicyName()));
decisionResults = Collections.singletonList(lastResult);
} else {
decisionResults = ruleResults;
}
updateStackWithDecisionResults(decisionResults, executionContext);
executionContext.getAuditContainer().setDecisionResult(decisionResults);
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\hitpolicy\HitPolicyUnique.java
| 1
|
请完成以下Java代码
|
private synchronized void stopParentAndCheckGroup(MessageListenerContainer parent) {
if (parent.isRunning()) {
LOGGER.debug(() -> "Stopping: " + parent);
parent.stop(() -> {
if (this.currentGroup != null) {
LOGGER.debug(() -> {
if (this.currentGroup != null) {
return "Checking group: " + this.currentGroup.toString();
}
else {
return "Current group is null";
}
});
if (this.currentGroup.allStopped()) {
if (Objects.requireNonNull(this.iterator).hasNext()) {
this.currentGroup = this.iterator.next();
LOGGER.debug(() -> "Starting next group: " + this.currentGroup);
this.currentGroup.start();
}
else {
this.currentGroup = null;
}
}
}
});
}
}
@Override
public synchronized void start() {
if (this.currentGroup != null) {
LOGGER.debug(() -> "Starting first group: " + this.currentGroup);
this.currentGroup.start();
}
this.running = true;
}
|
public void initialize() {
this.groups.clear();
for (String group : this.groupNames) {
this.groups.add(Objects.requireNonNull(this.applicationContext).getBean(group + ".group", ContainerGroup.class));
}
if (!this.groups.isEmpty()) {
this.iterator = this.groups.iterator();
this.currentGroup = this.iterator.next();
this.groups.forEach(grp -> {
Collection<String> ids = grp.getListenerIds();
ids.forEach(id -> {
MessageListenerContainer container = this.registry.getListenerContainer(id);
if (Objects.requireNonNull(container).getContainerProperties().getIdleEventInterval() == null) {
container.getContainerProperties().setIdleEventInterval(this.defaultIdleEventInterval);
container.setAutoStartup(false);
}
});
});
}
LOGGER.debug(() -> "Found: " + this.groups);
}
@Override
public synchronized void stop() {
this.running = false;
if (this.currentGroup != null) {
this.currentGroup.stop();
this.currentGroup = null;
}
}
@Override
public synchronized boolean isRunning() {
return this.running;
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ContainerGroupSequencer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CamundaBpmRunProcessEngineConfiguration extends SpringProcessEngineConfiguration {
private final String normalizedDeploymentDir;
public CamundaBpmRunProcessEngineConfiguration(String normalizedDeploymentDir,
boolean deployChangedOnly,
List<ProcessEnginePlugin> processEnginePluginsFromContext,
List<CamundaBpmRunProcessEnginePluginProperty> processEnginePluginsFromYaml) {
this.normalizedDeploymentDir = normalizedDeploymentDir;
setDeployChangedOnly(deployChangedOnly);
configureProcessEnginePlugins(processEnginePluginsFromContext, processEnginePluginsFromYaml);
}
@Override
protected String getFileResourceName(Resource resource) {
// only path relative to the root deployment directory as identifier to
// prevent re-deployments when the path changes (e.g. distro is moved)
try {
String resourceAbsolutePath = resource.getURI().toString();
int startIndex = resourceAbsolutePath.indexOf(normalizedDeploymentDir) + normalizedDeploymentDir.length();
return resourceAbsolutePath.substring(startIndex);
} catch (IOException e) {
throw new ProcessEngineException("Failed to locate resource " + resource.getFilename(), e);
}
}
|
@Override
protected void initTelemetryData() {
super.initTelemetryData();
Set<String> camundaIntegration = telemetryData.getProduct().getInternals().getCamundaIntegration();
camundaIntegration.add(CamundaIntegration.CAMUNDA_BPM_RUN);
}
protected void configureProcessEnginePlugins(List<ProcessEnginePlugin> processEnginePluginsFromContext,
List<CamundaBpmRunProcessEnginePluginProperty> processEnginePluginsFromYaml) {
// register process engine plugins defined in yaml
CamundaBpmRunProcessEnginePluginHelper.registerYamlPlugins(processEnginePluginsFromContext, processEnginePluginsFromYaml);
this.processEnginePlugins.add(new CompositeProcessEnginePlugin(processEnginePluginsFromContext));
}
}
|
repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\CamundaBpmRunProcessEngineConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class CoursesHardcodedService {
private static final List<Course> courses = new ArrayList<>();
private static long idCounter = 0;
static {
courses.add(new Course(++idCounter, "in28minutes", "Learn Full stack with Spring Boot and Angular"));
courses.add(new Course(++idCounter, "in28minutes", "Learn Full stack with Spring Boot and React"));
courses.add(new Course(++idCounter, "in28minutes", "Master Microservices with Spring Boot and Spring Cloud"));
courses.add(new Course(++idCounter, "in28minutes", "Deploy Spring Boot Microservices to Cloud with Docker and Kubernetes"));
}
public List<Course> findAll() {
return courses;
}
public Course save(Course course) {
if (course.getId() == -1 || course.getId() == 0) {
course.setId(++idCounter);
courses.add(course);
} else {
deleteById(course.getId());
courses.add(course);
}
return course;
}
|
public Course deleteById(long id) {
Course course = findById(id);
if (course == null)
return null;
if (courses.remove(course)) {
return course;
}
return null;
}
public Course findById(long id) {
return courses.stream()
.filter(course -> course.getId().equals(id))
.findFirst()
.orElse(null);
}
}
|
repos\spring-boot-examples-master\spring-boot-react-examples\spring-boot-react-crud-full-stack-with-maven\backend-spring-boot-react-crud-full-stack-with-maven\src\main\java\com\in28minutes\fullstack\springboot\maven\crud\springbootcrudfullstackwithmaven\course\CoursesHardcodedService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;
@Column(name = "content")
private String content;
@Column(name = "posted_at")
private Date postedAt = new Date();
@Column(name = "last_updated_at")
private Date lastUpdatedAt = new Date();
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "post_tags",
joinColumns = { @JoinColumn(name = "post_id")},
inverseJoinColumns = { @JoinColumn (name = "tag_id")})
private Set<Tag> tags = new HashSet<>();
public Post() {
}
public Post(String title, String description, String content) {
super();
this.title = title;
this.description = description;
this.content = content;
}
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
|
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getPostedAt() {
return postedAt;
}
public void setPostedAt(Date postedAt) {
this.postedAt = postedAt;
}
public Date getLastUpdatedAt() {
return lastUpdatedAt;
}
public void setLastUpdatedAt(Date lastUpdatedAt) {
this.lastUpdatedAt = lastUpdatedAt;
}
public Set<Tag> getTags() {
return tags;
}
public void setTags(Set<Tag> tags) {
this.tags = tags;
}
}
|
repos\Spring-Boot-Advanced-Projects-main\springboot-hibernate-many-to-many-mapping\src\main\java\net\alanbinu\springboot\entity\Post.java
| 2
|
请完成以下Java代码
|
private @Nullable Publisher<?> body() {
Publisher<?> body = this.body;
if (body != null) {
return body;
}
body = getRequestBody();
hasBody = true; // even if it's null
return body;
}
/**
* Search for the request body if it was already deserialized using
* <code>@RequestBody</code>. If it is not found then deserialize it in the same way
* that it would have been for a <code>@RequestBody</code>.
* @return the request body
*/
private @Nullable Mono<Object> getRequestBody() {
for (String key : bindingContext.getModel().asMap().keySet()) {
if (key.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
BindingResult result = (BindingResult) bindingContext.getModel().asMap().get(key);
Object target = result.getTarget();
if (target != null) {
return Mono.just(target);
}
}
}
return null;
}
protected static class BodyGrabber {
|
public Publisher<Object> body(@RequestBody Publisher<Object> body) {
return body;
}
}
protected static class BodySender {
@ResponseBody
public @Nullable Publisher<Object> body() {
return null;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webflux\src\main\java\org\springframework\cloud\gateway\webflux\ProxyExchange.java
| 1
|
请完成以下Java代码
|
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String[] getCc() {
return cc;
}
public void setCc(String[] cc) {
this.cc = cc;
}
public List<String> getBcc() {
return bcc;
}
public void setBcc(List<String> bcc) {
this.bcc = bcc;
}
public class Credential {
@NotNull
private String userName;
|
@Size(max= 15, min=6)
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-1 Spring Boot Basic Fund Projects\SpringBootSourceCode\SpringEmailProcess\src\main\java\spring\basic\MailProperties.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable String get(String key) {
return null;
}
@Override
public Duration step() {
return obtain(AtlasProperties::getStep, AtlasConfig.super::step);
}
@Override
public boolean enabled() {
return obtain(AtlasProperties::isEnabled, AtlasConfig.super::enabled);
}
@Override
public Duration connectTimeout() {
return obtain(AtlasProperties::getConnectTimeout, AtlasConfig.super::connectTimeout);
}
@Override
public Duration readTimeout() {
return obtain(AtlasProperties::getReadTimeout, AtlasConfig.super::readTimeout);
}
@Override
public int numThreads() {
return obtain(AtlasProperties::getNumThreads, AtlasConfig.super::numThreads);
}
@Override
public int batchSize() {
return obtain(AtlasProperties::getBatchSize, AtlasConfig.super::batchSize);
}
@Override
public String uri() {
return obtain(AtlasProperties::getUri, AtlasConfig.super::uri);
}
@Override
public Duration meterTTL() {
return obtain(AtlasProperties::getMeterTimeToLive, AtlasConfig.super::meterTTL);
|
}
@Override
public boolean lwcEnabled() {
return obtain(AtlasProperties::isLwcEnabled, AtlasConfig.super::lwcEnabled);
}
@Override
public Duration lwcStep() {
return obtain(AtlasProperties::getLwcStep, AtlasConfig.super::lwcStep);
}
@Override
public boolean lwcIgnorePublishStep() {
return obtain(AtlasProperties::isLwcIgnorePublishStep, AtlasConfig.super::lwcIgnorePublishStep);
}
@Override
public Duration configRefreshFrequency() {
return obtain(AtlasProperties::getConfigRefreshFrequency, AtlasConfig.super::configRefreshFrequency);
}
@Override
public Duration configTTL() {
return obtain(AtlasProperties::getConfigTimeToLive, AtlasConfig.super::configTTL);
}
@Override
public String configUri() {
return obtain(AtlasProperties::getConfigUri, AtlasConfig.super::configUri);
}
@Override
public String evalUri() {
return obtain(AtlasProperties::getEvalUri, AtlasConfig.super::evalUri);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\atlas\AtlasPropertiesConfigAdapter.java
| 2
|
请完成以下Java代码
|
protected void fireTransactionEvent(TransactionState transactionState, boolean executeInNewContext) {
if (stateTransactionListeners == null) {
return;
}
final List<TransactionListener> transactionListeners = stateTransactionListeners.get(transactionState);
if (transactionListeners == null) {
return;
}
if (executeInNewContext) {
CommandExecutor commandExecutor = commandContext.getProcessEngineConfiguration().getCommandExecutor();
CommandConfig commandConfig = new CommandConfig(false, TransactionPropagation.REQUIRES_NEW);
commandExecutor.execute(
commandConfig,
new Command<Void>() {
public Void execute(CommandContext commandContext) {
executeTransactionListeners(transactionListeners, commandContext);
return null;
}
}
);
} else {
executeTransactionListeners(transactionListeners, commandContext);
}
}
protected void executeTransactionListeners(
List<TransactionListener> transactionListeners,
CommandContext commandContext
) {
for (TransactionListener transactionListener : transactionListeners) {
transactionListener.execute(commandContext);
}
}
|
protected DbSqlSession getDbSqlSession() {
return commandContext.getDbSqlSession();
}
public void rollback() {
try {
try {
log.debug("firing event rolling back...");
fireTransactionEvent(TransactionState.ROLLINGBACK, false);
} catch (Throwable exception) {
log.info("Exception during transaction: {}", exception.getMessage());
commandContext.exception(exception);
} finally {
log.debug("rolling back ibatis sql session...");
getDbSqlSession().rollback();
}
} catch (Throwable exception) {
log.info("Exception during transaction: {}", exception.getMessage());
commandContext.exception(exception);
} finally {
log.debug("firing event rolled back...");
fireTransactionEvent(TransactionState.ROLLED_BACK, true);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\standalone\StandaloneMybatisTransactionContext.java
| 1
|
请完成以下Java代码
|
public Object getCachedValue() {
return null;
}
@Override
public void setCachedValue(Object cachedValue) {}
@Override
public String getId() {
return null;
}
@Override
public void setId(String id) {}
@Override
public boolean isInserted() {
return false;
}
@Override
public void setInserted(boolean inserted) {}
@Override
public boolean isUpdated() {
return false;
}
@Override
public void setUpdated(boolean updated) {}
@Override
public boolean isDeleted() {
return false;
}
@Override
public void setDeleted(boolean deleted) {}
@Override
public Object getPersistentState() {
return null;
}
@Override
public void setRevision(int revision) {}
@Override
public int getRevision() {
return 0;
}
@Override
public int getRevisionNext() {
return 0;
}
@Override
public void setName(String name) {}
@Override
public void setProcessInstanceId(String processInstanceId) {}
|
@Override
public void setExecutionId(String executionId) {}
@Override
public Object getValue() {
return variableValue;
}
@Override
public void setValue(Object value) {
variableValue = value;
}
@Override
public String getTypeName() {
return TYPE_TRANSIENT;
}
@Override
public void setTypeName(String typeName) {}
@Override
public String getProcessInstanceId() {
return null;
}
@Override
public String getTaskId() {
return null;
}
@Override
public void setTaskId(String taskId) {}
@Override
public String getExecutionId() {
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TransientVariableInstance.java
| 1
|
请完成以下Java代码
|
public void setRemote_Host (String Remote_Host)
{
set_Value (COLUMNNAME_Remote_Host, Remote_Host);
}
/** Get Remote Host.
@return Remote host Info
*/
public String getRemote_Host ()
{
return (String)get_Value(COLUMNNAME_Remote_Host);
}
/** Set Request Type.
@param RequestType Request Type */
public void setRequestType (String RequestType)
{
set_Value (COLUMNNAME_RequestType, RequestType);
}
/** Get Request Type.
@return Request Type */
public String getRequestType ()
{
return (String)get_Value(COLUMNNAME_RequestType);
}
/** Set Status Code.
@param StatusCode Status Code */
public void setStatusCode (int StatusCode)
{
set_Value (COLUMNNAME_StatusCode, Integer.valueOf(StatusCode));
}
/** Get Status Code.
@return Status Code */
public int getStatusCode ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StatusCode);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Agent.
@param UserAgent
|
Browser Used
*/
public void setUserAgent (String UserAgent)
{
set_Value (COLUMNNAME_UserAgent, UserAgent);
}
/** Get User Agent.
@return Browser Used
*/
public String getUserAgent ()
{
return (String)get_Value(COLUMNNAME_UserAgent);
}
/** Set Web Session.
@param WebSession
Web Session ID
*/
public void setWebSession (String WebSession)
{
set_Value (COLUMNNAME_WebSession, WebSession);
}
/** Get Web Session.
@return Web Session ID
*/
public String getWebSession ()
{
return (String)get_Value(COLUMNNAME_WebSession);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebAccessLog.java
| 1
|
请完成以下Java代码
|
public PaymentReservation createReservation(@NonNull final PaymentReservationCreateRequest createRequest)
{
//
// Create & save
final PaymentReservation paymentReservation = PaymentReservation.builder()
.clientId(createRequest.getClientId())
.orgId(createRequest.getOrgId())
.amount(createRequest.getAmount())
.payerContactId(createRequest.getPayerContactId())
.payerEmail(createRequest.getPayerEmail())
.salesOrderId(createRequest.getSalesOrderId())
.dateTrx(createRequest.getDateTrx())
.paymentRule(createRequest.getPaymentRule())
.status(PaymentReservationStatus.WAITING_PAYER_APPROVAL)
.build();
save(paymentReservation);
//
// Process
final PaymentProcessor paymentProcessor = getPaymentProcessor(paymentReservation.getPaymentRule());
paymentProcessor.processReservation(paymentReservation);
save(paymentReservation);
return paymentReservation;
}
private PaymentProcessor getPaymentProcessor(final PaymentRule paymentRule)
{
return getPaymentProcessorIfExists(paymentRule)
.orElseThrow(() -> new AdempiereException("No payment processor found for payment rule: " + paymentRule));
}
private Optional<PaymentProcessor> getPaymentProcessorIfExists(final PaymentRule paymentRule)
{
return paymentProcessors.getByPaymentRule(paymentRule);
}
public void captureAmount(@NonNull final PaymentReservationCaptureRequest request)
{
final PaymentReservation reservation = getBySalesOrderIdNotVoided(request.getSalesOrderId())
.orElse(null);
if (reservation == null)
|
{
return;
}
// eagerly fetching the processor to fail fast
final PaymentProcessor paymentProcessor = getPaymentProcessor(reservation.getPaymentRule());
final PaymentId paymentId = createPayment(request);
final PaymentReservationCapture capture = PaymentReservationCapture.builder()
.reservationId(reservation.getId())
.status(PaymentReservationCaptureStatus.NEW)
//
.orgId(reservation.getOrgId())
.salesOrderId(reservation.getSalesOrderId())
.salesInvoiceId(request.getSalesInvoiceId())
.paymentId(paymentId)
//
.amount(request.getAmount())
//
.build();
capturesRepo.save(capture);
paymentProcessor.processCapture(reservation, capture);
reservationsRepo.save(reservation);
capture.setStatusAsCompleted();
capturesRepo.save(capture);
}
private PaymentId createPayment(@NonNull final PaymentReservationCaptureRequest request)
{
final I_C_Payment payment = Services.get(IPaymentBL.class).newInboundReceiptBuilder()
.invoiceId(request.getSalesInvoiceId())
.bpartnerId(request.getCustomerId())
.payAmt(request.getAmount().toBigDecimal())
.currencyId(request.getAmount().getCurrencyId())
.tenderType(TenderType.DirectDeposit)
.dateTrx(request.getDateTrx())
.createAndProcess();
return PaymentId.ofRepoId(payment.getC_Payment_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\reservation\PaymentReservationService.java
| 1
|
请完成以下Java代码
|
public @Nullable SameSite getSameSite() {
return this.sameSite;
}
public void setSameSite(@Nullable SameSite sameSite) {
this.sameSite = sameSite;
}
public @Nullable Boolean getPartitioned() {
return this.partitioned;
}
public void setPartitioned(@Nullable Boolean partitioned) {
this.partitioned = partitioned;
}
/**
* SameSite values.
*/
public enum SameSite {
/**
* SameSite attribute will be omitted when creating the cookie.
*/
OMITTED(null),
/**
* SameSite attribute will be set to None. Cookies are sent in both first-party
* and cross-origin requests.
*/
NONE("None"),
|
/**
* SameSite attribute will be set to Lax. Cookies are sent in a first-party
* context, also when following a link to the origin site.
*/
LAX("Lax"),
/**
* SameSite attribute will be set to Strict. Cookies are only sent in a
* first-party context (i.e. not when following a link to the origin site).
*/
STRICT("Strict");
private @Nullable final String attributeValue;
SameSite(@Nullable String attributeValue) {
this.attributeValue = attributeValue;
}
public @Nullable String attributeValue() {
return this.attributeValue;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\Cookie.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getNamespace() {
return namespace;
}
public Double getExceedCount() {
return exceedCount;
}
public ServerFlowConfig setExceedCount(Double exceedCount) {
this.exceedCount = exceedCount;
return this;
}
public Double getMaxOccupyRatio() {
return maxOccupyRatio;
}
public ServerFlowConfig setMaxOccupyRatio(Double maxOccupyRatio) {
this.maxOccupyRatio = maxOccupyRatio;
return this;
}
public Integer getIntervalMs() {
return intervalMs;
}
public ServerFlowConfig setIntervalMs(Integer intervalMs) {
this.intervalMs = intervalMs;
return this;
}
|
public Integer getSampleCount() {
return sampleCount;
}
public ServerFlowConfig setSampleCount(Integer sampleCount) {
this.sampleCount = sampleCount;
return this;
}
public Double getMaxAllowedQps() {
return maxAllowedQps;
}
public ServerFlowConfig setMaxAllowedQps(Double maxAllowedQps) {
this.maxAllowedQps = maxAllowedQps;
return this;
}
@Override
public String toString() {
return "ServerFlowConfig{" +
"namespace='" + namespace + '\'' +
", exceedCount=" + exceedCount +
", maxOccupyRatio=" + maxOccupyRatio +
", intervalMs=" + intervalMs +
", sampleCount=" + sampleCount +
", maxAllowedQps=" + maxAllowedQps +
'}';
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\config\ServerFlowConfig.java
| 2
|
请完成以下Java代码
|
private static String getEnvOrDefault(String key, String def) {
String value = System.getenv(key);
return value == null ? def : value;
}
// 返回参数列表中第一个真实存在的路径,或者 null
private static String firstExists(File... paths) {
for (File path : paths) {
if (path.exists()) {
return path.getAbsolutePath();
}
}
return null;
}
public static String getUserDir() {
String userDir = System.getProperty("user.dir");
String binFolder = getEnvOrDefault("KKFILEVIEW_BIN_FOLDER", userDir);
File pluginPath = new File(binFolder);
// 如果指定了 bin 或其父目录,则返回父目录
if (new File(pluginPath, "bin").exists()) {
return pluginPath.getAbsolutePath();
} else if (pluginPath.exists() && pluginPath.getName().equals("bin")) {
return pluginPath.getParentFile().getAbsolutePath();
} else {
return firstExists(new File(pluginPath, MAIN_DIRECTORY_NAME),
new File(pluginPath.getParentFile(), MAIN_DIRECTORY_NAME));
}
}
public static String getCustomizedConfigPath() {
String homePath = getHomePath();
String separator = java.io.File.separator;
return homePath + separator + "config" + separator + "application.properties";
}
public synchronized static void restorePropertiesFromEnvFormat(Properties properties) {
Iterator<Map.Entry<Object, Object>> iterator = properties.entrySet().iterator();
|
while (iterator.hasNext()) {
Map.Entry<Object, Object> entry = iterator.next();
String key = entry.getKey().toString();
String value = entry.getValue().toString();
if (value.trim().startsWith("${") && value.trim().endsWith("}")) {
int beginIndex = value.indexOf(":");
if (beginIndex < 0) {
beginIndex = value.length() - 1;
}
int endIndex = value.length() - 1;
String envKey = value.substring(2, beginIndex);
String envValue = System.getenv(envKey);
if (envValue == null || "".equals(envValue.trim())) {
value = value.substring(beginIndex + 1, endIndex);
} else {
value = envValue;
}
properties.setProperty(key, value);
}
}
}
}
|
repos\kkFileView-master\server\src\main\java\cn\keking\utils\ConfigUtils.java
| 1
|
请完成以下Java代码
|
protected void executePlanItemParse(CmmnParserImpl cmmnParser, CmmnParseResult cmmnParseResult, PlanItem planItem, ServiceTask serviceTask) {
CmmnActivityBehaviorFactory activityBehaviorFactory = cmmnParser.getActivityBehaviorFactory();
switch (serviceTask.getType()) {
case HttpServiceTask.HTTP_TASK:
planItem.setBehavior(activityBehaviorFactory.createHttpActivityBehavior(planItem, serviceTask));
break;
case ServiceTask.MAIL_TASK:
planItem.setBehavior(activityBehaviorFactory.createEmailActivityBehavior(planItem, serviceTask));
break;
case SendEventServiceTask.SEND_EVENT:
planItem.setBehavior(activityBehaviorFactory.createSendEventActivityBehavior(planItem, (SendEventServiceTask) serviceTask));
break;
default:
// java task type was not set in the version <= 6.2.0 that's why we have to assume that default service task type is java
if (StringUtils.isNotEmpty(serviceTask.getImplementation())) {
if (ImplementationType.IMPLEMENTATION_TYPE_CLASS.equals(serviceTask.getImplementationType())) {
|
planItem.setBehavior(activityBehaviorFactory.createCmmnClassDelegate(planItem, serviceTask));
} else if (ImplementationType.IMPLEMENTATION_TYPE_EXPRESSION.equals(serviceTask.getImplementationType())) {
planItem.setBehavior(activityBehaviorFactory.createPlanItemExpressionActivityBehavior(planItem, serviceTask));
} else if (ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equals(serviceTask.getImplementationType())) {
planItem.setBehavior(activityBehaviorFactory.createPlanItemDelegateExpressionActivityBehavior(planItem, serviceTask));
}
}
break;
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\parser\handler\AbstractServiceTaskParseHandler.java
| 1
|
请完成以下Java代码
|
public static void ensureWhitelistedResourceId(CommandContext commandContext, String resourceType, String resourceId) {
String resourcePattern = determineResourceWhitelistPattern(commandContext.getProcessEngineConfiguration(), resourceType);
Pattern PATTERN = Pattern.compile(resourcePattern);
if (!PATTERN.matcher(resourceId).matches()) {
throw generateException(ProcessEngineException.class, resourceType + " has an invalid id", "'" + resourceId + "'", "is not a valid resource identifier.");
}
}
public static void ensureTrue(String message, boolean value) {
if (!value) {
throw new ProcessEngineException(message);
}
}
public static void ensureFalse(String message, boolean value) {
ensureTrue(message, !value);
}
protected static String determineResourceWhitelistPattern(ProcessEngineConfiguration processEngineConfiguration, String resourceType) {
String resourcePattern = null;
if (resourceType.equals("User")) {
resourcePattern = processEngineConfiguration.getUserResourceWhitelistPattern();
}
if (resourceType.equals("Group")) {
resourcePattern = processEngineConfiguration.getGroupResourceWhitelistPattern();
}
if (resourceType.equals("Tenant")) {
resourcePattern = processEngineConfiguration.getTenantResourceWhitelistPattern();
}
if (resourcePattern != null && !resourcePattern.isEmpty()) {
return resourcePattern;
}
return processEngineConfiguration.getGeneralResourceWhitelistPattern();
}
protected static <T extends ProcessEngineException> T generateException(Class<T> exceptionClass, String message, String variableName, String description) {
String formattedMessage = formatMessage(message, variableName, description);
try {
|
Constructor<T> constructor = exceptionClass.getConstructor(String.class);
return constructor.newInstance(formattedMessage);
}
catch (Exception e) {
throw LOG.exceptionWhileInstantiatingClass(exceptionClass.getName(), e);
}
}
protected static String formatMessage(String message, String variableName, String description) {
return formatMessageElement(message, ": ") + formatMessageElement(variableName, " ") + description;
}
protected static String formatMessageElement(String element, String delimiter) {
if (element != null && !element.isEmpty()) {
return element.concat(delimiter);
}
else {
return "";
}
}
public static void ensureActiveCommandContext(String operation) {
if(Context.getCommandContext() == null) {
throw LOG.notInsideCommandContext(operation);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\EnsureUtil.java
| 1
|
请完成以下Java代码
|
public class ConvertLongToInt {
static Function<Long, Integer> convert = val -> Optional.ofNullable(val)
.map(Long::intValue)
.orElse(null);
public static int longToIntCast(long number) {
return (int) number;
}
public static int longToIntJavaWithMath(long number) {
return Math.toIntExact(number);
}
public static int longToIntJavaWithLambda(long number) {
return convert.apply(number);
}
public static int longToIntBoxingValues(long number) {
return Long.valueOf(number)
.intValue();
|
}
public static int longToIntGuava(long number) {
return Ints.checkedCast(number);
}
public static int longToIntGuavaSaturated(long number) {
return Ints.saturatedCast(number);
}
public static int longToIntWithBigDecimal(long number) {
return new BigDecimal(number).intValueExact();
}
}
|
repos\tutorials-master\core-java-modules\core-java-numbers-4\src\main\java\com\baeldung\convertLongToInt\ConvertLongToInt.java
| 1
|
请完成以下Java代码
|
public Collection<ParameterMapping> getParameterMappings() {
return parameterMappingCollection.get(this);
}
public String getCamundaCaseBinding() {
return camundaCaseBindingAttribute.getValue(this);
}
public void setCamundaCaseBinding(String camundaCaseBinding) {
camundaCaseBindingAttribute.setValue(this, camundaCaseBinding);
}
public String getCamundaCaseVersion() {
return camundaCaseVersionAttribute.getValue(this);
}
public void setCamundaCaseVersion(String camundaCaseVersion) {
camundaCaseVersionAttribute.setValue(this, camundaCaseVersion);
}
public String getCamundaCaseTenantId() {
return camundaCaseTenantIdAttribute.getValue(this);
}
public void setCamundaCaseTenantId(String camundaCaseTenantId) {
camundaCaseTenantIdAttribute.setValue(this, camundaCaseTenantId);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseTask.class, CMMN_ELEMENT_CASE_TASK)
.extendsType(Task.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<CaseTask>() {
public CaseTask newInstance(ModelTypeInstanceContext instanceContext) {
return new CaseTaskImpl(instanceContext);
}
});
caseRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CASE_REF)
.build();
|
/** camunda extensions */
camundaCaseBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_BINDING)
.namespace(CAMUNDA_NS)
.build();
camundaCaseVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_VERSION)
.namespace(CAMUNDA_NS)
.build();
camundaCaseTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_TENANT_ID)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class)
.build();
caseRefExpressionChild = sequenceBuilder.element(CaseRefExpression.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseTaskImpl.java
| 1
|
请完成以下Java代码
|
public class ReceiptScheduleDeletedEvent extends AbstractReceiptScheduleEvent
{
public static ReceiptScheduleDeletedEvent cast(@NonNull final AbstractReceiptScheduleEvent event)
{
return (ReceiptScheduleDeletedEvent)event;
}
public static final String TYPE = "ReceiptScheduleDeletedEvent";
@JsonCreator
@Builder
public ReceiptScheduleDeletedEvent(
@JsonProperty("eventDescriptor") final EventDescriptor eventDescriptor,
@JsonProperty("materialDescriptor") final MaterialDescriptor materialDescriptor,
@JsonProperty("minMaxDescriptor") @Nullable final MinMaxDescriptor minMaxDescriptor,
@JsonProperty("reservedQuantity") final BigDecimal reservedQuantity,
@JsonProperty("receiptScheduleId") final int receiptScheduleId)
{
super(eventDescriptor,
materialDescriptor,
null, // we don't care about it, we're going to delete it anyway
minMaxDescriptor,
reservedQuantity,
|
receiptScheduleId);
}
@Override
public BigDecimal getOrderedQuantityDelta()
{
return getMaterialDescriptor().getQuantity().negate();
}
@Override
public BigDecimal getReservedQuantityDelta()
{
return getReservedQuantity().negate();
}
@Override
public String getEventName() {return TYPE;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\receiptschedule\ReceiptScheduleDeletedEvent.java
| 1
|
请完成以下Java代码
|
private LookupValuesList getM_HU_PI_Item_Products()
{
final Properties ctx = getCtx();
final I_M_ShipmentSchedule shipmentSchedule = getCurrentShipmentSchedule();
final ProductId productId = ProductId.ofRepoId(shipmentSchedule.getM_Product_ID());
return WEBUI_ProcessHelper.retrieveHUPIItemProducts(ctx,
productId,
Services.get(IShipmentScheduleEffectiveBL.class).getBPartnerId(shipmentSchedule),
true); // includeVirtualItem = true..similar case as with production
}
@Override
public Object getParameterDefaultValue(@NonNull final IProcessDefaultParameter parameter)
{
if (Objects.equals(PARAM_QtyCUsPerTU, parameter.getColumnName()))
{
return retrieveQtyToPick().toBigDecimal();
}
else if (Objects.equals(PARAM_M_HU_PI_Item_Product_ID, parameter.getColumnName()))
{
final I_M_ShipmentSchedule shipmentSchedule = getCurrentShipmentSchedule();
final HUPIItemProductId piItemProductId = HUPIItemProductId.ofRepoIdOrNull(shipmentSchedule.getM_HU_PI_Item_Product_ID());
if (piItemProductId == null)
{
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
else
{
final IHUPIItemProductBL hupiItemProductBL = Services.get(IHUPIItemProductBL.class);
final ITranslatableString displayName = hupiItemProductBL.getDisplayName(piItemProductId);
return IntegerLookupValue.of(piItemProductId, displayName);
}
}
|
else
{
return DEFAULT_VALUE_NOTAVAILABLE;
}
}
/**
* Creates a new M_HU within the processe's interited trx.
*/
private static I_M_HU createTU(
@NonNull final I_M_HU_PI_Item_Product itemProduct,
@NonNull final LocatorId locatorId)
{
final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
final IHUTrxBL huTrxBL = Services.get(IHUTrxBL.class);
final I_M_HU_PI huPI = itemProduct.getM_HU_PI_Item().getM_HU_PI_Version().getM_HU_PI();
return huTrxBL.createHUContextProcessorExecutor()
.call(huContext -> handlingUnitsDAO.createHUBuilder(huContext)
.setM_HU_Item_Parent(null) // no parent
.setM_HU_PI_Item_Product(itemProduct)
.setLocatorId(locatorId)
// we are going to load from a "real" source HU onto this HU, so both shall be active. Otherwise it would look as if stuff was vanishing for the source HU
.setHUStatus(X_M_HU.HUSTATUS_Active)
.create(huPI));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_PickQtyToNewHU.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return shipmentSchedule + "/" + salesOrderLine.orElse(null);
}
public BigDecimal getQtyOrdered()
{
return deliverRequest.getQtyOrdered();
}
public boolean hasSalesOrderLine()
{
return salesOrderLine.isPresent();
}
private I_C_OrderLine getSalesOrderLine()
{
return salesOrderLine.get();
}
public ProductId getProductId()
{
return ProductId.ofRepoId(shipmentSchedule.getM_Product_ID());
}
public WarehouseId getWarehouseId()
{
return Services.get(IShipmentScheduleEffectiveBL.class).getWarehouseId(shipmentSchedule);
}
public I_C_UOM getOrderPriceUOM()
{
final int priceUomId = getSalesOrderLine().getPrice_UOM_ID();
return Services.get(IUOMDAO.class).getById(priceUomId);
}
public BigDecimal getOrderQtyReserved()
{
return getSalesOrderLine().getQtyReserved();
}
public BigDecimal getOrderPriceActual()
{
return getSalesOrderLine().getPriceActual();
}
public DocStatus getOrderDocStatus()
{
return DocStatus.ofCode(getSalesOrderLine().getC_Order().getDocStatus());
}
public I_M_ShipmentSchedule getSched()
{
return shipmentSchedule;
}
public ShipmentScheduleId getShipmentScheduleId()
{
return ShipmentScheduleId.ofRepoId(shipmentSchedule.getM_ShipmentSchedule_ID());
}
/**
* @return shipment schedule's QtyToDeliver_Override or <code>null</code>
*/
public BigDecimal getQtyOverride()
|
{
return InterfaceWrapperHelper.getValueOrNull(shipmentSchedule, I_M_ShipmentSchedule.COLUMNNAME_QtyToDeliver_Override);
}
public BigDecimal getInitialSchedQtyDelivered()
{
return initialSchedQtyDelivered;
}
public void setShipmentScheduleLineNetAmt(final BigDecimal lineNetAmt)
{
shipmentSchedule.setLineNetAmt(lineNetAmt);
}
@Nullable
public String getSalesOrderPORef()
{
return salesOrder.map(I_C_Order::getPOReference).orElse(null);
}
@Nullable
public InputDataSourceId getSalesOrderADInputDatasourceID()
{
if(!salesOrder.isPresent())
{
return null;
}
final I_C_Order orderRecord = salesOrder.get();
return InputDataSourceId.ofRepoIdOrNull(orderRecord.getAD_InputDataSource_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\OlAndSched.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ConsumerSDK {
@Value("${ips.stream}")
private String IPS_STREAM;
@Value("${ips.shard.id}")
private String IPS_SHARD_ID;
@Autowired
private AmazonKinesis kinesis;
private GetShardIteratorResult shardIterator;
public void consumeWithKinesis() {
GetRecordsRequest recordsRequest = new GetRecordsRequest();
recordsRequest.setShardIterator(shardIterator.getShardIterator());
recordsRequest.setLimit(25);
GetRecordsResult recordsResult = kinesis.getRecords(recordsRequest);
while (!recordsResult.getRecords().isEmpty()) {
recordsResult.getRecords()
.stream()
.map(record -> new String(record.getData()
|
.array()))
.forEach(System.out::println);
recordsRequest.setShardIterator(recordsResult.getNextShardIterator());
recordsResult = kinesis.getRecords(recordsRequest);
}
}
@PostConstruct
private void buildShardIterator() {
GetShardIteratorRequest readShardsRequest = new GetShardIteratorRequest();
readShardsRequest.setStreamName(IPS_STREAM);
readShardsRequest.setShardIteratorType(ShardIteratorType.LATEST);
readShardsRequest.setShardId(IPS_SHARD_ID);
this.shardIterator = kinesis.getShardIterator(readShardsRequest);
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-stream\spring-cloud-stream-kinesis\src\main\java\com\baeldung\sdk\ConsumerSDK.java
| 2
|
请完成以下Java代码
|
public Set<String> toJsonSet()
{
if (all)
{
return ALL_StringSet;
}
return toSet(DocumentId::toJson);
}
public SelectionSize toSelectionSize()
{
if (isAll())
{
return SelectionSize.ofAll();
}
return SelectionSize.ofSize(size());
}
public DocumentIdsSelection addAll(@NonNull final DocumentIdsSelection documentIdsSelection)
{
if (this.isEmpty())
{
return documentIdsSelection;
}
else if (documentIdsSelection.isEmpty())
{
return this;
}
if (this.all)
{
return this;
}
else if (documentIdsSelection.all)
{
return documentIdsSelection;
|
}
final ImmutableSet<DocumentId> combinedIds = Stream.concat(this.stream(), documentIdsSelection.stream()).collect(ImmutableSet.toImmutableSet());
final DocumentIdsSelection result = DocumentIdsSelection.of(combinedIds);
if (this.equals(result))
{
return this;
}
else if (documentIdsSelection.equals(result))
{
return documentIdsSelection;
}
else
{
return result;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentIdsSelection.java
| 1
|
请完成以下Java代码
|
public class NeuralNetworkDependencyParser extends AbstractDependencyParser
{
private parser_dll parser_dll;
public NeuralNetworkDependencyParser(Segment segment)
{
super(segment);
parser_dll = new parser_dll();
setDeprelTranslater(ConfigOption.DEPRL_DESCRIPTION_PATH).enableDeprelTranslator(true);
}
public NeuralNetworkDependencyParser()
{
this(NLPTokenizer.ANALYZER);
}
@Override
public CoNLLSentence parse(List<Term> termList)
{
List<String> posTagList = PosTagUtil.to863(termList);
List<String> wordList = new ArrayList<String>(termList.size());
for (Term term : termList)
{
wordList.add(term.word);
}
List<Integer> heads = new ArrayList<Integer>(termList.size());
List<String> deprels = new ArrayList<String>(termList.size());
parser_dll.parse(wordList, posTagList, heads, deprels);
CoNLLWord[] wordArray = new CoNLLWord[termList.size()];
for (int i = 0; i < wordArray.length; ++i)
{
wordArray[i] = new CoNLLWord(i + 1, wordList.get(i), posTagList.get(i), termList.get(i).nature.toString());
wordArray[i].DEPREL = deprels.get(i);
}
for (int i = 0; i < wordArray.length; ++i)
{
int index = heads.get(i) - 1;
if (index < 0)
{
wordArray[i].HEAD = CoNLLWord.ROOT;
continue;
}
wordArray[i].HEAD = wordArray[index];
|
}
return new CoNLLSentence(wordArray);
}
/**
* 分析句子的依存句法
*
* @param termList 句子,可以是任何具有词性标注功能的分词器的分词结果
* @return CoNLL格式的依存句法树
*/
public static CoNLLSentence compute(List<Term> termList)
{
return new NeuralNetworkDependencyParser().parse(termList);
}
/**
* 分析句子的依存句法
*
* @param sentence 句子
* @return CoNLL格式的依存句法树
*/
public static CoNLLSentence compute(String sentence)
{
return new NeuralNetworkDependencyParser().parse(sentence);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\NeuralNetworkDependencyParser.java
| 1
|
请完成以下Java代码
|
public class Book {
@MongoId
private ObjectId id;
@Field("bookName")
private String bookName;
@Field("authorName")
private String authorName;
public ObjectId getId() {
return id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthorName() {
return authorName;
}
|
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Book book = (Book) o;
return Objects.equals(id, book.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb\src\main\java\com\baeldung\logging\model\Book.java
| 1
|
请完成以下Java代码
|
public static String get(String language) {
language = language.toLowerCase();
if("ecmascript".equals(language)) {
language = "javascript";
}
String extension = extensions.get(language);
if(extension == null) {
return null;
} else {
return loadScriptEnv(language, extension);
}
}
protected static String loadScriptEnv(String language, String extension) {
String scriptEnvPath = String.format(ENV_PATH_TEMPLATE, language, extension);
|
InputStream envResource = SpinScriptException.class.getClassLoader().getResourceAsStream(scriptEnvPath);
if(envResource == null) {
throw LOG.noScriptEnvFoundForLanguage(language, scriptEnvPath);
} else {
try {
return SpinIoUtil.inputStreamAsString(envResource);
} finally {
SpinIoUtil.closeSilently(envResource);
}
}
}
}
|
repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\scripting\SpinScriptEnv.java
| 1
|
请完成以下Java代码
|
protected ActivitiElContext createElContext(VariableScope variableScope) {
return (ActivitiElContext) new ELContextBuilder()
.withResolvers(createElResolver(variableScope))
.buildWithCustomFunctions(customFunctionProviders);
}
protected ELResolver createElResolver(VariableScope variableScope) {
CompositeELResolver elResolver = new CompositeELResolver();
elResolver.add(new VariableScopeElResolver(variableScope));
if (customELResolvers != null) {
customELResolvers.forEach(elResolver::add);
}
addBeansResolver(elResolver);
addBaseResolvers(elResolver);
return elResolver;
}
protected void addBeansResolver(CompositeELResolver elResolver) {
if (beans != null) {
// ACT-1102: Also expose all beans in configuration when using
// standalone activiti, not
// in spring-context
elResolver.add(new ReadOnlyMapELResolver(beans));
}
}
private void addBaseResolvers(CompositeELResolver elResolver) {
elResolver.add(new ArrayELResolver());
elResolver.add(new ListELResolver());
elResolver.add(new MapELResolver());
elResolver.add(new CustomMapperJsonNodeELResolver());
elResolver.add(new DynamicBeanPropertyELResolver(ItemInstance.class, "getFieldValue", "setFieldValue")); // TODO: needs verification
elResolver.add(new ELResolverReflectionBlockerDecorator(new BeanELResolver()));
}
|
public Map<Object, Object> getBeans() {
return beans;
}
public void setBeans(Map<Object, Object> beans) {
this.beans = beans;
}
public ELContext getElContext(Map<String, Object> availableVariables) {
CompositeELResolver elResolver = new CompositeELResolver();
addBaseResolvers(elResolver);
return new ELContextBuilder()
.withResolvers(elResolver)
.withVariables(availableVariables)
.buildWithCustomFunctions(customFunctionProviders);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\el\ExpressionManager.java
| 1
|
请完成以下Java代码
|
public void setMSV3_Grund (java.lang.String MSV3_Grund)
{
set_Value (COLUMNNAME_MSV3_Grund, MSV3_Grund);
}
/** Get Grund.
@return Grund */
@Override
public java.lang.String getMSV3_Grund ()
{
return (java.lang.String)get_Value(COLUMNNAME_MSV3_Grund);
}
/** Set MSV3_LieferPzn.
@param MSV3_LieferPzn MSV3_LieferPzn */
@Override
public void setMSV3_LieferPzn (java.lang.String MSV3_LieferPzn)
{
set_Value (COLUMNNAME_MSV3_LieferPzn, MSV3_LieferPzn);
}
/** Get MSV3_LieferPzn.
@return MSV3_LieferPzn */
@Override
public java.lang.String getMSV3_LieferPzn ()
{
return (java.lang.String)get_Value(COLUMNNAME_MSV3_LieferPzn);
}
/** Set Substitution.
@param MSV3_Substitution_ID Substitution */
@Override
public void setMSV3_Substitution_ID (int MSV3_Substitution_ID)
{
if (MSV3_Substitution_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_Substitution_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MSV3_Substitution_ID, Integer.valueOf(MSV3_Substitution_ID));
}
/** Get Substitution.
@return Substitution */
@Override
public int getMSV3_Substitution_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Substitution_ID);
if (ii == null)
return 0;
return ii.intValue();
|
}
/**
* MSV3_Substitutionsgrund AD_Reference_ID=540818
* Reference name: MSV3_Substitutionsgrund
*/
public static final int MSV3_SUBSTITUTIONSGRUND_AD_Reference_ID=540818;
/** Nachfolgeprodukt = Nachfolgeprodukt */
public static final String MSV3_SUBSTITUTIONSGRUND_Nachfolgeprodukt = "Nachfolgeprodukt";
/** ReUndParallelImport = ReUndParallelImport */
public static final String MSV3_SUBSTITUTIONSGRUND_ReUndParallelImport = "ReUndParallelImport";
/** Vorschlag = Vorschlag */
public static final String MSV3_SUBSTITUTIONSGRUND_Vorschlag = "Vorschlag";
/** Set Substitutionsgrund.
@param MSV3_Substitutionsgrund Substitutionsgrund */
@Override
public void setMSV3_Substitutionsgrund (java.lang.String MSV3_Substitutionsgrund)
{
set_Value (COLUMNNAME_MSV3_Substitutionsgrund, MSV3_Substitutionsgrund);
}
/** Get Substitutionsgrund.
@return Substitutionsgrund */
@Override
public java.lang.String getMSV3_Substitutionsgrund ()
{
return (java.lang.String)get_Value(COLUMNNAME_MSV3_Substitutionsgrund);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_Substitution.java
| 1
|
请完成以下Java代码
|
public int compareTo(@NonNull final QuantityTU other)
{
return this.value - other.value;
}
public QuantityTU add(@NonNull final QuantityTU toAdd)
{
if (this.value == 0)
{
return toAdd;
}
else if (toAdd.value == 0)
{
return this;
}
else
{
return ofInt(this.value + toAdd.value);
|
}
}
public QuantityTU subtract(@NonNull final QuantityTU toSubtract)
{
if (toSubtract.value == 0)
{
return this;
}
else
{
return ofInt(this.value - toSubtract.value);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\QuantityTU.java
| 1
|
请完成以下Java代码
|
public void setQtyReject (final @Nullable BigDecimal QtyReject)
{
set_Value (COLUMNNAME_QtyReject, QtyReject);
}
@Override
public BigDecimal getQtyReject()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReject);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyToIssue (final BigDecimal QtyToIssue)
{
set_ValueNoCheck (COLUMNNAME_QtyToIssue, QtyToIssue);
}
@Override
public BigDecimal getQtyToIssue()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToIssue);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* RejectReason AD_Reference_ID=541422
* Reference name: QtyNotPicked RejectReason
*/
|
public static final int REJECTREASON_AD_Reference_ID=541422;
/** NotFound = N */
public static final String REJECTREASON_NotFound = "N";
/** Damaged = D */
public static final String REJECTREASON_Damaged = "D";
@Override
public void setRejectReason (final @Nullable java.lang.String RejectReason)
{
set_ValueNoCheck (COLUMNNAME_RejectReason, RejectReason);
}
@Override
public java.lang.String getRejectReason()
{
return get_ValueAsString(COLUMNNAME_RejectReason);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_PP_Order_IssueSchedule.java
| 1
|
请完成以下Java代码
|
protected void prepare()
{
if (I_ESR_ImportLine.Table_Name.equals(getTableName()))
{
p_ESR_ImportLine_ID = getRecord_ID();
}
}
@Override
protected String doIt() throws Exception
{
if (p_ESR_ImportLine_ID <= 0)
{
throw new FillMandatoryException(I_ESR_ImportLine.COLUMNNAME_ESR_ImportLine_ID);
}
final I_ESR_ImportLine esrImportLine = InterfaceWrapperHelper.create(getCtx(), p_ESR_ImportLine_ID, I_ESR_ImportLine.class, get_TrxName());
|
Check.assume(get_TrxName().equals(InterfaceWrapperHelper.getTrxName(esrImportLine)), "TrxName {0} of {1} is equal to the process-TrxName {2}",
InterfaceWrapperHelper.getTrxName(esrImportLine),
esrImportLine,
get_TrxName());
final String description = getProcessInfo().getTitle() + " #" + getPinstanceId().getRepoId();
esrImportLine.setProcessed(true);
esrImportLine.setDescription(description);
InterfaceWrapperHelper.save(esrImportLine);
return "OK";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\process\ESR_SetLineToProcessed.java
| 1
|
请完成以下Java代码
|
public boolean isCurrentBPartnerIdSet()
{
return getCurrentBPartnerIdOrNull() != null;
}
public BPartner getCurrentBPartner()
{
final BPartnerId bpartnerId = getCurrentBPartnerIdOrNull();
return getBpartnersCache().getBPartnerById(bpartnerId);
}
public BPartnerId getCurrentBPartnerIdOrNull()
{
final I_I_BPartner currentImportRecord = getCurrentImportRecord();
return currentImportRecord != null
? BPartnerId.ofRepoIdOrNull(currentImportRecord.getC_BPartner_ID())
: null;
}
public void setCurrentBPartnerId(@NonNull final BPartnerId bpartnerId)
{
final I_I_BPartner currentImportRecord = getCurrentImportRecord();
Check.assumeNotNull(currentImportRecord, "Parameter currentImportRecord is not null");
currentImportRecord.setC_BPartner_ID(bpartnerId.getRepoId());
}
public BPartnerLocationId getCurrentBPartnerLocationIdOrNull()
{
final I_I_BPartner currentImportRecord = getCurrentImportRecord();
return currentImportRecord != null
? BPartnerLocationId.ofRepoIdOrNull(currentImportRecord.getC_BPartner_ID(), currentImportRecord.getC_BPartner_Location_ID())
: null;
}
public void setCurrentBPartnerLocationId(@NonNull final BPartnerLocationId bpLocationId)
{
final I_I_BPartner currentImportRecord = getCurrentImportRecord();
|
Check.assumeNotNull(currentImportRecord, "Parameter currentImportRecord is not null");
currentImportRecord.setC_BPartner_Location_ID(bpLocationId.getRepoId());
}
public BPartnerContactId getCurrentBPartnerContactIdOrNull()
{
final I_I_BPartner currentImportRecord = getCurrentImportRecord();
return currentImportRecord != null
? BPartnerContactId.ofRepoIdOrNull(currentImportRecord.getC_BPartner_ID(), currentImportRecord.getAD_User_ID())
: null;
}
public void setCurrentBPartnerContactId(@NonNull final BPartnerContactId bpContactId)
{
final I_I_BPartner currentImportRecord = getCurrentImportRecord();
Check.assumeNotNull(currentImportRecord, "Parameter currentImportRecord is not null");
currentImportRecord.setAD_User_ID(bpContactId.getRepoId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnerImportContext.java
| 1
|
请完成以下Java代码
|
public final class TableColumnPermissions extends AbstractPermissions<TableColumnPermission>
{
public static final Builder builder()
{
return new Builder();
}
private TableColumnPermissions(final Builder builder)
{
super(builder);
}
public Builder asNewBuilder()
{
final Builder builder = builder();
builder.addPermissions(this, CollisionPolicy.Override);
return builder;
}
@Override
protected TableColumnPermission noPermission()
{
return TableColumnPermission.NONE;
}
public boolean isColumnAccess(final int AD_Table_ID, final int AD_Column_ID, final Access access)
{
// If we were asked for a AD_Column_ID <= 0 then return false automatically
// NOTE: this is the case of GridTable.addField which is checking for access to a generated field (not one that has AD_Column_ID binding).
if (AD_Column_ID <= 0)
{
return false;
|
}
final TableColumnResource resource = TableColumnResource.of(AD_Table_ID, AD_Column_ID);
return hasAccess(resource, access);
}
public static class Builder extends PermissionsBuilder<TableColumnPermission, TableColumnPermissions>
{
@Override
protected TableColumnPermissions createPermissionsInstance()
{
return new TableColumnPermissions(this);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TableColumnPermissions.java
| 1
|
请完成以下Java代码
|
public I_AD_Table getAD_Table() throws RuntimeException
{
return (I_AD_Table)MTable.get(getCtx(), I_AD_Table.Table_Name)
.getPO(getAD_Table_ID(), get_TrxName()); }
/** Set Table.
@param AD_Table_ID
Database Table information
*/
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get Table.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sales Transaction.
@param IsSOTrx
This is a Sales Transaction
*/
public void setIsSOTrx (boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx));
}
/** Get Sales Transaction.
@return This is a Sales Transaction
*/
public boolean isSOTrx ()
{
Object oo = get_Value(COLUMNNAME_IsSOTrx);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
|
/** Set Exclude Attribute Set.
@param M_AttributeSetExclude_ID
Exclude the ability to enter Attribute Sets
*/
public void setM_AttributeSetExclude_ID (int M_AttributeSetExclude_ID)
{
if (M_AttributeSetExclude_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, Integer.valueOf(M_AttributeSetExclude_ID));
}
/** Get Exclude Attribute Set.
@return Exclude the ability to enter Attribute Sets
*/
public int getM_AttributeSetExclude_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetExclude_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_AttributeSet getM_AttributeSet() throws RuntimeException
{
return (I_M_AttributeSet)MTable.get(getCtx(), I_M_AttributeSet.Table_Name)
.getPO(getM_AttributeSet_ID(), get_TrxName()); }
/** Set Attribute Set.
@param M_AttributeSet_ID
Product Attribute Set
*/
public void setM_AttributeSet_ID (int M_AttributeSet_ID)
{
if (M_AttributeSet_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, Integer.valueOf(M_AttributeSet_ID));
}
/** Get Attribute Set.
@return Product Attribute Set
*/
public int getM_AttributeSet_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSet_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSetExclude.java
| 1
|
请完成以下Java代码
|
public class RegulatoryReporting3 {
@XmlElement(name = "DbtCdtRptgInd")
@XmlSchemaType(name = "string")
protected RegulatoryReportingType1Code dbtCdtRptgInd;
@XmlElement(name = "Authrty")
protected RegulatoryAuthority2 authrty;
@XmlElement(name = "Dtls")
protected List<StructuredRegulatoryReporting3> dtls;
/**
* Gets the value of the dbtCdtRptgInd property.
*
* @return
* possible object is
* {@link RegulatoryReportingType1Code }
*
*/
public RegulatoryReportingType1Code getDbtCdtRptgInd() {
return dbtCdtRptgInd;
}
/**
* Sets the value of the dbtCdtRptgInd property.
*
* @param value
* allowed object is
* {@link RegulatoryReportingType1Code }
*
*/
public void setDbtCdtRptgInd(RegulatoryReportingType1Code value) {
this.dbtCdtRptgInd = value;
}
/**
* Gets the value of the authrty property.
*
* @return
* possible object is
* {@link RegulatoryAuthority2 }
*
*/
public RegulatoryAuthority2 getAuthrty() {
return authrty;
}
/**
* Sets the value of the authrty property.
*
* @param value
* allowed object is
* {@link RegulatoryAuthority2 }
*
|
*/
public void setAuthrty(RegulatoryAuthority2 value) {
this.authrty = value;
}
/**
* Gets the value of the dtls property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dtls property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDtls().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link StructuredRegulatoryReporting3 }
*
*
*/
public List<StructuredRegulatoryReporting3> getDtls() {
if (dtls == null) {
dtls = new ArrayList<StructuredRegulatoryReporting3>();
}
return this.dtls;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\RegulatoryReporting3.java
| 1
|
请完成以下Java代码
|
protected AbstractConnector createConnector(InetSocketAddress address, Server server) {
return this.createConnector(address, server, null, null, null);
}
protected AbstractConnector createConnector(InetSocketAddress address, Server server, @Nullable Executor executor,
@Nullable Scheduler scheduler, @Nullable ByteBufferPool pool) {
HttpConfiguration httpConfiguration = new HttpConfiguration();
httpConfiguration.setSendServerVersion(false);
List<ConnectionFactory> connectionFactories = new ArrayList<>();
connectionFactories.add(new HttpConnectionFactory(httpConfiguration));
if (getHttp2() != null && getHttp2().isEnabled()) {
connectionFactories.add(new HTTP2CServerConnectionFactory(httpConfiguration));
}
ServerConnector connector = new ServerConnector(server, executor, scheduler, pool, this.getAcceptors(),
this.getSelectors(), connectionFactories.toArray(new ConnectionFactory[0]));
connector.setHost(address.getHostString());
connector.setPort(address.getPort());
return connector;
}
protected void customizeSsl(Server server, InetSocketAddress address) {
Ssl ssl = getSsl();
Assert.state(ssl != null, "'ssl' must not be null");
Assert.state(ssl.getServerNameBundles().isEmpty(), "Server name SSL bundles are not supported with Jetty");
new SslServerCustomizer(getHttp2(), address, ssl.getClientAuth(), getSslBundle()).customize(server);
}
|
protected Handler addHandlerWrappers(Handler handler) {
if (getCompression() != null && getCompression().getEnabled()) {
handler = applyWrapper(handler, JettyHandlerWrappers.createGzipHandlerWrapper(getCompression()));
}
if (StringUtils.hasText(getServerHeader())) {
handler = applyWrapper(handler, JettyHandlerWrappers.createServerHeaderHandlerWrapper(getServerHeader()));
}
return handler;
}
protected Handler applyWrapper(Handler handler, Handler.Wrapper wrapper) {
wrapper.setHandler(handler);
return wrapper;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\JettyWebServerFactory.java
| 1
|
请完成以下Java代码
|
public class Overflow {
public static void showIntegerOverflow() {
int value = Integer.MAX_VALUE-1;
for(int i = 0; i < 4; i++, value++) {
System.out.println(value);
}
}
public static void noOverflowWithBigInteger() {
BigInteger largeValue = new BigInteger(Integer.MAX_VALUE + "");
for(int i = 0; i < 4; i++) {
System.out.println(largeValue);
largeValue = largeValue.add(BigInteger.ONE);
}
}
public static void exceptionWithAddExact() {
int value = Integer.MAX_VALUE-1;
for(int i = 0; i < 4; i++) {
System.out.println(value);
value = Math.addExact(value, 1);
}
}
public static int addExact(int x, int y) {
int r = x + y;
if (((x ^ r) & (y ^ r)) < 0) {
throw new ArithmeticException("int overflow");
}
return r;
}
public static void demonstrateUnderflow() {
|
for(int i = 1073; i <= 1076; i++) {
System.out.println("2^" + i + " = " + Math.pow(2, -i));
}
}
public static double powExact(double base, double exponent)
{
if(base == 0.0) {
return 0.0;
}
double result = Math.pow(base, exponent);
if(result == Double.POSITIVE_INFINITY ) {
throw new ArithmeticException("Double overflow resulting in POSITIVE_INFINITY");
} else if(result == Double.NEGATIVE_INFINITY) {
throw new ArithmeticException("Double overflow resulting in NEGATIVE_INFINITY");
} else if(Double.compare(-0.0f, result) == 0) {
throw new ArithmeticException("Double overflow resulting in negative zero");
} else if(Double.compare(+0.0f, result) == 0) {
throw new ArithmeticException("Double overflow resulting in positive zero");
}
return result;
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-math\src\main\java\com\baeldung\overflow\Overflow.java
| 1
|
请完成以下Java代码
|
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Customs Tariff.
@param M_CustomsTariff_ID Customs Tariff */
@Override
public void setM_CustomsTariff_ID (int M_CustomsTariff_ID)
{
if (M_CustomsTariff_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CustomsTariff_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CustomsTariff_ID, Integer.valueOf(M_CustomsTariff_ID));
}
/** Get Customs Tariff.
@return Customs Tariff */
@Override
public int getM_CustomsTariff_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_CustomsTariff_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name Name */
@Override
|
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@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_M_CustomsTariff.java
| 1
|
请完成以下Java代码
|
public I_M_PickingSlot retrievePickingSlotForHU(@NonNull final HuId huId)
{
final IQueryBuilder<I_M_PickingSlot> queryBuilder = queryBL.createQueryBuilder(I_M_PickingSlot.class);
final ICompositeQueryFilter<I_M_PickingSlot> filters = queryBL.createCompositeQueryFilter(I_M_PickingSlot.class);
filters.setJoinOr();
//
// Picking Slot has given HU as current HU
filters.addEqualsFilter(I_M_PickingSlot.COLUMNNAME_M_HU_ID, huId);
//
// or given HU is in Picking Slot queue
final IQuery<I_M_PickingSlot_HU> pickingSlotHUQuery = queryBL.createQueryBuilder(I_M_PickingSlot_HU.class)
.addEqualsFilter(I_M_PickingSlot_HU.COLUMNNAME_M_HU_ID, huId)
.create();
filters.addInSubQueryFilter(de.metas.picking.model.I_M_PickingSlot.COLUMNNAME_M_PickingSlot_ID,
I_M_PickingSlot_HU.COLUMNNAME_M_PickingSlot_ID,
pickingSlotHUQuery);
//
// Retrieve Picking Slot
return queryBuilder
.filter(filters)
.create()
.firstOnly(I_M_PickingSlot.class);
}
@Override
public IQueryFilter<I_M_HU> createHUOnPickingSlotQueryFilter(final Object contextProvider)
{
final ICompositeQueryFilter<I_M_HU> filters = queryBL.createCompositeQueryFilter(I_M_HU.class);
filters.setJoinOr();
//
// Filter HUs which are open on Picking Slot
{
final IQuery<I_M_PickingSlot> pickingSlotsQuery = queryBL.createQueryBuilder(I_M_PickingSlot.class, contextProvider)
.addOnlyActiveRecordsFilter()
// NOTE: make sure that we are considering only those picking slots where M_HU_ID is set
// If not, well, postgresql will be confused and will evaluate this expression like always false
.addNotEqualsFilter(I_M_PickingSlot.COLUMNNAME_M_HU_ID, null)
.create();
filters.addInSubQueryFilter(I_M_HU.COLUMNNAME_M_HU_ID,
I_M_PickingSlot.COLUMNNAME_M_HU_ID,
pickingSlotsQuery);
}
|
//
// Filter HUs which are in Picking Slot queue
{
final IQuery<I_M_PickingSlot_HU> pickingSlotsQueueQuery = queryBL.createQueryBuilder(I_M_PickingSlot_HU.class, contextProvider)
.addOnlyActiveRecordsFilter()
.addNotEqualsFilter(I_M_PickingSlot_HU.COLUMN_M_HU_ID, null) // M_HU_ID IS NOT NULL
.create();
filters.addInSubQueryFilter(I_M_HU.COLUMNNAME_M_HU_ID,
I_M_PickingSlot_HU.COLUMNNAME_M_HU_ID,
pickingSlotsQueueQuery);
}
return filters;
}
@Override
public boolean isEmpty(final de.metas.picking.model.I_M_PickingSlot pickingSlot)
{
return !queryPickingSlotHUs(pickingSlot).anyMatch();
}
private IQuery<I_M_PickingSlot_HU> queryPickingSlotHUs(final de.metas.picking.model.I_M_PickingSlot pickingSlot)
{
return queryBL.createQueryBuilder(I_M_PickingSlot_HU.class, pickingSlot)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_PickingSlot_HU.COLUMNNAME_M_PickingSlot_ID, pickingSlot.getM_PickingSlot_ID())
.create();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\impl\HUPickingSlotDAO.java
| 1
|
请完成以下Java代码
|
public void detachState() {
userTask.getExecution().removeTask(userTask);
userTask.setExecution(null);
}
@Override
public void attachState(MigratingScopeInstance owningInstance) {
ExecutionEntity representativeExecution = owningInstance.resolveRepresentativeExecution();
representativeExecution.addTask(userTask);
for (VariableInstanceEntity variable : userTask.getVariablesInternal()) {
variable.setExecution(representativeExecution);
}
userTask.setExecution(representativeExecution);
}
@Override
public void attachState(MigratingTransitionInstance targetTransitionInstance) {
throw MIGRATION_LOGGER.cannotAttachToTransitionInstance(this);
}
@Override
|
public void migrateState() {
userTask.setProcessDefinitionId(migratingActivityInstance.getTargetScope().getProcessDefinition().getId());
userTask.setTaskDefinitionKey(migratingActivityInstance.getTargetScope().getId());
migrateHistory();
}
protected void migrateHistory() {
HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel();
if (historyLevel.isHistoryEventProduced(HistoryEventTypes.TASK_INSTANCE_MIGRATE, this)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createTaskInstanceMigrateEvt(userTask);
}
});
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingUserTaskInstance.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
loggger.info("请求地址 : " + request.getRequestURL().toString());
loggger.info("HTTP METHOD : " + request.getMethod());
loggger.info("IP : " + request.getRemoteAddr());
loggger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
+ joinPoint.getSignature().getName());
loggger.info("参数 : " + Arrays.toString(joinPoint.getArgs()));
// loggger.info("参数 : " + joinPoint.getArgs());
}
|
@AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的参数名一致
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
loggger.info("返回值 : " + ret);
}
@Around("logPointCut()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
Object ob = pjp.proceed();// ob 为方法的返回值
loggger.info("耗时 : " + (System.currentTimeMillis() - startTime));
return ob;
}
}
|
repos\spring-boot-quick-master\quick-img2txt\src\main\java\com\quick\config\WebLogAspect.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private StringEncryptor createAsymmetricDefault() {
SimpleAsymmetricConfig config = new SimpleAsymmetricConfig();
config.setPrivateKey(get(configProps::getPrivateKeyString, propertyPrefix + ".private-key-string", null));
config.setPrivateKeyLocation(get(configProps::getPrivateKeyLocation, propertyPrefix + ".private-key-location", null));
config.setPrivateKeyFormat(get(configProps::getPrivateKeyFormat, propertyPrefix + ".private-key-format", AsymmetricCryptography.KeyFormat.DER));
config.setPublicKey(get(configProps::getPublicKeyString, propertyPrefix + ".public-key-string", null));
config.setPublicKeyLocation(get(configProps::getPublicKeyLocation, propertyPrefix + ".public-key-location", null));
config.setPublicKeyFormat(get(configProps::getPublicKeyFormat, propertyPrefix + ".public-key-format", AsymmetricCryptography.KeyFormat.DER));
return new SimpleAsymmetricStringEncryptor(config);
}
private StringEncryptor createPBEDefault() {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword(getRequired(configProps::getPassword, propertyPrefix + ".password"));
config.setAlgorithm(get(configProps::getAlgorithm, propertyPrefix + ".algorithm", "PBEWITHHMACSHA512ANDAES_256"));
config.setKeyObtentionIterations(get(configProps::getKeyObtentionIterations, propertyPrefix + ".key-obtention-iterations", "1000"));
config.setPoolSize(get(configProps::getPoolSize, propertyPrefix + ".pool-size", "1"));
config.setProviderName(get(configProps::getProviderName, propertyPrefix + ".provider-name", null));
config.setProviderClassName(get(configProps::getProviderClassName, propertyPrefix + ".provider-class-name", null));
config.setSaltGeneratorClassName(get(configProps::getSaltGeneratorClassname, propertyPrefix + ".salt-generator-classname", "org.jasypt.salt.RandomSaltGenerator"));
config.setIvGeneratorClassName(get(configProps::getIvGeneratorClassname, propertyPrefix + ".iv-generator-classname", "org.jasypt.iv.RandomIvGenerator"));
config.setStringOutputType(get(configProps::getStringOutputType, propertyPrefix + ".string-output-type", "base64"));
encryptor.setConfig(config);
return encryptor;
|
}
private <T> T getRequired(Supplier<T> supplier, String key) {
T value = supplier.get();
if (value == null) {
throw new IllegalStateException(String.format("Required Encryption configuration property missing: %s", key));
}
return value;
}
private <T> T get(Supplier<T> supplier, String key, T defaultValue) {
T value = supplier.get();
if (value == defaultValue) {
log.info("Encryptor config not found for property {}, using default value: {}", key, value);
}
return value;
}
}
|
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\configuration\StringEncryptorBuilder.java
| 2
|
请完成以下Java代码
|
private List<I_AD_TreeNodeMM> retrieveADTreeNodeMM(final I_AD_Menu menu)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(menu);
final String trxName = InterfaceWrapperHelper.getTrxName(menu);
final StringBuilder whereClause = new StringBuilder();
final List<Object> params = new ArrayList<Object>();
whereClause.append(I_AD_TreeNodeMM.COLUMNNAME_Node_ID).append("=?");
params.add(menu.getAD_Menu_ID());
return new TypedSqlQuery<I_AD_TreeNodeMM>(ctx, I_AD_TreeNodeMM.class, whereClause.toString(), trxName)
.setParameters(params)
.list();
}
private Iterator<I_AD_Table> retrieveTablesWithEntityType()
{
final StringBuilder whereClause = new StringBuilder();
final List<Object> params = new ArrayList<Object>();
whereClause.append(" EXISTS (select 1 from AD_Column c where c.AD_Table_ID=AD_Table.AD_Table_ID and c.ColumnName=?)");
params.add("EntityType");
whereClause.append(" AND ").append(I_AD_Table.COLUMNNAME_IsView).append("=?");
params.add(false);
// whereClause.append(" AND ").append(I_AD_Table.COLUMNNAME_TableName).append("='AD_Menu'");
return new TypedSqlQuery<I_AD_Table>(getCtx(), I_AD_Table.class, whereClause.toString(), ITrx.TRXNAME_None)
.setParameters(params)
.setOrderBy(I_AD_Table.Table_Name)
.list(I_AD_Table.class)
|
.iterator();
}
private Iterator<PO> retrieveRecordsForEntityType(final I_AD_Table table, final String entityType)
{
final String whereClause = "EntityType=?";
final Iterator<PO> records = new Query(getCtx(), table.getTableName(), whereClause, ITrx.TRXNAME_None)
.setParameters(entityType)
.setOrderBy("Created")
.iterate(null, false);
return records;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\process\AD_Migration_CreateFromEntityType.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.