instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public Map<String, String[]> getParameterMap() {
Set<String> names = getCombinedParameterNames();
Map<String, String[]> parameterMap = new HashMap<>(names.size());
for (String name : names) {
parameterMap.put(name, getParameterValues(name));
}
return parameterMap;
}
private Set<String> getCombinedParameterNames() {
Set<String> names = new HashSet<>();
names.addAll(super.getParameterMap().keySet());
names.addAll(this.savedRequest.getParameterMap().keySet());
return names;
}
@Override
public Enumeration<String> getParameterNames() {
return new Enumerator<>(getCombinedParameterNames());
}
@Override
public String[] getParameterValues(String name) {
String[] savedRequestParams = this.savedRequest.getParameterValues(name); | String[] wrappedRequestParams = super.getParameterValues(name);
if (savedRequestParams == null) {
return wrappedRequestParams;
}
if (wrappedRequestParams == null) {
return savedRequestParams;
}
// We have parameters in both saved and wrapped requests so have to merge them
List<String> wrappedParamsList = Arrays.asList(wrappedRequestParams);
List<String> combinedParams = new ArrayList<>(wrappedParamsList);
// We want to add all parameters of the saved request *apart from* duplicates of
// those already added
for (String savedRequestParam : savedRequestParams) {
if (!wrappedParamsList.contains(savedRequestParam)) {
combinedParams.add(savedRequestParam);
}
}
return combinedParams.toArray(new String[0]);
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\SavedRequestAwareWrapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public S3AsyncClient s3client(S3ClientConfigurarionProperties s3props, AwsCredentialsProvider credentialsProvider) {
SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
.writeTimeout(Duration.ZERO)
.maxConcurrency(64)
.build();
S3Configuration serviceConfiguration = S3Configuration.builder()
.checksumValidationEnabled(false)
.chunkedEncodingEnabled(true)
.build();
S3AsyncClientBuilder b = S3AsyncClient.builder()
.httpClient(httpClient)
.region(s3props.getRegion())
.credentialsProvider(credentialsProvider)
.serviceConfiguration(serviceConfiguration);
if (s3props.getEndpoint() != null) {
b = b.endpointOverride(s3props.getEndpoint());
} | return b.build();
}
@Bean
public AwsCredentialsProvider awsCredentialsProvider(S3ClientConfigurarionProperties s3props) {
if (StringUtils.isBlank(s3props.getAccessKeyId())) {
// Return default provider
return DefaultCredentialsProvider.create();
}
else {
// Return custom credentials provider
return () -> {
AwsCredentials creds = AwsBasicCredentials.create(s3props.getAccessKeyId(), s3props.getSecretAccessKey());
return creds;
};
}
}
} | repos\tutorials-master\aws-modules\aws-reactive\src\main\java\com\baeldung\aws\reactive\s3\S3ClientConfiguration.java | 2 |
请完成以下Java代码 | public static BPartnerId ofObject(@NonNull final Object object)
{
return RepoIdAwares.ofObject(object, BPartnerId.class, BPartnerId::ofRepoId);
}
public static int toRepoId(@Nullable final BPartnerId bpartnerId)
{
return toRepoIdOr(bpartnerId, -1);
}
public static int toRepoIdOr(@Nullable final BPartnerId bpartnerId, final int defaultValue)
{
return bpartnerId != null ? bpartnerId.getRepoId() : defaultValue;
}
private BPartnerId(final int repoId) | {
this.repoId = Check.assumeGreaterThanZero(repoId, "C_BPartner_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
public static boolean equals(@Nullable final BPartnerId o1, @Nullable final BPartnerId o2)
{
return Objects.equals(o1, o2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerId.java | 1 |
请完成以下Java代码 | public class StaticServerHttpHeadersWriter implements ServerHttpHeadersWriter {
private final HttpHeaders headersToAdd;
public StaticServerHttpHeadersWriter(HttpHeaders headersToAdd) {
this.headersToAdd = headersToAdd;
}
@Override
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
HttpHeaders headers = exchange.getResponse().getHeaders();
// Note: We need to ensure that the following algorithm compares headers
// case insensitively, which should be true of headers.containsKey().
boolean containsNoHeadersToAdd = true;
for (String headerName : this.headersToAdd.headerNames()) {
if (headers.containsHeader(headerName)) {
containsNoHeadersToAdd = false;
break;
}
}
if (containsNoHeadersToAdd) {
this.headersToAdd.forEach(headers::put);
}
return Mono.empty(); | }
public static Builder builder() {
return new Builder();
}
public static class Builder {
private HttpHeaders headers = new HttpHeaders();
public Builder header(String headerName, String... values) {
this.headers.put(headerName, Arrays.asList(values));
return this;
}
public StaticServerHttpHeadersWriter build() {
return new StaticServerHttpHeadersWriter(this.headers);
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\StaticServerHttpHeadersWriter.java | 1 |
请完成以下Java代码 | public <ID extends RepoIdAware> ID getRepoId(@NonNull final Function<Integer, ID> idMapper)
{
try
{
final int repoIdInt = Integer.parseInt(idPart);
return idMapper.apply(repoIdInt);
}
catch (final Exception ex)
{
throw new AdempiereException("Failed converting " + this + " to ID", ex);
}
}
@NonNull
public <ID extends RepoIdAware> ID getRepoIdAssumingApplicationId(@NonNull MobileApplicationId expectedApplicationId, @NonNull final Function<Integer, ID> idMapper) | {
assertApplicationId(expectedApplicationId);
return getRepoId(idMapper);
}
public void assertApplicationId(@NonNull final MobileApplicationId expectedApplicationId)
{
if (!Objects.equals(this.applicationId, expectedApplicationId))
{
throw new AdempiereException("Expected applicationId `" + expectedApplicationId + "` but was `" + this.applicationId + "`");
}
}
public static boolean equals(@Nullable final WFProcessId id1, @Nullable final WFProcessId id2) {return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WFProcessId.java | 1 |
请完成以下Java代码 | public class MybatisEventDeploymentDataManager extends AbstractEventDataManager<EventDeploymentEntity> implements EventDeploymentDataManager {
public MybatisEventDeploymentDataManager(EventRegistryEngineConfiguration eventRegistryConfiguration) {
super(eventRegistryConfiguration);
}
@Override
public Class<? extends EventDeploymentEntity> getManagedEntityClass() {
return EventDeploymentEntityImpl.class;
}
@Override
public EventDeploymentEntity create() {
return new EventDeploymentEntityImpl();
}
@Override
public long findDeploymentCountByQueryCriteria(EventDeploymentQueryImpl deploymentQuery) {
return (Long) getDbSqlSession().selectOne("selectEventDeploymentCountByQueryCriteria", deploymentQuery);
}
@Override | @SuppressWarnings("unchecked")
public List<EventDeployment> findDeploymentsByQueryCriteria(EventDeploymentQueryImpl deploymentQuery) {
return getDbSqlSession().selectList("selectEventDeploymentsByQueryCriteria", deploymentQuery);
}
@Override
public List<String> getDeploymentResourceNames(String deploymentId) {
return getDbSqlSession().getSqlSession().selectList("selectEventResourceNamesByDeploymentId", deploymentId);
}
@Override
@SuppressWarnings("unchecked")
public List<EventDeployment> findDeploymentsByNativeQuery(Map<String, Object> parameterMap) {
return getDbSqlSession().selectListWithRawParameter("selectEventDeploymentByNativeQuery", parameterMap);
}
@Override
public long findDeploymentCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectEventDeploymentCountByNativeQuery", parameterMap);
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\data\impl\MybatisEventDeploymentDataManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configureClientInboundChannel(ChannelRegistration registration) {
// TODO Auto-generated method stub
}
@Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
// TODO Auto-generated method stub
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
// TODO Auto-generated method stub | }
@Override
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
// TODO Auto-generated method stub
}
@Override
public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
// TODO Auto-generated method stub
return false;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-sockets\src\main\java\com\baeldung\springsockets\config\WebSocketMessageBrokerConfig.java | 2 |
请完成以下Java代码 | public void pointCutMethod() {
}
@Pointcut("@within(com.xiaolyuh.aop.annotations.Log)")
public void pointCutType() {
}
// 建言
@Before("pointCutMethod() || pointCutType()")
// @Before("execution(* com.xiaolyuh.aop.controller.UserController.*(..))")
public void before(JoinPoint joinPoint) {
// 通过反射可以获得注解上的属性,然后做日志记录相关的操作
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
System.out.println("日志切面 befor:" + log.value() + ":::" + JSON.toJSONString(joinPoint.getArgs()));
}
@After(value = "pointCutMethod() || pointCutType()")
public void after(JoinPoint joinPoint) {
// 通过反射可以获得注解上的属性,然后做日志记录相关的操作
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
System.out.println("日志切面 after:" + log.value());
}
@AfterReturning(value = "pointCutMethod() || pointCutType()", returning = "result")
public void afterReturning(JoinPoint joinPoint, Object result) {
// 通过反射可以获得注解上的属性,然后做日志记录相关的操作
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
System.out.println("日志切面 afterReturning:" + log.value() + ":::" + JSON.toJSONString(result));
}
@AfterThrowing(value = "pointCutMethod() || pointCutType()", throwing = "t")
public void afterThrowing(JoinPoint joinPoint, Throwable t) { | // 通过反射可以获得注解上的属性,然后做日志记录相关的操作
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
System.out.println("日志切面 afterThrowing:" + log.value() + ":::" + JSON.toJSONString(t.getStackTrace()));
}
// @Around(value = "pointCutMethod() || pointCutType()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
// 通过反射可以获得注解上的属性,然后做日志记录相关的操作
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
System.out.println("日志切面 Around before:" + log.value() + ":::" + JSON.toJSONString(joinPoint.getArgs()));
Object result = joinPoint.proceed();
System.out.println("日志切面 Around after:" + log.value() + ":::" + JSON.toJSONString(result));
return result;
}
} | repos\spring-boot-student-master\spring-boot-student-spring\src\main\java\com\xiaolyuh\aop\aspect\LogAspect.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Author implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int age;
private String name;
private String genre;
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 String getGenre() {
return genre; | }
public void setGenre(String genre) {
this.genre = genre;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", age=" + age
+ ", name=" + name + ", genre=" + genre + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootAssignSequentialNumber\src\main\java\com\bookstore\entity\Author.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private static Map<String, String> extractParameters(@NonNull final Throwable throwable, @NonNull final String adLanguage)
{
return AdempiereException.extractParameters(throwable)
.entrySet()
.stream()
.map(e -> GuavaCollectors.entry(e.getKey(), convertParameterToJson(e.getValue(), adLanguage)))
.collect(GuavaCollectors.toImmutableMap());
}
@NonNull
private static String convertParameterToJson(final Object value, final String adLanguage)
{
if (Null.isNull(value))
{
return "<null>";
}
else if (value instanceof ITranslatableString) | {
return ((ITranslatableString)value).translate(adLanguage);
}
else if (value instanceof RepoIdAware)
{
return String.valueOf(((RepoIdAware)value).getRepoId());
}
else if (value instanceof ReferenceListAwareEnum)
{
return ((ReferenceListAwareEnum)value).getCode();
}
else
{
return value.toString();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\rest\ReportRestController.java | 2 |
请完成以下Java代码 | public Builder setCaption(final ITranslatableString caption)
{
this.caption = caption;
return this;
}
public Builder setDescription(final ITranslatableString description)
{
this.description = description;
return this;
}
public ITranslatableString getDescription()
{
return description;
}
public Builder addElement(final DocumentLayoutElementDescriptor element)
{
Check.assumeNotNull(element, "Parameter element is not null");
elements.add(element);
return this;
}
public Builder addElement(final DocumentFieldDescriptor processParaDescriptor)
{
Check.assumeNotNull(processParaDescriptor, "Parameter processParaDescriptor is not null");
final DocumentLayoutElementDescriptor element = DocumentLayoutElementDescriptor.builder()
.setCaption(processParaDescriptor.getCaption())
.setDescription(processParaDescriptor.getDescription())
.setWidgetType(processParaDescriptor.getWidgetType())
.setAllowShowPassword(processParaDescriptor.isAllowShowPassword())
.barcodeScannerType(processParaDescriptor.getBarcodeScannerType())
.addField(DocumentLayoutElementFieldDescriptor.builder(processParaDescriptor.getFieldName())
.setLookupInfos(processParaDescriptor.getLookupDescriptor().orElse(null))
.setPublicField(true)
.setSupportZoomInto(processParaDescriptor.isSupportZoomInto())) | .build();
addElement(element);
return this;
}
public Builder addElements(@Nullable final DocumentEntityDescriptor parametersDescriptor)
{
if (parametersDescriptor != null)
{
parametersDescriptor.getFields().forEach(this::addElement);
}
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\descriptor\ProcessLayout.java | 1 |
请完成以下Java代码 | public class X_C_BPartner_Department extends org.compiere.model.PO implements I_C_BPartner_Department, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1284889818L;
/** Standard Constructor */
public X_C_BPartner_Department (final Properties ctx, final int C_BPartner_Department_ID, @Nullable final String trxName)
{
super (ctx, C_BPartner_Department_ID, trxName);
}
/** Load Constructor */
public X_C_BPartner_Department (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 setC_BPartner_Department_ID (final int C_BPartner_Department_ID)
{
if (C_BPartner_Department_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_Department_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_Department_ID, C_BPartner_Department_ID);
}
@Override
public int getC_BPartner_Department_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Department_ID);
}
@Override
public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
} | @Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Department.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonResponseBPartnerCompositeUpsertItem
{
@ApiModelProperty(position = 10)
@JsonInclude(Include.NON_NULL)
JsonResponseUpsertItem responseBPartnerItem;
@ApiModelProperty(position = 20)
@JsonInclude(Include.NON_EMPTY)
List<JsonResponseUpsertItem> responseLocationItems;
@ApiModelProperty(position = 30)
@JsonInclude(Include.NON_EMPTY)
List<JsonResponseUpsertItem> responseContactItems;
@ApiModelProperty(position = 40)
@JsonInclude(Include.NON_EMPTY)
List<JsonResponseUpsertItem> responseBankAccountItems; | @Builder
@JsonCreator
public JsonResponseBPartnerCompositeUpsertItem(
@JsonProperty("responseBPartnerItem") @Nullable final JsonResponseUpsertItem responseBPartnerItem,
@JsonProperty("responseLocationItems") @Singular final List<JsonResponseUpsertItem> responseLocationItems,
@JsonProperty("responseContactItems") @Singular final List<JsonResponseUpsertItem> responseContactItems,
@JsonProperty("responseBankAccountItems") @Singular final List<JsonResponseUpsertItem> responseBankAccountItems)
{
this.responseBPartnerItem = responseBPartnerItem;
this.responseLocationItems = responseLocationItems;
this.responseContactItems = responseContactItems;
this.responseBankAccountItems = responseBankAccountItems;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\response\JsonResponseBPartnerCompositeUpsertItem.java | 2 |
请完成以下Java代码 | public void setDescription (final @Nullable java.lang.String Description)
{
set_ValueNoCheck (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setFileName (final @Nullable java.lang.String FileName)
{
set_ValueNoCheck (COLUMNNAME_FileName, FileName);
}
@Override
public java.lang.String getFileName()
{
return get_ValueAsString(COLUMNNAME_FileName);
}
@Override
public void setM_Product_AttachmentEntry_ReferencedRecord_v_ID (final int M_Product_AttachmentEntry_ReferencedRecord_v_ID)
{
if (M_Product_AttachmentEntry_ReferencedRecord_v_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_AttachmentEntry_ReferencedRecord_v_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_AttachmentEntry_ReferencedRecord_v_ID, M_Product_AttachmentEntry_ReferencedRecord_v_ID);
}
@Override
public int getM_Product_AttachmentEntry_ReferencedRecord_v_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_AttachmentEntry_ReferencedRecord_v_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
} | @Override
public void setType (final boolean Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
@Override
public boolean isType()
{
return get_ValueAsBoolean(COLUMNNAME_Type);
}
@Override
public void setURL (final @Nullable java.lang.String URL)
{
set_ValueNoCheck (COLUMNNAME_URL, URL);
}
@Override
public java.lang.String getURL()
{
return get_ValueAsString(COLUMNNAME_URL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_AttachmentEntry_ReferencedRecord_v.java | 1 |
请完成以下Java代码 | protected EventLogEntryEntity createEventLogEntry(
String type,
String processDefinitionId,
String processInstanceId,
String executionId,
String taskId,
Map<String, Object> data
) {
EventLogEntryEntity eventLogEntry = Context.getCommandContext().getEventLogEntryEntityManager().create();
eventLogEntry.setProcessDefinitionId(processDefinitionId);
eventLogEntry.setProcessInstanceId(processInstanceId);
eventLogEntry.setExecutionId(executionId);
eventLogEntry.setTaskId(taskId);
eventLogEntry.setType(type);
eventLogEntry.setTimeStamp(timeStamp);
putInMapIfNotNull(data, Fields.TIMESTAMP, timeStamp);
// Current user
String userId = Authentication.getAuthenticatedUserId();
if (userId != null) {
eventLogEntry.setUserId(userId);
putInMapIfNotNull(data, "userId", userId);
}
// Current tenant
if (!data.containsKey(Fields.TENANT_ID) && processDefinitionId != null) {
ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition(processDefinitionId);
if (
processDefinition != null &&
!ProcessEngineConfigurationImpl.NO_TENANT_ID.equals(processDefinition.getTenantId())
) {
putInMapIfNotNull(data, Fields.TENANT_ID, processDefinition.getTenantId());
}
}
try {
eventLogEntry.setData(objectMapper.writeValueAsBytes(data));
} catch (Exception e) {
logger.warn("Could not serialize event data. Data will not be written to the database", e);
}
return eventLogEntry;
}
@Override | public void setEvent(ActivitiEvent event) {
this.event = event;
}
@Override
public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
@Override
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
// Helper methods //////////////////////////////////////////////////////
@SuppressWarnings("unchecked")
public <T> T getEntityFromEvent() {
return (T) ((ActivitiEntityEvent) event).getEntity();
}
public void putInMapIfNotNull(Map<String, Object> map, String key, Object value) {
if (value != null) {
map.put(key, value);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\event\logger\handler\AbstractDatabaseEventLoggerEventHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UploadController {
private static String UPLOADED_FOLDER = "E://temp//";
@GetMapping("/")
public String index() {
return "upload";
}
@GetMapping("/more")
public String uploadMore() {
return "uploadMore";
}
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/uploadStatus";
} | @PostMapping("/uploadMore")
public String moreFileUpload(@RequestParam("file") MultipartFile[] files,
RedirectAttributes redirectAttributes) {
if (files.length==0) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
for(MultipartFile file:files){
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
redirectAttributes.addFlashAttribute("message", "You successfully uploaded all");
return "redirect:/uploadStatus";
}
@GetMapping("/uploadStatus")
public String uploadStatus() {
return "uploadStatus";
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-6 课:使用 Spring Boot 和 Thymeleaf 演示上传文件\spring-boot-file-upload\src\main\java\com\neo\controller\UploadController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private final AuthorRepository authorRepository;
public BookstoreService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Transactional
public void longRunningServiceMethod() throws InterruptedException {
System.out.println("Service-method start ...");
System.out.println("Sleeping before triggering SQL to simulate a long running code ...");
Thread.sleep(40000);
Author author = authorRepository.fetchByName("Joana Nimar");
authorRepository.deleteByNeGenre(author.getGenre());
System.out.println("Service-method done ...");
}
@Transactional
public void newAuthors() {
Author a1 = new Author();
a1.setName("Mark Janel");
a1.setGenre("Anthology");
a1.setId(1L);
a1.setAge(23);
Author a2 = new Author();
a2.setName("Olivia Goy");
a2.setGenre("Anthology");
a2.setId(2L);
a2.setAge(43); | Author a3 = new Author();
a3.setName("Quartis Young");
a3.setGenre("Anthology");
a3.setId(3L);
a3.setAge(51);
Author a4 = new Author();
a4.setName("Joana Nimar");
a4.setGenre("History");
a4.setId(4L);
a4.setAge(34);
authorRepository.save(a1);
authorRepository.save(a2);
authorRepository.save(a3);
authorRepository.save(a4);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootTransactionalInRepository\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public static ExchangeBuilder directExchange(String name) {
return new ExchangeBuilder(name, ExchangeTypes.DIRECT);
}
/**
* Return a {@link TopicExchange} builder.
* @param name the name.
* @return the builder.
*/
public static ExchangeBuilder topicExchange(String name) {
return new ExchangeBuilder(name, ExchangeTypes.TOPIC);
}
/**
* Return a {@link FanoutExchange} builder.
* @param name the name.
* @return the builder.
*/
public static ExchangeBuilder fanoutExchange(String name) {
return new ExchangeBuilder(name, ExchangeTypes.FANOUT);
}
/**
* Return a {@link HeadersExchange} builder.
* @param name the name.
* @return the builder.
*/
public static ExchangeBuilder headersExchange(String name) {
return new ExchangeBuilder(name, ExchangeTypes.HEADERS);
}
/**
* Return an {@code x-consistent-hash} exchange builder.
* @param name the name.
* @return the builder.
* @since 3.2
*/
public static ConsistentHashExchangeBuilder consistentHashExchange(String name) {
return new ConsistentHashExchangeBuilder(name);
}
/**
* An {@link ExchangeBuilder} extension for the {@link ConsistentHashExchange}.
*
* @since 3.2
*/
public static final class ConsistentHashExchangeBuilder extends BaseExchangeBuilder<ConsistentHashExchangeBuilder> {
/**
* Construct an instance of the builder for {@link ConsistentHashExchange}.
* | * @param name the exchange name
* @see ExchangeTypes
*/
public ConsistentHashExchangeBuilder(String name) {
super(name, ExchangeTypes.CONSISTENT_HASH);
}
public ConsistentHashExchangeBuilder hashHeader(String headerName) {
withArgument("hash-header", headerName);
return this;
}
public ConsistentHashExchangeBuilder hashProperty(String propertyName) {
withArgument("hash-property", propertyName);
return this;
}
@Override
@SuppressWarnings("unchecked")
public ConsistentHashExchange build() {
return configureExchange(
new ConsistentHashExchange(this.name, this.durable, this.autoDelete, getArguments()));
}
}
} | repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\ExchangeBuilder.java | 1 |
请完成以下Java代码 | public void setSQLStatement (java.lang.String SQLStatement)
{
set_Value (COLUMNNAME_SQLStatement, SQLStatement);
}
/** Get SQLStatement.
@return SQLStatement */
@Override
public java.lang.String getSQLStatement ()
{
return (java.lang.String)get_Value(COLUMNNAME_SQLStatement);
}
/**
* StatusCode AD_Reference_ID=53311
* Reference name: AD_Migration Status
*/
public static final int STATUSCODE_AD_Reference_ID=53311;
/** Applied = A */
public static final String STATUSCODE_Applied = "A";
/** Unapplied = U */
public static final String STATUSCODE_Unapplied = "U";
/** Failed = F */
public static final String STATUSCODE_Failed = "F";
/** Partially applied = P */
public static final String STATUSCODE_PartiallyApplied = "P";
/** Set Status Code.
@param StatusCode Status Code */
@Override
public void setStatusCode (java.lang.String StatusCode)
{
set_ValueNoCheck (COLUMNNAME_StatusCode, StatusCode);
}
/** Get Status Code.
@return Status Code */
@Override
public java.lang.String getStatusCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_StatusCode);
}
/**
* StepType AD_Reference_ID=53313
* Reference name: Migration step type
*/ | public static final int STEPTYPE_AD_Reference_ID=53313;
/** Application Dictionary = AD */
public static final String STEPTYPE_ApplicationDictionary = "AD";
/** SQL Statement = SQL */
public static final String STEPTYPE_SQLStatement = "SQL";
/** Set Step type.
@param StepType
Migration step type
*/
@Override
public void setStepType (java.lang.String StepType)
{
set_ValueNoCheck (COLUMNNAME_StepType, StepType);
}
/** Get Step type.
@return Migration step type
*/
@Override
public java.lang.String getStepType ()
{
return (java.lang.String)get_Value(COLUMNNAME_StepType);
}
/** Set Name der DB-Tabelle.
@param TableName Name der DB-Tabelle */
@Override
public void setTableName (java.lang.String TableName)
{
set_Value (COLUMNNAME_TableName, TableName);
}
/** Get Name der DB-Tabelle.
@return Name der DB-Tabelle */
@Override
public java.lang.String getTableName ()
{
return (java.lang.String)get_Value(COLUMNNAME_TableName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_MigrationStep.java | 1 |
请完成以下Java代码 | public void setIsAutoPrint (final boolean IsAutoPrint)
{
set_Value (COLUMNNAME_IsAutoPrint, IsAutoPrint);
}
@Override
public boolean isAutoPrint()
{
return get_ValueAsBoolean(COLUMNNAME_IsAutoPrint);
}
@Override
public void setLabelReport_Process_ID (final int LabelReport_Process_ID)
{
if (LabelReport_Process_ID < 1)
set_Value (COLUMNNAME_LabelReport_Process_ID, null);
else
set_Value (COLUMNNAME_LabelReport_Process_ID, LabelReport_Process_ID);
}
@Override
public int getLabelReport_Process_ID()
{
return get_ValueAsInt(COLUMNNAME_LabelReport_Process_ID);
}
@Override
public void setM_HU_Label_Config_ID (final int M_HU_Label_Config_ID)
{
if (M_HU_Label_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_Label_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_Label_Config_ID, M_HU_Label_Config_ID);
}
@Override | public int getM_HU_Label_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Label_Config_ID);
}
@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_M_HU_Label_Config.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TaskConfig {
public static final String SIMPLE_TASK = "simple-task";
private final SchedulerFactoryBean schedulerFactoryBean;
/**
* 动态添加任务
* @throws SchedulerException
*/
@PostConstruct
public void init() throws SchedulerException {
Scheduler scheduler = schedulerFactoryBean.getScheduler();
boolean exists = scheduler.checkExists(JobKey.jobKey(SIMPLE_TASK));
if (!exists) {
scheduler.scheduleJob(simpleTask(), simpleTaskTrigger());
}
}
// @Bean
public JobDetail simpleTask() {
return JobBuilder.newJob(SimpleTask.class) | .withIdentity(SIMPLE_TASK)
.withDescription("简单任务")
.storeDurably()
.build();
}
// @Bean
public Trigger simpleTaskTrigger() {
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ? *");
return TriggerBuilder.newTrigger()
.withIdentity("simple-task-trigger")
.forJob(simpleTask())
.withSchedule(cronScheduleBuilder)
.build();
}
} | repos\spring-boot-best-practice-master\spring-boot-quartz\src\main\java\cn\javastack\springboot\quartz\TaskConfig.java | 2 |
请完成以下Java代码 | public String getTableName()
{
return tableName;
}
@Override
public final boolean isEnabled()
{
return enabled;
}
@Override
public void setEnabled(final boolean enabled)
{
this.enabled = enabled;
}
@Override
public TrxLevel getTrxLevel()
{
return this.trxLevel;
}
@Override
public void setTrxLevel(final TrxLevel trxLevel)
{
Check.assumeNotNull(trxLevel, "trxLevel not null");
this.trxLevel = trxLevel;
}
@Override
public CacheMapType getCacheMapType()
{
return cacheMapType;
}
@Override
public void setCacheMapType(CacheMapType cacheMapType)
{
Check.assumeNotNull(cacheMapType, "cacheMapType not null");
this.cacheMapType = cacheMapType;
}
@Override
public int getInitialCapacity()
{
return initialCapacity;
}
@Override
public void setInitialCapacity(int initalCapacity)
{ | Check.assume(initalCapacity > 0, "initialCapacity > 0");
this.initialCapacity = initalCapacity;
}
@Override
public int getMaxCapacity()
{
return maxCapacity;
}
@Override
public void setMaxCapacity(int maxCapacity)
{
this.maxCapacity = maxCapacity;
}
@Override
public int getExpireMinutes()
{
return expireMinutes;
}
@Override
public void setExpireMinutes(int expireMinutes)
{
this.expireMinutes = expireMinutes > 0 ? expireMinutes : EXPIREMINUTES_Never;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\MutableTableCacheConfig.java | 1 |
请完成以下Java代码 | public OtaPackageInfo findById(TenantId tenantId, UUID id) {
return DaoUtil.getData(otaPackageInfoRepository.findOtaPackageInfoById(id));
}
@Transactional
@Override
public OtaPackageInfo save(TenantId tenantId, OtaPackageInfo otaPackageInfo) {
OtaPackageInfo savedOtaPackage = super.save(tenantId, otaPackageInfo);
if (otaPackageInfo.getId() == null) {
return savedOtaPackage;
} else {
return findById(tenantId, savedOtaPackage.getId().getId());
}
}
@Override
public PageData<OtaPackageInfo> findOtaPackageInfoByTenantId(TenantId tenantId, PageLink pageLink) {
return DaoUtil.toPageData(otaPackageInfoRepository
.findAllByTenantId(
tenantId.getId(),
pageLink.getTextSearch(),
DaoUtil.toPageable(pageLink)));
}
@Override
public PageData<OtaPackageInfo> findOtaPackageInfoByTenantIdAndDeviceProfileIdAndTypeAndHasData(TenantId tenantId, DeviceProfileId deviceProfileId, OtaPackageType otaPackageType, PageLink pageLink) { | return DaoUtil.toPageData(otaPackageInfoRepository
.findAllByTenantIdAndTypeAndDeviceProfileIdAndHasData(
tenantId.getId(),
deviceProfileId.getId(),
otaPackageType,
pageLink.getTextSearch(),
DaoUtil.toPageable(pageLink)));
}
@Override
public boolean isOtaPackageUsed(OtaPackageId otaPackageId, OtaPackageType otaPackageType, DeviceProfileId deviceProfileId) {
return otaPackageInfoRepository.isOtaPackageUsed(otaPackageId.getId(), deviceProfileId.getId(), otaPackageType.name());
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\ota\JpaOtaPackageInfoDao.java | 1 |
请完成以下Java代码 | public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
@Override
public String toString() {
return this.getClass().getSimpleName() | + "[id=" + id
+ ", processDefinitionKey=" + processDefinitionKey
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", removalTime=" + removalTime
+ ", processInstanceId=" + processInstanceId
+ ", taskId=" + taskId
+ ", executionId=" + executionId
+ ", tenantId=" + tenantId
+ ", activityInstanceId=" + activityInstanceId
+ ", caseDefinitionKey=" + caseDefinitionKey
+ ", caseDefinitionId=" + caseDefinitionId
+ ", caseInstanceId=" + caseInstanceId
+ ", caseExecutionId=" + caseExecutionId
+ ", name=" + name
+ ", createTime=" + createTime
+ ", revision=" + revision
+ ", serializerName=" + getSerializerName()
+ ", longValue=" + longValue
+ ", doubleValue=" + doubleValue
+ ", textValue=" + textValue
+ ", textValue2=" + textValue2
+ ", state=" + state
+ ", byteArrayId=" + getByteArrayId()
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricVariableInstanceEntity.java | 1 |
请完成以下Java代码 | public ExternalTaskQueryTopicBuilder withoutTenantId() {
currentInstruction.setTenantIds(null);
return this;
}
public ExternalTaskQueryTopicBuilder tenantIdIn(String... tenantIds) {
currentInstruction.setTenantIds(tenantIds);
return this;
}
protected void submitCurrentInstruction() {
if (currentInstruction != null) {
this.instructions.put(currentInstruction.getTopicName(), currentInstruction);
}
}
public ExternalTaskQueryTopicBuilder enableCustomObjectDeserialization() { | currentInstruction.setDeserializeVariables(true);
return this;
}
public ExternalTaskQueryTopicBuilder localVariables() {
currentInstruction.setLocalVariables(true);
return this;
}
public ExternalTaskQueryTopicBuilder includeExtensionProperties() {
currentInstruction.setIncludeExtensionProperties(true);
return this;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\ExternalTaskQueryTopicBuilderImpl.java | 1 |
请完成以下Java代码 | public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
@Override
public int hashCode() { | return Objects.hash(id, name, position, salary);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
return id == other.id && Objects.equals(name, other.name) && Objects.equals(position, other.position) && Double.doubleToLongBits(salary) == Double.doubleToLongBits(other.salary);
}
} | repos\tutorials-master\persistence-modules\core-java-persistence\src\main\java\com\baeldung\spring\jdbc\Employee.java | 1 |
请完成以下Java代码 | public Integer getId() {
return id;
}
public SolrProductDO setId(Integer id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public SolrProductDO setName(String name) {
this.name = name;
return this;
}
public String getDescription() {
return description;
}
public SolrProductDO setDescription(String description) {
this.description = description;
return this;
}
public Integer getCid() {
return cid; | }
public SolrProductDO setCid(Integer cid) {
this.cid = cid;
return this;
}
public String getCategoryName() {
return categoryName;
}
public SolrProductDO setCategoryName(String categoryName) {
this.categoryName = categoryName;
return this;
}
@Override
public String toString() {
return "SolrProductDO{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", cid=" + cid +
", categoryName='" + categoryName + '\'' +
'}';
}
} | repos\SpringBoot-Labs-master\lab-66\lab-66-spring-data-solr\src\main\java\cn\iocoder\springboot\lab15\springdatasolr\dataobject\SolrProductDO.java | 1 |
请完成以下Java代码 | public void setS_ExpenseType_ID (int S_ExpenseType_ID)
{
if (S_ExpenseType_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_ExpenseType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_ExpenseType_ID, Integer.valueOf(S_ExpenseType_ID));
}
/** Get Expense Type.
@return Expense report type
*/
public int getS_ExpenseType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_ExpenseType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Search Key. | @param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_ExpenseType.java | 1 |
请完成以下Java代码 | public static Registration.Builder create(String name, String healthUrl) {
return builder().name(name).healthUrl(healthUrl);
}
public static Registration.Builder copyOf(Registration registration) {
return registration.toBuilder();
}
/**
* Determines the service url. It might be overriden by metadata entries to override
* the service url.
* @param serviceUrl original serviceUrl
* @param metadata metadata information of registered instance
* @return the actual service url
*/
@Nullable
private String getServiceUrl(@Nullable String serviceUrl, Map<String, String> metadata) {
if (serviceUrl == null) {
return null;
}
String url = metadata.getOrDefault("service-url", serviceUrl);
try {
URI baseUri = new URI(url);
return baseUri.toString();
}
catch (URISyntaxException ex) {
log.warn("Invalid service url: " + serviceUrl, ex);
}
return serviceUrl;
}
public Map<String, String> getMetadata() { | return Collections.unmodifiableMap(this.metadata);
}
/**
* Checks the syntax of the given URL.
* @param url the URL.
* @return true, if valid.
*/
private boolean checkUrl(String url) {
try {
URI uri = new URI(url);
return uri.isAbsolute();
}
catch (URISyntaxException ex) {
return false;
}
}
public static class Builder {
// Will be generated by lombok
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\values\Registration.java | 1 |
请完成以下Java代码 | public class HandleTaskBpmnErrorCmd implements Command<Void>, Serializable{
private static final long serialVersionUID = 1L;
protected String taskId;
protected String errorCode;
protected String errorMessage;
protected Map<String, Object> variables;
public HandleTaskBpmnErrorCmd(String taskId, String errorCode) {
this.taskId = taskId;
this.errorCode = errorCode;
}
public HandleTaskBpmnErrorCmd(String taskId, String errorCode, String errorMessage) {
this(taskId, errorCode);
this.errorMessage = errorMessage;
}
public HandleTaskBpmnErrorCmd(String taskId, String errorCode, String errorMessage, Map<String, Object> variables) {
this(taskId, errorCode, errorMessage);
this.variables = variables;
} | protected void validateInput() {
ensureNotEmpty(BadUserRequestException.class,"taskId", taskId);
ensureNotEmpty(BadUserRequestException.class, "errorCode", errorCode);
}
@Override
public Void execute(CommandContext commandContext) {
validateInput();
TaskEntity task = commandContext.getTaskManager().findTaskById(taskId);
ensureNotNull(NotFoundException.class,"Cannot find task with id " + taskId, "task", task);
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkTaskWork(task);
}
task.bpmnError(errorCode, errorMessage, variables);
return null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\HandleTaskBpmnErrorCmd.java | 1 |
请完成以下Java代码 | private String getPrototypeValue(final PropertyDescriptor pd)
{
String prototypeValue = getPrototypeValue(pd.getReadMethod());
if (Check.isEmpty(prototypeValue))
{
prototypeValue = getPrototypeValue(pd.getWriteMethod());
}
return prototypeValue;
}
private String getPrototypeValue(final Method method)
{
if (method == null)
{
return null;
}
final ColumnInfo info = method.getAnnotation(ColumnInfo.class);
if (info == null)
{
return null;
}
final String prototypeValue = info.prototypeValue();
if (Check.isEmpty(prototypeValue, false))
{
return null;
}
return prototypeValue;
}
private int getDisplayType(final PropertyDescriptor pd)
{
int displayType = getDisplayType(pd.getReadMethod());
if (displayType <= 0)
{
displayType = getDisplayType(pd.getWriteMethod());
}
if (displayType <= 0)
{
displayType = suggestDisplayType(pd.getReadMethod().getReturnType());
}
return displayType;
}
private static final int suggestDisplayType(final Class<?> returnType)
{
if (returnType == String.class)
{
return DisplayType.String;
}
else if (returnType == Boolean.class || returnType == boolean.class)
{
return DisplayType.YesNo;
}
else if (returnType == BigDecimal.class)
{
return DisplayType.Amount;
}
else if (returnType == Integer.class)
{ | return DisplayType.Integer;
}
else if (Date.class.isAssignableFrom(returnType))
{
return DisplayType.Date;
}
else
{
return -1;
}
}
private int getDisplayType(final Method method)
{
if (method == null)
{
return -1;
}
final ColumnInfo info = method.getAnnotation(ColumnInfo.class);
if (info == null)
{
return -1;
}
final int displayType = info.displayType();
return displayType > 0 ? displayType : -1;
}
private boolean isSelectionColumn(final PropertyDescriptor pd)
{
Boolean selectionColumn = getSelectionColumn(pd.getReadMethod());
if (selectionColumn == null)
{
selectionColumn = getSelectionColumn(pd.getWriteMethod());
}
return selectionColumn != null ? selectionColumn : false;
}
private Boolean getSelectionColumn(final Method method)
{
if (method == null)
{
return null;
}
final ColumnInfo info = method.getAnnotation(ColumnInfo.class);
if (info == null)
{
return null;
}
return info.selectionColumn();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\TableModelMetaInfo.java | 1 |
请完成以下Java代码 | public class UriElementReferenceCollectionImpl<Target extends ModelElementInstance, Source extends ModelElementInstance> extends ElementReferenceCollectionImpl<Target, Source> {
public UriElementReferenceCollectionImpl(ChildElementCollection<Source> referenceSourceCollection) {
super(referenceSourceCollection);
}
@Override
public String getReferenceIdentifier(ModelElementInstance referenceSourceElement) {
// TODO: implement something more robust (CAM-4028)
String identifier = referenceSourceElement.getAttributeValue("href");
if (identifier != null) {
String[] parts = identifier.split("#");
if (parts.length > 1) {
return parts[parts.length - 1];
} | else {
return parts[0];
}
}
else {
return null;
}
}
@Override
protected void setReferenceIdentifier(ModelElementInstance referenceSourceElement, String referenceIdentifier) {
// TODO: implement something more robust (CAM-4028)
referenceSourceElement.setAttributeValue("href", "#" + referenceIdentifier);
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\reference\UriElementReferenceCollectionImpl.java | 1 |
请完成以下Java代码 | public void setModal (boolean Modal)
{
set_Value (COLUMNNAME_Modal, Boolean.valueOf(Modal));
}
/** Get Is Modal.
@return Is Modal */
@Override
public boolean isModal ()
{
Object oo = get_Value(COLUMNNAME_Modal);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
} | /** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Form.java | 1 |
请完成以下Java代码 | private static URI extractIPPUrl(final @NonNull I_AD_PrinterHW printerRecord)
{
final String ippUrl = StringUtils.trimBlankToNull(printerRecord.getIPP_URL());
if (ippUrl == null)
{
return null;
}
return URI.create(ippUrl);
}
@NonNull
private static HardwareTray fromRecord(@NonNull final I_AD_PrinterHW_MediaTray trayRecord)
{
final HardwareTrayId trayId = HardwareTrayId.ofRepoId(trayRecord.getAD_PrinterHW_ID(), trayRecord.getAD_PrinterHW_MediaTray_ID());
return new HardwareTray(trayId, trayRecord.getName(), trayRecord.getTrayNumber());
}
public void deleteCalibrations(@NonNull final HardwarePrinterId printerId) {printingDAO.deleteCalibrations(printerId);}
public void deleteMediaTrays(@NonNull final HardwarePrinterId hardwarePrinterId) {printingDAO.deleteMediaTrays(hardwarePrinterId);}
public void deleteMediaSizes(@NonNull final HardwarePrinterId hardwarePrinterId) {printingDAO.deleteMediaSizes(hardwarePrinterId);}
//
//
//
//
//
private static class HardwarePrinterMap
{
private final ImmutableMap<HardwarePrinterId, HardwarePrinter> byId;
private HardwarePrinterMap(final List<HardwarePrinter> list)
{
this.byId = Maps.uniqueIndex(list, HardwarePrinter::getId);
} | public HardwarePrinter getById(@NonNull final HardwarePrinterId id)
{
final HardwarePrinter hardwarePrinter = byId.get(id);
if (hardwarePrinter == null)
{
throw new AdempiereException("No active hardware printer found for id " + id);
}
return hardwarePrinter;
}
public Collection<HardwarePrinter> getByIds(final @NonNull Collection<HardwarePrinterId> ids)
{
return streamByIds(ids).collect(ImmutableList.toImmutableList());
}
public Stream<HardwarePrinter> streamByIds(final @NonNull Collection<HardwarePrinterId> ids)
{
if (ids.isEmpty())
{
return Stream.empty();
}
return ids.stream()
.map(byId::get)
.filter(Objects::nonNull);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\HardwarePrinterRepository.java | 1 |
请完成以下Java代码 | public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return Mono.just(exchange)
.filter(this::isInsecure)
.flatMap(this.requiresHttpsRedirectMatcher::matches)
.filter((matchResult) -> matchResult.isMatch())
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.map((matchResult) -> createRedirectUri(exchange))
.flatMap((uri) -> this.redirectStrategy.sendRedirect(exchange, uri));
}
/**
* Use this {@link PortMapper} for mapping custom ports
* @param portMapper the {@link PortMapper} to use
*/
public void setPortMapper(PortMapper portMapper) {
Assert.notNull(portMapper, "portMapper cannot be null");
this.portMapper = portMapper;
}
/**
* Use this {@link ServerWebExchangeMatcher} to narrow which requests are redirected
* to HTTPS.
*
* The filter already first checks for HTTPS in the uri scheme, so it is not necessary
* to include that check in this matcher.
* @param requiresHttpsRedirectMatcher the {@link ServerWebExchangeMatcher} to use | */
public void setRequiresHttpsRedirectMatcher(ServerWebExchangeMatcher requiresHttpsRedirectMatcher) {
Assert.notNull(requiresHttpsRedirectMatcher, "requiresHttpsRedirectMatcher cannot be null");
this.requiresHttpsRedirectMatcher = requiresHttpsRedirectMatcher;
}
private boolean isInsecure(ServerWebExchange exchange) {
return !"https".equals(exchange.getRequest().getURI().getScheme());
}
private URI createRedirectUri(ServerWebExchange exchange) {
int port = exchange.getRequest().getURI().getPort();
UriComponentsBuilder builder = UriComponentsBuilder.fromUri(exchange.getRequest().getURI());
if (port > 0) {
Integer httpsPort = this.portMapper.lookupHttpsPort(port);
Assert.state(httpsPort != null, () -> "HTTP Port '" + port + "' does not have a corresponding HTTPS Port");
builder.port(httpsPort);
}
return builder.scheme("https").build().toUri();
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\transport\HttpsRedirectWebFilter.java | 1 |
请完成以下Java代码 | public Object get(Object key) {
if ((key == null) || (!String.class.isAssignableFrom(key.getClass()))) {
return null;
}
return beanFactory.getBean((String) key);
}
public boolean containsKey(Object key) {
if ((key == null) || (!String.class.isAssignableFrom(key.getClass()))) {
return false;
}
return beanFactory.containsBean((String) key);
}
public Set<Object> keySet() {
throw new ActivitiException("unsupported operation on configuration beans");
// List<String> beanNames =
// asList(beanFactory.getBeanDefinitionNames());
// return new HashSet<Object>(beanNames);
}
public void clear() {
throw new ActivitiException("can't clear configuration beans");
}
public boolean containsValue(Object value) {
throw new ActivitiException("can't search values in configuration beans");
}
public Set<Map.Entry<Object, Object>> entrySet() {
throw new ActivitiException("unsupported operation on configuration beans");
}
public boolean isEmpty() { | throw new ActivitiException("unsupported operation on configuration beans");
}
public Object put(Object key, Object value) {
throw new ActivitiException("unsupported operation on configuration beans");
}
public void putAll(Map<? extends Object, ? extends Object> m) {
throw new ActivitiException("unsupported operation on configuration beans");
}
public Object remove(Object key) {
throw new ActivitiException("unsupported operation on configuration beans");
}
public int size() {
throw new ActivitiException("unsupported operation on configuration beans");
}
public Collection<Object> values() {
throw new ActivitiException("unsupported operation on configuration beans");
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\SpringBeanFactoryProxyMap.java | 1 |
请完成以下Java代码 | public boolean isAllowNullValues() {
return allowNullValues;
}
public String getDefaultSpec() {
return defaultSpec;
}
public void setAllowNullValues(boolean allowNullValues) {
this.allowNullValues = allowNullValues;
}
public void setDefaultSpec(String defaultSpec) {
this.defaultSpec = defaultSpec;
}
public boolean isUseSystemScheduler() {
return useSystemScheduler;
}
public void setUseSystemScheduler(boolean useSystemScheduler) {
this.useSystemScheduler = useSystemScheduler;
} | }
public static class SimpleCacheProviderProperties {
private boolean allowNullValues = true;
public boolean isAllowNullValues() {
return allowNullValues;
}
public void setAllowNullValues(boolean allowNullValues) {
this.allowNullValues = allowNullValues;
}
}
} | repos\Activiti-develop\activiti-core-common\activiti-spring-cache-manager\src\main\java\org\activiti\spring\cache\ActivitiSpringCacheManagerProperties.java | 1 |
请完成以下Java代码 | public class PrincipalNameIndexResolver<S extends Session> extends SingleIndexResolver<S> {
private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT";
private static final Expression expression = new SpelExpressionParser().parseExpression("authentication?.name");
public PrincipalNameIndexResolver() {
super(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
}
/**
* Create a new instance specifying the name of the index to be resolved.
* @param indexName the name of the index to be resolved
* @since 3.3
*/
public PrincipalNameIndexResolver(String indexName) { | super(indexName);
}
public String resolveIndexValueFor(S session) {
String principalName = session.getAttribute(getIndexName());
if (principalName != null) {
return principalName;
}
Object authentication = session.getAttribute(SPRING_SECURITY_CONTEXT);
if (authentication != null) {
return expression.getValue(authentication, String.class);
}
return null;
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\PrincipalNameIndexResolver.java | 1 |
请完成以下Java代码 | public IHUAssignmentBuilder setTemplateForNewRecord(final I_M_HU_Assignment assignmentRecord)
{
this.assignment = newInstance(I_M_HU_Assignment.class);
return updateFromRecord(assignmentRecord);
}
@Override
public IHUAssignmentBuilder setAssignmentRecordToUpdate(@NonNull final I_M_HU_Assignment assignmentRecord)
{
this.assignment = assignmentRecord;
return updateFromRecord(assignmentRecord);
}
private IHUAssignmentBuilder updateFromRecord(final I_M_HU_Assignment assignmentRecord)
{
setTopLevelHU(assignmentRecord.getM_HU());
setM_LU_HU(assignmentRecord.getM_LU_HU());
setM_TU_HU(assignmentRecord.getM_TU_HU());
setVHU(assignmentRecord.getVHU());
setQty(assignmentRecord.getQty());
setIsTransferPackingMaterials(assignmentRecord.isTransferPackingMaterials());
setIsActive(assignmentRecord.isActive());
return this;
} | @Override
public I_M_HU_Assignment build()
{
Check.assumeNotNull(model, "model not null");
Check.assumeNotNull(topLevelHU, "topLevelHU not null");
Check.assumeNotNull(assignment, "assignment not null");
TableRecordCacheLocal.setReferencedValue(assignment, model);
assignment.setM_HU(topLevelHU);
assignment.setM_LU_HU(luHU);
assignment.setM_TU_HU(tuHU);
assignment.setVHU(vhu);
assignment.setQty(qty);
assignment.setIsTransferPackingMaterials(isTransferPackingMaterials);
assignment.setIsActive(isActive);
InterfaceWrapperHelper.save(assignment);
return assignment;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAssignmentBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<EntityRelationInfo> findInfoByQuery(@Parameter(description = "A JSON value representing the entity relations query object.", required = true)
@RequestBody EntityRelationsQuery query) throws ThingsboardException, ExecutionException, InterruptedException {
checkNotNull(query.getParameters());
checkNotNull(query.getFilters());
checkEntityId(query.getParameters().getEntityId(), Operation.READ);
return checkNotNull(filterRelationsByReadPermission(relationService.findInfoByQuery(getTenantId(), query).get()));
}
private void checkCanCreateRelation(EntityId entityId) throws ThingsboardException {
SecurityUser currentUser = getCurrentUser();
var isTenantAdminAndRelateToSelf = currentUser.isTenantAdmin() && currentUser.getTenantId().equals(entityId);
if (!isTenantAdminAndRelateToSelf) {
checkEntityId(entityId, Operation.WRITE);
}
}
private <T extends EntityRelation> List<T> filterRelationsByReadPermission(List<T> relationsByQuery) {
return relationsByQuery.stream().filter(relationByQuery -> {
try {
checkEntityId(relationByQuery.getTo(), Operation.READ);
} catch (ThingsboardException e) {
return false;
}
try {
checkEntityId(relationByQuery.getFrom(), Operation.READ);
} catch (ThingsboardException e) {
return false; | }
return true;
}).toList();
}
private static RelationTypeGroup parseRelationTypeGroup(String strRelationTypeGroup, RelationTypeGroup defaultValue) {
if (StringUtils.isBlank(strRelationTypeGroup)) {
return defaultValue;
}
try {
return RelationTypeGroup.valueOf(strRelationTypeGroup);
} catch (IllegalArgumentException e) {
return defaultValue;
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\EntityRelationController.java | 2 |
请完成以下Java代码 | public class User implements Serializable {
private static final long serialVersionUID = -1840831686851699943L;
/**
* 主键
*/
private Long id;
/**
* 用户名
*/
private String name;
/**
* 加密后的密码
*/
private String password;
/**
* 加密使用的盐
*/
private String salt;
/**
* 邮箱
*/
private String email;
/**
* 手机号码
*/
private String phoneNumber; | /**
* 状态,-1:逻辑删除,0:禁用,1:启用
*/
private Integer status;
/**
* 创建时间
*/
private Date createTime;
/**
* 上次登录时间
*/
private Date lastLoginTime;
/**
* 上次更新时间
*/
private Date lastUpdateTime;
} | repos\spring-boot-demo-master\demo-orm-beetlsql\src\main\java\com\xkcoding\orm\beetlsql\entity\User.java | 1 |
请完成以下Java代码 | public EncryptionPropertiesType getEncryptionProperties() {
return encryptionProperties;
}
/**
* Sets the value of the encryptionProperties property.
*
* @param value
* allowed object is
* {@link EncryptionPropertiesType }
*
*/
public void setEncryptionProperties(EncryptionPropertiesType value) {
this.encryptionProperties = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/ | public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the mimeType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMimeType() {
return mimeType;
}
/**
* Sets the value of the mimeType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMimeType(String value) {
this.mimeType = value;
}
/**
* Gets the value of the encoding property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEncoding() {
return encoding;
}
/**
* Sets the value of the encoding property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEncoding(String value) {
this.encoding = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\EncryptedType.java | 1 |
请完成以下Java代码 | public static ServerWebExchangeMatcher pathMatchers(PathPattern... pathPatterns) {
return pathMatchers(null, pathPatterns);
}
/**
* Creates a matcher that matches on the specific method and any of the provided
* {@link PathPattern}s.
* @param method the method to match on. If null, any method will be matched.
* @param pathPatterns the {@link PathPattern}s to match on
* @return the matcher to use
*/
public static ServerWebExchangeMatcher pathMatchers(@Nullable HttpMethod method, PathPattern... pathPatterns) {
List<ServerWebExchangeMatcher> matchers = new ArrayList<>(pathPatterns.length);
for (PathPattern pathPattern : pathPatterns) {
matchers.add(new PathPatternParserServerWebExchangeMatcher(pathPattern, method));
}
return new OrServerWebExchangeMatcher(matchers);
}
/**
* Creates a matcher that will match on any of the provided matchers
* @param matchers the matchers to match on
* @return the matcher to use
*/
public static ServerWebExchangeMatcher matchers(ServerWebExchangeMatcher... matchers) {
return new OrServerWebExchangeMatcher(matchers);
}
/**
* Matches any exchange
* @return the matcher to use | */
@SuppressWarnings("Convert2Lambda")
public static ServerWebExchangeMatcher anyExchange() {
// we don't use a lambda to ensure a unique equals and hashcode
// which otherwise can cause problems with adding multiple entries to an ordered
// LinkedHashMap
return new ServerWebExchangeMatcher() {
@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) {
return ServerWebExchangeMatcher.MatchResult.match();
}
};
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\util\matcher\ServerWebExchangeMatchers.java | 1 |
请完成以下Java代码 | public Idm getIdm() {
return idm;
}
public void setIdm(Idm idm) {
this.idm = idm;
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
}
public class Idm {
private String url;
private String user;
private String password;
private String description;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
} | }
public class Service {
private String url;
private String token;
private String description;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-properties\src\main\java\com\baeldung\yaml\YAMLConfig.java | 1 |
请完成以下Java代码 | public void logPointcut() {
// 该方法无方法体,主要为了让同类中其他方法使用此切入点
}
/**
* 配置环绕通知,使用在方法logPointcut()上注册的切入点
*
* @param joinPoint join point for advice
*/
@Around("logPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object result;
currentTime.set(System.currentTimeMillis());
result = joinPoint.proceed();
SysLog sysLog = new SysLog("INFO",System.currentTimeMillis() - currentTime.get());
currentTime.remove();
HttpServletRequest request = RequestHolder.getHttpServletRequest();
sysLogService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request),joinPoint, sysLog);
return result;
}
/**
* 配置异常通知
*
* @param joinPoint join point for advice
* @param e exception
*/
@AfterThrowing(pointcut = "logPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
SysLog sysLog = new SysLog("ERROR",System.currentTimeMillis() - currentTime.get()); | currentTime.remove();
sysLog.setExceptionDetail(ThrowableUtil.getStackTrace(e).getBytes());
HttpServletRequest request = RequestHolder.getHttpServletRequest();
sysLogService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), (ProceedingJoinPoint)joinPoint, sysLog);
}
/**
* 获取用户名
* @return /
*/
public String getUsername() {
try {
return SecurityUtils.getCurrentUsername();
}catch (Exception e){
return "";
}
}
} | repos\eladmin-master\eladmin-logging\src\main\java\me\zhengjie\aspect\LogAspect.java | 1 |
请完成以下Java代码 | public void markCriteriaChanged() {
criteriaChanged = true;
}
public int getActiveChildren() {
return activeChildren;
}
public boolean isCriteriaChanged() {
return criteriaChanged;
}
public boolean hasNewChildPlanItemInstances() {
return newChildPlanItemInstances != null && newChildPlanItemInstances.size() > 0;
}
public List<PlanItemInstanceEntity> getNewChildPlanItemInstances() {
return newChildPlanItemInstances;
}
public boolean criteriaChangedOrNewActiveChildren() {
return criteriaChanged || activeChildren > 0;
}
public List<PlanItemInstanceEntity> getAllChildPlanItemInstances() {
return allChildPlanItemInstances; | }
/**
* Returns true, if the given plan item instance has at least one instance in completed state (only possible of course for repetition based plan items).
*
* @param planItemInstance the plan item instance to check for a completed instance of the same plan item
* @return true, if a completed instance was found, false otherwise
*/
public boolean hasCompletedPlanItemInstance(PlanItemInstanceEntity planItemInstance) {
if (allChildPlanItemInstances == null || allChildPlanItemInstances.size() == 0) {
return false;
}
for (PlanItemInstanceEntity childPlanItemInstance : allChildPlanItemInstances) {
if (childPlanItemInstance.getPlanItemDefinitionId().equals(planItemInstance.getPlanItemDefinitionId()) && PlanItemInstanceState.COMPLETED
.equals(childPlanItemInstance.getState())) {
return true;
}
}
return false;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\PlanItemEvaluationResult.java | 1 |
请完成以下Java代码 | protected String doIt()
{
final ImmutableSet<ShipmentScheduleId> shipmentScheduleIds = getSelectedShipmentScheduleIds();
if (shipmentScheduleIds.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
final ViewId viewId = viewsFactory.createView(CreateViewRequest.builder(ShipmentCandidatesViewFactory.WINDOWID)
.setFilterOnlyIds(ShipmentScheduleId.toIntSet(shipmentScheduleIds))
.build())
.getViewId();
getResult().setWebuiViewToOpen(WebuiViewToOpen.builder()
.viewId(viewId.getViewId())
.target(ViewOpenTarget.ModalOverlay)
.build());
return MSG_OK;
}
private ImmutableSet<ShipmentScheduleId> getSelectedShipmentScheduleIds()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isEmpty()) | {
return ImmutableSet.of();
}
else if (selectedRowIds.isAll())
{
return getView().streamByIds(DocumentIdsSelection.ALL)
.map(IViewRow::getId)
.map(rowId -> ShipmentScheduleId.ofRepoId(rowId.toInt()))
.collect(ImmutableSet.toImmutableSet());
}
else
{
return selectedRowIds
.stream()
.map(rowId -> ShipmentScheduleId.ofRepoId(rowId.toInt()))
.collect(ImmutableSet.toImmutableSet());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\shipment_candidates_editor\process\ShipmentCandidatesView_Launcher.java | 1 |
请完成以下Java代码 | public Builder setCurrencyISOCode(final CurrencyCode currencyISOCode)
{
this.currencyISOCode = currencyISOCode;
return this;
}
public Builder setGrandTotal(final BigDecimal grandTotal)
{
this.grandTotal = grandTotal;
return this;
}
public Builder setGrandTotalConv(final BigDecimal grandTotalConv)
{
this.grandTotalConv = grandTotalConv;
return this;
}
public Builder setOpenAmtConv(final BigDecimal openAmtConv)
{
this.openAmtConv = openAmtConv;
return this;
}
public Builder setDiscount(final BigDecimal discount)
{
this.discount = discount;
return this;
}
public Builder setPaymentRequestAmt(final BigDecimal paymentRequestAmt)
{
Check.assumeNotNull(paymentRequestAmt, "paymentRequestAmt not null");
this.paymentRequestAmtSupplier = Suppliers.ofInstance(paymentRequestAmt);
return this;
}
public Builder setPaymentRequestAmt(final Supplier<BigDecimal> paymentRequestAmtSupplier)
{
this.paymentRequestAmtSupplier = paymentRequestAmtSupplier;
return this; | }
public Builder setMultiplierAP(final BigDecimal multiplierAP)
{
this.multiplierAP = multiplierAP;
return this;
}
public Builder setIsPrepayOrder(final boolean isPrepayOrder)
{
this.isPrepayOrder = isPrepayOrder;
return this;
}
public Builder setPOReference(final String POReference)
{
this.POReference = POReference;
return this;
}
public Builder setCreditMemo(final boolean creditMemo)
{
this.creditMemo = creditMemo;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceRow.java | 1 |
请完成以下Java代码 | public void setContractStatus (final @Nullable java.lang.String ContractStatus)
{
set_Value (COLUMNNAME_ContractStatus, ContractStatus);
}
@Override
public java.lang.String getContractStatus()
{
return get_ValueAsString(COLUMNNAME_ContractStatus);
}
@Override
public void setDeadLine (final int DeadLine)
{
set_Value (COLUMNNAME_DeadLine, DeadLine);
}
@Override
public int getDeadLine()
{
return get_ValueAsInt(COLUMNNAME_DeadLine);
}
/**
* DeadLineUnit AD_Reference_ID=540281
* Reference name: TermDurationUnit
*/
public static final int DEADLINEUNIT_AD_Reference_ID=540281;
/** Monat(e) = month */
public static final String DEADLINEUNIT_MonatE = "month";
/** Woche(n) = week */
public static final String DEADLINEUNIT_WocheN = "week";
/** Tag(e) = day */
public static final String DEADLINEUNIT_TagE = "day";
/** Jahr(e) = year */
public static final String DEADLINEUNIT_JahrE = "year";
@Override
public void setDeadLineUnit (final java.lang.String DeadLineUnit)
{
set_Value (COLUMNNAME_DeadLineUnit, DeadLineUnit);
}
@Override
public java.lang.String getDeadLineUnit()
{
return get_ValueAsString(COLUMNNAME_DeadLineUnit);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{ | set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setM_PricingSystem_ID (final int M_PricingSystem_ID)
{
if (M_PricingSystem_ID < 1)
set_Value (COLUMNNAME_M_PricingSystem_ID, null);
else
set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID);
}
@Override
public int getM_PricingSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID);
}
@Override
public void setM_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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Contract_Change.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!getPaymentRowsSelectedForAllocation().isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("No payments shall be selected");
}
return creatPlan()
.resolve(plan -> ProcessPreconditionsResolution.accept().deriveWithCaptionOverride(computeCaption(plan)),
ProcessPreconditionsResolution::rejectWithInternalReason);
}
private ExplainedOptional<Plan> creatPlan()
{
return createPlan(getInvoiceRowsSelectedForAllocation(), action);
}
private static ITranslatableString computeCaption(@NonNull final Plan plan)
{
return TranslatableStrings.builder()
.appendADElement(plan.getAction().getColumnName()).append(": ").append(plan.getAmountToDiscountOrWriteOff())
.build();
}
@Override
protected String doIt()
{
final Plan plan = creatPlan().orElseThrow();
final I_C_Invoice invoice = invoiceBL.getById(plan.getInvoiceId());
final InvoiceAmtMultiplier amtMultiplier = plan.getAmtMultiplier();
final Money amountToDiscountOrWriteOff = amtMultiplier.convertToRealValue(plan.getAmountToDiscountOrWriteOff())
.toMoney(moneyService::getCurrencyIdByCurrencyCode);
allocationBL.invoiceDiscountAndWriteOff(
IAllocationBL.InvoiceDiscountAndWriteOffRequest.builder()
.invoice(invoice)
.dateTrx(TimeUtil.asInstant(p_DateTrx))
.discountAmt(plan.getAction() == PlanAction.Discount ? amountToDiscountOrWriteOff : null)
.writeOffAmt(plan.getAction() == PlanAction.WriteOff ? amountToDiscountOrWriteOff : null)
.build());
return MSG_OK;
}
//
//
//
private static ExplainedOptional<Plan> createPlan(@NonNull final ImmutableList<InvoiceRow> invoiceRows, final PlanAction action)
{
if (invoiceRows.size() != 1)
{
return ExplainedOptional.emptyBecause("Only one invoice row can be selected");
}
final InvoiceRow invoiceRow = CollectionUtils.singleElement(invoiceRows);
if (invoiceRow.getDocBaseType().isCreditMemo())
{
return ExplainedOptional.emptyBecause("Credit Memos are not eligible");
}
final Amount openAmt = invoiceRow.getOpenAmt();
if (openAmt.signum() == 0)
{
return ExplainedOptional.emptyBecause("Zero open amount"); | }
return ExplainedOptional.of(
Plan.builder()
.invoiceId(invoiceRow.getInvoiceId())
.action(action)
.amtMultiplier(invoiceRow.getInvoiceAmtMultiplier())
.amountToDiscountOrWriteOff(openAmt)
.build());
}
@AllArgsConstructor
enum PlanAction
{
Discount("DiscountAmt"),
WriteOff("WriteOffAmt"),
;
// used mainly to build the action caption
@Getter
private final String columnName;
}
@Value
@Builder
private static class Plan
{
@NonNull InvoiceId invoiceId;
@NonNull PlanAction action;
@NonNull InvoiceAmtMultiplier amtMultiplier;
@NonNull Amount amountToDiscountOrWriteOff;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentsView_InvoiceDiscountOrWriteOff.java | 1 |
请完成以下Java代码 | public Stream<CostDetailCreateResult> stream() {return list.stream();}
public CostDetailCreateResult getSingleResult() {return CollectionUtils.singleElement(list);}
public Optional<CostAmountAndQty> getAmtAndQtyToPost(@NonNull final CostAmountType type, @NonNull AcctSchema as)
{
return list.stream()
.filter(result -> isAccountable(result, as))
.map(result -> result.getAmtAndQty(type))
.reduce(CostAmountAndQty::add);
}
public CostAmount getMainAmountToPost(@NonNull final AcctSchema as)
{
return getAmtAndQtyToPost(CostAmountType.MAIN, as)
.map(CostAmountAndQty::getAmt)
.orElseThrow(() -> new NoSuchElementException("No value present"));
}
public CostAmountDetailed getTotalAmountToPost(@NonNull final AcctSchema as)
{
return toAggregatedCostAmount().getTotalAmountToPost(as); | }
public AggregatedCostAmount toAggregatedCostAmount()
{
final CostSegment costSegment = CollectionUtils.extractSingleElement(list, CostDetailCreateResult::getCostSegment);
final Map<CostElement, CostAmountDetailed> amountsByCostElement = list.stream()
.collect(Collectors.toMap(
CostDetailCreateResult::getCostElement, // keyMapper
CostDetailCreateResult::getAmt, // valueMapper
CostAmountDetailed::add)); // mergeFunction
return AggregatedCostAmount.builder()
.costSegment(costSegment)
.amounts(amountsByCostElement)
.build();
}
private static boolean isAccountable(@NonNull CostDetailCreateResult result, @NonNull final AcctSchema as)
{
return result.getCostElement().isAccountable(as.getCosting());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostDetailCreateResultsList.java | 1 |
请完成以下Java代码 | public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getResourceCode() {
return resourceCode;
}
public Long getSuccessQps() {
return successQps;
}
public void setSuccessQps(Long successQps) {
this.successQps = successQps;
}
@Override
public String toString() {
return "MetricEntity{" +
"id=" + id + | ", gmtCreate=" + gmtCreate +
", gmtModified=" + gmtModified +
", app='" + app + '\'' +
", timestamp=" + timestamp +
", resource='" + resource + '\'' +
", passQps=" + passQps +
", blockQps=" + blockQps +
", successQps=" + successQps +
", exceptionQps=" + exceptionQps +
", rt=" + rt +
", count=" + count +
", resourceCode=" + resourceCode +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MetricEntity.java | 1 |
请完成以下Java代码 | public @Nullable Object getReturnValue() {
return this.returnValue;
}
public @Nullable Expression getSendTo() {
return this.sendTo;
}
@Nullable
public Type getReturnType() {
return this.returnType;
}
@Nullable
public Object getBean() {
return this.bean;
} | @Nullable
public Method getMethod() {
return this.method;
}
@Override
public String toString() {
return "InvocationResult [returnValue=" + this.returnValue
+ (this.sendTo != null ? ", sendTo=" + this.sendTo : "")
+ ", returnType=" + this.returnType
+ ", bean=" + this.bean
+ ", method=" + this.method
+ "]";
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\adapter\InvocationResult.java | 1 |
请完成以下Java代码 | public class Motorcycle extends Vehicle implements Serializable {
private static final long serialVersionUID = 5973661295933599929L;
private int year;
private String features = "";
public Motorcycle() {
super();
}
public Motorcycle(String make, String model, String color, int weight, boolean statusNew, int year) {
super(make, model, color, weight, statusNew);
this.year = year;
}
public Motorcycle(Vehicle vehicle, int year) {
super(vehicle);
this.year = year;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public void setFeatures(String features) {
this.features = features; | }
public String getFeatures() {
return features;
}
public void addMotorcycleFeatures(String... features) {
StringBuilder str = new StringBuilder(this.getFeatures());
for (String feature : features) {
if (!str.toString().isEmpty())
str.append(", ");
str.append(feature);
}
this.setFeatures(str.toString());
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-methods-2\src\main\java\com\baeldung\methods\Motorcycle.java | 1 |
请完成以下Java代码 | public class X_RV_PP_WIP extends PO implements I_RV_PP_WIP, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20090915L;
/** Standard Constructor */
public X_RV_PP_WIP (Properties ctx, int RV_PP_WIP_ID, String trxName)
{
super (ctx, RV_PP_WIP_ID, trxName);
/** if (RV_PP_WIP_ID == 0)
{
} */
}
/** Load Constructor */
public X_RV_PP_WIP (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 3 - Client - Org
*/
protected int get_AccessLevel()
{
return accessLevel.intValue(); | }
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_RV_PP_WIP[")
.append(get_ID()).append("]");
return sb.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_RV_PP_WIP.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PickingSlotId implements RepoIdAware
{
public static PickingSlotId ofRepoId(final int repoId)
{
return new PickingSlotId(repoId);
}
@JsonCreator
public static PickingSlotId ofObject(@NonNull final Object obj)
{
return RepoIdAwares.ofObject(obj, PickingSlotId.class, PickingSlotId::ofRepoId);
}
@Nullable
public static PickingSlotId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new PickingSlotId(repoId) : null;
}
public static Optional<PickingSlotId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final PickingSlotId pickingSlotId)
{ | return pickingSlotId != null ? pickingSlotId.getRepoId() : -1;
}
int repoId;
private PickingSlotId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_PickingSlot_ID");
}
public static boolean equals(final PickingSlotId o1, final PickingSlotId o2)
{
return Objects.equals(o1, o2);
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\picking\api\PickingSlotId.java | 2 |
请完成以下Java代码 | private ImmutableList<JsonOLCandCreateRequestBuilder> insertServicesIntoBuilder(
@NonNull final JsonOLCandCreateRequest invoiceRecipient,
@NonNull final ServicesType services,
@NonNull final HighLevelContext context)
{
final ImmutableList.Builder<JsonOLCandCreateRequestBuilder> result = ImmutableList.builder();
final List<Object> records = services.getRecordTarmedOrRecordDrgOrRecordLab();
for (final Object record : records)
{
result.addAll(XmlServiceRecordUtil.insertServiceRecordIntoBuilder(invoiceRecipient, record, context));
}
return result.build();
} | private String createExternalHeaderId(@NonNull final JsonOLCandCreateRequestBuilder requestBuilder)
{
final JsonOLCandCreateRequest request = requestBuilder.build();
final String poReference = assumeNotEmpty(request.getPoReference(), "request.poReference may not be empty; request={}", request);
final JsonExternalId billerExternalId = assumeNotNull(request.getOrg().getBpartner().getBpartner().getExternalId(), "request.org.bpartner.bpartner.externalId may not be null; request={}", request);
final JsonExternalId billRecipientExternalId = assumeNotNull(request.getBpartner().getBpartner().getExternalId(), "request.bpartner.bpartner.externalId may not be null; request={}", request);
return poReference // probably the "diversest" property
+ "_"
+ billerExternalId.getValue() // biller, might be the same for different bill receivers
+ "_"
+ billRecipientExternalId.getValue(); // bill receiver, might be the same for different billers
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_rest-api\src\main\java\de\metas\vertical\healthcare\forum_datenaustausch_ch\rest\xml_to_olcands\XmlToOLCandsService.java | 1 |
请完成以下Java代码 | public ImmutableList<HUDescriptor> createHuDescriptors(@NonNull final I_M_HU huRecord)
{
return createHuDescriptors(huRecord, false);
}
public ImmutableList<HUDescriptor> createHuDescriptors(
@NonNull final I_M_HU huRecord,
final boolean deleted)
{
final IMutableHUContext huContext = huContextFactory.createMutableHUContext();
final IHUStorage storage = huContext.getHUStorageFactory().getStorage(huRecord);
// Important note: we could have the AttributesKey without making an ASI, but we need the ASI-ID for display reasons in the material dispo window.
final IPair<AttributesKey, AttributeSetInstanceId> attributesKeyAndAsiId = createAttributesKeyAndAsiId(huContext, huRecord);
final AttributesKey attributesKey = attributesKeyAndAsiId.getLeft();
final AttributeSetInstanceId asiId = attributesKeyAndAsiId.getRight();
final ImmutableList.Builder<HUDescriptor> descriptors = ImmutableList.builder();
for (final IHUProductStorage productStorage : storage.getProductStorages())
{
final ProductDescriptor productDescriptor = ProductDescriptor.forProductAndAttributes(
productStorage.getProductId().getRepoId(),
attributesKey,
asiId.getRepoId());
final BigDecimal quantity = productStorage.getQtyInStockingUOM()
.toBigDecimal()
.max(BigDecimal.ZERO); // guard against the quantity being e.g. -0.001 for whatever reason
final HUDescriptor descriptor = HUDescriptor.builder()
.huId(huRecord.getM_HU_ID())
.productDescriptor(productDescriptor)
.quantity(deleted ? BigDecimal.ZERO : quantity)
.build();
descriptors.add(descriptor);
}
return descriptors.build(); | }
private IPair<AttributesKey, AttributeSetInstanceId> createAttributesKeyAndAsiId(
@NonNull final IHUContext huContext,
@NonNull final I_M_HU hu)
{
final IAttributeSet attributeStorage = huContext.getHUAttributeStorageFactory().getAttributeStorage(hu);
// we don't want all the non-storage-relevant attributes to pollute the ASI we will display in the material disposition window
final IAttributeSet storageRelevantSubSet = ImmutableAttributeSet.createSubSet(attributeStorage, I_M_Attribute::isStorageRelevant);
final I_M_AttributeSetInstance asi = attributeSetInstanceBL.createASIFromAttributeSet(storageRelevantSubSet);
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(asi.getM_AttributeSetInstance_ID());
final AttributesKey attributesKey = AttributesKeys
.createAttributesKeyFromASIStorageAttributes(asiId)
.orElse(AttributesKey.NONE);
return ImmutablePair.of(attributesKey, asiId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\transactionevent\HUDescriptorService.java | 1 |
请完成以下Java代码 | private I_C_DocType getOldDocType()
{
if (_oldDocType == null)
{
final int oldDocTypeId = _oldDocType_ID;
if (oldDocTypeId > 0)
{
_oldDocType = InterfaceWrapperHelper.create(getCtx(), oldDocTypeId, I_C_DocType.class, ITrx.TRXNAME_None);
}
}
return _oldDocType;
}
@Override
public IPreliminaryDocumentNoBuilder setOldDocumentNo(final String oldDocumentNo)
{
assertNotBuilt();
_oldDocumentNo = oldDocumentNo;
return this;
}
private String getOldDocumentNo()
{
return _oldDocumentNo;
}
private boolean isNewDocumentNo()
{
final String oldDocumentNo = getOldDocumentNo();
if (oldDocumentNo == null)
{
return true;
}
if (IPreliminaryDocumentNoBuilder.hasPreliminaryMarkers(oldDocumentNo))
{
return true;
} | return false;
}
@Override
public IPreliminaryDocumentNoBuilder setDocumentModel(final Object documentModel)
{
_documentModel = documentModel;
return this;
}
private Object getDocumentModel()
{
Check.assumeNotNull(_documentModel, "_documentModel not null");
return _documentModel;
}
private java.util.Date getDocumentDate(final String dateColumnName)
{
final Object documentModel = getDocumentModel();
final Optional<java.util.Date> date = InterfaceWrapperHelper.getValue(documentModel, dateColumnName);
return date.orElse(null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\PreliminaryDocumentNoBuilder.java | 1 |
请完成以下Java代码 | private void dbInsert(final IScript script, final boolean ignored)
{
final String developerName = null;
final String filename = script.getFileName();
final String description;
if (ignored)
{
description = "Ignored by " + getClass().getCanonicalName();
}
else
{
description = "Applied by " + getClass().getCanonicalName();
}
final long durationMillis = script.getLastDurationMillis();
//
final String sql = "INSERT INTO AD_MigrationScript("
// + " AD_MigrationScript_ID, "
+ " AD_Client_ID, AD_Org_ID, Created, CreatedBy, Updated, UpdatedBy"
+ ", Description"
+ ", DeveloperName"
+ ", IsActive, ReleaseNo, Status"
+ ", IsApply"
+ ", FileName"
+ ", Name"
+ ", ProjectName"
+ ", DurationMillis"
+ ") VALUES ("
// + "nextIdFunc(?, 'N'), "
+ "0, 0, now(), 100, now(), 100" // AD_Client_ID, AD_Org_ID, Created, CreatedBy, Updated, UpdatedBy
+ ",?" // description
+ ",?" // developername
+ ",'Y' , 1, 'CO'" // IsActive, ReleaseNo, Status
+ ",?" // IsApply
+ ",?" // FileName
+ ",?" // Name
+ ",?" // ProjectName
+ ",?" // DurationMillis
+ ")";
final ScriptName scriptName = ScriptName.of(script);
final String name = scriptName.getName();
final String projectName = scriptName.getProjectName();
sqlHelper.executeUpdate(sql, description, developerName, ignored, filename, name, projectName, durationMillis);
}
private Collection<ScriptName> dbRetrieveAll()
{
final Stopwatch stopwatch = Stopwatch.createStarted();
final Collection<ScriptName> scriptNames = sqlHelper.<ScriptName> retrieveRecords()
.sql("SELECT ProjectName, Name FROM AD_MigrationScript")
.collectionFactory(HashSet::new)
.rowLoader(rs -> ScriptName.ofProjectNameAndName(rs.getString("ProjectName"), rs.getString("Name")))
.execute();
stopwatch.stop();
logger.info("Loaded {} registry entries from database in {}", scriptNames.size(), stopwatch);
return scriptNames;
}
@Value
private static class ScriptName
{
public static ScriptName of(final IScript script) | {
final String projectName = script.getProjectName();
if (projectName == null)
{
throw new IllegalArgumentException("No projectName was set for " + script);
}
final String fileName = script.getFileName();
final String name = projectName + "->" + fileName;
return new ScriptName(projectName, name);
}
public static ScriptName ofProjectNameAndName(final String projectName, final String name)
{
return new ScriptName(projectName, name);
}
String projectName;
String name;
private ScriptName(final String projectName, final String name)
{
this.projectName = projectName;
this.name = name;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\impl\SQLDatabaseScriptsRegistry.java | 1 |
请完成以下Java代码 | public void setOtherClause (String OtherClause)
{
set_Value (COLUMNNAME_OtherClause, OtherClause);
}
/** Get Other SQL Clause.
@return Other SQL Clause
*/
public String getOtherClause ()
{
return (String)get_Value(COLUMNNAME_OtherClause);
}
/** Set Record ID.
@param Record_ID
Direct internal record ID
*/
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Record ID.
@return Direct internal record ID
*/
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ContainerTTable.java | 1 |
请完成以下Java代码 | public int getSqlType() {
return Types.ARRAY;
}
@Override
public Class<String[]> returnedClass() {
return String[].class;
}
@Override
public boolean equals(String[] x, String[] y) {
if (x instanceof String[] && y instanceof String[]) {
return Arrays.deepEquals(x, y);
} else {
return false;
}
}
@Override
public int hashCode(String[] x) {
return Arrays.hashCode(x);
}
@Override
public String[] nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
Array array = rs.getArray(position);
return array != null ? (String[]) array.getArray() : null;
}
@Override
public void nullSafeSet(PreparedStatement st, String[] value, int index, SharedSessionContractImplementor session) throws SQLException {
if (st != null) {
if (value != null) {
Array array = session.getJdbcConnectionAccess().obtainConnection().createArrayOf("text", value);
st.setArray(index, array);
} else {
st.setNull(index, Types.ARRAY);
}
}
}
@Override
public String[] deepCopy(String[] value) { | return value != null ? Arrays.copyOf(value, value.length) : null;
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(String[] value) {
return value;
}
@Override
public String[] assemble(Serializable cached, Object owner) {
return (String[]) cached;
}
@Override
public String[] replace(String[] detached, String[] managed, Object owner) {
return detached;
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\arraymapping\CustomStringArrayType.java | 1 |
请完成以下Java代码 | protected boolean writeExtensionChildElements(BaseElement element, boolean didWriteExtensionStartElement, XMLStreamWriter xtw) throws Exception {
ValuedDataObject dataObject = (ValuedDataObject) element;
if (StringUtils.isNotEmpty(dataObject.getId()) && dataObject.getValue() != null) {
if (!didWriteExtensionStartElement) {
xtw.writeStartElement(ELEMENT_EXTENSIONS);
didWriteExtensionStartElement = true;
}
xtw.writeStartElement(FLOWABLE_EXTENSIONS_PREFIX, ELEMENT_DATA_VALUE, FLOWABLE_EXTENSIONS_NAMESPACE);
if (dataObject.getValue() != null) {
String value = null;
if (dataObject instanceof DateDataObject) {
value = sdf.format(dataObject.getValue());
} else {
value = dataObject.getValue().toString();
} | if (dataObject instanceof StringDataObject && xmlChars.matcher(value).find()) {
xtw.writeCData(value);
} else {
xtw.writeCharacters(value);
}
}
xtw.writeEndElement();
}
return didWriteExtensionStartElement;
}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception {
}
} | repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\ValuedDataObjectXMLConverter.java | 1 |
请完成以下Java代码 | public FeatureIndex getFeature_index_()
{
return feature_index_;
}
public void setFeature_index_(FeatureIndex feature_index_)
{
this.feature_index_ = feature_index_;
}
public List<List<String>> getX_()
{
return x_;
}
public void setX_(List<List<String>> x_)
{
this.x_ = x_;
}
public List<List<Node>> getNode_()
{
return node_;
}
public void setNode_(List<List<Node>> node_)
{
this.node_ = node_;
}
public List<Integer> getAnswer_()
{
return answer_;
}
public void setAnswer_(List<Integer> answer_)
{
this.answer_ = answer_;
}
public List<Integer> getResult_()
{
return result_;
}
public void setResult_(List<Integer> result_)
{
this.result_ = result_;
}
public static void main(String[] args) throws Exception
{
if (args.length < 1)
{
return;
} | TaggerImpl tagger = new TaggerImpl(Mode.TEST);
InputStream stream = null;
try
{
stream = IOUtil.newInputStream(args[0]);
}
catch (IOException e)
{
System.err.printf("model not exits for %s", args[0]);
return;
}
if (stream != null && !tagger.open(stream, 2, 0, 1.0))
{
System.err.println("open error");
return;
}
System.out.println("Done reading model");
if (args.length >= 2)
{
InputStream fis = IOUtil.newInputStream(args[1]);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
while (true)
{
ReadStatus status = tagger.read(br);
if (ReadStatus.ERROR == status)
{
System.err.println("read error");
return;
}
else if (ReadStatus.EOF == status)
{
break;
}
if (tagger.getX_().isEmpty())
{
break;
}
if (!tagger.parse())
{
System.err.println("parse error");
return;
}
System.out.print(tagger.toString());
}
br.close();
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\TaggerImpl.java | 1 |
请完成以下Java代码 | public static ValueCreator byStaticMethodInvocation(final Class<?> compatibleType, final String methodName)
{
return new ValueCreator()
{
public Object createValue(Class<?> type, String value)
{
Object v = null;
if (compatibleType.isAssignableFrom(type))
{
try
{
Method m = type.getMethod(methodName, String.class);
return m.invoke(null, value);
}
catch (NoSuchMethodException e)
{
// ignore
}
catch (Exception e)
{
throw new IllegalArgumentException(String.format("could not invoke %s#%s to create an obejct from %s", type.toString(), methodName, value));
}
}
return v;
}
};
}
/**
* {@link ValueCreator} building object using a one arg constructor taking a {@link String} object as parameter
*/
public static final ValueCreator FROM_STRING_CONSTRUCTOR = new ValueCreator()
{
public Object createValue(Class<?> type, String value)
{
Object v = null;
try
{
Constructor<?> init = type.getDeclaredConstructor(String.class);
v = init.newInstance(value);
}
catch (NoSuchMethodException e)
{
// ignore
}
catch (Exception e)
{
throw new IllegalArgumentException("Failed to convertPKUtoCWS " + value + " to type " + type.getName(), e);
}
return v;
}
};
public static final ValueCreator ENUM_CREATOR = new ValueCreator()
{
@SuppressWarnings({"unchecked", "rawtypes"})
public Object createValue(Class type, String value) | {
if (Enum.class.isAssignableFrom(type))
{
return Enum.valueOf(type, value);
}
return null;
}
};
private static final List<ValueCreator> DEFAULT_VALUE_CREATORS = Arrays.asList(Args.FROM_STRING_CONSTRUCTOR, Args.ENUM_CREATOR);
private static List<ValueCreator> valueCreators = new ArrayList<ValueCreator>(DEFAULT_VALUE_CREATORS);
/**
* Allows external extension of the valiue creators.
*
* @param vc another value creator to take into account for trying to create values
*/
public static void registerValueCreator(ValueCreator vc)
{
valueCreators.add(vc);
}
/**
* Cleanup of registered ValueCreators (mainly for tests)
*/
public static void resetValueCreators()
{
valueCreators.clear();
valueCreators.addAll(DEFAULT_VALUE_CREATORS);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\cli\Args.java | 1 |
请完成以下Java代码 | public class Confirmation {
private int ackNumber;
private String verificationComment;
public Confirmation() {
}
public Confirmation(int ackNumber, String verificationComment) {
this.ackNumber = ackNumber;
this.verificationComment = verificationComment;
}
public int getAckNumber() {
return ackNumber;
}
public void setAckNumber(int ackNumber) {
this.ackNumber = ackNumber;
} | public String getVerificationComment() {
return verificationComment;
}
public void setVerificationComment(String verificationComment) {
this.verificationComment = verificationComment;
}
@Override
public String toString() {
return "Confirmation{" +
"ackNumber='" + ackNumber + '\'' +
", verificationComment=" + verificationComment +
'}';
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot2-jms-activemq\src\main\java\net\alanbinu\springboot\jms\Confirmation.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8081
keycloak:
auth-server-url: http://localhost:8080 # Keycloak server url
realm: SpringBootKeycloak # Keycloak Realm
spring:
security:
oauth2:
resourceserver:
jwt.issuer-uri: http://loca | lhost:8080/realms/SpringBootKeycloak
springdoc:
swagger-ui:
oauth:
client-id: login-app | repos\tutorials-master\spring-boot-modules\spring-boot-swagger-keycloak\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID)
{
if (ExternalSystem_Config_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_Config_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID);
}
@Override
public int getExternalSystem_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
}
@Override
public void setHostKey (final @Nullable java.lang.String HostKey)
{
set_ValueNoCheck (COLUMNNAME_HostKey, HostKey);
}
@Override
public java.lang.String getHostKey()
{
return get_ValueAsString(COLUMNNAME_HostKey);
}
@Override
public void setIPP_URL (final @Nullable java.lang.String IPP_URL)
{
set_Value (COLUMNNAME_IPP_URL, IPP_URL);
}
@Override
public java.lang.String getIPP_URL()
{
return get_ValueAsString(COLUMNNAME_IPP_URL);
}
@Override
public void setName (final java.lang.String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
} | /**
* OutputType AD_Reference_ID=540632
* Reference name: OutputType
*/
public static final int OUTPUTTYPE_AD_Reference_ID=540632;
/** Attach = Attach */
public static final String OUTPUTTYPE_Attach = "Attach";
/** Store = Store */
public static final String OUTPUTTYPE_Store = "Store";
/** Queue = Queue */
public static final String OUTPUTTYPE_Queue = "Queue";
/** Frontend = Frontend */
public static final String OUTPUTTYPE_Frontend = "Frontend";
@Override
public void setOutputType (final java.lang.String OutputType)
{
set_Value (COLUMNNAME_OutputType, OutputType);
}
@Override
public java.lang.String getOutputType()
{
return get_ValueAsString(COLUMNNAME_OutputType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterHW.java | 1 |
请完成以下Java代码 | private StringBuffer appendTabified(final StringBuffer buffer, final String value)
{
// return buffer.append(String.valueOf(value).replace("\n", "\n" + tabs.substring(0, getDepth())));
final Matcher matcher = NEWLINE_PATTERN.matcher(value);
final String replacement = NEWLINE_STRING + tabs.substring(0, getDepth());
while (matcher.find())
{
matcher.appendReplacement(buffer, replacement);
}
matcher.appendTail(buffer);
return buffer;
}
@Override
protected void appendFieldSeparator(final StringBuffer buffer)
{
buffer.append(getFieldSeparator());
padDepth(buffer);
}
@Override
public void appendStart(final StringBuffer buffer, final Object object)
{
depth.get().increment();
super.appendStart(buffer, object);
}
@Override
public void appendEnd(final StringBuffer buffer, final Object object)
{
super.appendEnd(buffer, object);
buffer.setLength(buffer.length() - getContentEnd().length());
buffer.append(SystemUtils.LINE_SEPARATOR);
depth.get().decrement();
padDepth(buffer);
appendContentEnd(buffer);
}
@Override
protected void removeLastFieldSeparator(final StringBuffer buffer)
{
final int len = buffer.length();
final int sepLen = getFieldSeparator().length() + getDepth();
if (len > 0 && sepLen > 0 && len >= sepLen)
{
buffer.setLength(len - sepLen);
}
}
private boolean noReflectionNeeded(final Object value)
{
try
{
return value != null &&
(value.getClass().getName().startsWith("java.lang.")
|| value.getClass().getMethod("toString").getDeclaringClass() != Object.class);
}
catch (final NoSuchMethodException e)
{
throw new IllegalStateException(e);
}
}
@Override
protected void appendDetail(final StringBuffer buffer, final String fieldName, final Object value)
{
if (getDepth() >= maxDepth || noReflectionNeeded(value))
{
appendTabified(buffer, String.valueOf(value));
}
else
{
new ExtendedReflectionToStringBuilder(value, this, buffer, null, false, false).toString();
}
} | // another helpful method, for collections:
@Override
protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection<?> col)
{
appendSummarySize(buffer, fieldName, col.size());
final ExtendedReflectionToStringBuilder builder = new ExtendedReflectionToStringBuilder(
col.toArray(), // object
this, // style,
buffer, //buffer,
null, //reflectUpToClass,
true, // outputTransients,
true // outputStatics
);
builder.toString();
}
@Override
protected String getShortClassName(final Class<?> cls)
{
if (cls != null && cls.isArray() && getDepth() > 0)
{
return "";
}
return super.getShortClassName(cls);
}
static class MutableInteger
{
private int value;
MutableInteger(final int value)
{
this.value = value;
}
public final int get()
{
return value;
}
public final void increment()
{
++value;
}
public final void decrement()
{
--value;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\text\RecursiveIndentedMultilineToStringStyle.java | 1 |
请完成以下Java代码 | class PostingExecutionException extends AdempiereException
{
/**
* Wraps given <code>throwable</code> as {@link PostingExecutionException}, if it's not already an {@link PostingExecutionException}.
*
* @param throwable
* @return {@link PostingExecutionException} or <code>null</code> if the throwable was null.
*/
public static final AdempiereException wrapIfNeeded(final Throwable throwable)
{
if (throwable == null)
{
return null;
}
else if (throwable instanceof PostingExecutionException)
{
return (PostingExecutionException)throwable;
}
else
{
final Throwable cause = extractCause(throwable);
if (cause instanceof PostingExecutionException)
{
return (PostingExecutionException)cause;
}
else
{
final String message = extractMessage(cause);
return new PostingExecutionException(message, cause);
}
}
} | public PostingExecutionException(final String message)
{
this(message, /* serverStackTrace */(String)null);
}
private PostingExecutionException(final String message, final String serverStackTrace)
{
super(buildMessage(message, serverStackTrace));
}
private PostingExecutionException(final String message, final Throwable cause)
{
super(message, cause);
}
private static final String buildMessage(final String message, final String serverStackTrace)
{
final StringBuilder sb = new StringBuilder();
sb.append(!Check.isEmpty(message) ? message.trim() : "unknow error");
if (!Check.isEmpty(serverStackTrace))
{
sb.append("\nServer stack trace: ").append(serverStackTrace.trim());
}
return sb.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\api\impl\PostingExecutionException.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<PrivilegeResponse> createPrivilegeResponseList(List<Privilege> privileges) {
List<PrivilegeResponse> responseList = new ArrayList<>(privileges.size());
for (Privilege privilege : privileges) {
responseList.add(createPrivilegeResponse(privilege));
}
return responseList;
}
public PrivilegeResponse createPrivilegeResponse(Privilege privilege) {
return new PrivilegeResponse(privilege.getId(), privilege.getName());
}
public PrivilegeResponse createPrivilegeResponse(Privilege privilege, List<User> users, List<Group> groups) {
PrivilegeResponse response = createPrivilegeResponse(privilege);
List<UserResponse> userResponses = new ArrayList<>(users.size());
for (User user : users) {
userResponses.add(createUserResponse(user, false));
}
response.setUsers(userResponses); | List<GroupResponse> groupResponses = new ArrayList<>(groups.size());
for (Group group : groups) {
groupResponses.add(createGroupResponse(group));
}
response.setGroups(groupResponses);
return response;
}
protected RestUrlBuilder createUrlBuilder() {
return RestUrlBuilder.fromCurrentRequest();
}
} | repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\IdmRestResponseFactory.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class C_Tax
{
private final ICountryAreaBL countryAreaBL = Services.get(ICountryAreaBL.class);
private final ICountryDAO countryDAO = Services.get(ICountryDAO.class);
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Tax.COLUMNNAME_To_Country_ID })
public void updateTypeOfDestCountry(@NonNull final I_C_Tax tax)
{
final CountryId toCountryId = CountryId.ofRepoIdOrNull(tax.getTo_Country_ID());
if (toCountryId == null)
{
final OrgId orgId = OrgId.ofRepoId(tax.getAD_Org_ID());
if (orgId.isAny())
{
tax.setTypeOfDestCountry(WITHIN_COUNTRY_AREA.getCode());
}
}
else
{
if (tax.getC_Country_ID() == tax.getTo_Country_ID())
{
tax.setTypeOfDestCountry(DOMESTIC.getCode());
}
else
{
final String countryCode = countryDAO.retrieveCountryCode2ByCountryId(toCountryId);
final boolean isEULocation = countryAreaBL.isMemberOf(Env.getCtx(),
ICountryAreaBL.COUNTRYAREAKEY_EU,
countryCode,
tax.getUpdated());
final TypeOfDestCountry typeOfDestCountry = isEULocation ? WITHIN_COUNTRY_AREA : OUTSIDE_COUNTRY_AREA;
tax.setTypeOfDestCountry(typeOfDestCountry.getCode());
}
}
} | @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Tax.COLUMNNAME_TypeOfDestCountry })
public void updateToCountryId(@NonNull final I_C_Tax tax)
{
final TypeOfDestCountry typeOfDestCountry = TypeOfDestCountry.ofNullableCode(tax.getTypeOfDestCountry());
final int countryId = tax.getC_Country_ID();
final int toCountryIdRepoId = tax.getTo_Country_ID();
if ((DOMESTIC.equals(typeOfDestCountry) && countryId != toCountryIdRepoId) || (countryId == toCountryIdRepoId && !DOMESTIC.equals(typeOfDestCountry)))
{
tax.setTo_Country_ID(0);
}
else
{
final CountryId toCountryId = CountryId.ofRepoIdOrNull(toCountryIdRepoId);
if (toCountryId != null)
{
final String countryCode = countryDAO.retrieveCountryCode2ByCountryId(toCountryId);
final boolean isEULocation = countryAreaBL.isMemberOf(Env.getCtx(),
ICountryAreaBL.COUNTRYAREAKEY_EU,
countryCode,
Env.getDate());
if ((isEULocation && !WITHIN_COUNTRY_AREA.equals(typeOfDestCountry)) || (!isEULocation && OUTSIDE_COUNTRY_AREA.equals(typeOfDestCountry)))
{
tax.setTo_Country_ID(0);
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\tax\interceptor\C_Tax.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class HandlingUnitsService
{
@NonNull final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
@NonNull private final HUQRCodesService huQRCodesService;
public HULoadingCache newLoadingCache()
{
return HULoadingCache.builder()
.huService(this)
.build();
}
public I_M_HU getById(HuId huId) {return handlingUnitsBL.getById(huId);}
public HUProductStorages getProductStorages(final I_M_HU hu)
{
final List<IHUProductStorage> productStorages = handlingUnitsBL.getStorageFactory().getProductStorages(hu);
return new HUProductStorages(productStorages);
}
public Quantity getQty(final HuId huId, final ProductId productId)
{
final I_M_HU hu = getById(huId);
return getProductStorages(hu).getQty(productId);
}
public Attributes getImmutableAttributeSet(final I_M_HU hu) {return Attributes.of(handlingUnitsBL.getImmutableAttributeSet(hu));} | public IHUQRCode parse(final @NonNull ScannedCode scannedCode)
{
return huQRCodesService.parse(scannedCode);
}
public HuId getHuIdByQRCode(final @NonNull HUQRCode huQRCode)
{
return huQRCodesService.getHuIdByQRCode(huQRCode);
}
public String getDisplayName(final I_M_HU hu)
{
return handlingUnitsBL.getDisplayName(hu);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\deps\handlingunits\HandlingUnitsService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public TbImageDeleteResult delete(TbResourceInfo imageInfo, User user, boolean force) {
TenantId tenantId = imageInfo.getTenantId();
TbResourceId imageId = imageInfo.getId();
try {
TbImageDeleteResult result = imageService.deleteImage(imageInfo, force);
if (result.isSuccess()) {
logEntityActionService.logEntityAction(tenantId, imageId, imageInfo, ActionType.DELETED, user, imageId.toString());
List<ImageCacheKey> toEvict = new ArrayList<>();
toEvict.add(ImageCacheKey.forImage(tenantId, imageInfo.getResourceKey()));
if (imageInfo.isPublic()) {
toEvict.add(ImageCacheKey.forPublicImage(imageInfo.getPublicResourceKey()));
}
evictFromCache(tenantId, toEvict);
}
return result;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, imageId, ActionType.DELETED, user, e, imageId.toString());
throw e;
}
}
@Override
public TbResourceInfo importImage(ResourceExportData imageData, boolean checkExisting, SecurityUser user) throws Exception {
TbResource image = imageService.toImage(user.getTenantId(), imageData, checkExisting);
if (checkExisting && image.getId() != null) {
accessControlService.checkPermission(user, Resource.TB_RESOURCE, Operation.READ, image.getId(), image);
return image;
} else { | accessControlService.checkPermission(user, Resource.TB_RESOURCE, Operation.CREATE, null, image);
}
return save(image, user);
}
private void evictFromCache(TenantId tenantId, List<ImageCacheKey> toEvict) {
toEvict.forEach(this::evictETags);
clusterService.broadcastToCore(TransportProtos.ToCoreNotificationMsg.newBuilder()
.setResourceCacheInvalidateMsg(TransportProtos.ResourceCacheInvalidateMsg.newBuilder()
.setTenantIdMSB(tenantId.getId().getMostSignificantBits())
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits())
.addAllKeys(toEvict.stream().map(ImageCacheKey::toProto).collect(Collectors.toList()))
.build())
.build());
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\resource\DefaultTbImageService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public HttpTracing httpTracing(Tracing tracing) {
return HttpTracing.create(tracing);
}
/**
* Creates server spans for http requests
*/
@Bean
public Filter tracingFilter(HttpTracing httpTracing) {
return TracingFilter.create(httpTracing);
}
// ==================== SpringMVC 相关 ====================
// @see SpringMvcConfiguration 类上的,@Import(SpanCustomizingAsyncHandlerInterceptor.class)
// ==================== HttpClient 相关 ==================== | @Bean
public RestTemplateCustomizer useTracedHttpClient(HttpTracing httpTracing) {
// 创建 CloseableHttpClient 对象,内置 HttpTracing 进行 HTTP 链路追踪。
final CloseableHttpClient httpClient = TracingHttpClientBuilder.create(httpTracing).build();
// 创建 RestTemplateCustomizer 对象
return new RestTemplateCustomizer() {
@Override
public void customize(RestTemplate restTemplate) {
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
}
};
}
} | repos\SpringBoot-Labs-master\lab-40\lab-40-demo\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\config\ZipkinConfiguration.java | 2 |
请完成以下Java代码 | public static void applyFieldDeclaration(FieldDeclaration declaration, Object target) {
Method setterMethod = ReflectUtil.getSetter(declaration.getName(), target.getClass(), declaration.getValue().getClass());
if (setterMethod != null) {
try {
setterMethod.invoke(target, declaration.getValue());
} catch (IllegalArgumentException e) {
throw new FlowableException("Error while invoking '" + declaration.getName() + "' on class " + target.getClass().getName(), e);
} catch (IllegalAccessException e) {
throw new FlowableException("Illegal access when calling '" + declaration.getName() + "' on class " + target.getClass().getName(), e);
} catch (InvocationTargetException e) {
throw new FlowableException("Exception while invoking '" + declaration.getName() + "' on class " + target.getClass().getName(), e);
}
} else {
Field field = ReflectUtil.getField(declaration.getName(), target);
if (field == null) {
throw new FlowableIllegalArgumentException("Field definition uses non-existing field '" + declaration.getName() + "' on class " + target.getClass().getName());
}
// Check if the delegate field's type is correct
if (!fieldTypeCompatible(declaration, field)) { | throw new FlowableIllegalArgumentException("Incompatible type set on field declaration '" + declaration.getName() + "' for class " + target.getClass().getName() + ". Declared value has type "
+ declaration.getValue().getClass().getName() + ", while expecting " + field.getType().getName());
}
ReflectUtil.setField(field, target, declaration.getValue());
}
}
public static boolean fieldTypeCompatible(FieldDeclaration declaration, Field field) {
if (declaration.getValue() != null) {
return field.getType().isAssignableFrom(declaration.getValue().getClass());
} else {
// Null can be set any field type
return true;
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\helper\ClassDelegateUtil.java | 1 |
请完成以下Java代码 | private CurrencyCode getCurrencyCodeById(final int currencyRepoId)
{
final ICurrencyDAO currenciesRepo = Services.get(ICurrencyDAO.class);
return currenciesRepo.getCurrencyCodeById(CurrencyId.ofRepoId(currencyRepoId));
}
/**
* Updates the pay selection's name if paydate or the bank account are changed. the name is set to be <PayDate>_<Bank>_<Currency>.
*
* @param paySelection
* @task 08267
*/
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_PaySelection.COLUMNNAME_C_BP_BankAccount_ID, I_C_PaySelection.COLUMNNAME_PayDate })
public void updateNameIfNotSet(final I_C_PaySelection paySelection)
{
final StringBuilder name = new StringBuilder();
if (paySelection.getPayDate() != null)
{
final DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
final String formattedDate = dateFormat.format(paySelection.getPayDate());
name.append(formattedDate);
}
if (name.length() > 0)
{
name.append("_");
}
final BankAccountId bankAccountId = BankAccountId.ofRepoIdOrNull(paySelection.getC_BP_BankAccount_ID()); | if (bankAccountId != null)
{
final String bankAccountName = bankAccountService.createBankAccountName(bankAccountId);
name.append(bankAccountName);
}
if (name.length() > 0 && !paySelection.getName().startsWith(name.toString()))
{
paySelection.setName(name.toString());
}
}
// TODO: Fix this in the followup https://github.com/metasfresh/metasfresh/issues/2841
// @DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE)
// public void createPayments(final I_C_PaySelection paySelection)
// {
// Services.get(IPaySelectionBL.class).createPayments(paySelection);
// }
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\modelvalidator\C_PaySelection.java | 1 |
请完成以下Java代码 | public class PlainHandlingUnitsInfo implements IHandlingUnitsInfo
{
private final String tuName;
private final int qtyTU;
public PlainHandlingUnitsInfo(final String tuName, final int qtyTU)
{
super();
Check.assumeNotEmpty(tuName, "tuName not empty");
this.tuName = tuName;
this.qtyTU = qtyTU;
}
@Override
public String toString()
{
return "PlainHandlingUnitsInfo [tuName=" + tuName + ", qtyTU=" + qtyTU + "]";
}
@Override
public int getQtyTU()
{
return qtyTU;
}
@Override
public String getTUName()
{
return tuName;
} | @Override
public IHandlingUnitsInfo add(@Nullable final IHandlingUnitsInfo infoToAdd)
{
if (infoToAdd == null)
{
return this; // shall not happen
}
final String tuName = getTUName();
if (!tuName.equals(infoToAdd.getTUName()))
{
throw new AdempiereException("TU Names are not matching."
+ "\n This: " + this
+ "\n Other: " + infoToAdd);
}
final int qtyTU = getQtyTU();
final int qtyTU_ToAdd = infoToAdd.getQtyTU();
final int qtyTU_New = qtyTU + qtyTU_ToAdd;
final PlainHandlingUnitsInfo infoNew = new PlainHandlingUnitsInfo(tuName, qtyTU_New);
return infoNew;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\PlainHandlingUnitsInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonResponseCompositeList
{
@JsonInclude(Include.NON_NULL)
@JsonUnwrapped
JsonPagingDescriptor pagingDescriptor;
@JsonInclude(Include.NON_NULL)
List<JsonResponseComposite> items;
@JsonInclude(Include.NON_EMPTY)
@Singular
List<JsonErrorItem> errors;
public static JsonResponseCompositeList ok(
@NonNull final JsonPagingDescriptor pagingDescriptor, | @NonNull final List<JsonResponseComposite> items)
{
return _builder()
.pagingDescriptor(pagingDescriptor)
.items(items)
.build();
}
public static JsonResponseCompositeList error(@NonNull final JsonErrorItem error)
{
return _builder()
.error(error)
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\response\JsonResponseCompositeList.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public byte[] getVariableData(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId,
@ApiParam(name = "variableName") @PathVariable("variableName") String variableName,
@ApiParam(hidden = true) @RequestParam(value = "scope", required = false) String scope,
HttpServletResponse response) {
try {
byte[] result = null;
RestVariable variable = getVariableFromRequest(taskId, variableName, scope, true);
if (CmmnRestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variable.getType())) {
result = (byte[]) variable.getValue();
response.setContentType("application/octet-stream");
} else if (CmmnRestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variable.getType())) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutputStream outputStream = new ObjectOutputStream(buffer); | outputStream.writeObject(variable.getValue());
outputStream.close();
result = buffer.toByteArray();
response.setContentType("application/x-java-serialized-object");
} else {
throw new FlowableObjectNotFoundException("The variable does not have a binary data stream.", null);
}
return result;
} catch (IOException ioe) {
// Re-throw IOException
throw new FlowableException("Unexpected error getting variable data", ioe);
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskVariableDataResource.java | 2 |
请完成以下Java代码 | public List<RelatedDocumentsCandidateGroup> retrieveRelatedDocumentsCandidates(
@NonNull final IZoomSource fromDocument,
@Nullable final AdWindowId targetWindowId)
{
if (!fromDocument.isSingleKeyRecord())
{
return ImmutableList.of();
}
//
// Get the Issues AD_Window_ID
final AdWindowId issuesWindowId = RecordWindowFinder.findAdWindowId(I_AD_Issue.Table_Name).orElse(null);
if (issuesWindowId == null)
{
return ImmutableList.of();
}
// If not our target window ID, return nothing
if (targetWindowId != null && !AdWindowId.equals(targetWindowId, issuesWindowId))
{
return ImmutableList.of();
}
final TableRecordReference recordRef = TableRecordReference.of(fromDocument.getAD_Table_ID(), fromDocument.getRecord_ID());
final Supplier<IssueCountersByCategory> issueCountersSupplier = getIssueCountersByCategorySupplier(recordRef);
final RelatedDocumentsCandidateGroup.RelatedDocumentsCandidateGroupBuilder groupBuilder = RelatedDocumentsCandidateGroup.builder();
for (final IssueCategory issueCategory : IssueCategory.values())
{
final RelatedDocumentsId id = RelatedDocumentsId.ofString("issues-" + issueCategory.getCode());
final ITranslatableString issueCategoryDisplayName = adReferenceService.retrieveListNameTranslatableString(IssueCategory.AD_REFERENCE_ID, issueCategory.getCode());
groupBuilder.candidate(
RelatedDocumentsCandidate.builder()
.id(id)
.internalName(id.toJson())
.targetWindow(RelatedDocumentsTargetWindow.ofAdWindowIdAndCategory(issuesWindowId, issueCategory))
.priority(relatedDocumentsPriority)
.querySupplier(createQuerySupplier(recordRef, issueCategory))
.windowCaption(issueCategoryDisplayName)
.filterByFieldCaption(issueCategoryDisplayName)
.documentsCountSupplier(new AdIssueRelatedDocumentsCountSupplier(issueCountersSupplier, issueCategory)) | .build());
}
return ImmutableList.of(groupBuilder.build());
}
private Supplier<IssueCountersByCategory> getIssueCountersByCategorySupplier(@NonNull final TableRecordReference recordRef)
{
return Suppliers.memoize(() -> errorManager.getIssueCountersByCategory(recordRef, onlyNotAcknowledged));
}
private RelatedDocumentsQuerySupplier createQuerySupplier(@NonNull final TableRecordReference recordRef, @NonNull final IssueCategory issueCategory)
{
final MQuery query = new MQuery(I_AD_Issue.Table_Name);
query.addRestriction(I_AD_Issue.COLUMNNAME_AD_Table_ID, Operator.EQUAL, recordRef.getAD_Table_ID());
query.addRestriction(I_AD_Issue.COLUMNNAME_Record_ID, Operator.EQUAL, recordRef.getRecord_ID());
query.addRestriction(I_AD_Issue.COLUMNNAME_IssueCategory, Operator.EQUAL, issueCategory.getCode());
if (onlyNotAcknowledged)
{
query.addRestriction(I_AD_Issue.COLUMNNAME_Processed, Operator.EQUAL, false);
}
return RelatedDocumentsQuerySuppliers.ofQuery(query);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\error\related_documents\AdIssueRelatedDocumentsProvider.java | 1 |
请完成以下Java代码 | private void initProcessorMap() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
// 获取ProcessEngine所在的路径
String pkg = getPackage();
// 获取ProcessEngine的Class对象
Class<ProcessEngine> processEngineClazz = (Class<ProcessEngine>) Class.forName(pkg);
// 获取processorMapField
Field processorMapField = processEngineClazz.getDeclaredField("processorMap");
// 获取@InjectProcessors
InjectProcessors injectProcessors = processorMapField.getAnnotation(InjectProcessors.class);
// 创建processorMap对象
Map<ProcessReqEnum, Processor> processorMap = createProcessorMap(injectProcessors);
// 赋值
setValueForProcessorMap(processorMap, processorMapField);
}
/**
* 给ProcessorEngine的processorMap对象赋值
* @param processorMap processorMap对象
* @param processorMapField processorMap的Field对象
*/
private void setValueForProcessorMap(Map<ProcessReqEnum, Processor> processorMap, Field processorMapField) throws IllegalAccessException {
// 获取ProcessEngine对象
ProcessEngine processEngine = applicationContext.getBean(ProcessEngine.class);
// 将processorMapField设为public
processorMapField.setAccessible(true);
// 赋值
processorMapField.set(processEngine, processorMap);
}
/**
* 创建ProcessorMap
* @param injectProcessors injectProcessors注解对象
* @return ProcessorMap | */
private Map<ProcessReqEnum, Processor> createProcessorMap(InjectProcessors injectProcessors) {
// 初始化容器
Map<ProcessReqEnum, Processor> processorMap = Maps.newHashMap();
// 获取注解中的值
Class[] processorClazzList = injectProcessors.value();
if (processorClazzList==null || processorClazzList.length<=0) {
return processorMap;
}
// 遍历
for (Class<Processor> processorClazz : processorClazzList) {
// 获取Processor
Processor processor = applicationContext.getBean(processorClazz);
// 获取枚举
ProcessReqEnum processReqEnum = EnumUtil.msgOf(ProcessReqEnum.class, processorClazz.getSimpleName());
// 加入map
processorMap.put(processReqEnum, processor);
System.out.println(processor);
System.out.println("------------");
}
System.out.println(processorMap);
return processorMap;
}
/**
* 获取需要扫描的包名
*/
private String getPackage() {
PackageScan packageScan = AnnotationUtil.getAnnotationValueByClass(this.getClass(), PackageScan.class);
return packageScan.value();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\init\InitProcessorMap.java | 1 |
请完成以下Java代码 | public MChatEntry[] getEntries (boolean reload)
{
if (m_entries != null && !reload)
return m_entries;
ArrayList<MChatEntry> list = new ArrayList<MChatEntry>();
String sql = "SELECT * FROM CM_ChatEntry WHERE CM_Chat_ID=? ORDER BY Created";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, getCM_Chat_ID());
rs = pstmt.executeQuery ();
while (rs.next ())
{
list.add (new MChatEntry (getCtx(), rs, get_TrxName()));
}
}
catch (Exception e)
{
log.error(sql, e);
}
finally
{
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
//
m_entries = new MChatEntry[list.size ()];
list.toArray (m_entries);
return m_entries;
} // getEntries
/**
* Set Description
*
* @param Description
*/
@Override
public void setDescription (String Description)
{
if (Description != null && Description.length() > 0)
super.setDescription (Description);
else
super.setDescription (getAD_Table_ID() + "#" + getRecord_ID());
} // setDescription | /**
* Get History as htlp paragraph
* @param ConfidentialType confidentiality
* @return html paragraph
*/
public p getHistory (String ConfidentialType)
{
p history = new p();
getEntries(false);
boolean first = true;
for (int i = 0; i < m_entries.length; i++)
{
MChatEntry entry = m_entries[i];
if (!entry.isActive() || !entry.isConfidentialType(ConfidentialType))
continue;
if (first)
first = false;
else
history.addElement(new hr());
// User & Date
b b = new b();
final I_AD_User user = Services.get(IUserDAO.class).getById(entry.getCreatedBy());
b.addElement(user.getName());
b.addElement(" \t");
Timestamp created = entry.getCreated();
if (m_format == null)
m_format = DisplayType.getDateFormat(DisplayType.DateTime);
b.addElement(m_format.format(created));
history.addElement(b);
// history.addElement(new br());
//
p p = new p();
String data = entry.getCharacterData();
data = StringUtils.maskHTML(data, true);
p.addElement(data);
history.addElement(p);
} // entry
//
return history;
} // getHistory
} // MChat | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MChat.java | 1 |
请完成以下Java代码 | protected TimerJobEntity createTimerJobFromOtherJob(AbstractJobEntity otherJob) {
TimerJobEntity timerJob = processEngineConfiguration.getTimerJobEntityManager().create();
copyJobInfo(timerJob, otherJob);
return timerJob;
}
protected SuspendedJobEntity createSuspendedJobFromOtherJob(AbstractJobEntity otherJob) {
SuspendedJobEntity suspendedJob = processEngineConfiguration.getSuspendedJobEntityManager().create();
copyJobInfo(suspendedJob, otherJob);
return suspendedJob;
}
protected DeadLetterJobEntity createDeadLetterJobFromOtherJob(AbstractJobEntity otherJob) {
DeadLetterJobEntity deadLetterJob = processEngineConfiguration.getDeadLetterJobEntityManager().create();
copyJobInfo(deadLetterJob, otherJob);
return deadLetterJob;
}
protected AbstractJobEntity copyJobInfo(AbstractJobEntity copyToJob, AbstractJobEntity copyFromJob) {
copyToJob.setDuedate(copyFromJob.getDuedate());
copyToJob.setEndDate(copyFromJob.getEndDate());
copyToJob.setExclusive(copyFromJob.isExclusive());
copyToJob.setExecutionId(copyFromJob.getExecutionId());
copyToJob.setId(copyFromJob.getId());
copyToJob.setJobHandlerConfiguration(copyFromJob.getJobHandlerConfiguration());
copyToJob.setJobHandlerType(copyFromJob.getJobHandlerType());
copyToJob.setJobType(copyFromJob.getJobType());
copyToJob.setExceptionMessage(copyFromJob.getExceptionMessage());
copyToJob.setExceptionStacktrace(copyFromJob.getExceptionStacktrace());
copyToJob.setMaxIterations(copyFromJob.getMaxIterations());
copyToJob.setProcessDefinitionId(copyFromJob.getProcessDefinitionId());
copyToJob.setProcessInstanceId(copyFromJob.getProcessInstanceId());
copyToJob.setRepeat(copyFromJob.getRepeat());
copyToJob.setRetries(copyFromJob.getRetries());
copyToJob.setRevision(copyFromJob.getRevision());
copyToJob.setTenantId(copyFromJob.getTenantId());
return copyToJob;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
} | public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
}
protected boolean isAsyncExecutorActive() {
return processEngineConfiguration.getAsyncExecutor().isActive();
}
protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected AsyncExecutor getAsyncExecutor() {
return processEngineConfiguration.getAsyncExecutor();
}
protected ExecutionEntityManager getExecutionEntityManager() {
return processEngineConfiguration.getExecutionEntityManager();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\DefaultJobManager.java | 1 |
请完成以下Java代码 | public class X_M_AttributeSet extends org.compiere.model.PO implements I_M_AttributeSet, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1636107389L;
/** Standard Constructor */
public X_M_AttributeSet (final Properties ctx, final int M_AttributeSet_ID, @Nullable final String trxName)
{
super (ctx, M_AttributeSet_ID, trxName);
}
/** Load Constructor */
public X_M_AttributeSet (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 setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsInstanceAttribute (final boolean IsInstanceAttribute)
{
set_Value (COLUMNNAME_IsInstanceAttribute, IsInstanceAttribute);
}
@Override
public boolean isInstanceAttribute()
{
return get_ValueAsBoolean(COLUMNNAME_IsInstanceAttribute);
}
/**
* MandatoryType AD_Reference_ID=324
* Reference name: M_AttributeSet MandatoryType
*/
public static final int MANDATORYTYPE_AD_Reference_ID=324;
/** Not Mandatary = N */ | public static final String MANDATORYTYPE_NotMandatary = "N";
/** Always Mandatory = Y */
public static final String MANDATORYTYPE_AlwaysMandatory = "Y";
/** WhenShipping = S */
public static final String MANDATORYTYPE_WhenShipping = "S";
@Override
public void setMandatoryType (final java.lang.String MandatoryType)
{
set_Value (COLUMNNAME_MandatoryType, MandatoryType);
}
@Override
public java.lang.String getMandatoryType()
{
return get_ValueAsString(COLUMNNAME_MandatoryType);
}
@Override
public void setM_AttributeSet_ID (final int M_AttributeSet_ID)
{
if (M_AttributeSet_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, M_AttributeSet_ID);
}
@Override
public int getM_AttributeSet_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSet_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSet.java | 1 |
请完成以下Java代码 | public static boolean isAccessContainer (Properties ctx, int CM_Container_ID,
int AD_Role_ID, int C_BPGroup_ID)
{
// NIT
return true;
} // isAccessContainer
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param CM_AccessProfile_ID id
* @param trxName transaction
*/
public MAccessProfile (Properties ctx, int CM_AccessProfile_ID,
String trxName)
{
super (ctx, CM_AccessProfile_ID, trxName); | } // MAccessProfile
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAccessProfile (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MAccessProfile
} // MAccessProfile | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAccessProfile.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
@Version
private int version;
// Constructors
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and Setters
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
} | repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\persistence\model\Person.java | 2 |
请完成以下Java代码 | public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set UPC/EAN.
@param UPC
Produktidentifikation (Barcode) durch Universal Product Code oder European Article Number)
*/
@Override
public void setUPC (java.lang.String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN. | @return Produktidentifikation (Barcode) durch Universal Product Code oder European Article Number)
*/
@Override
public java.lang.String getUPC ()
{
return (java.lang.String)get_Value(COLUMNNAME_UPC);
}
/** Set Verwendet für Kunden.
@param UsedForCustomer Verwendet für Kunden */
@Override
public void setUsedForCustomer (boolean UsedForCustomer)
{
set_Value (COLUMNNAME_UsedForCustomer, Boolean.valueOf(UsedForCustomer));
}
/** Get Verwendet für Kunden.
@return Verwendet für Kunden */
@Override
public boolean isUsedForCustomer ()
{
Object oo = get_Value(COLUMNNAME_UsedForCustomer);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_EDI_M_Product_Lookup_UPC_v.java | 1 |
请完成以下Java代码 | public class ProcessInstanceModificationBatchCmd extends AbstractModificationCmd<Batch> {
public ProcessInstanceModificationBatchCmd(ModificationBuilderImpl modificationBuilderImpl) {
super(modificationBuilderImpl);
}
@Override
public Batch execute(CommandContext commandContext) {
List<AbstractProcessInstanceModificationCommand> instructions = builder.getInstructions();
ensureNotEmpty(BadUserRequestException.class,
"Modification instructions cannot be empty", instructions);
Collection<String> collectedInstanceIds = collectProcessInstanceIds();
ensureNotEmpty(BadUserRequestException.class, "Process instance ids cannot be empty",
"Process instance ids", collectedInstanceIds);
ensureNotContainsNull(BadUserRequestException.class, "Process instance ids cannot be null",
"Process instance ids", collectedInstanceIds);
String processDefinitionId = builder.getProcessDefinitionId();
ProcessDefinitionEntity processDefinition =
getProcessDefinition(commandContext, processDefinitionId);
ensureNotNull(BadUserRequestException.class,
"Process definition id cannot be null", processDefinition);
String tenantId = processDefinition.getTenantId();
String annotation = builder.getAnnotation();
return new BatchBuilder(commandContext)
.type(Batch.TYPE_PROCESS_INSTANCE_MODIFICATION)
.config(getConfiguration(collectedInstanceIds, processDefinition.getDeploymentId()))
.tenantId(tenantId)
.permission(BatchPermissions.CREATE_BATCH_MODIFY_PROCESS_INSTANCES) | .operationLogHandler((ctx, instanceCount) ->
writeUserOperationLog(ctx, processDefinition, instanceCount, true, annotation))
.build();
}
public BatchConfiguration getConfiguration(Collection<String> instanceIds, String deploymentId) {
return new ModificationBatchConfiguration(new ArrayList<>(instanceIds),
DeploymentMappings.of(new DeploymentMapping(deploymentId, instanceIds.size())),
builder.getProcessDefinitionId(),
builder.getInstructions(),
builder.isSkipCustomListeners(),
builder.isSkipIoMappings());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ProcessInstanceModificationBatchCmd.java | 1 |
请完成以下Java代码 | public Product getProduct() {
return this.pk.getProduct();
}
@Transient
public Double getTotalPrice() {
return getProduct().getPrice() * getQuantity();
}
public OrderProductPK getPk() {
return pk;
}
public void setPk(OrderProductPK pk) {
this.pk = pk;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
@Override
public int hashCode() {
final int prime = 31; | int result = 1;
result = prime * result + ((pk == null) ? 0 : pk.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
OrderProduct other = (OrderProduct) obj;
if (pk == null) {
if (other.pk != null) {
return false;
}
} else if (!pk.equals(other.pk)) {
return false;
}
return true;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\model\OrderProduct.java | 1 |
请完成以下Java代码 | public void postMaterialEvent_qtyDelivered(@NonNull final I_PP_Order ppOrderRecord)
{
final PPOrderChangedEvent changeEvent = PPOrderChangedEventFactory
.newWithPPOrderBeforeChange(ppOrderConverter, ppOrderRecord)
.inspectPPOrderAfterChange();
materialEventService.enqueueEventAfterNextCommit(changeEvent);
}
private void postPPOrderCreatedEvent(@NonNull final I_PP_Order ppOrderRecord, @NonNull final ModelChangeType type)
{
final boolean newPPOrder = type.isNew() || ModelChangeUtil.isJustActivated(ppOrderRecord);
if (!newPPOrder)
{
return;
} | if (isPPOrderCreatedFromCandidate(ppOrderRecord))
{
// dev-note: see org.eevolution.productioncandidate.service.produce.PPOrderProducerFromCandidate#postPPOrderCreatedEvent(I_PP_Order)
return;
}
ppOrderService.postPPOrderCreatedEvent(ppOrderRecord);
}
private boolean isPPOrderCreatedFromCandidate(@NonNull final I_PP_Order ppOrderRecord)
{
final ImmutableList<I_PP_OrderCandidate_PP_Order> orderAllocations = ppOrderDAO.getPPOrderAllocations(PPOrderId.ofRepoId(ppOrderRecord.getPP_Order_ID()));
return !orderAllocations.isEmpty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\validator\PP_Order_PostMaterialEvent.java | 1 |
请完成以下Java代码 | public void useStatement(){
try {
String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES ('%s','%s','%s');";
String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES ('%s','%s','%s');";
Statement statement = connection.createStatement();
for(int i = 0; i < EMPLOYEES.length; i++){
String employeeId = UUID.randomUUID().toString();
statement.addBatch(String.format(insertEmployeeSQL, employeeId, EMPLOYEES[i],DESIGNATIONS[i]));
statement.addBatch(String.format(insertEmployeeAddrSQL, UUID.randomUUID().toString(),employeeId,ADDRESSES[i]));
}
statement.executeBatch();
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException ex) {
System.out.println("Error during rollback");
System.out.println(ex.getMessage());
}
e.printStackTrace(System.out);
}
}
public void usePreparedStatement(){
try {
String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?);";
String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES (?,?,?);";
PreparedStatement employeeStmt = connection.prepareStatement(insertEmployeeSQL);
PreparedStatement empAddressStmt = connection.prepareStatement(insertEmployeeAddrSQL);
for(int i = 0; i < EMPLOYEES.length; i++){
String employeeId = UUID.randomUUID().toString();
employeeStmt.setString(1,employeeId);
employeeStmt.setString(2,EMPLOYEES[i]);
employeeStmt.setString(3,DESIGNATIONS[i]);
employeeStmt.addBatch(); | empAddressStmt.setString(1,UUID.randomUUID().toString());
empAddressStmt.setString(2,employeeId);
empAddressStmt.setString(3,ADDRESSES[i]);
empAddressStmt.addBatch();
}
employeeStmt.executeBatch();
empAddressStmt.executeBatch();
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException ex) {
System.out.println("Error during rollback");
System.out.println(ex.getMessage());
}
e.printStackTrace(System.out);
}
}
public static void main(String[] args) {
BatchProcessing batchProcessing = new BatchProcessing();
batchProcessing.getConnection();
batchProcessing.createTables();
batchProcessing.useStatement();
batchProcessing.usePreparedStatement();
}
} | repos\tutorials-master\persistence-modules\core-java-persistence\src\main\java\com\baeldung\spring\jdbc\BatchProcessing.java | 1 |
请完成以下Java代码 | public static void writeCriteriaElements(PlanItem planItem, XMLStreamWriter xtw) throws Exception {
if (!(planItem.getPlanItemDefinition() instanceof TimerEventListener)) {
// Timer event listeners are not allowed to have criteria.
// However the planItemStartTrigger is implemented as a fake criterion.
// Therefore we ignore writing the entry criteria elements for Timer Event listeners
writeEntryCriteriaElements(planItem.getEntryCriteria(), xtw);
}
writeExitCriteriaElements(planItem.getExitCriteria(), xtw);
}
public static void writeEntryCriteriaElements(List<Criterion> criterionList, XMLStreamWriter xtw) throws Exception {
writeCriteriaElements(ELEMENT_ENTRY_CRITERION, criterionList, xtw);
}
public static void writeExitCriteriaElements(List<Criterion> criterionList, XMLStreamWriter xtw) throws Exception {
writeCriteriaElements(ELEMENT_EXIT_CRITERION, criterionList, xtw);
}
public static void writeCriteriaElements(String criteriaElementLabel, List<Criterion> criterionList, XMLStreamWriter xtw) throws Exception {
for (Criterion criterion : criterionList) {
// start entry criterion element
xtw.writeStartElement(criteriaElementLabel);
xtw.writeAttribute(ATTRIBUTE_ID, criterion.getId());
if (StringUtils.isNotEmpty(criterion.getName())) {
xtw.writeAttribute(ATTRIBUTE_NAME, criterion.getName());
} | if (StringUtils.isNotEmpty(criterion.getSentryRef())) {
xtw.writeAttribute(ATTRIBUTE_SENTRY_REF, criterion.getSentryRef());
}
if (StringUtils.isNotEmpty(criterion.getExitType())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_EXIT_TYPE, criterion.getExitType());
}
if (StringUtils.isNotEmpty(criterion.getExitEventType())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_EXIT_EVENT_TYPE, criterion.getExitEventType());
}
// end entry criterion element
xtw.writeEndElement();
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\CriteriaExport.java | 1 |
请完成以下Java代码 | public final PInstanceId getSelectionToLock_AD_PInstance_ID()
{
return _recordsToLock.getSelection_PInstanceId();
}
@Override
public final Iterator<TableRecordReference> getRecordsToLockIterator()
{
return _recordsToLock.getRecordsIterator();
}
@Override
public LockCommand addRecordByModel(final Object model)
{
_recordsToLock.addRecordByModel(model);
return this; | }
@Override
public LockCommand addRecordsByModel(final Collection<?> models)
{
_recordsToLock.addRecordByModels(models);
return this;
}
@Override
public ILockCommand addRecord(@NonNull final TableRecordReference record)
{
_recordsToLock.addRecords(ImmutableSet.of(record));
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\LockCommand.java | 1 |
请完成以下Java代码 | public BatchDto setRetries(SetJobRetriesDto setJobRetriesDto) {
try {
EnsureUtil.ensureNotNull("setJobRetriesDto", setJobRetriesDto);
EnsureUtil.ensureNotNull("retries", setJobRetriesDto.getRetries());
} catch (NullValueException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
JobQuery jobQuery = null;
if (setJobRetriesDto.getJobQuery() != null) {
JobQueryDto jobQueryDto = setJobRetriesDto.getJobQuery();
jobQueryDto.setObjectMapper(getObjectMapper());
jobQuery = jobQueryDto.toQuery(getProcessEngine());
}
try {
SetJobRetriesByJobsAsyncBuilder builder = getProcessEngine().getManagementService()
.setJobRetriesByJobsAsync(setJobRetriesDto.getRetries().intValue())
.jobIds(setJobRetriesDto.getJobIds())
.jobQuery(jobQuery);
if(setJobRetriesDto.isDueDateSet()) {
builder.dueDate(setJobRetriesDto.getDueDate()); | }
Batch batch = builder.executeAsync();
return BatchDto.fromBatch(batch);
} catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
}
@Override
public void updateSuspensionState(JobSuspensionStateDto dto) {
if (dto.getJobId() != null) {
String message = "Either jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey can be set to update the suspension state.";
throw new InvalidRequestException(Status.BAD_REQUEST, message);
}
dto.updateSuspensionState(getProcessEngine());
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\JobRestServiceImpl.java | 1 |
请完成以下Java代码 | class TimeOutTask extends TimerTask {
private Thread t;
private Timer timer;
TimeOutTask(Thread t, Timer timer) {
this.t = t;
this.timer = timer;
}
public void run() {
if (t != null && t.isAlive()) {
t.interrupt();
timer.cancel();
}
}
}
class LongRunningTask implements Runnable {
@Override
public void run() {
longRunningSort();
}
private void longRunningSort() {
LOG.info("Long running task started");
int len = 100000;
List<Integer> numbers = new ArrayList<>();
try {
for (int i = len; i > 0; i--) {
//Thread.sleep(5)
numbers.add(i);
}
int i = 0;
for (i = 0; i < len; i++) {
int minIndex = i; | for (int j = i + 1; j < len; j++) {
if (numbers.get(minIndex) > numbers.get(j))
minIndex = j;
}
if (minIndex != i) {
int temp = numbers.get(i);
numbers.set(i, numbers.get(minIndex));
numbers.set(minIndex, temp);
}
throwExceptionOnThreadInterrupt();
}
LOG.info("Index position: " + i);
LOG.info("Long running task finished");
} catch (InterruptedException e) {
LOG.info("Long running operation interrupted");
}
}
private void throwExceptionOnThreadInterrupt() throws InterruptedException {
if (Thread.currentThread().interrupted()) {
throw new InterruptedException();
}
}
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-basic-2\src\main\java\com\baeldung\concurrent\stopexecution\StopExecution.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SpringbootHibernateOneOneMappingApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpringbootHibernateOneOneMappingApplication.class, args);
}
@Autowired
private UserRepository userRepository;
@Override
public void run(String... args) throws Exception {
// user object
User user = new User();
user.setName("Ramesh"); | user.setEmail("ramesh@gmail.com");
UserProfile userProfile = new UserProfile();
userProfile.setAddress("Pune");
userProfile.setBirthOfDate(LocalDate.of(1991, 03, 24));
userProfile.setGender(Gender.MALE);
userProfile.setPhoneNumber("1234567899");
user.setUserProfile(userProfile);
userProfile.setUser(user);
userRepository.save(user);
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot-hibernate-one-one-mapping\src\main\java\net\alanbinu\springboot\SpringbootHibernateOneOneMappingApplication.java | 2 |
请完成以下Java代码 | protected ScriptHttpHandler createScriptHttpHandler(ExpressionManager expressionManager, ScriptInfo scriptInfo) {
ScriptHttpHandler scriptHttpHandler = new ScriptHttpHandler(createExpression(expressionManager, scriptInfo.getLanguage()), scriptInfo.getScript());
if (scriptInfo.getResultVariable() != null) {
scriptHttpHandler.setResultVariable(createExpression(expressionManager, scriptInfo.getResultVariable()));
}
return scriptHttpHandler;
}
protected List<FieldDeclaration> createFieldDeclarations(List<FieldExtension> fieldList, ProcessEngineConfigurationImpl processEngineConfiguration) {
List<FieldDeclaration> fieldDeclarations = new ArrayList<>();
for (FieldExtension fieldExtension : fieldList) {
FieldDeclaration fieldDeclaration;
if (StringUtils.isNotEmpty(fieldExtension.getExpression())) {
fieldDeclaration = new FieldDeclaration(fieldExtension.getFieldName(), Expression.class.getName(),
processEngineConfiguration.getExpressionManager().createExpression(fieldExtension.getExpression()));
} else { | fieldDeclaration = new FieldDeclaration(fieldExtension.getFieldName(), Expression.class.getName(),
new FixedValue(fieldExtension.getStringValue()));
}
fieldDeclarations.add(fieldDeclaration);
}
return fieldDeclarations;
}
@Override
protected void propagateError(VariableContainer container, String code) {
ErrorPropagation.propagateError("HTTP" + code, (DelegateExecution) container);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\http\DefaultBpmnHttpActivityDelegate.java | 1 |
请完成以下Java代码 | public font addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the Element.
@param element adds and Element to the Element.
*/
public font addElement(String element)
{
addElementToRegistry(element);
return(this);
} | /**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public font removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\font.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HealthEndpointProperties extends HealthProperties {
/**
* When to show full health details.
*/
private Show showDetails = Show.NEVER;
/**
* Health endpoint groups.
*/
private final Map<String, Group> group = new LinkedHashMap<>();
private final Logging logging = new Logging();
@Override
public Show getShowDetails() {
return this.showDetails;
}
public void setShowDetails(Show showDetails) {
this.showDetails = showDetails;
}
public Map<String, Group> getGroup() {
return this.group;
}
public Logging getLogging() {
return this.logging;
}
/**
* A health endpoint group.
*/
public static class Group extends HealthProperties {
public static final String SERVER_PREFIX = "server:";
public static final String MANAGEMENT_PREFIX = "management:";
/**
* Health indicator IDs that should be included or '*' for all.
*/
private @Nullable Set<String> include;
/**
* Health indicator IDs that should be excluded or '*' for all.
*/
private @Nullable Set<String> exclude;
/**
* When to show full health details. Defaults to the value of
* 'management.endpoint.health.show-details'.
*/
private @Nullable Show showDetails;
/**
* Additional path that this group can be made available on. The additional path
* must start with a valid prefix, either `server` or `management` to indicate if
* it will be available on the main port or the management port. For instance,
* `server:/healthz` will configure the group on the main port at `/healthz`.
*/
private @Nullable String additionalPath;
public @Nullable Set<String> getInclude() {
return this.include;
}
public void setInclude(@Nullable Set<String> include) {
this.include = include;
}
public @Nullable Set<String> getExclude() {
return this.exclude;
} | public void setExclude(@Nullable Set<String> exclude) {
this.exclude = exclude;
}
@Override
public @Nullable Show getShowDetails() {
return this.showDetails;
}
public void setShowDetails(@Nullable Show showDetails) {
this.showDetails = showDetails;
}
public @Nullable String getAdditionalPath() {
return this.additionalPath;
}
public void setAdditionalPath(@Nullable String additionalPath) {
this.additionalPath = additionalPath;
}
}
/**
* Health logging properties.
*/
public static class Logging {
/**
* Threshold after which a warning will be logged for slow health indicators.
*/
private Duration slowIndicatorThreshold = Duration.ofSeconds(10);
public Duration getSlowIndicatorThreshold() {
return this.slowIndicatorThreshold;
}
public void setSlowIndicatorThreshold(Duration slowIndicatorThreshold) {
this.slowIndicatorThreshold = slowIndicatorThreshold;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\actuate\endpoint\HealthEndpointProperties.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.