instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
@Override
public void setHelp (java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return (java.lang.String)get_Value(COLUMNNAME_Help);
}
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
} | @Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setUIStyle (java.lang.String UIStyle)
{
set_Value (COLUMNNAME_UIStyle, UIStyle);
}
@Override
public java.lang.String getUIStyle()
{
return (java.lang.String)get_Value(COLUMNNAME_UIStyle);
}
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_Section.java | 1 |
请完成以下Java代码 | public int getM_DeliveryDay_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DeliveryDay_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (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 Gelieferte Menge.
@param QtyDelivered
Gelieferte Menge
*/
@Override
public void setQtyDelivered (java.math.BigDecimal QtyDelivered)
{
set_Value (COLUMNNAME_QtyDelivered, QtyDelivered);
}
/** Get Gelieferte Menge.
@return Gelieferte Menge
*/
@Override
public java.math.BigDecimal getQtyDelivered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyDelivered);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Bestellt/ Beauftragt.
@param QtyOrdered
Bestellt/ Beauftragt
*/
@Override
public void setQtyOrdered (java.math.BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
/** Get Bestellt/ Beauftragt.
@return Bestellt/ Beauftragt
*/
@Override
public java.math.BigDecimal getQtyOrdered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Ausliefermenge.
@param QtyToDeliver Ausliefermenge */
@Override
public void setQtyToDeliver (java.math.BigDecimal QtyToDeliver) | {
set_Value (COLUMNNAME_QtyToDeliver, QtyToDeliver);
}
/** Get Ausliefermenge.
@return Ausliefermenge */
@Override
public java.math.BigDecimal getQtyToDeliver ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToDeliver);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
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 Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_DeliveryDay_Alloc.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExprotController {
@GetMapping("/excel")
public void exportExcel(HttpServletResponse response) {
List<Person> list = new ArrayList<>();
list.add(new Person(1L, "姓名1", 28, "地址1"));
list.add(new Person(2L, "姓名2", 29, "地址2"));
String[] headers = new String[]{"ID", "名称", "年龄", "地址"};
List<String[]> contents = new ArrayList<>(list.size());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for (Person person : list) {
int i = 0;
String[] row = new String[headers.length];
row[i++] = person.getId() + "";
row[i++] = person.getName();
row[i++] = person.getAge() + "";
row[i++] = person.getAddress();
contents.add(row);
}
ExcelExportUtils.exportExcel("PersonInfo", headers, contents, response);
}
@GetMapping("/csv")
public void exportCsv(HttpServletResponse response) throws IOException {
String fileName = "PersonInfo";
List<String> titles = Arrays.asList("ID", "名称", "年龄", "地址");
List<Person> list = new ArrayList<>();
list.add(new Person(1L, "姓名1", 28, "地址1"));
list.add(new Person(2L, "姓名2", 29, "地址2")); | List<List<Object>> dataList = list.stream().map(person -> {
List<Object> data = new ArrayList<>();
data.add(person.getId());
data.add(person.getName());
data.add(person.getAge());
data.add(person.getAddress());
return data;
}).collect(Collectors.toList());
OutputStream os = response.getOutputStream();
CsvExportUtil.responseSetProperties(fileName, response);
CsvExportUtil.doExportByList(dataList, titles, os);
CsvExportUtil.doExportByList(dataList, null, os);
}
} | repos\spring-boot-student-master\spring-boot-student-export\src\main\java\com\xiaolyuh\ExprotController.java | 2 |
请完成以下Java代码 | public TypeSpec getStudentClass() {
return TypeSpec
.classBuilder("Student")
.addSuperinterface(ClassName.get(PERSON_PACKAGE_NAME, "Person"))
.addModifiers(Modifier.PUBLIC)
.addField(FieldSpec
.builder(String.class, "name")
.addModifiers(Modifier.PRIVATE)
.build())
.addMethod(MethodSpec
.methodBuilder("getName")
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.returns(String.class)
.addStatement("return this.name")
.build())
.addMethod(MethodSpec
.methodBuilder("setName")
.addParameter(String.class, "name")
.addModifiers(Modifier.PUBLIC)
.addStatement("this.name = name")
.build())
.addMethod(getPrintNameMultipleTimesMethod())
.addMethod(getSortByLengthMethod())
.build();
}
public TypeSpec getComparatorAnonymousClass() {
return TypeSpec
.anonymousClassBuilder("")
.addSuperinterface(ParameterizedTypeName.get(Comparator.class, String.class))
.addMethod(MethodSpec
.methodBuilder("compare")
.addModifiers(Modifier.PUBLIC) | .addAnnotation(Override.class)
.addParameter(String.class, "a")
.addParameter(String.class, "b")
.returns(int.class)
.addStatement("return a.length() - b.length()")
.build())
.build();
}
public void generateGenderEnum() throws IOException {
writeToOutputFile(getPersonPackageName(), getGenderEnum());
}
public void generatePersonInterface() throws IOException {
writeToOutputFile(getPersonPackageName(), getPersonInterface());
}
public void generateStudentClass() throws IOException {
writeToOutputFile(getPersonPackageName(), getStudentClass());
}
private void writeToOutputFile(String packageName, TypeSpec typeSpec) throws IOException {
JavaFile javaFile = JavaFile
.builder(packageName, typeSpec)
.skipJavaLangImports(true)
.indent(FOUR_WHITESPACES)
.build();
javaFile.writeTo(outputFile);
}
} | repos\tutorials-master\libraries-2\src\main\java\com\baeldung\javapoet\PersonGenerator.java | 1 |
请完成以下Java代码 | public ResponseEntity<JsonResponseBPRelationComposite> retrieveBPartner(
@ApiParam(required = true, value = ORG_CODE_PARAMETER_DOC)
@PathVariable("orgCode") //
@Nullable final String orgCode, // may be null if called from other metasfresh-code
@ApiParam(required = true, value = BPARTNER_IDENTIFIER_DOC) //
@PathVariable("bpartnerIdentifier") //
@NonNull final String bpartnerIdentifierStr)
{
final IdentifierString bpartnerIdentifier = IdentifierString.of(bpartnerIdentifierStr);
final OrgId orgId = RestUtils.retrieveOrgIdOrDefault(orgCode);
final JsonResponseBPRelationComposite result = bpRelationsService.getRelationsForPartner(orgId, bpartnerIdentifier);
return okOrNotFound(result);
}
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Successfully created or updated bpartner relation(s)"),
@ApiResponse(code = 401, message = "You are not authorized to create or update the resource"),
@ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
@ApiResponse(code = 422, message = "The request entity could not be processed")
}) | @PutMapping(value = "{bpartnerIdentifier}", consumes = "application/json")
public ResponseEntity<String> createOrUpdateBPartnerRelation(
@ApiParam(required = true, value = BPARTNER_IDENTIFIER_DOC) //
@PathVariable("bpartnerIdentifier") //
@NonNull final String bpartnerIdentifierStr,
@RequestBody @NonNull final JsonRequestBPRelationsUpsert bpartnerUpsertRequest)
{
final OrgId orgId = RestUtils.retrieveOrgIdOrDefault(bpartnerUpsertRequest.getOrgCode());
final IdentifierString bpartnerIdentifier = IdentifierString.of(bpartnerIdentifierStr);
final IdentifierString locationIdentifier = IdentifierString.ofOrNull(bpartnerUpsertRequest.getLocationIdentifier());
bpRelationsService.createOrUpdateRelations(orgId, bpartnerIdentifier, locationIdentifier, bpartnerUpsertRequest.getRelatesTo());
return new ResponseEntity<>("Ok", HttpStatus.CREATED);
}
private static ResponseEntity<JsonResponseBPRelationComposite> okOrNotFound(final JsonResponseBPRelationComposite optionalResult)
{
return optionalResult.getResponseItems().isEmpty() ? ResponseEntity.notFound().build() : ResponseEntity.ok(optionalResult);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\bpartner\relation\BpartnerRelationRestController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Customer extends BaseModel {
public Customer(String name, Address address) {
super();
this.name = name;
this.address = address;
}
private String name;
@OneToOne(cascade = CascadeType.ALL)
Address address;
public String getName() {
return name;
} | public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
}
} | repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\ebean\model\Customer.java | 2 |
请完成以下Java代码 | public int getM_InOutLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID);
}
@Override
public void setQtyDeliveredInUOM (final @Nullable BigDecimal QtyDeliveredInUOM)
{
set_Value (COLUMNNAME_QtyDeliveredInUOM, QtyDeliveredInUOM);
}
@Override
public BigDecimal getQtyDeliveredInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyEntered (final @Nullable BigDecimal QtyEntered)
{
set_Value (COLUMNNAME_QtyEntered, QtyEntered);
}
@Override
public BigDecimal getQtyEntered() | {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyInvoicedInUOM (final @Nullable BigDecimal QtyInvoicedInUOM)
{
set_Value (COLUMNNAME_QtyInvoicedInUOM, QtyInvoicedInUOM);
}
@Override
public BigDecimal getQtyInvoicedInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoicedInUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_CallOrderDetail.java | 1 |
请完成以下Java代码 | public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
ZooKeeper zk = new ZooKeeper(address, session_timeout, new Watcher() {
// 事件通知
@Override
public void process(WatchedEvent event) {
// 事件状态
Event.KeeperState state = event.getState();
// 连接状态
if (Event.KeeperState.SyncConnected == state) {
Event.EventType type = event.getType();
// 事件类型
if (Event.EventType.None == type) {
cout.countDown();
System.out.println("--------zk开始连接.");
}
}
} | });
cout.await();
//创建节点
String path="/test";
String create = zk.create(path, "fzp".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("-------创建节点: " + create);
System.out.println(new String(zk.getData(path,true,stat)));
System.out.println(stat.getCzxid()+","+ stat.getMzxid()+","+stat.getVersion());
zk.setData(path,"123".getBytes(),-1);
zk.close();
}
} | repos\SpringBootLearning-master\version2.x\springboot-zk-demo\src\main\java\io\github\forezp\springbootzkdemo\ZkTest.java | 1 |
请完成以下Java代码 | public class DefaultBatchToRecordAdapter<K, V> implements BatchToRecordAdapter<K, V> {
private static final LogAccessor LOGGER = new LogAccessor(DefaultBatchToRecordAdapter.class);
private final ConsumerRecordRecoverer recoverer;
/**
* Construct an instance with the default recoverer which simply logs the failed
* record.
*/
public DefaultBatchToRecordAdapter() {
this((record, ex) -> LOGGER.error(ex, () -> "Failed to process " + record));
}
/**
* Construct an instance with the provided recoverer.
* @param recoverer the recoverer.
*/
public DefaultBatchToRecordAdapter(ConsumerRecordRecoverer recoverer) {
Assert.notNull(recoverer, "'recoverer' cannot be null");
this.recoverer = recoverer;
}
@Override | public void adapt(List<Message<?>> messages, List<ConsumerRecord<K, V>> records, @Nullable Acknowledgment ack,
@Nullable Consumer<?, ?> consumer, Callback<K, V> callback) {
for (int i = 0; i < messages.size(); i++) {
Message<?> message = messages.get(i);
try {
callback.invoke(records.get(i), ack, consumer, message);
}
catch (Exception e) {
this.recoverer.accept(records.get(i), e);
}
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\adapter\DefaultBatchToRecordAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static final class CouchbaseUrlCondition {
}
@ConditionalOnBean(CouchbaseConnectionDetails.class)
private static final class CouchbaseConnectionDetailsCondition {
}
}
/**
* Adapts {@link CouchbaseProperties} to {@link CouchbaseConnectionDetails}.
*/
static final class PropertiesCouchbaseConnectionDetails implements CouchbaseConnectionDetails {
private final CouchbaseProperties properties;
private final @Nullable SslBundles sslBundles;
PropertiesCouchbaseConnectionDetails(CouchbaseProperties properties, @Nullable SslBundles sslBundles) {
this.properties = properties;
this.sslBundles = sslBundles;
}
@Override
public String getConnectionString() {
String connectionString = this.properties.getConnectionString();
Assert.state(connectionString != null, "'connectionString' must not be null");
return connectionString;
}
@Override
public @Nullable String getUsername() {
return this.properties.getUsername(); | }
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
@Override
public @Nullable SslBundle getSslBundle() {
Ssl ssl = this.properties.getEnv().getSsl();
if (!ssl.getEnabled()) {
return null;
}
if (StringUtils.hasLength(ssl.getBundle())) {
Assert.notNull(this.sslBundles, "SSL bundle name has been set but no SSL bundles found in context");
return this.sslBundles.getBundle(ssl.getBundle());
}
return SslBundle.systemDefault();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-couchbase\src\main\java\org\springframework\boot\couchbase\autoconfigure\CouchbaseAutoConfiguration.java | 2 |
请完成以下Java代码 | public void setParent_ID (int Parent_ID)
{
if (Parent_ID < 1)
set_Value (COLUMNNAME_Parent_ID, null);
else
set_Value (COLUMNNAME_Parent_ID, Integer.valueOf(Parent_ID));
}
/** Get Parent.
@return Parent of Entity
*/
@Override
public int getParent_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Parent_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Permission Issuer.
@param PermissionIssuer Permission Issuer */
@Override
public void setPermissionIssuer (java.lang.String PermissionIssuer)
{
set_Value (COLUMNNAME_PermissionIssuer, PermissionIssuer);
}
/** Get Permission Issuer.
@return Permission Issuer */
@Override
public java.lang.String getPermissionIssuer ()
{
return (java.lang.String)get_Value(COLUMNNAME_PermissionIssuer);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Root Entry.
@param Root_ID Root Entry */
@Override
public void setRoot_ID (int Root_ID)
{
if (Root_ID < 1) | set_Value (COLUMNNAME_Root_ID, null);
else
set_Value (COLUMNNAME_Root_ID, Integer.valueOf(Root_ID));
}
/** Get Root Entry.
@return Root Entry */
@Override
public int getRoot_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Root_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Record_Access.java | 1 |
请完成以下Java代码 | public void warning(SAXParseException spe) {
LOGGER.warning(getParseExceptionInfo(spe));
}
public void error(SAXParseException spe) throws SAXException {
String message = "Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}
public void fatalError(SAXParseException spe) throws SAXException {
String message = "Fatal Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}
}
/**
* Get an empty DOM document
*
* @param documentBuilderFactory the factory to build to DOM document
* @return the new empty document
* @throws ModelParseException if unable to create a new document
*/
public static DomDocument getEmptyDocument(DocumentBuilderFactory documentBuilderFactory) {
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
return new DomDocumentImpl(documentBuilder.newDocument());
} catch (ParserConfigurationException e) {
throw new ModelParseException("Unable to create a new document", e);
}
}
/**
* Create a new DOM document from the input stream
*
* @param documentBuilderFactory the factory to build to DOM document
* @param inputStream the input stream to parse
* @return the new DOM document
* @throws ModelParseException if a parsing or IO error is triggered
*/
public static DomDocument parseInputStream(DocumentBuilderFactory documentBuilderFactory, InputStream inputStream) { | try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
documentBuilder.setErrorHandler(new DomErrorHandler());
return new DomDocumentImpl(documentBuilder.parse(inputStream));
} catch (ParserConfigurationException e) {
throw new ModelParseException("ParserConfigurationException while parsing input stream", e);
} catch (SAXException e) {
throw new ModelParseException("SAXException while parsing input stream", e);
} catch (IOException e) {
throw new ModelParseException("IOException while parsing input stream", e);
}
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\util\DomUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CommissionHierarchyFactory
{
// very crude but simple implementation; expand and make more efficient as needed
@NonNull
public Hierarchy createForCustomer(@NonNull final BPartnerId bPartnerId, @NonNull final BPartnerId salesRepId)
{
if (bPartnerId.equals(salesRepId))
{
return createFor(salesRepId, Hierarchy.builder(), new HashSet<>());
}
final HierarchyBuilder hierarchyBuilder = Hierarchy.builder()
.addChildren(node(salesRepId), ImmutableList.of(node(bPartnerId)));
final HashSet<BPartnerId> seenBPartnerIds = new HashSet<>();
seenBPartnerIds.add(bPartnerId);
return createFor(
salesRepId/* starting point */,
hierarchyBuilder /* result builder */,
seenBPartnerIds /* helper to make sure we don't enter a cycle */
);
}
@NonNull
private Hierarchy createFor(
@NonNull final BPartnerId bPartnerId,
@NonNull final HierarchyBuilder hierarchyBuilder,
@NonNull final HashSet<BPartnerId> seenBPartnerIds)
{
if (!seenBPartnerIds.add(bPartnerId))
{
return hierarchyBuilder.build(); // there is a loop in our supposed tree; stoppping now, because we saw it all
} | final I_C_BPartner bPartnerRecord = loadOutOfTrx(bPartnerId, I_C_BPartner.class);
final BPartnerId parentBPartnerId = BPartnerId.ofRepoIdOrNull(bPartnerRecord.getC_BPartner_SalesRep_ID());
if (parentBPartnerId == null || seenBPartnerIds.contains(parentBPartnerId))
{
hierarchyBuilder.addChildren(node(bPartnerId), ImmutableList.of());
return hierarchyBuilder.build();
}
hierarchyBuilder.addChildren(node(parentBPartnerId), ImmutableList.of(node(bPartnerId)));
// recurse
createFor(parentBPartnerId, hierarchyBuilder, seenBPartnerIds);
return hierarchyBuilder.build();
}
private HierarchyNode node(@NonNull final BPartnerId bPartnerId)
{
return HierarchyNode.of(Beneficiary.of(bPartnerId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\hierarchy\CommissionHierarchyFactory.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public UserResponse updateUser(@ApiParam(name = "userId") @PathVariable String userId, @RequestBody UserRequest userRequest) {
User user = getUserFromRequest(userId);
if (userRequest.isEmailChanged()) {
user.setEmail(userRequest.getEmail());
}
if (userRequest.isFirstNameChanged()) {
user.setFirstName(userRequest.getFirstName());
}
if (userRequest.isLastNameChanged()) {
user.setLastName(userRequest.getLastName());
}
if (userRequest.isDisplayNameChanged()) {
user.setDisplayName(userRequest.getDisplayName());
}
if (userRequest.isPasswordChanged()) {
user.setPassword(userRequest.getPassword());
identityService.updateUserPassword(user);
} else {
identityService.saveUser(user);
} | return restResponseFactory.createUserResponse(user, false);
}
@ApiOperation(value = "Delete a user", tags = { "Users" }, code = 204)
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Indicates the user was found and has been deleted. Response-body is intentionally empty."),
@ApiResponse(code = 404, message = "Indicates the requested user was not found.")
})
@DeleteMapping("/users/{userId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteUser(@ApiParam(name = "userId") @PathVariable String userId) {
User user = getUserFromRequest(userId);
if (restApiInterceptor != null) {
restApiInterceptor.deleteUser(user);
}
identityService.deleteUser(user.getId());
}
} | repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\user\UserResource.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<QueryVariableValue> getQueryVariableValues() {
return queryVariableValues;
}
public boolean hasValueComparisonQueryVariables() {
for (QueryVariableValue qvv : queryVariableValues) {
if (!QueryOperator.EXISTS.toString().equals(qvv.getOperator()) && !QueryOperator.NOT_EXISTS.toString().equals(qvv.getOperator())) {
return true;
}
}
return false;
}
public boolean hasLocalQueryVariableValue() {
for (QueryVariableValue qvv : queryVariableValues) {
if (qvv.isLocal()) {
return true; | }
}
return false;
}
public boolean hasNonLocalQueryVariableValue() {
for (QueryVariableValue qvv : queryVariableValues) {
if (!qvv.isLocal()) {
return true;
}
}
return false;
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\AbstractVariableQueryImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private RegistrationStore registrationStore() {
return redisConfiguration.isPresent() ?
new TbLwM2mRedisRegistrationStore(config, getConnectionFactory(), modelProvider) :
new TbInMemoryRegistrationStore(config, config.getCleanPeriodInSec(), modelProvider);
}
@Bean
private TbMainSecurityStore securityStore() {
return new TbLwM2mSecurityStore(redisConfiguration.isPresent() ?
new TbLwM2mRedisSecurityStore(getConnectionFactory()) : new TbInMemorySecurityStore(), validator);
}
@Bean
private TbLwM2MClientStore clientStore() {
return redisConfiguration.isPresent() ? new TbRedisLwM2MClientStore(getConnectionFactory()) : new TbDummyLwM2MClientStore();
}
@Bean
private TbLwM2MModelConfigStore modelConfigStore() {
return redisConfiguration.isPresent() ? new TbRedisLwM2MModelConfigStore(getConnectionFactory()) : new TbDummyLwM2MModelConfigStore(); | }
@Bean
private TbLwM2MClientOtaInfoStore otaStore() {
return redisConfiguration.isPresent() ? new TbLwM2mRedisClientOtaInfoStore(getConnectionFactory()) : new TbDummyLwM2MClientOtaInfoStore();
}
@Bean
private TbLwM2MDtlsSessionStore sessionStore() {
return redisConfiguration.isPresent() ? new TbLwM2MDtlsSessionRedisStore(getConnectionFactory()) : new TbL2M2MDtlsSessionInMemoryStore();
}
private RedisConnectionFactory getConnectionFactory() {
return redisConfiguration.get().redisConnectionFactory();
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbLwM2mStoreFactory.java | 2 |
请完成以下Java代码 | public void removeVariables() {
Iterator<T> valuesIt = getVariablesMap().values().iterator();
removedVariables.putAll(variables);
while (valuesIt.hasNext()) {
T nextVariable = valuesIt.next();
valuesIt.remove();
for (VariableStoreObserver<T> observer : observers) {
observer.onRemove(nextVariable);
}
}
}
public void addObserver(VariableStoreObserver<T> observer) {
observers.add(observer);
}
public void removeObserver(VariableStoreObserver<T> observer) {
observers.remove(observer);
}
public static interface VariableStoreObserver<T extends CoreVariableInstance> { | void onAdd(T variable);
void onRemove(T variable);
}
public static interface VariablesProvider<T extends CoreVariableInstance> {
Collection<T> provideVariables();
Collection<T> provideVariables(Collection<String> variableNames);
}
public boolean isRemoved(String variableName) {
return removedVariables.containsKey(variableName);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\VariableStore.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Access route(String pattern) {
RSocketMessageHandler handler = getBean(RSocketMessageHandler.class);
PayloadExchangeMatcher matcher = new RoutePayloadExchangeMatcher(handler.getMetadataExtractor(),
handler.getRouteMatcher(), pattern);
return matcher(matcher);
}
public Access matcher(PayloadExchangeMatcher matcher) {
return new Access(matcher);
}
public final class Access {
private final PayloadExchangeMatcher matcher;
private Access(PayloadExchangeMatcher matcher) {
this.matcher = matcher;
}
public AuthorizePayloadsSpec authenticated() {
return access(AuthenticatedReactiveAuthorizationManager.authenticated());
}
public AuthorizePayloadsSpec hasAuthority(String authority) {
return access(AuthorityReactiveAuthorizationManager.hasAuthority(authority));
}
public AuthorizePayloadsSpec hasRole(String role) {
return access(AuthorityReactiveAuthorizationManager.hasRole(role));
}
public AuthorizePayloadsSpec hasAnyRole(String... roles) {
return access(AuthorityReactiveAuthorizationManager.hasAnyRole(roles));
}
public AuthorizePayloadsSpec permitAll() {
return access((a, ctx) -> Mono.just(new AuthorizationDecision(true)));
}
public AuthorizePayloadsSpec hasAnyAuthority(String... authorities) {
return access(AuthorityReactiveAuthorizationManager.hasAnyAuthority(authorities)); | }
public AuthorizePayloadsSpec access(
ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> authorization) {
AuthorizePayloadsSpec.this.authzBuilder
.add(new PayloadExchangeMatcherEntry<>(this.matcher, authorization));
return AuthorizePayloadsSpec.this;
}
public AuthorizePayloadsSpec denyAll() {
return access((a, ctx) -> Mono.just(new AuthorizationDecision(false)));
}
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\rsocket\RSocketSecurity.java | 2 |
请完成以下Java代码 | public final void putValue(String key, Object value)
{
// immutable, nothing to do
}
@Override
public final void setEnabled(boolean enabled)
{
// immutable, nothing to do
}
@Override
public final boolean isEnabled()
{
return true; | }
@Override
public final void addPropertyChangeListener(PropertyChangeListener listener)
{
// immutable, nothing to do
}
@Override
public final void removePropertyChangeListener(PropertyChangeListener listener)
{
// immutable, nothing to do
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\UIAction.java | 1 |
请完成以下Java代码 | public final class ImportRecordsSelection
{
@NonNull @Getter private final String importTableName;
@NonNull private final String importKeyColumnName;
@NonNull private final ClientId clientId;
@Nullable @Getter @With private final PInstanceId selectionId;
@Getter @With private final boolean empty;
/**
* @return `AND ...` where clause
*/
public String toSqlWhereClause() {return toSqlWhereClause0(importTableName, true);}
/**
* @return `AND ...` where clause
*/
public String toSqlWhereClause(@Nullable final String importTableAlias)
{
return toSqlWhereClause0(importTableAlias, true);
}
private String toSqlWhereClause0(@Nullable final String importTableAlias, final boolean prefixWithAND)
{
final String importTableAliasWithDot = StringUtils.trimBlankToOptional(importTableAlias).map(alias -> alias + ".").orElse("");
final StringBuilder whereClause = new StringBuilder();
if (prefixWithAND)
{
whereClause.append(" AND ");
}
whereClause.append("(");
if (empty)
{ | return "1=2";
}
else
{
// AD_Client
whereClause.append(importTableAliasWithDot).append(ImportTableDescriptor.COLUMNNAME_AD_Client_ID).append("=").append(clientId.getRepoId());
// Selection_ID
if (selectionId != null)
{
final String importKeyColumnNameFQ = importTableAliasWithDot + importKeyColumnName;
whereClause.append(" AND ").append(DB.createT_Selection_SqlWhereClause(selectionId, importKeyColumnNameFQ));
}
}
whereClause.append(")");
return whereClause.toString();
}
public IQueryFilter<Object> toQueryFilter(@Nullable final String importTableAlias)
{
return empty
? ConstantQueryFilter.of(false)
: TypedSqlQueryFilter.of(toSqlWhereClause0(importTableAlias, false));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\ImportRecordsSelection.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static Map<String, String> getAllRequestParam(final byte[] body) throws IOException {
if(body==null){
return null;
}
String wholeStr = new String(body);
// 转化成json对象
return JSONObject.parseObject(wholeStr.toString(), Map.class);
}
/**
* 将URL请求参数转换成Map
*
* @param request
*/
public static Map<String, String> getUrlParams(HttpServletRequest request) {
Map<String, String> result = new HashMap<>(16);
if (oConvertUtils.isEmpty(request.getQueryString())) {
return result;
}
String param = "";
try {
param = URLDecoder.decode(request.getQueryString(), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String[] params = param.split("&");
for (String s : params) {
int index = s.indexOf("=");
// 代码逻辑说明: [issues/5879]数据查询传ds=“”造成的异常------------
if (index != -1) {
result.put(s.substring(0, index), s.substring(index + 1));
}
}
return result;
}
/**
* 将URL请求参数转换成Map
*
* @param queryString
*/
public static Map<String, String> getUrlParams(String queryString) {
Map<String, String> result = new HashMap<>(16);
if (oConvertUtils.isEmpty(queryString)) { | return result;
}
String param = "";
try {
param = URLDecoder.decode(queryString, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String[] params = param.split("&");
for (String s : params) {
int index = s.indexOf("=");
// 代码逻辑说明: [issues/5879]数据查询传ds=“”造成的异常------------
if (index != -1) {
result.put(s.substring(0, index), s.substring(index + 1));
}
}
return result;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\sign\util\HttpUtils.java | 2 |
请完成以下Java代码 | public boolean remove(Object o)
{
return pipeList.remove(o);
}
@Override
public boolean containsAll(Collection<?> c)
{
return pipeList.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends Pipe<List<IWord>, List<IWord>>> c)
{
return pipeList.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends Pipe<List<IWord>, List<IWord>>> c)
{
return pipeList.addAll(c);
}
@Override
public boolean removeAll(Collection<?> c)
{
return pipeList.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c)
{
return pipeList.retainAll(c);
}
@Override
public void clear()
{
pipeList.clear();
}
@Override
public boolean equals(Object o)
{
return pipeList.equals(o);
}
@Override
public int hashCode()
{
return pipeList.hashCode();
}
@Override
public Pipe<List<IWord>, List<IWord>> get(int index)
{
return pipeList.get(index);
}
@Override
public Pipe<List<IWord>, List<IWord>> set(int index, Pipe<List<IWord>, List<IWord>> element)
{
return pipeList.set(index, element);
} | @Override
public void add(int index, Pipe<List<IWord>, List<IWord>> element)
{
pipeList.add(index, element);
}
@Override
public Pipe<List<IWord>, List<IWord>> remove(int index)
{
return pipeList.remove(index);
}
@Override
public int indexOf(Object o)
{
return pipeList.indexOf(o);
}
@Override
public int lastIndexOf(Object o)
{
return pipeList.lastIndexOf(o);
}
@Override
public ListIterator<Pipe<List<IWord>, List<IWord>>> listIterator()
{
return pipeList.listIterator();
}
@Override
public ListIterator<Pipe<List<IWord>, List<IWord>>> listIterator(int index)
{
return pipeList.listIterator(index);
}
@Override
public List<Pipe<List<IWord>, List<IWord>>> subList(int fromIndex, int toIndex)
{
return pipeList.subList(fromIndex, toIndex);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\SegmentPipeline.java | 1 |
请完成以下Java代码 | private static List<Optional<? extends AbstractTsKvEntity>> toResultList(EntityId entityId, String key, List<TimescaleTsKvEntity> timescaleTsKvEntities) {
if (!CollectionUtils.isEmpty(timescaleTsKvEntities)) {
List<Optional<? extends AbstractTsKvEntity>> result = new ArrayList<>();
timescaleTsKvEntities.forEach(entity -> {
if (entity != null && entity.isNotEmpty()) {
entity.setEntityId(entityId.getId());
entity.setStrKey(key);
result.add(Optional.of(entity));
} else {
result.add(Optional.empty());
}
});
return result;
} else {
return Collections.emptyList();
}
}
private List<TimescaleTsKvEntity> switchAggregation(String key, long startTs, long endTs, long timeBucket, Aggregation aggregation, UUID entityId) {
Integer keyId = keyDictionaryDao.getOrSaveKeyId(key); | switch (aggregation) {
case AVG:
return aggregationRepository.findAvg(entityId, keyId, timeBucket, startTs, endTs);
case MAX:
return aggregationRepository.findMax(entityId, keyId, timeBucket, startTs, endTs);
case MIN:
return aggregationRepository.findMin(entityId, keyId, timeBucket, startTs, endTs);
case SUM:
return aggregationRepository.findSum(entityId, keyId, timeBucket, startTs, endTs);
case COUNT:
return aggregationRepository.findCount(entityId, keyId, timeBucket, startTs, endTs);
default:
throw new IllegalArgumentException("Not supported aggregation type: " + aggregation);
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\timescale\TimescaleTimeseriesDao.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public List<String> getCategoryIn() {
return categoryIn;
}
public void setCategoryIn(List<String> categoryIn) {
this.categoryIn = categoryIn;
}
public List<String> getCategoryNotIn() {
return categoryNotIn;
}
public void setCategoryNotIn(List<String> categoryNotIn) {
this.categoryNotIn = categoryNotIn;
}
public Boolean getWithoutCategory() {
return withoutCategory;
}
public void setWithoutCategory(Boolean withoutCategory) {
this.withoutCategory = withoutCategory;
}
public String getRootScopeId() {
return rootScopeId;
}
public void setRootScopeId(String rootScopeId) { | this.rootScopeId = rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
}
public void setParentScopeId(String parentScopeId) {
this.parentScopeId = parentScopeId;
}
public Set<String> getScopeIds() {
return scopeIds;
}
public void setScopeIds(Set<String> scopeIds) {
this.scopeIds = scopeIds;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskQueryRequest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public HistoricTaskLogEntryBuilder executionId(String executionId) {
this.executionId = executionId;
return this;
}
@Override
public HistoricTaskLogEntryBuilder scopeId(String scopeId) {
this.scopeId = scopeId;
return this;
}
@Override
public HistoricTaskLogEntryBuilder scopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
return this;
}
@Override
public HistoricTaskLogEntryBuilder subScopeId(String subScopeId) {
this.subScopeId = subScopeId;
return this;
}
@Override
public HistoricTaskLogEntryBuilder scopeType(String scopeType) {
this.scopeType = scopeType;
return this;
}
@Override
public HistoricTaskLogEntryBuilder tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
@Override
public String getType() {
return type;
}
@Override
public String getTaskId() {
return taskId;
}
@Override
public Date getTimeStamp() {
return timeStamp;
}
@Override
public String getUserId() {
return userId;
}
@Override
public String getData() {
return data;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override | public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getScopeId() {
return scopeId;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void create() {
// add is not supported by default
throw new RuntimeException("Operation is not supported");
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\BaseHistoricTaskLogEntryBuilderImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | static class JacksonJsonEncoderSupplierConfiguration {
@Bean
JsonEncoderSupplier jacksonJsonEncoderSupplier(JsonMapper jsonMapper) {
return () -> new JacksonJsonEncoder(jsonMapper);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(ObjectMapper.class)
@Conditional(NoJacksonOrJackson2Preferred.class)
@Deprecated(since = "4.0.0", forRemoval = true)
@SuppressWarnings("removal")
static class Jackson2JsonEncoderSupplierConfiguration {
@Bean
JsonEncoderSupplier jackson2JsonEncoderSupplier(ObjectMapper objectMapper) {
return () -> new org.springframework.http.codec.json.Jackson2JsonEncoder(objectMapper);
}
}
static class NoJacksonOrJackson2Preferred extends AnyNestedCondition {
NoJacksonOrJackson2Preferred() {
super(ConfigurationPhase.PARSE_CONFIGURATION); | }
@ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper")
static class NoJackson {
}
@ConditionalOnProperty(name = "spring.graphql.rsocket.preferred-json-mapper", havingValue = "jackson2")
static class Jackson2Preferred {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-graphql\src\main\java\org\springframework\boot\graphql\autoconfigure\rsocket\GraphQlRSocketAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private void loadWebParsers() {
this.parsers.put(Elements.DEBUG, new DebugBeanDefinitionParser());
this.parsers.put(Elements.HTTP, new HttpSecurityBeanDefinitionParser());
this.parsers.put(Elements.HTTP_FIREWALL, new HttpFirewallBeanDefinitionParser());
this.parsers.put(Elements.FILTER_SECURITY_METADATA_SOURCE, new FilterInvocationSecurityMetadataSourceParser());
this.parsers.put(Elements.FILTER_CHAIN, new FilterChainBeanDefinitionParser());
this.filterChainMapBDD = new FilterChainMapBeanDefinitionDecorator();
this.parsers.put(Elements.CLIENT_REGISTRATIONS, new ClientRegistrationsBeanDefinitionParser());
this.parsers.put(Elements.RELYING_PARTY_REGISTRATIONS, new RelyingPartyRegistrationsBeanDefinitionParser());
}
private void loadWebSocketParsers() {
this.parsers.put(Elements.WEBSOCKET_MESSAGE_BROKER, new WebSocketMessageBrokerSecurityBeanDefinitionParser());
}
/**
* Check that the schema location declared in the source file being parsed matches the
* Spring Security version. The old 2.0 schema is not compatible with the 3.1 parser,
* so it is an error to explicitly use 2.0.
* <p>
* There are also differences between 3.0 and 3.1 which are sufficient that we report
* using 3.0 as an error too. It might be an error to declare spring-security.xsd as
* an alias, but you are only going to find that out when one of the sub parsers | * breaks.
* @param element the element that is to be parsed next
* @return true if we find a schema declaration that matches
*/
private boolean namespaceMatchesVersion(Element element) {
return matchesVersionInternal(element)
&& matchesVersionInternal(element.getOwnerDocument().getDocumentElement());
}
private boolean matchesVersionInternal(Element element) {
String schemaLocation = element.getAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation");
return schemaLocation.matches("(?m).*spring-security-7\\.0.*.xsd.*")
|| schemaLocation.matches("(?m).*spring-security.xsd.*")
|| !schemaLocation.matches("(?m).*spring-security.*");
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\SecurityNamespaceHandler.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Book implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String isbn;
@Enumerated(EnumType.STRING)
private BookStatus status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
} | public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title
+ ", isbn=" + isbn + ", status=" + status + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootMySqlSkipLocked\src\main\java\com\bookstore\entity\Book.java | 2 |
请完成以下Java代码 | public static String certTrimNewLines(String input) {
return input.replaceAll("-----BEGIN CERTIFICATE-----", "")
.replaceAll("\n", "")
.replaceAll("\r", "")
.replaceAll("-----END CERTIFICATE-----", "");
}
public static String certTrimNewLinesForChainInDeviceProfile(String input) {
return input.replaceAll("\n", "")
.replaceAll("\r", "")
.replaceAll("-----BEGIN CERTIFICATE-----", "-----BEGIN CERTIFICATE-----\n")
.replaceAll("-----END CERTIFICATE-----", "\n-----END CERTIFICATE-----\n")
.trim();
}
public static String pubkTrimNewLines(String input) {
return input.replaceAll("-----BEGIN PUBLIC KEY-----", "")
.replaceAll("\n", "")
.replaceAll("\r", "")
.replaceAll("-----END PUBLIC KEY-----", "");
}
public static String prikTrimNewLines(String input) {
return input.replaceAll("-----BEGIN EC PRIVATE KEY-----", "")
.replaceAll("\n", "")
.replaceAll("\r", "")
.replaceAll("-----END EC PRIVATE KEY-----", "");
} | public static String getSha3Hash(String data) {
String trimmedData = certTrimNewLines(data);
byte[] dataBytes = trimmedData.getBytes();
SHA3Digest md = new SHA3Digest(256);
md.reset();
md.update(dataBytes, 0, dataBytes.length);
byte[] hashedBytes = new byte[256 / 8];
md.doFinal(hashedBytes, 0);
String sha3Hash = ByteUtils.toHexString(hashedBytes);
return sha3Hash;
}
public static String getSha3Hash(String delim, String... tokens) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String token : tokens) {
if (token != null && !token.isEmpty()) {
if (first) {
first = false;
} else {
sb.append(delim);
}
sb.append(token);
}
}
return getSha3Hash(sb.toString());
}
} | repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\EncryptionUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String uri() {
return obtain(AtlasProperties::getUri, AtlasConfig.super::uri);
}
@Override
public Duration meterTTL() {
return obtain(AtlasProperties::getMeterTimeToLive, AtlasConfig.super::meterTTL);
}
@Override
public boolean lwcEnabled() {
return obtain(AtlasProperties::isLwcEnabled, AtlasConfig.super::lwcEnabled);
}
@Override
public Duration lwcStep() {
return obtain(AtlasProperties::getLwcStep, AtlasConfig.super::lwcStep);
}
@Override
public boolean lwcIgnorePublishStep() {
return obtain(AtlasProperties::isLwcIgnorePublishStep, AtlasConfig.super::lwcIgnorePublishStep);
} | @Override
public Duration configRefreshFrequency() {
return obtain(AtlasProperties::getConfigRefreshFrequency, AtlasConfig.super::configRefreshFrequency);
}
@Override
public Duration configTTL() {
return obtain(AtlasProperties::getConfigTimeToLive, AtlasConfig.super::configTTL);
}
@Override
public String configUri() {
return obtain(AtlasProperties::getConfigUri, AtlasConfig.super::configUri);
}
@Override
public String evalUri() {
return obtain(AtlasProperties::getEvalUri, AtlasConfig.super::evalUri);
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\atlas\AtlasPropertiesConfigAdapter.java | 2 |
请完成以下Java代码 | public class ResponseData<T> implements Serializable {
/**
* 响应状态码
*/
private Integer code;
/**
* 响应信息
*/
private String message;
/**
* 响应对象
*/
private T data;
private ResponseData() {
}
private ResponseData(T data) {
this.data = data;
}
private ResponseData(String message) {
this.message = message;
}
private ResponseData(Integer code, String message) {
this.code = code;
this.message = message;
}
private ResponseData(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message; | }
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public static ResponseData success() {
return new ResponseData(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMessage(), null);
}
public static <E> ResponseData<E> success(E object) {
return new ResponseData(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMessage(), object);
}
public static <E> ResponseData<E> success(Integer code, String message, E object) {
return new ResponseData(code, message, object);
}
public static ResponseData error() {
return new ResponseData(ResponseCode.FAILED.getCode(), ResponseCode.FAILED.getMessage(), null);
}
public static ResponseData error(ResponseCode code) {
return new ResponseData(code.getCode(), code.getMessage(), null);
}
public static ResponseData error(String message) {
return new ResponseData(ResponseCode.FAILED.getCode(), message, null);
}
public static ResponseData error(Integer code, String message) {
return new ResponseData(code, message, null);
}
public static <E> ResponseData<E> error(Integer code, String message, E object) {
return new ResponseData(code, message, object);
}
} | repos\spring-boot-quick-master\quick-flowable\src\main\java\com\quick\flowable\common\ResponseData.java | 1 |
请完成以下Java代码 | class ServletComponentScanRegistrar implements ImportBeanDefinitionRegistrar {
private static final String BEAN_NAME = "servletComponentRegisteringPostProcessor";
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
Set<String> packagesToScan = getPackagesToScan(importingClassMetadata);
if (registry.containsBeanDefinition(BEAN_NAME)) {
updatePostProcessor(registry, packagesToScan);
}
else {
addPostProcessor(registry, packagesToScan);
}
}
private void updatePostProcessor(BeanDefinitionRegistry registry, Set<String> packagesToScan) {
ServletComponentRegisteringPostProcessorBeanDefinition definition = (ServletComponentRegisteringPostProcessorBeanDefinition) registry
.getBeanDefinition(BEAN_NAME);
definition.addPackageNames(packagesToScan);
}
private void addPostProcessor(BeanDefinitionRegistry registry, Set<String> packagesToScan) {
ServletComponentRegisteringPostProcessorBeanDefinition definition = new ServletComponentRegisteringPostProcessorBeanDefinition(
packagesToScan);
registry.registerBeanDefinition(BEAN_NAME, definition);
}
private Set<String> getPackagesToScan(AnnotationMetadata metadata) {
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(metadata.getAnnotationAttributes(ServletComponentScan.class.getName()));
Assert.state(attributes != null, "'attributes' must not be null");
String[] basePackages = attributes.getStringArray("basePackages");
Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses");
Set<String> packagesToScan = new LinkedHashSet<>(Arrays.asList(basePackages));
for (Class<?> basePackageClass : basePackageClasses) {
packagesToScan.add(ClassUtils.getPackageName(basePackageClass)); | }
if (packagesToScan.isEmpty()) {
packagesToScan.add(ClassUtils.getPackageName(metadata.getClassName()));
}
return packagesToScan;
}
static final class ServletComponentRegisteringPostProcessorBeanDefinition extends RootBeanDefinition {
private final Set<String> packageNames = new LinkedHashSet<>();
ServletComponentRegisteringPostProcessorBeanDefinition(Collection<String> packageNames) {
setBeanClass(ServletComponentRegisteringPostProcessor.class);
setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
addPackageNames(packageNames);
}
@Override
public Supplier<?> getInstanceSupplier() {
return () -> new ServletComponentRegisteringPostProcessor(this.packageNames);
}
private void addPackageNames(Collection<String> additionalPackageNames) {
this.packageNames.addAll(additionalPackageNames);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\context\ServletComponentScanRegistrar.java | 1 |
请完成以下Java代码 | public TaxCategoryId getTaxCategoryId(@NonNull final I_M_ProductPrice productPrice)
{
return getTaxCategoryIdOptional(productPrice)
.orElseThrow(() -> new AdempiereException(msgBL.getTranslatableMsgText(MSG_NO_C_TAX_CATEGORY_FOR_PRODUCT_PRICE))
.appendParametersToMessage()
.setParameter("productPriceId", productPrice.getM_ProductPrice_ID())
.setParameter("productId", productPrice.getM_Product_ID())
.setParameter("priceListVersionId", productPrice.getM_PriceList_Version_ID()));
}
@NonNull
public Optional<TaxCategoryId> getTaxCategoryIdOptional(@NonNull final I_M_ProductPrice productPrice)
{
final TaxCategoryId productPriceTaxCategoryId = TaxCategoryId.ofRepoIdOrNull(productPrice.getC_TaxCategory_ID());
if (productPriceTaxCategoryId != null)
{
return Optional.of(productPriceTaxCategoryId);
}
return findTaxCategoryId(productPrice);
}
@NonNull
public Optional<TaxCategoryId> findTaxCategoryId(@NonNull final LookupTaxCategoryRequest lookupTaxCategoryRequest)
{
return productTaxCategoryRepository.getTaxCategoryId(lookupTaxCategoryRequest);
}
@NonNull
public Stream<ProductTaxCategory> findAllFor(@NonNull final I_M_ProductPrice productPrice)
{
return productTaxCategoryRepository.findAllFor(createLookupTaxCategoryRequest(productPrice));
}
@NonNull
private Optional<TaxCategoryId> findTaxCategoryId(@NonNull final I_M_ProductPrice productPrice)
{
return productTaxCategoryRepository.getTaxCategoryId(createLookupTaxCategoryRequest(productPrice));
} | @NonNull
private LookupTaxCategoryRequest createLookupTaxCategoryRequest(@NonNull final I_M_ProductPrice productPrice)
{
final ProductId productId = ProductId.ofRepoId(productPrice.getM_Product_ID());
final PriceListVersionId priceListVersionId = PriceListVersionId.ofRepoId(productPrice.getM_PriceList_Version_ID());
final I_M_PriceList_Version priceListVersionRecord = priceListDAO.getPriceListVersionById(priceListVersionId);
final I_M_PriceList priceListRecord = priceListDAO.getById(priceListVersionRecord.getM_PriceList_ID());
return LookupTaxCategoryRequest.builder()
.productId(productId)
.targetDate(TimeUtil.asInstant(priceListVersionRecord.getValidFrom()))
.countryId(CountryId.ofRepoIdOrNull(priceListRecord.getC_Country_ID()))
.build();
}
@NonNull
public Optional<ProductTaxCategory> getProductTaxCategoryByUniqueKey(
@NonNull final ProductId productId,
@NonNull final CountryId countryId)
{
return productTaxCategoryRepository.getProductTaxCategoryByUniqueKey(productId, countryId);
}
public void save(@NonNull final ProductTaxCategory request)
{
productTaxCategoryRepository.save(request);
}
@NonNull
public ProductTaxCategory createProductTaxCategory(@NonNull final CreateProductTaxCategoryRequest createProductTaxCategoryRequest)
{
return productTaxCategoryRepository.createProductTaxCategory(createProductTaxCategoryRequest);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\tax\ProductTaxCategoryService.java | 1 |
请完成以下Java代码 | public static Path fileOutOnePath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.CSV_ONE).toURI();
return Paths.get(uri);
}
// Read Files
public static Path twoColumnCsvPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.TWO_COLUMN_CSV).toURI();
return Paths.get(uri);
}
public static Path fourColumnCsvPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.FOUR_COLUMN_CSV).toURI();
return Paths.get(uri);
}
public static Path namedColumnCsvPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.NAMED_COLUMN_CSV).toURI();
return Paths.get(uri);
}
public static String readFile(Path path) throws IOException {
return IOUtils.toString(path.toUri()); | }
// Dummy Data for Writing
public static List<String[]> twoColumnCsvString() {
List<String[]> list = new ArrayList<>();
list.add(new String[]{"ColA", "ColB"});
list.add(new String[]{"A", "B"});
return list;
}
public static List<String[]> fourColumnCsvString() {
List<String[]> list = new ArrayList<>();
list.add(new String[]{"ColA", "ColB", "ColC", "ColD"});
list.add(new String[]{"A", "B", "A", "B"});
list.add(new String[]{"BB", "AB", "AA", "B"});
return list;
}
} | repos\tutorials-master\libraries-data-io\src\main\java\com\baeldung\libraries\opencsv\helpers\Helpers.java | 1 |
请完成以下Java代码 | public class ApplicationReader {
private List<ApplicationEntryDiscovery> applicationEntryDiscoveries;
public ApplicationReader(List<ApplicationEntryDiscovery> applicationEntryDiscoveries) {
this.applicationEntryDiscoveries = applicationEntryDiscoveries;
}
public ApplicationContent read(InputStream inputStream) {
ApplicationContent application = new ApplicationContent();
try (ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
ZipEntry currentEntry = zipEntry;
applicationEntryDiscoveries
.stream()
.filter(applicationEntryDiscovery ->
applicationEntryDiscovery.filter(currentEntry).test(currentEntry)
)
.findFirst()
.ifPresent(applicationEntryDiscovery -> | application.add(
new ApplicationEntry(
applicationEntryDiscovery.getEntryType(),
new FileContent(currentEntry.getName(), readBytes(zipInputStream))
)
)
);
}
} catch (IOException e) {
throw new ApplicationLoadException("Unable to read zip file", e);
}
return application;
}
private byte[] readBytes(ZipInputStream zipInputStream) {
try {
return StreamUtils.copyToByteArray(zipInputStream);
} catch (IOException e) {
throw new ApplicationLoadException("Unable to read zip file", e);
}
}
} | repos\Activiti-develop\activiti-core-common\activiti-spring-application\src\main\java\org\activiti\application\ApplicationReader.java | 1 |
请完成以下Java代码 | public class CatTracer implements Tracer {
public ScopeManager scopeManager() {
return null;
}
public Span activeSpan() {
return null;
}
public Scope activateSpan(Span span) {
return null;
}
public SpanBuilder buildSpan(String operationName) { | return new CatSpanBuilder(operationName);
}
public <C> void inject(SpanContext spanContext, Format<C> format, C carrier) {
}
public <C> SpanContext extract(Format<C> format, C carrier) {
return null;
}
public void close() {
}
} | repos\SpringBoot-Labs-master\lab-61\lab-61-cat-opentracing\src\main\java\cn\iocoder\springboot\lab61\cat\opentracing\CatTracer.java | 1 |
请完成以下Java代码 | public <V> V get(Object key) {
return hasKey(key) ? (V) this.context.get(key) : null;
}
@Override
public boolean hasKey(Object key) {
Assert.notNull(key, "key cannot be null");
return this.context.containsKey(key);
}
/**
* Returns a new {@link Builder}.
* @return the {@link Builder}
*/
public static Builder builder() {
return new Builder();
}
/**
* A builder for {@link DefaultOAuth2TokenContext}. | */
public static final class Builder extends AbstractBuilder<DefaultOAuth2TokenContext, Builder> {
private Builder() {
}
/**
* Builds a new {@link DefaultOAuth2TokenContext}.
* @return the {@link DefaultOAuth2TokenContext}
*/
@Override
public DefaultOAuth2TokenContext build() {
return new DefaultOAuth2TokenContext(getContext());
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\DefaultOAuth2TokenContext.java | 1 |
请完成以下Java代码 | public class PrinterHW implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private List<PrinterHWMediaSize> printerHWMediaSizes;
private List<PrinterHWMediaTray> printerHWMediaTrays;
public PrinterHW()
{
super();
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public List<PrinterHWMediaSize> getPrinterHWMediaSizes()
{
return this.printerHWMediaSizes;
}
public void setPrinterHWMediaSizes(List<PrinterHWMediaSize> printerHWMediaSizes)
{
this.printerHWMediaSizes = printerHWMediaSizes;
}
public List<PrinterHWMediaTray> getPrinterHWMediaTrays()
{
return this.printerHWMediaTrays;
}
public void setPrinterHWMediaTrays(List<PrinterHWMediaTray> printerHWMediaTrays)
{
this.printerHWMediaTrays = printerHWMediaTrays;
}
@Override
public String toString()
{
return "PrinterHW [name=" + name + ", printerHWMediaSizes=" + printerHWMediaSizes + ", printerHWMediaTrays=" + printerHWMediaTrays + "]";
}
/**
* Printer HW Media Size Object
*
* @author al
*/
public static class PrinterHWMediaSize implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 5962990173434911764L;
private String name;
private String isDefault;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getIsDefault()
{
return isDefault;
}
public void setIsDefault(String isDefault)
{
this.isDefault = isDefault;
}
@Override
public String toString()
{ | return "PrinterHWMediaSize [name=" + name + ", isDefault=" + isDefault + "]";
}
}
/**
* Printer HW Media Tray Object
*
* @author al
*/
public static class PrinterHWMediaTray implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -1833627999553124042L;
private String name;
private String trayNumber;
private String isDefault;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getTrayNumber()
{
return trayNumber;
}
public void setTrayNumber(String trayNumber)
{
this.trayNumber = trayNumber;
}
public String getIsDefault()
{
return isDefault;
}
public void setIsDefault(String isDefault)
{
this.isDefault = isDefault;
}
@Override
public String toString()
{
return "PrinterHWMediaTray [name=" + name + ", trayNumber=" + trayNumber + ", isDefault=" + isDefault + "]";
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrinterHW.java | 1 |
请完成以下Java代码 | public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void setContent(InputStream content, Integer length) {
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
try {
StreamUtil.copy(content, byteOutputStream);
byte[] temp = byteOutputStream.toByteArray();
if (temp.length > length) {
this.content = new byte[length];
System.arraycopy(temp, 0, this.content, 0, length);
} else {
this.content = temp;
} | } catch (IOException e) {
LOG.error("异常", e);
}
}
/**
* 如果成功,则可以靠这个方法将数据输出
*
* @param out 调用者给的输出流
* @throws IOException 写流出现异常
*/
public void writeTo(OutputStream out) throws IOException {
out.write(this.content);
out.flush();
out.close();
}
} | repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\response\DownloadMediaResponse.java | 1 |
请完成以下Java代码 | public void setVariables(String processId, Map<String, Object> variables) {
Map<String, TypedValueField> typedValueDtoMap = typedValues.serializeVariables(variables);
SetVariablesRequestDto payload = new SetVariablesRequestDto(workerId, typedValueDtoMap);
String resourcePath = SET_VARIABLES_RESOURCE_PATH.replace("{id}", processId);
String resourceUrl = getBaseUrl() + resourcePath;
engineInteraction.postRequest(resourceUrl, payload, Void.class);
}
public void failure(String taskId,
String errorMessage,
String errorDetails,
int retries,
long retryTimeout,
Map<String, Object> variables,
Map<String, Object> localVariables) {
Map<String, TypedValueField> typedValueDtoMap = typedValues.serializeVariables(variables);
Map<String, TypedValueField> localTypedValueDtoMap = typedValues.serializeVariables(localVariables);
FailureRequestDto payload = new FailureRequestDto(workerId, errorMessage, errorDetails, retries, retryTimeout,
typedValueDtoMap, localTypedValueDtoMap);
String resourcePath = FAILURE_RESOURCE_PATH.replace("{id}", taskId);
String resourceUrl = getBaseUrl() + resourcePath;
engineInteraction.postRequest(resourceUrl, payload, Void.class);
}
public void bpmnError(String taskId, String errorCode, String errorMessage, Map<String, Object> variables) {
Map<String, TypedValueField> typeValueDtoMap = typedValues.serializeVariables(variables);
BpmnErrorRequestDto payload = new BpmnErrorRequestDto(workerId, errorCode, errorMessage, typeValueDtoMap);
String resourcePath = BPMN_ERROR_RESOURCE_PATH.replace("{id}", taskId);
String resourceUrl = getBaseUrl() + resourcePath;
engineInteraction.postRequest(resourceUrl, payload, Void.class);
}
public void extendLock(String taskId, long newDuration) {
ExtendLockRequestDto payload = new ExtendLockRequestDto(workerId, newDuration);
String resourcePath = EXTEND_LOCK_RESOURCE_PATH.replace("{id}", taskId);
String resourceUrl = getBaseUrl() + resourcePath;
engineInteraction.postRequest(resourceUrl, payload, Void.class);
} | public byte[] getLocalBinaryVariable(String variableName, String executionId) {
String resourcePath = getBaseUrl() + GET_BINARY_VARIABLE
.replace(ID_PATH_PARAM, executionId)
.replace(NAME_PATH_PARAM, variableName);
return engineInteraction.getRequest(resourcePath);
}
public String getBaseUrl() {
return urlResolver.getBaseUrl();
}
public String getWorkerId() {
return workerId;
}
public void setTypedValues(TypedValues typedValues) {
this.typedValues = typedValues;
}
public boolean isUsePriority() {
return usePriority;
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\EngineClient.java | 1 |
请完成以下Java代码 | public void perform()
{
pickingCandidates.stream()
.filter(this::isEligible)
.forEach(this::close);
//
// Release the picking slots
final Set<PickingSlotId> pickingSlotIds = PickingCandidate.extractPickingSlotIds(pickingCandidates);
huPickingSlotBL.releasePickingSlotsIfPossible(pickingSlotIds);
}
private boolean isEligible(final PickingCandidate pickingCandidate)
{
return pickingCandidate.isProcessed()
&& (pickingSlotIsRackSystem == null || pickingSlotIsRackSystem == isPickingSlotRackSystem(pickingCandidate));
}
private boolean isPickingSlotRackSystem(final PickingCandidate pickingCandidate)
{
final PickingSlotId pickingSlotId = pickingCandidate.getPickingSlotId();
return pickingSlotId != null && huPickingSlotBL.isPickingRackSystem(pickingSlotId);
}
private void close(final PickingCandidate pickingCandidate)
{
try
{
pickingCandidate.assertProcessed();
final PickingSlotId pickingSlotId = pickingCandidate.getPickingSlotId();
if (pickingSlotId != null)
{
huPickingSlotBL.addToPickingSlotQueue(pickingSlotId, pickingCandidate.getPackedToHuId());
} | changeStatusToProcessedAndSave(pickingCandidate);
}
catch (final Exception ex)
{
if (failOnError)
{
throw AdempiereException.wrapIfNeeded(ex).setParameter("pickingCandidate", pickingCandidate);
}
else
{
logger.warn("Failed closing {}. Skipped", pickingCandidate, ex);
}
}
}
private void changeStatusToProcessedAndSave(final PickingCandidate pickingCandidate)
{
pickingCandidate.changeStatusToClosed();
pickingCandidateRepository.save(pickingCandidate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\ClosePickingCandidateCommand.java | 1 |
请完成以下Java代码 | public class CustomPair {
private String key;
private String value;
public CustomPair(String key, String value) {
super();
this.key = key;
this.value = value;
}
public String getKey() {
return key;
} | public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Object[] getPair() {
return new Object[] { this.key, this.value};
}
} | repos\tutorials-master\core-java-modules\core-java-methods\src\main\java\com\baeldung\pairs\CustomPair.java | 1 |
请完成以下Java代码 | private static String getStrNum(int num) {
String s = String.format("%0" + NUM_LENGTH + "d", num);
return s;
}
/**
* 递增获取下个数字
*
* @param num
* @return
*/
private static int getNextNum(int num) {
num++;
return num;
}
/**
* 递增获取下个字母
*
* @param num
* @return
*/
private static char getNextZiMu(char zimu) {
if (zimu == LETTER) {
return 'A';
}
zimu++;
return zimu;
}
/**
* 根据数字位数获取最大值
* @param length
* @return
*/
private static int getMaxNumByLength(int length){
if(length==0){
return 0;
}
StringBuilder maxNum = new StringBuilder();
for (int i=0;i<length;i++){ | maxNum.append("9");
}
return Integer.parseInt(maxNum.toString());
}
public static String[] cutYouBianCode(String code){
if(code==null || StringUtil.isNullOrEmpty(code)){
return null;
}else{
//获取标准长度为numLength+1,截取的数量为code.length/numLength+1
int c = code.length()/(NUM_LENGTH +1);
String[] cutcode = new String[c];
for(int i =0 ; i <c;i++){
cutcode[i] = code.substring(0,(i+1)*(NUM_LENGTH +1));
}
return cutcode;
}
}
// public static void main(String[] args) {
// // org.jeecgframework.core.util.LogUtil.info(getNextZiMu('C'));
// // org.jeecgframework.core.util.LogUtil.info(getNextNum(8));
// // org.jeecgframework.core.util.LogUtil.info(cutYouBianCode("C99A01B01")[2]);
// }
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\YouBianCodeUtil.java | 1 |
请完成以下Java代码 | private void assertPresent(boolean present, Range<?> range) {
Assert.state(present, () -> "Could not get random number for range '" + range + "'");
}
private Object getRandomBytes() {
byte[] bytes = new byte[16];
getSource().nextBytes(bytes);
return HexFormat.of().withLowerCase().formatHex(bytes);
}
/**
* Add a {@link RandomValuePropertySource} to the given {@link Environment}.
* @param environment the environment to add the random property source to
*/
public static void addToEnvironment(ConfigurableEnvironment environment) {
addToEnvironment(environment, logger);
}
/**
* Add a {@link RandomValuePropertySource} to the given {@link Environment}.
* @param environment the environment to add the random property source to
* @param logger logger used for debug and trace information
* @since 4.0.0
*/
public static void addToEnvironment(ConfigurableEnvironment environment, Log logger) {
MutablePropertySources sources = environment.getPropertySources();
PropertySource<?> existing = sources.get(RANDOM_PROPERTY_SOURCE_NAME);
if (existing != null) {
logger.trace("RandomValuePropertySource already present");
return;
}
RandomValuePropertySource randomSource = new RandomValuePropertySource(RANDOM_PROPERTY_SOURCE_NAME);
if (sources.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME) != null) {
sources.addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, randomSource);
}
else {
sources.addLast(randomSource);
}
logger.trace("RandomValuePropertySource add to Environment");
}
static final class Range<T extends Number> { | private final String value;
private final T min;
private final T max;
private Range(String value, T min, T max) {
this.value = value;
this.min = min;
this.max = max;
}
T getMin() {
return this.min;
}
T getMax() {
return this.max;
}
@Override
public String toString() {
return this.value;
}
static <T extends Number & Comparable<T>> Range<T> of(String value, Function<String, T> parse) {
T zero = parse.apply("0");
String[] tokens = StringUtils.commaDelimitedListToStringArray(value);
T min = parse.apply(tokens[0]);
if (tokens.length == 1) {
Assert.state(min.compareTo(zero) > 0, "Bound must be positive.");
return new Range<>(value, zero, min);
}
T max = parse.apply(tokens[1]);
Assert.state(min.compareTo(max) < 0, "Lower bound must be less than upper bound.");
return new Range<>(value, min, max);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\RandomValuePropertySource.java | 1 |
请完成以下Java代码 | public class CorporateAction9 {
@XmlElement(name = "EvtTp", required = true)
protected String evtTp;
@XmlElement(name = "EvtId", required = true)
protected String evtId;
/**
* Gets the value of the evtTp property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEvtTp() {
return evtTp;
}
/**
* Sets the value of the evtTp property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEvtTp(String value) {
this.evtTp = value;
}
/**
* Gets the value of the evtId property.
* | * @return
* possible object is
* {@link String }
*
*/
public String getEvtId() {
return evtId;
}
/**
* Sets the value of the evtId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEvtId(String value) {
this.evtId = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CorporateAction9.java | 1 |
请完成以下Java代码 | private boolean canReadProcessInstance(org.activiti.engine.runtime.ProcessInstance processInstance) {
return (
securityPoliciesManager.canRead(processInstance.getProcessDefinitionKey()) &&
(securityManager.getAuthenticatedUserId().equals(processInstance.getStartUserId()) ||
isATaskAssigneeOrACandidate(processInstance.getProcessInstanceId()))
);
}
private boolean canWriteProcessInstance(org.activiti.engine.runtime.ProcessInstance processInstance) {
return (
securityPoliciesManager.canWrite(processInstance.getProcessDefinitionKey()) &&
securityManager.getAuthenticatedUserId().equals(processInstance.getStartUserId())
);
}
private boolean isATaskAssigneeOrACandidate(String processInstanceId) {
String authenticatedUserId = securityManager.getAuthenticatedUserId();
TaskQuery taskQuery = taskService.createTaskQuery().processInstanceId(processInstanceId); | taskQuery
.or()
.taskCandidateOrAssigned(
securityManager.getAuthenticatedUserId(),
securityManager.getAuthenticatedUserGroups()
)
.taskOwner(authenticatedUserId)
.endOr();
return taskQuery.count() > 0;
}
private List<String> getCurrentUserGroupsIncludingEveryOneGroup() {
List<String> groups = new ArrayList<>(securityManager.getAuthenticatedUserGroups());
groups.add(EVERYONE_GROUP);
return groups;
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\impl\ProcessRuntimeImpl.java | 1 |
请完成以下Java代码 | public List<JSONAttachment> getAttachments(
@PathVariable("windowId") final String windowIdStr //
, @PathVariable("documentId") final String documentId //
)
{
userSession.assertLoggedIn();
final DocumentPath documentPath = DocumentPath.rootDocumentPath(WindowId.fromJson(windowIdStr), documentId);
if (documentPath.isComposedKey())
{
// document with composed keys does not support attachments
return ImmutableList.of();
}
final boolean allowDelete = isAllowDeletingAttachments();
final List<JSONAttachment> attachments = getDocumentAttachments(documentPath)
.toJson();
attachments.forEach(attachment -> attachment.setAllowDelete(allowDelete));
return attachments;
}
private boolean isAllowDeletingAttachments()
{
return userSession
.getUserRolePermissions()
.hasPermission(IUserRolePermissions.PERMISSION_IsAttachmentDeletionAllowed);
}
@GetMapping("/{id}")
public ResponseEntity<StreamingResponseBody> getAttachmentById(
@PathVariable("windowId") final String windowIdStr //
, @PathVariable("documentId") final String documentId //
, @PathVariable("id") final String entryIdStr)
{
userSession.assertLoggedIn();
final DocumentId entryId = DocumentId.of(entryIdStr.toUpperCase());
final IDocumentAttachmentEntry entry = getDocumentAttachments(windowIdStr, documentId)
.getEntry(entryId); | return toResponseBody(entry);
}
@NonNull
private static ResponseEntity<StreamingResponseBody> toResponseBody(@NonNull final IDocumentAttachmentEntry entry)
{
final AttachmentEntryType type = entry.getType();
switch (type)
{
case Data:
return DocumentAttachmentRestControllerHelper.extractResponseEntryFromData(entry);
case URL:
return DocumentAttachmentRestControllerHelper.extractResponseEntryFromURL(entry);
case LocalFileURL:
return DocumentAttachmentRestControllerHelper.extractResponseEntryFromLocalFileURL(entry);
default:
throw new AdempiereException("Invalid attachment entry")
.setParameter("reason", "invalid type")
.setParameter("type", type)
.setParameter("entry", entry);
}
}
@DeleteMapping("/{id}")
public void deleteAttachmentById(
@PathVariable("windowId") final String windowIdStr //
, @PathVariable("documentId") final String documentId //
, @PathVariable("id") final String entryIdStr //
)
{
userSession.assertLoggedIn();
if (!isAllowDeletingAttachments())
{
throw new AdempiereException("Delete not allowed");
}
final DocumentId entryId = DocumentId.of(entryIdStr);
getDocumentAttachments(windowIdStr, documentId)
.deleteEntry(entryId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attachments\DocumentAttachmentsRestController.java | 1 |
请完成以下Java代码 | public String getNewState() {
return PlanItemInstanceState.ACTIVE;
}
@Override
public String getLifeCycleTransition() {
return PlanItemTransition.START;
}
@Override
protected void internalExecute() {
// Sentries are not needed to be kept around, as the plan item is being started
removeSentryRelatedData();
planItemInstanceEntity.setEntryCriterionId(entryCriterionId);
planItemInstanceEntity.setLastStartedTime(getCurrentTime(commandContext));
executeActivityBehavior();
CommandContextUtil.getCmmnHistoryManager(commandContext).recordPlanItemInstanceStarted(planItemInstanceEntity);
}
protected void executeActivityBehavior() {
CmmnActivityBehavior activityBehavior = (CmmnActivityBehavior) planItemInstanceEntity.getPlanItem().getBehavior();
if (migrationContext != null && activityBehavior instanceof CmmnActivityWithMigrationContextBehavior) {
((CmmnActivityWithMigrationContextBehavior) activityBehavior).execute(commandContext, planItemInstanceEntity, migrationContext);
} else if (activityBehavior instanceof ChildTaskActivityBehavior) {
((ChildTaskActivityBehavior) activityBehavior).execute(commandContext, planItemInstanceEntity, childTaskVariableInfo); | } else if (activityBehavior instanceof CoreCmmnActivityBehavior) {
((CoreCmmnActivityBehavior) activityBehavior).execute(commandContext, planItemInstanceEntity);
} else if (activityBehavior != null) {
activityBehavior.execute(planItemInstanceEntity);
} else {
throw new FlowableException(planItemInstanceEntity + " does not have a behavior");
}
}
@Override
public String getOperationName() {
return "[Start plan item]";
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\StartPlanItemInstanceOperation.java | 1 |
请完成以下Spring Boot application配置 | # Local server port
server.port=8443
server.ssl.enabled=true
#
#
## The path to the keystore containing the certificate
server.ssl.key-store = src/main/resources/securePC.p12
#
## The format used for the keystore. It could be set to JKS in case it is a JKS file
server.ssl.key-store-type = PKCS12
#
## The password used to generate the certificate
server.ssl.key-store-password = 123456
#
# Database configuration
#spring.datasource.driver-class-name=com.mysql.jdbc.Dr | iver
#spring.datasource.url=jdbc:mysql://localhost:3306/management
#spring.datasource.username=root
#spring.datasource.password=posilka2020
#spring.jpa.hibernate.ddl-auto=update
#spring.jpa.show-sql=true | repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\7. SpringSecureDB\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public Optional<Product> importProduct(final SyncProduct syncProduct)
{
final Product product = productsRepo.findByUuid(syncProduct.getUuid());
return importProduct(syncProduct, product);
}
/**
* Imports the given <code>syncProduct</code>, updating the given <code>product</code> if feasible.
* If it's not feasible, then the method attempts to load the {@link Product} to update using the given <code>syncProduct</code>'s UUID.<br>
* If there is no such existing product, the method creates a new one.
*
* @param product the product to be updated. If <code>null</code> or if its UUID doesn't match the given <code>syncProduct</code>'s UUID, then this parameter is ignored.
*/
public Optional<Product> importProduct(
@NonNull final SyncProduct syncProduct,
@Nullable Product product)
{
final String uuid = syncProduct.getUuid();
if (product != null && !Objects.equals(product.getUuid(), uuid))
{
product = null;
}
if (product == null)
{
product = productsRepo.findByUuid(uuid);
}
//
// Handle delete request
if (syncProduct.isDeleted())
{
if (product != null)
{
deleteProduct(product);
}
return Optional.empty();
}
if (product == null)
{
product = new Product();
product.setUuid(uuid);
}
product.setDeleted(false);
product.setName(syncProduct.getName());
product.setPackingInfo(syncProduct.getPackingInfo());
product.setShared(syncProduct.isShared());
productsRepo.save(product);
logger.debug("Imported: {} -> {}", syncProduct, product);
//
// Import product translations
final Map<String, ProductTrl> productTrls = mapByLanguage(productTrlsRepo.findByRecord(product));
for (final Map.Entry<String, String> lang2nameTrl : syncProduct.getNameTrls().entrySet())
{
final String language = lang2nameTrl.getKey();
final String nameTrl = lang2nameTrl.getValue(); | ProductTrl productTrl = productTrls.remove(language);
if (productTrl == null)
{
productTrl = new ProductTrl();
productTrl.setLanguage(language);
productTrl.setRecord(product);
}
productTrl.setName(nameTrl);
productTrlsRepo.save(productTrl);
logger.debug("Imported: {}", productTrl);
}
for (final ProductTrl productTrl : productTrls.values())
{
productTrlsRepo.delete(productTrl);
}
return Optional.of(product);
}
private void deleteProduct(final Product product)
{
if (product.isDeleted())
{
return;
}
product.setDeleted(true);
productsRepo.save(product);
logger.debug("Deleted: {}", product);
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\SyncProductImportService.java | 2 |
请完成以下Java代码 | public void validateBOMVersions(final I_PP_Product_BOM bom)
{
final int productId = bom.getM_Product_ID();
final ProductBOMVersionsId bomVersionsId = ProductBOMVersionsId.ofRepoId(bom.getPP_Product_BOMVersions_ID());
final I_PP_Product_BOMVersions bomVersions = bomVersionsDAO.getBOMVersions(bomVersionsId);
if (productId != bomVersions.getM_Product_ID())
{
throw new AdempiereException(AdMessageKey.of("PP_Product_BOMVersions_BOM_Doesnt_Match"))
.markAsUserValidationError()
.appendParametersToMessage()
.setParameter("PP_Product_BOM", bom)
.setParameter("PP_Product_BOMVersions", bomVersions);
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, | ifColumnsChanged = { I_PP_Product_BOM.COLUMNNAME_M_AttributeSetInstance_ID })
public void validateBOMAttributes(final I_PP_Product_BOM productBom)
{
final ProductBOMVersionsId productBOMVersionsId = ProductBOMVersionsId.ofRepoId(productBom.getPP_Product_BOMVersions_ID());
productPlanningDAO.retrieveProductPlanningForBomVersions(productBOMVersionsId)
.forEach(productPlanning -> productBOMService.verifyBOMAssignment(productPlanning, productBom));
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = { I_PP_Product_BOM.COLUMNNAME_SerialNo_Sequence_ID, I_PP_Product_BOM.COLUMNNAME_C_UOM_ID })
public void validateSeqNo(final I_PP_Product_BOM productBom)
{
if (DocSequenceId.ofRepoIdOrNull(productBom.getSerialNo_Sequence_ID()) != null
&& !UomId.ofRepoId(productBom.getC_UOM_ID()).isEach())
{
throw new AdempiereException(UOM_ID_MUST_BE_EACH_IF_SEQ_NO_IS_SET);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\validator\PP_Product_BOM.java | 1 |
请完成以下Java代码 | public Integer getGiftIntegration() {
return giftIntegration;
}
public void setGiftIntegration(Integer giftIntegration) {
this.giftIntegration = giftIntegration;
}
public Integer getGiftGrowth() {
return giftGrowth;
}
public void setGiftGrowth(Integer giftGrowth) {
this.giftGrowth = giftGrowth;
}
public String getProductAttr() {
return productAttr;
}
public void setProductAttr(String productAttr) {
this.productAttr = productAttr;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", orderId=").append(orderId);
sb.append(", orderSn=").append(orderSn);
sb.append(", productId=").append(productId);
sb.append(", productPic=").append(productPic);
sb.append(", productName=").append(productName);
sb.append(", productBrand=").append(productBrand);
sb.append(", productSn=").append(productSn);
sb.append(", productPrice=").append(productPrice); | sb.append(", productQuantity=").append(productQuantity);
sb.append(", productSkuId=").append(productSkuId);
sb.append(", productSkuCode=").append(productSkuCode);
sb.append(", productCategoryId=").append(productCategoryId);
sb.append(", promotionName=").append(promotionName);
sb.append(", promotionAmount=").append(promotionAmount);
sb.append(", couponAmount=").append(couponAmount);
sb.append(", integrationAmount=").append(integrationAmount);
sb.append(", realAmount=").append(realAmount);
sb.append(", giftIntegration=").append(giftIntegration);
sb.append(", giftGrowth=").append(giftGrowth);
sb.append(", productAttr=").append(productAttr);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderItem.java | 1 |
请完成以下Java代码 | public static class BPartnerContact
{
private final int C_BPartner_ID;
private final int AD_User_ID;
public BPartnerContact(int cBPartnerID, int aDUserID)
{
super();
C_BPartner_ID = cBPartnerID;
AD_User_ID = aDUserID;
}
public int getC_BPartner_ID()
{
return C_BPartner_ID; | }
public int getAD_User_ID()
{
return AD_User_ID;
}
@Override
public String toString()
{
return "BPartnerContact [C_BPartner_ID=" + C_BPartner_ID
+ ", AD_User_ID=" + AD_User_ID + "]";
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\form\CalloutR_Group.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Attribute
{
public static final Comparator<Attribute> ORDER_BY_DisplayName = Comparator.<Attribute, String>comparing(attribute -> attribute.getDisplayName().getDefaultValue())
.thenComparing(Attribute::getAttributeId);
@NonNull AttributeId attributeId;
@NonNull AttributeCode attributeCode;
@NonNull AttributeValueType valueType;
@NonNull ITranslatableString displayName;
@Nullable ITranslatableString description;
@Nullable IStringExpression descriptionPattern;
@Nullable IStringExpression defaultValueSQL;
@Builder.Default boolean isActive = true;
boolean isInstanceAttribute;
boolean isMandatory;
boolean isReadOnlyValues;
boolean isPricingRelevant;
boolean isStorageRelevant;
@Nullable UomId uomId;
boolean isHighVolume;
@Nullable JavaClassId listValuesProviderJavaClassId;
@Nullable AdValRuleId listValRuleId; | @Nullable AttributeValuesOrderByType listOrderBy;
public boolean isHighVolumeValuesList()
{
return this.isHighVolume && valueType.isList();
}
public int getNumberDisplayType()
{
return isInteger(uomId)
? DisplayType.Integer
: DisplayType.Number;
}
public static boolean isInteger(@Nullable final UomId uomId)
{
return uomId != null && UomId.equals(uomId, UomId.EACH);
}
public boolean isDefaultValueSet() {return defaultValueSQL != null;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\Attribute.java | 2 |
请完成以下Java代码 | public List<DefaultMetadataElement> getJavaVersions() {
return this.javaVersions;
}
public List<DefaultMetadataElement> getLanguages() {
return this.languages;
}
public List<DefaultMetadataElement> getConfigurationFileFormats() {
return this.configurationFileFormats;
}
public List<DefaultMetadataElement> getBootVersions() {
return this.bootVersions;
}
public SimpleElement getGroupId() {
return this.groupId;
}
public SimpleElement getArtifactId() {
return this.artifactId;
}
public SimpleElement getVersion() {
return this.version;
}
public SimpleElement getName() {
return this.name;
}
public SimpleElement getDescription() {
return this.description;
}
public SimpleElement getPackageName() {
return this.packageName;
}
/**
* A simple element from the properties.
*/
public static final class SimpleElement {
/**
* Element title.
*/
private String title;
/**
* Element description.
*/
private String description;
/**
* Element default value.
*/
private String value;
/**
* Create a new instance with the given value.
* @param value the value
*/
public SimpleElement(String value) {
this.value = value;
}
public String getTitle() { | return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
public void apply(TextCapability capability) {
if (StringUtils.hasText(this.title)) {
capability.setTitle(this.title);
}
if (StringUtils.hasText(this.description)) {
capability.setDescription(this.description);
}
if (StringUtils.hasText(this.value)) {
capability.setContent(this.value);
}
}
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\InitializrProperties.java | 1 |
请完成以下Java代码 | public @Nullable T getListener() {
return this.listener;
}
@Override
protected String getDescription() {
Assert.notNull(this.listener, "'listener' must not be null");
return "listener " + this.listener;
}
@Override
protected void register(String description, ServletContext servletContext) {
try {
servletContext.addListener(this.listener);
}
catch (RuntimeException ex) {
throw new IllegalStateException("Failed to add listener '" + this.listener + "' to servlet context", ex);
}
}
/**
* Returns {@code true} if the specified listener is one of the supported types. | * @param listener the listener to test
* @return if the listener is of a supported type
*/
public static boolean isSupportedType(EventListener listener) {
for (Class<?> type : SUPPORTED_TYPES) {
if (ClassUtils.isAssignableValue(type, listener)) {
return true;
}
}
return false;
}
/**
* Return the supported types for this registration.
* @return the supported types
*/
public static Set<Class<?>> getSupportedTypes() {
return SUPPORTED_TYPES;
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\ServletListenerRegistrationBean.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult cancelOrder(Long orderId) {
portalOrderService.sendDelayMessageCancelOrder(orderId);
return CommonResult.success(null);
}
@ApiOperation("按状态分页获取用户订单列表")
@ApiImplicitParam(name = "status", value = "订单状态:-1->全部;0->待付款;1->待发货;2->已发货;3->已完成;4->已关闭",
defaultValue = "-1", allowableValues = "-1,0,1,2,3,4", paramType = "query", dataType = "int")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<OmsOrderDetail>> list(@RequestParam Integer status,
@RequestParam(required = false, defaultValue = "1") Integer pageNum,
@RequestParam(required = false, defaultValue = "5") Integer pageSize) {
CommonPage<OmsOrderDetail> orderPage = portalOrderService.list(status,pageNum,pageSize);
return CommonResult.success(orderPage);
}
@ApiOperation("根据ID获取订单详情")
@RequestMapping(value = "/detail/{orderId}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<OmsOrderDetail> detail(@PathVariable Long orderId) {
OmsOrderDetail orderDetail = portalOrderService.detail(orderId);
return CommonResult.success(orderDetail);
}
@ApiOperation("用户取消订单")
@RequestMapping(value = "/cancelUserOrder", method = RequestMethod.POST)
@ResponseBody
public CommonResult cancelUserOrder(Long orderId) {
portalOrderService.cancelOrder(orderId);
return CommonResult.success(null); | }
@ApiOperation("用户确认收货")
@RequestMapping(value = "/confirmReceiveOrder", method = RequestMethod.POST)
@ResponseBody
public CommonResult confirmReceiveOrder(Long orderId) {
portalOrderService.confirmReceiveOrder(orderId);
return CommonResult.success(null);
}
@ApiOperation("用户删除订单")
@RequestMapping(value = "/deleteOrder", method = RequestMethod.POST)
@ResponseBody
public CommonResult deleteOrder(Long orderId) {
portalOrderService.deleteOrder(orderId);
return CommonResult.success(null);
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\OmsPortalOrderController.java | 2 |
请完成以下Java代码 | private StockQtyAndUOMQty getQtyInvoiceable(@NonNull final InvoiceCandidateId invoiceCandidateId)
{
final StockQtyAndUOMQty qtyInvoiceable = _ic2QtyInvoiceable.get(invoiceCandidateId);
return Check.assumeNotNull(qtyInvoiceable, "qtyInvoiceable not null for invoiceCandidateId={}", invoiceCandidateId);
}
private void addLineNetAmount(final Money candLineNetAmt)
{
_netLineAmt = _netLineAmt.add(candLineNetAmt);
}
public boolean hasAtLeastOneValidICS()
{
return _hasAtLeastOneValidICS;
}
/**
* Checks if given invoice candidate is amount based invoicing (i.e. NOT quantity based invoicing).
* <p>
* TODO: find a better way to track this. Consider having a field in C_Invoice_Candidate.
* <p>
* To track where it's used, search also for {@link InvalidQtyForPartialAmtToInvoiceException}.
*/
private boolean isAmountBasedInvoicing(final I_C_Invoice_Candidate cand)
{
// We can consider manual invoices as amount based invoices | if (cand.isManual())
{
return true;
}
// We can consider those candidates which have a SplitAmt set to be amount based invoices
final BigDecimal splitAmt = cand.getSplitAmt();
if (splitAmt.signum() != 0)
{
return true;
}
// More ideas to check:
// * UOM shall be stuck?!
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\aggregator\standard\InvoiceCandidateWithInOutLineAggregator.java | 1 |
请完成以下Java代码 | public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@Override
public String getActivityId() {
return activityId;
}
@Override
public void setActivityId(String activityId) {
this.activityId = activityId;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public boolean isFailed() {
return failed;
}
@Override
public void setFailed(boolean failed) {
this.failed = failed;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getExecutionJson() {
return executionJson;
} | @Override
public void setExecutionJson(String executionJson) {
this.executionJson = executionJson;
}
@Override
public String getDecisionKey() {
return decisionKey;
}
public void setDecisionKey(String decisionKey) {
this.decisionKey = decisionKey;
}
@Override
public String getDecisionName() {
return decisionName;
}
public void setDecisionName(String decisionName) {
this.decisionName = decisionName;
}
@Override
public String getDecisionVersion() {
return decisionVersion;
}
public void setDecisionVersion(String decisionVersion) {
this.decisionVersion = decisionVersion;
}
@Override
public String toString() {
return "HistoricDecisionExecutionEntity[" + id + "]";
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\HistoricDecisionExecutionEntityImpl.java | 1 |
请完成以下Java代码 | public String getProfileInfo ()
{
return (String)get_Value(COLUMNNAME_ProfileInfo);
}
/** Set Issue Project.
@param R_IssueProject_ID
Implementation Projects
*/
public void setR_IssueProject_ID (int R_IssueProject_ID)
{
if (R_IssueProject_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_IssueProject_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_IssueProject_ID, Integer.valueOf(R_IssueProject_ID));
}
/** Get Issue Project.
@return Implementation Projects
*/
public int getR_IssueProject_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueProject_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Statistics.
@param StatisticsInfo
Information to help profiling the system for solving support issues
*/
public void setStatisticsInfo (String StatisticsInfo)
{
set_Value (COLUMNNAME_StatisticsInfo, StatisticsInfo);
}
/** Get Statistics.
@return Information to help profiling the system for solving support issues
*/
public String getStatisticsInfo ()
{
return (String)get_Value(COLUMNNAME_StatisticsInfo);
}
/** SystemStatus AD_Reference_ID=374 */
public static final int SYSTEMSTATUS_AD_Reference_ID=374;
/** Evaluation = E */
public static final String SYSTEMSTATUS_Evaluation = "E"; | /** Implementation = I */
public static final String SYSTEMSTATUS_Implementation = "I";
/** Production = P */
public static final String SYSTEMSTATUS_Production = "P";
/** Set System Status.
@param SystemStatus
Status of the system - Support priority depends on system status
*/
public void setSystemStatus (String SystemStatus)
{
set_Value (COLUMNNAME_SystemStatus, SystemStatus);
}
/** Get System Status.
@return Status of the system - Support priority depends on system status
*/
public String getSystemStatus ()
{
return (String)get_Value(COLUMNNAME_SystemStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueProject.java | 1 |
请在Spring Boot框架中完成以下Java代码 | CompositeHandlerExceptionResolver compositeHandlerExceptionResolver() {
return new CompositeHandlerExceptionResolver();
}
@Bean
@ConditionalOnMissingBean({ RequestContextListener.class, RequestContextFilter.class })
RequestContextFilter requestContextFilter() {
return new OrderedRequestContextFilter();
}
/**
* {@link WebServerFactoryCustomizer} to add an {@link ErrorPage} so that the
* {@link ManagementErrorEndpoint} can be used.
*/
static class ManagementErrorPageCustomizer
implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered {
private final WebProperties properties; | ManagementErrorPageCustomizer(WebProperties properties) {
this.properties = properties;
}
@Override
public void customize(ConfigurableServletWebServerFactory factory) {
factory.addErrorPages(new ErrorPage(this.properties.getError().getPath()));
}
@Override
public int getOrder() {
return 10; // Run after ManagementWebServerFactoryCustomizer
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\actuate\web\WebMvcEndpointChildContextConfiguration.java | 2 |
请完成以下Java代码 | public boolean hasProcessedReceiptSchedules(final I_C_Order order)
{
// services
final IOrderDAO orderDAO = Services.get(IOrderDAO.class);
final IReceiptScheduleDAO receiptScheduleDAO = Services.get(IReceiptScheduleDAO.class);
final List<I_C_OrderLine> orderLines = orderDAO.retrieveOrderLines(order);
for (final I_C_OrderLine orderLine : orderLines)
{
final I_M_ReceiptSchedule receiptSchedule = receiptScheduleDAO.retrieveForRecord(orderLine);
// Throw exception if at least one processed receipt schedule is linked to a line of this order
if (receiptSchedule != null && receiptSchedule.isProcessed())
{
return true;
}
}
return false;
}
@DocValidate(timings = ModelValidator.TIMING_BEFORE_CLOSE)
public void closeReceiptSchedules(final I_C_Order order)
{
if (!isEligibleForReceiptSchedule(order))
{
return;
}
// services
final IOrderDAO orderDAO = Services.get(IOrderDAO.class);
final IReceiptScheduleDAO receiptScheduleDAO = Services.get(IReceiptScheduleDAO.class); | final IReceiptScheduleBL receiptScheduleBL = Services.get(IReceiptScheduleBL.class);
final List<I_C_OrderLine> orderLines = orderDAO.retrieveOrderLines(order);
for (final I_C_OrderLine orderLine : orderLines)
{
final I_M_ReceiptSchedule receiptSchedule = receiptScheduleDAO.retrieveForRecord(orderLine);
if (receiptSchedule == null || receiptScheduleBL.isClosed(receiptSchedule))
{
continue;
}
receiptScheduleBL.close(receiptSchedule);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\C_Order_ReceiptSchedule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void updateCommissionShares(@NonNull final CommissionTriggerChange change)
{
try
{
final ImmutableList<CommissionType> commissionTypes = CollectionUtils.extractDistinctElements(
change.getInstanceToUpdate().getShares(),
share -> share.getConfig().getCommissionType());
for (final CommissionType commissionType : commissionTypes)
{
try (final MDCCloseable ignore = MDC.putCloseable("commissionType", commissionType.name()))
{
final CommissionAlgorithm algorithm = createAlgorithmInstance(commissionType);
// invoke the algorithm
algorithm.applyTriggerChangeToShares(change);
}
}
}
catch (final RuntimeException e)
{
throw AdempiereException.wrapIfNeeded(e).setParameter("change", change);
}
}
@NonNull
private CommissionAlgorithm createAlgorithmInstance(@NonNull final CommissionType commissionType)
{ | final CommissionAlgorithmFactory commissionAlgorithmFactory = commissionType2AlgorithmFactory.get(commissionType);
if (commissionAlgorithmFactory != null)
{
return commissionAlgorithmFactory.instantiateAlgorithm();
}
final Class<? extends CommissionAlgorithm> algorithmClass = commissionType.getAlgorithmClass();
final CommissionAlgorithm algorithm;
try
{
algorithm = algorithmClass.newInstance();
}
catch (InstantiationException | IllegalAccessException e)
{
throw new AdempiereException("Unable to instantiate commission algorithm from class " + algorithmClass)
.appendParametersToMessage()
.setParameter("commissionType", commissionType);
}
return algorithm;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\CommissionAlgorithmInvoker.java | 2 |
请完成以下Java代码 | public class MySerializationUtils {
public static <T extends Serializable> byte[] serialize(T obj) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
return baos.toByteArray();
}
public static <T extends Serializable> T deserialize(byte[] b, Class<T> cl) throws IOException, ClassNotFoundException {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
ObjectInputStream ois = new ObjectInputStream(bais);
Object o = ois.readObject();
return cl.cast(o);
}
public static boolean isSerializable(Class<?> it) {
boolean serializable = it.isPrimitive() || it.isInterface() || Serializable.class.isAssignableFrom(it); | if (!serializable) {
return false;
}
Field[] declaredFields = it.getDeclaredFields();
for (Field field : declaredFields) {
if (Modifier.isVolatile(field.getModifiers()) || Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) {
continue;
}
Class<?> fieldType = field.getType();
if (!isSerializable(fieldType)) {
return false;
}
}
return true;
}
} | repos\tutorials-master\core-java-modules\core-java-serialization\src\main\java\com\baeldung\util\MySerializationUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ChatRoomServerEndpoint {
private static final Logger logger = LoggerFactory.getLogger(ChatRoomServerEndpoint.class);
@OnOpen
public void openSession(@PathParam("username") String username, Session session) {
ONLINE_USER_SESSIONS.put(username, session);
String message = "欢迎用户[" + username + "] 来到聊天室!";
logger.info("用户登录:"+message);
sendMessageAll(message);
}
@OnMessage
public void onMessage(@PathParam("username") String username, String message) {
logger.info("发送消息:"+message);
sendMessageAll("用户[" + username + "] : " + message);
}
@OnClose
public void onClose(@PathParam("username") String username, Session session) {
//当前的Session 移除
ONLINE_USER_SESSIONS.remove(username);
//并且通知其他人当前用户已经离开聊天室了
sendMessageAll("用户[" + username + "] 已经离开聊天室了!");
try {
session.close(); | } catch (IOException e) {
logger.error("onClose error",e);
}
}
@OnError
public void onError(Session session, Throwable throwable) {
try {
session.close();
} catch (IOException e) {
logger.error("onError excepiton",e);
}
logger.info("Throwable msg "+throwable.getMessage());
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-10 课: 使用 Spring Boot WebSocket 创建聊天室\spring-boot-websocket\src\main\java\com\neo\ChatRoomServerEndpoint.java | 2 |
请完成以下Java代码 | public PPOrderCost addingAccumulatedAmountAndQty(
@NonNull final CostAmount amt,
@NonNull final Quantity qty,
@NonNull final QuantityUOMConverter uomConverter)
{
if (amt.isZero() && qty.isZero())
{
return this;
}
final boolean amtIsPositiveOrZero = amt.signum() >= 0;
final boolean amtIsNotZero = amt.signum() != 0;
final boolean qtyIsPositiveOrZero = qty.signum() >= 0;
if (amtIsNotZero && amtIsPositiveOrZero != qtyIsPositiveOrZero )
{
throw new AdempiereException("Amount and Quantity shall have the same sign: " + amt + ", " + qty);
}
final Quantity accumulatedQty = getAccumulatedQty();
final Quantity qtyConv = uomConverter.convertQuantityTo(qty, getProductId(), accumulatedQty.getUomId());
return toBuilder()
.accumulatedAmount(getAccumulatedAmount().add(amt))
.accumulatedQty(accumulatedQty.add(qtyConv))
.build();
}
public PPOrderCost subtractingAccumulatedAmountAndQty(
@NonNull final CostAmount amt,
@NonNull final Quantity qty,
@NonNull final QuantityUOMConverter uomConverter)
{
return addingAccumulatedAmountAndQty(amt.negate(), qty.negate(), uomConverter);
}
public PPOrderCost withPrice(@NonNull final CostPrice newPrice) | {
if (this.getPrice().equals(newPrice))
{
return this;
}
return toBuilder().price(newPrice).build();
}
/* package */void setPostCalculationAmount(@NonNull final CostAmount postCalculationAmount)
{
this.postCalculationAmount = postCalculationAmount;
}
/* package */void setPostCalculationAmountAsAccumulatedAmt()
{
setPostCalculationAmount(getAccumulatedAmount());
}
/* package */void setPostCalculationAmountAsZero()
{
setPostCalculationAmount(getPostCalculationAmount().toZero());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderCost.java | 1 |
请完成以下Java代码 | public class DeptrackFrontendServiceResource extends CRUDKubernetesDependentResource<Service, DeptrackResource> {
public static final String COMPONENT = "frontend-service";
private Service template;
public DeptrackFrontendServiceResource() {
super(Service.class);
this.template = BuilderHelper.loadTemplate(Service.class, "templates/frontend-service.yaml");
}
@Override
protected Service desired(DeptrackResource primary, Context<DeptrackResource> context) {
ObjectMeta meta = fromPrimary(primary,COMPONENT)
.build();
Map<String, String> selector = new HashMap<>(meta.getLabels());
selector.put("component", DeptrackFrontendDeploymentResource.COMPONENT);
return new ServiceBuilder(template)
.withMetadata(meta)
.editSpec()
.withSelector(selector) | .endSpec()
.build();
}
// static class Discriminator implements ResourceDiscriminator<Service,DeptrackResource> {
// @Override
// public Optional<Service> distinguish(Class<Service> resource, DeptrackResource primary, Context<DeptrackResource> context) {
// var ies = context.eventSourceRetriever().getResourceEventSourceFor(Service.class,COMPONENT);
// return ies.getSecondaryResource(primary);
// }
// }
static class Discriminator extends ResourceIDMatcherDiscriminator<Service,DeptrackResource> {
public Discriminator() {
super(COMPONENT, (p) -> new ResourceID(p.getMetadata().getName() + "-" + COMPONENT,p.getMetadata().getNamespace()));
}
}
} | repos\tutorials-master\kubernetes-modules\k8s-operator\src\main\java\com\baeldung\operators\deptrack\resources\deptrack\DeptrackFrontendServiceResource.java | 1 |
请完成以下Java代码 | public EncryptedDataType getEncryptedData() {
return encryptedData;
}
/**
* Sets the value of the encryptedData property.
*
* @param value
* allowed object is
* {@link EncryptedDataType }
*
*/
public void setEncryptedData(EncryptedDataType value) {
this.encryptedData = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
if (type == null) {
return "invoice";
} else {
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 storno property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isStorno() {
if (storno == null) {
return false;
} else {
return storno;
}
}
/**
* Sets the value of the storno property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setStorno(Boolean value) {
this.storno = value;
}
/**
* Gets the value of the copy property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isCopy() { | if (copy == null) {
return false;
} else {
return copy;
}
}
/**
* Sets the value of the copy property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setCopy(Boolean value) {
this.copy = value;
}
/**
* Gets the value of the creditAdvice property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isCreditAdvice() {
if (creditAdvice == null) {
return false;
} else {
return creditAdvice;
}
}
/**
* Sets the value of the creditAdvice property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setCreditAdvice(Boolean value) {
this.creditAdvice = 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\PayloadType.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(fetcher)
.toString();
}
@Override
public DocumentZoomIntoInfo getDocumentZoomInto(final int id)
{
final String tableName = fetcher.getLookupTableName()
.orElseThrow(() -> new IllegalStateException("Failed converting id=" + id + " to " + DocumentZoomIntoInfo.class + " because the fetcher returned null tablename: " + fetcher));
return DocumentZoomIntoInfo.of(tableName, id);
}
@Override
public final LookupValuesPage findEntities(final Evaluatee ctx, final int pageLength)
{
return findEntities(ctx, LookupDataSourceContext.FILTER_Any, FIRST_ROW, pageLength);
}
@Override
public final LookupValuesPage findEntities(final Evaluatee ctx, final String filter, final int firstRow, final int pageLength)
{
final String filterEffective;
if (Check.isBlank(filter))
{
filterEffective = LookupDataSourceContext.FILTER_Any;
}
else
{
filterEffective = filter.trim();
}
final LookupDataSourceContext evalCtx = fetcher.newContextForFetchingList()
.setParentEvaluatee(ctx)
.putFilter(filterEffective, firstRow, pageLength)
.requiresFilterAndLimit() // make sure the filter, limit and offset will be kept on build
.build();
return fetcher.retrieveEntities(evalCtx);
}
@Override
public LookupValue findById(final Object idObj)
{
if (idObj == null)
{
return null;
}
//
// Normalize the ID to Integer/String
final Object idNormalized = LookupValue.normalizeId(idObj, fetcher.isNumericKey());
if (idNormalized == null)
{
return null;
}
//
// Build the validation context
final LookupDataSourceContext evalCtx = fetcher.newContextForFetchingById(idNormalized)
.putFilterById(IdsToFilter.ofSingleValue(idNormalized))
.putShowInactive(true)
.build();
//
// Get the lookup value
final LookupValue lookupValue = fetcher.retrieveLookupValueById(evalCtx);
if (lookupValue == LookupDataSourceFetcher.LOOKUPVALUE_NULL) | {
return null;
}
return lookupValue;
}
@Override
public @NonNull LookupValuesList findByIdsOrdered(final @NonNull Collection<?> ids)
{
final LookupDataSourceContext evalCtx = fetcher.newContextForFetchingByIds(ids)
.putShowInactive(true)
.build();
return fetcher.retrieveLookupValueByIdsInOrder(evalCtx);
}
@Override
public List<CCacheStats> getCacheStats()
{
return fetcher.getCacheStats();
}
@Override
public void cacheInvalidate()
{
fetcher.cacheInvalidate();
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return fetcher.getZoomIntoWindowId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LookupDataSourceAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JobAlarmer implements ApplicationContextAware, InitializingBean {
private static Logger logger = LoggerFactory.getLogger(JobAlarmer.class);
private ApplicationContext applicationContext;
private List<JobAlarm> jobAlarmList;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void afterPropertiesSet() throws Exception {
Map<String, JobAlarm> serviceBeanMap = applicationContext.getBeansOfType(JobAlarm.class);
if (serviceBeanMap != null && serviceBeanMap.size() > 0) {
jobAlarmList = new ArrayList<JobAlarm>(serviceBeanMap.values());
}
}
/**
* job alarm
*
* @param info
* @param jobLog
* @return | */
public boolean alarm(XxlJobInfo info, XxlJobLog jobLog) {
boolean result = false;
if (jobAlarmList!=null && jobAlarmList.size()>0) {
result = true; // success means all-success
for (JobAlarm alarm: jobAlarmList) {
boolean resultItem = false;
try {
resultItem = alarm.doAlarm(info, jobLog);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
if (!resultItem) {
result = false;
}
}
}
return result;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\alarm\JobAlarmer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getAppDefinitionEntityManager(commandContext).findAppDefinitionCountByQueryCriteria(this);
}
@Override
public List<AppDefinition> executeList(CommandContext commandContext) {
return CommandContextUtil.getAppDefinitionEntityManager(commandContext).findAppDefinitionsByQueryCriteria(this);
}
// getters ////////////////////////////////////////////
public String getDeploymentId() {
return deploymentId;
}
public Set<String> getDeploymentIds() {
return deploymentIds;
}
public String getId() {
return id;
}
public Set<String> getIds() {
return ids;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public Integer getVersion() {
return version;
}
public Integer getVersionGt() {
return versionGt;
}
public Integer getVersionGte() {
return versionGte;
} | public Integer getVersionLt() {
return versionLt;
}
public Integer getVersionLte() {
return versionLte;
}
public boolean isLatest() {
return latest;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDefinitionQueryImpl.java | 2 |
请完成以下Java代码 | public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public Date getLastUpdatedTime() {
return lastUpdatedTime;
}
public void setLastUpdatedTime(Date lastUpdatedTime) {
this.lastUpdatedTime = lastUpdatedTime;
}
@Override
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@Override
public Date getTime() {
return getCreateTime();
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricVariableInstanceEntity[");
sb.append("id=").append(id);
sb.append(", name=").append(name); | sb.append(", revision=").append(revision);
sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null");
if (longValue != null) {
sb.append(", longValue=").append(longValue);
}
if (doubleValue != null) {
sb.append(", doubleValue=").append(doubleValue);
}
if (textValue != null) {
sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40));
}
if (textValue2 != null) {
sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40));
}
if (byteArrayRef.getId() != null) {
sb.append(", byteArrayValueId=").append(byteArrayRef.getId());
}
sb.append("]");
return sb.toString();
}
// non-supported (v6)
@Override
public String getScopeId() {
return null;
}
@Override
public String getSubScopeId() {
return null;
}
@Override
public String getScopeType() {
return null;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricVariableInstanceEntity.java | 1 |
请完成以下Java代码 | public void setValue(Object value)
{
if (value == null)
m_oldText = "";
else
m_oldText = value.toString();
if (m_setting)
return;
super.setValue(m_oldText);
m_initialText = m_oldText;
// Always position Top
setCaretPosition(0);
} // setValue
/**
* Property Change Listener
* @param evt event
*/
@Override
public void propertyChange (PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
setValue(evt.getNewValue());
// metas: request focus (2009_0027_G131)
if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS))
requestFocus();
// metas end
} // propertyChange
/**
* Action Listener Interface - NOP
* @param listener listener
*/
@Override
public void addActionListener(ActionListener listener)
{
} // addActionListener
/**************************************************************************
* Key Listener Interface
* @param e event
*/
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {}
/**
* Key Released
* if Escape restore old Text.
* @param e event
*/
@Override
public void keyReleased(KeyEvent e)
{
// ESC
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
setText(m_initialText);
m_setting = true;
try
{ | fireVetoableChange(m_columnName, m_oldText, getText());
}
catch (PropertyVetoException pve) {}
m_setting = false;
} // keyReleased
/**
* Set Field/WindowNo for ValuePreference (NOP)
* @param mField field model
*/
@Override
public void setField (org.compiere.model.GridField mField)
{
m_mField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField() {
return m_mField;
}
// metas: begin
@Override
public boolean isAutoCommit()
{
return true;
}
// metas: end
} // VText | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VText.java | 1 |
请完成以下Java代码 | public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
@CamundaQueryParam("processInstanceId")
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getActivityId() {
return activityId;
}
@CamundaQueryParam("activityId")
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public List<String> getTenantIdIn() {
return tenantIdIn;
}
@CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class)
public void setTenantIdIn(List<String> tenantIdIn) {
this.tenantIdIn = tenantIdIn;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
@CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class)
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Boolean getIncludeEventSubscriptionsWithoutTenantId() {
return includeEventSubscriptionsWithoutTenantId;
}
@CamundaQueryParam(value = "includeEventSubscriptionsWithoutTenantId", converter = BooleanConverter.class)
public void setIncludeEventSubscriptionsWithoutTenantId(Boolean includeEventSubscriptionsWithoutTenantId) {
this.includeEventSubscriptionsWithoutTenantId = includeEventSubscriptionsWithoutTenantId;
}
@Override
protected boolean isValidSortByValue(String value) { | return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected EventSubscriptionQuery createNewQuery(ProcessEngine engine) {
return engine.getRuntimeService().createEventSubscriptionQuery();
}
@Override
protected void applyFilters(EventSubscriptionQuery query) {
if (eventSubscriptionId != null) {
query.eventSubscriptionId(eventSubscriptionId);
}
if (eventName != null) {
query.eventName(eventName);
}
if (eventType != null) {
query.eventType(eventType);
}
if (executionId != null) {
query.executionId(executionId);
}
if (processInstanceId != null) {
query.processInstanceId(processInstanceId);
}
if (activityId != null) {
query.activityId(activityId);
}
if (tenantIdIn != null && !tenantIdIn.isEmpty()) {
query.tenantIdIn(tenantIdIn.toArray(new String[tenantIdIn.size()]));
}
if (TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (TRUE.equals(includeEventSubscriptionsWithoutTenantId)) {
query.includeEventSubscriptionsWithoutTenantId();
}
}
@Override
protected void applySortBy(EventSubscriptionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_CREATED)) {
query.orderByCreated();
} else if (sortBy.equals(SORT_BY_TENANT_ID)) {
query.orderByTenantId();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\EventSubscriptionQueryDto.java | 1 |
请完成以下Java代码 | public void setPA_SLA_Goal_ID (int PA_SLA_Goal_ID)
{
if (PA_SLA_Goal_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_SLA_Goal_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_SLA_Goal_ID, Integer.valueOf(PA_SLA_Goal_ID));
}
/** Get SLA Goal.
@return Service Level Agreement Goal
*/
public int getPA_SLA_Goal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Goal_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set SLA Measure.
@param PA_SLA_Measure_ID
Service Level Agreement Measure
*/
public void setPA_SLA_Measure_ID (int PA_SLA_Measure_ID)
{
if (PA_SLA_Measure_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_SLA_Measure_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_SLA_Measure_ID, Integer.valueOf(PA_SLA_Measure_ID));
}
/** Get SLA Measure.
@return Service Level Agreement Measure
*/
public int getPA_SLA_Measure_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Measure_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now. | @param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Record ID.
@param Record_ID
Direct internal record ID
*/
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (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();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_SLA_Measure.java | 1 |
请完成以下Java代码 | private static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* 路径安全校验
*/
private static void validatePathSecurity(String customPath) throws JeecgBootException {
if (customPath == null || customPath.trim().isEmpty()) {
return;
}
// 统一分隔符为 /
String normalized = customPath.replace("\\", "/");
// 1. 防止路径遍历攻击
if (normalized.contains("..") || normalized.contains("~")) {
throw new JeecgBootException("上传业务路径包含非法字符!");
} | // 2. 限制路径深度
int depth = normalized.split("/").length;
if (depth > 5) {
throw new JeecgBootException("上传业务路径深度超出限制!");
}
// 3. 限制字符集(只允许字母、数字、下划线、横线、斜杠)
if (!normalized.matches("^[a-zA-Z0-9/_-]+$")) {
throw new JeecgBootException("上传业务路径包含非法字符!");
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\filter\SsrfFileTypeFilter.java | 1 |
请完成以下Java代码 | public void put(String propertyName, Integer value) {
jsonNode.put(propertyName, value);
}
@Override
public void put(String propertyName, Long value) {
jsonNode.put(propertyName, value);
}
@Override
public void put(String propertyName, Double value) {
jsonNode.put(propertyName, value);
}
@Override
public void put(String propertyName, Float value) {
jsonNode.put(propertyName, value);
}
@Override
public void put(String propertyName, BigDecimal value) {
jsonNode.put(propertyName, value);
}
@Override
public void put(String propertyName, BigInteger value) {
jsonNode.put(propertyName, value);
}
@Override
public void put(String propertyName, byte[] value) {
jsonNode.put(propertyName, value); | }
@Override
public void putNull(String propertyName) {
jsonNode.putNull(propertyName);
}
@Override
public FlowableArrayNode putArray(String propertyName) {
return new FlowableJackson2ArrayNode(jsonNode.putArray(propertyName));
}
@Override
public void set(String propertyName, FlowableJsonNode value) {
jsonNode.set(propertyName, asJsonNode(value));
}
@Override
public FlowableObjectNode putObject(String propertyName) {
return new FlowableJackson2ObjectNode(jsonNode.putObject(propertyName));
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\json\jackson2\FlowableJackson2ObjectNode.java | 1 |
请完成以下Java代码 | public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public org.compiere.model.I_S_TimeExpenseLine getS_TimeExpenseLine()
{
return get_ValueAsPO(COLUMNNAME_S_TimeExpenseLine_ID, org.compiere.model.I_S_TimeExpenseLine.class);
}
@Override
public void setS_TimeExpenseLine(final org.compiere.model.I_S_TimeExpenseLine S_TimeExpenseLine)
{
set_ValueFromPO(COLUMNNAME_S_TimeExpenseLine_ID, org.compiere.model.I_S_TimeExpenseLine.class, S_TimeExpenseLine);
} | @Override
public void setS_TimeExpenseLine_ID (final int S_TimeExpenseLine_ID)
{
if (S_TimeExpenseLine_ID < 1)
set_Value (COLUMNNAME_S_TimeExpenseLine_ID, null);
else
set_Value (COLUMNNAME_S_TimeExpenseLine_ID, S_TimeExpenseLine_ID);
}
@Override
public int getS_TimeExpenseLine_ID()
{
return get_ValueAsInt(COLUMNNAME_S_TimeExpenseLine_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectIssue.java | 1 |
请完成以下Java代码 | public String[] getCc() {
return Arrays.copyOf(cc, cc.length);
}
public void setCc(String[] cc) {
this.cc = Arrays.copyOf(cc, cc.length);
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTemplate() {
return template;
}
public void setTemplate(String template) { | this.template = template;
}
@Nullable
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(@Nullable String baseUrl) {
this.baseUrl = baseUrl;
}
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
public void setAdditionalProperties(Map<String, Object> additionalProperties) {
this.additionalProperties = additionalProperties;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\MailNotifier.java | 1 |
请完成以下Java代码 | public boolean hasVariable(String variableName) {
return variables.containsKey(variableName);
}
@Override
public Object getVariable(String variableName) {
return variables.get(variableName);
}
@Override
public void setVariable(String variableName, Object variableValue) {
variables.put(variableName, variableValue);
}
@Override
public void setTransientVariable(String variableName, Object variableValue) {
throw new UnsupportedOperationException();
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
} | @Override
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public Set<String> getVariableNames() {
return variables.keySet();
}
@Override
public String toString() {
return new StringJoiner(", ", getClass().getSimpleName() + "[", "]")
.add("instanceId='" + instanceId + "'")
.add("scopeType='" + scopeType + "'")
.add("tenantId='" + tenantId + "'")
.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\VariableContainerWrapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PostSaleAuthenticationProgram status(String status)
{
this.status = status;
return this;
}
/**
* The value in this field indicates whether the order line item has passed or failed the authenticity verification inspection, or if the inspection and/or results are still pending. The possible values returned here are PENDING, PASSED, FAILED, or PASSED_WITH_EXCEPTION. For implementation help, refer to <a
* href='https://developer.ebay.com/api-docs/sell/fulfillment/types/sel:AuthenticityVerificationStatusEnum'>eBay API documentation</a>
*
* @return status
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The value in this field indicates whether the order line item has passed or failed the authenticity verification inspection, or if the inspection and/or results are still pending. The possible values returned here are PENDING, PASSED, FAILED, or PASSED_WITH_EXCEPTION. For implementation help, refer to <a href='https://developer.ebay.com/api-docs/sell/fulfillment/types/sel:AuthenticityVerificationStatusEnum'>eBay API documentation</a>")
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
PostSaleAuthenticationProgram postSaleAuthenticationProgram = (PostSaleAuthenticationProgram)o;
return Objects.equals(this.outcomeReason, postSaleAuthenticationProgram.outcomeReason) &&
Objects.equals(this.status, postSaleAuthenticationProgram.status);
}
@Override | public int hashCode()
{
return Objects.hash(outcomeReason, status);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class PostSaleAuthenticationProgram {\n");
sb.append(" outcomeReason: ").append(toIndentedString(outcomeReason)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\PostSaleAuthenticationProgram.java | 2 |
请完成以下Java代码 | protected TbFetchDeviceCredentialsNodeConfiguration loadNodeConfiguration(TbNodeConfiguration configuration) throws TbNodeException {
return TbNodeUtils.convert(configuration, TbFetchDeviceCredentialsNodeConfiguration.class);
}
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException {
var originator = msg.getOriginator();
var msgDataAsObjectNode = TbMsgSource.DATA.equals(fetchTo) ? getMsgDataAsObjectNode(msg) : null;
if (!EntityType.DEVICE.equals(originator.getEntityType())) {
ctx.tellFailure(msg, new RuntimeException("Unsupported originator type: " + originator.getEntityType() + "!"));
return;
}
var deviceId = new DeviceId(msg.getOriginator().getId());
var deviceCredentials = ctx.getDeviceCredentialsService().findDeviceCredentialsByDeviceId(ctx.getTenantId(), deviceId);
if (deviceCredentials == null) {
ctx.tellFailure(msg, new RuntimeException("Failed to get Device Credentials for device: " + deviceId + "!"));
return;
}
var credentialsType = deviceCredentials.getCredentialsType();
var credentialsInfo = ctx.getDeviceCredentialsService().toCredentialsInfo(deviceCredentials);
var metaData = msg.getMetaData().copy();
if (TbMsgSource.METADATA.equals(fetchTo)) {
metaData.putValue(CREDENTIALS_TYPE, credentialsType.name());
if (credentialsType.equals(DeviceCredentialsType.ACCESS_TOKEN) || credentialsType.equals(DeviceCredentialsType.X509_CERTIFICATE)) {
metaData.putValue(CREDENTIALS, credentialsInfo.asText());
} else {
metaData.putValue(CREDENTIALS, JacksonUtil.toString(credentialsInfo));
}
} else if (TbMsgSource.DATA.equals(fetchTo)) {
msgDataAsObjectNode.put(CREDENTIALS_TYPE, credentialsType.name());
msgDataAsObjectNode.set(CREDENTIALS, credentialsInfo);
} | TbMsg transformedMsg = transformMessage(msg, msgDataAsObjectNode, metaData);
ctx.tellSuccess(transformedMsg);
}
@Override
public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException {
return fromVersion == 0 ?
upgradeRuleNodesWithOldPropertyToUseFetchTo(
oldConfiguration,
"fetchToMetadata",
TbMsgSource.METADATA.name(),
TbMsgSource.DATA.name()) :
new TbPair<>(false, oldConfiguration);
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\metadata\TbFetchDeviceCredentialsNode.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Principal
{
public static final Principal userId(@NonNull final UserId userId)
{
return builder().userId(userId).build();
}
public static final Principal userGroupId(@NonNull final UserGroupId userGroupId)
{
return builder().userGroupId(userGroupId).build();
}
@JsonProperty("userId")
@JsonInclude(JsonInclude.Include.NON_NULL)
UserId userId;
@JsonProperty("userGroupId")
@JsonInclude(JsonInclude.Include.NON_NULL)
UserGroupId userGroupId;
@Builder(toBuilder = true)
@JsonCreator | private Principal(
@JsonProperty("userId") final UserId userId,
@JsonProperty("userGroupId") final UserGroupId userGroupId)
{
if (userId != null)
{
Check.assume(userGroupId == null, "Setting both {} and {} not allowed", userId, userGroupId);
this.userId = userId;
this.userGroupId = null;
}
else if (userGroupId != null)
{
Check.assume(userId == null, "Setting both {} and {} not allowed", userId, userGroupId);
this.userId = null;
this.userGroupId = userGroupId;
}
else
{
throw new AdempiereException("UserId or UserGroupId shall be set");
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\Principal.java | 2 |
请完成以下Java代码 | public TenantQuery createTenantQuery(CommandContext commandContext) {
return new DbTenantQueryImpl();
}
public long findTenantCountByQueryCriteria(DbTenantQueryImpl query) {
configureQuery(query, Resources.TENANT);
return (Long) getDbEntityManager().selectOne("selectTenantCountByQueryCriteria", query);
}
public List<Tenant> findTenantByQueryCriteria(DbTenantQueryImpl query) {
configureQuery(query, Resources.TENANT);
return getDbEntityManager().selectList("selectTenantByQueryCriteria", query);
}
//memberships //////////////////////////////////////////
protected boolean existsMembership(String userId, String groupId) {
Map<String, String> key = new HashMap<>();
key.put("userId", userId);
key.put("groupId", groupId);
return ((Long) getDbEntityManager().selectOne("selectMembershipCount", key)) > 0;
}
protected boolean existsTenantMembership(String tenantId, String userId, String groupId) {
Map<String, String> key = new HashMap<>();
key.put("tenantId", tenantId);
if (userId != null) {
key.put("userId", userId);
}
if (groupId != null) {
key.put("groupId", groupId);
} | return ((Long) getDbEntityManager().selectOne("selectTenantMembershipCount", key)) > 0;
}
//authorizations ////////////////////////////////////////////////////
@Override
protected void configureQuery(@SuppressWarnings("rawtypes") AbstractQuery query, Resource resource) {
Context.getCommandContext()
.getAuthorizationManager()
.configureQuery(query, resource);
}
@Override
protected void checkAuthorization(Permission permission, Resource resource, String resourceId) {
Context.getCommandContext()
.getAuthorizationManager()
.checkAuthorization(permission, resource, resourceId);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\identity\db\DbReadOnlyIdentityServiceProvider.java | 1 |
请完成以下Java代码 | private void deleteFactAcct(final List<MatchInv> matchInvs)
{
for (final MatchInv matchInv : matchInvs)
{
if (matchInv.isPosted())
{
MPeriod.testPeriodOpen(Env.getCtx(), Timestamp.from(matchInv.getDateAcct()), DocBaseType.MatchInvoice, matchInv.getOrgId().getRepoId());
factAcctDAO.deleteForRecordRef(toTableRecordReference(matchInv));
}
}
}
private void unpostInvoiceIfNeeded(final List<MatchInv> matchInvs)
{
final HashSet<InvoiceId> invoiceIds = new HashSet<>(); | for (final MatchInv matchInv : matchInvs)
{
// Reposting is required if a M_MatchInv was created for a purchase invoice.
// ... because we book the matched quantity on InventoryClearing and on Expense the not matched quantity
if (matchInv.getSoTrx().isPurchase())
{
costDetailService.voidAndDeleteForDocument(CostingDocumentRef.ofMatchInvoiceId(matchInv.getId()));
invoiceIds.add(matchInv.getInvoiceId());
}
}
invoiceBL.getByIds(invoiceIds)
.forEach(Doc_Invoice::unpostIfNeeded);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\AcctMatchInvListener.java | 1 |
请完成以下Java代码 | public static void setMigrationScriptDirectory(@NonNull final Path path)
{
_migrationScriptsDirectory = path;
logger.info("Set migration scripts directory: {}", path);
}
/**
* Appends given SQL statement.
* <p>
* If this method is called within a database transaction then the SQL statement will not be written to file directly,
* but it will be collected and written when the transaction is committed.
*/
public synchronized void appendSqlStatement(@NonNull final Sql sqlStatement)
{
collectorFactory.collect(sqlStatement);
}
public synchronized void appendSqlStatements(@NonNull final SqlBatch sqlBatch)
{
sqlBatch.streamSqls().forEach(collectorFactory::collect);
}
private synchronized void appendNow(final String sqlStatements)
{
if (sqlStatements == null || sqlStatements.isEmpty())
{
return;
}
try
{ | final Path path = getCreateFilePath();
FileUtil.writeString(path, sqlStatements, CHARSET, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
catch (final IOException ex)
{
logger.error("Failed writing to {}:\n {}", this, sqlStatements, ex);
close(); // better to close the file ... so, next time a new one will be created
}
}
/**
* Close underling file.
* <p>
* Next time, {@link #appendSqlStatement(Sql)} will be called, a new file will be created, so it's safe to call this method as many times as needed.
*/
public synchronized void close()
{
watcher.addLog("Closed migration script: " + _path);
_path = null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\MigrationScriptFileLogger.java | 1 |
请完成以下Java代码 | public class Article {
@BsonId
public ObjectId id;
public String author;
public String title;
public String description;
// getters and setters
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author; | }
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
} | repos\tutorials-master\quarkus-modules\mongo-db\src\main\java\com\baeldung\mongoclient\Article.java | 1 |
请完成以下Java代码 | public boolean isPerfMonActive()
{
return getSysConfigBooleanValue(PM_SYSCONFIG_NAME, PM_SYS_CONFIG_DEFAULT_VALUE);
}
public void performanceMonitoringServiceSaveEx(@NonNull final Runnable runnable)
{
final PerformanceMonitoringService performanceMonitoringService = performanceMonitoringService();
performanceMonitoringService.monitor(runnable, PM_METADATA_SAVE_EX);
}
public boolean performanceMonitoringServiceLoad(@NonNull final Callable<Boolean> callable)
{
final PerformanceMonitoringService performanceMonitoringService = performanceMonitoringService();
return performanceMonitoringService.monitor(callable, PM_METADATA_LOAD);
}
private PerformanceMonitoringService performanceMonitoringService()
{
PerformanceMonitoringService performanceMonitoringService = _performanceMonitoringService;
if (performanceMonitoringService == null || performanceMonitoringService instanceof NoopPerformanceMonitoringService)
{
performanceMonitoringService = _performanceMonitoringService = SpringContextHolder.instance.getBeanOr(
PerformanceMonitoringService.class,
NoopPerformanceMonitoringService.INSTANCE);
}
return performanceMonitoringService;
}
//
//
//
public boolean isDeveloperMode()
{
return developerModeBL().isEnabled();
}
public boolean getSysConfigBooleanValue(final String sysConfigName, final boolean defaultValue, final int ad_client_id, final int ad_org_id)
{
return sysConfigBL().getBooleanValue(sysConfigName, defaultValue, ad_client_id, ad_org_id);
}
public boolean getSysConfigBooleanValue(final String sysConfigName, final boolean defaultValue)
{
return sysConfigBL().getBooleanValue(sysConfigName, defaultValue); | }
public boolean isChangeLogEnabled()
{
return sessionBL().isChangeLogEnabled();
}
public String getInsertChangeLogType(final int adClientId)
{
return sysConfigBL().getValue("SYSTEM_INSERT_CHANGELOG", "N", adClientId);
}
public void saveChangeLogs(final List<ChangeLogRecord> changeLogRecords)
{
sessionDAO().saveChangeLogs(changeLogRecords);
}
public void logMigration(final MFSession session, final PO po, final POInfo poInfo, final String actionType)
{
migrationLogger().logMigration(session, po, poInfo, actionType);
}
public void fireDocumentNoChange(final PO po, final String value)
{
documentNoBL().fireDocumentNoChange(po, value); // task 09776
}
public ADRefList getRefListById(@NonNull final ReferenceId referenceId)
{
return adReferenceService().getRefListById(referenceId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POServicesFacade.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ClientProperties {
/**
* The admin server urls to register at
*/
private String[] url = new String[] {};
/**
* The admin rest-apis path.
*/
private String apiPath = "instances";
/**
* Time interval the registration is repeated
*/
@DurationUnit(ChronoUnit.MILLIS)
private Duration period = Duration.ofMillis(10_000L);
/**
* Connect timeout for the registration.
*/
@DurationUnit(ChronoUnit.MILLIS)
private Duration connectTimeout = Duration.ofMillis(5_000L);
/**
* Read timeout (in ms) for the registration.
*/
@DurationUnit(ChronoUnit.MILLIS)
private Duration readTimeout = Duration.ofMillis(5_000L);
/**
* Username for basic authentication on admin server
*/
@Nullable
private String username;
/**
* Password for basic authentication on admin server
*/
@Nullable
private String password;
/** | * Enable automatic deregistration on shutdown If not set it defaults to true if an
* active {@link CloudPlatform} is present;
*/
@Nullable
private Boolean autoDeregistration = null;
/**
* Enable automatic registration when the application is ready.
*/
private boolean autoRegistration = true;
/**
* Enable registration against one or all admin servers
*/
private boolean registerOnce = true;
/**
* Enable Spring Boot Admin Client.
*/
private boolean enabled = true;
public String[] getAdminUrl() {
String[] adminUrls = this.url.clone();
for (int i = 0; i < adminUrls.length; i++) {
adminUrls[i] += "/" + this.apiPath;
}
return adminUrls;
}
public boolean isAutoDeregistration(Environment environment) {
return (this.autoDeregistration != null) ? this.autoDeregistration
: (CloudPlatform.getActive(environment) != null);
}
} | repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\config\ClientProperties.java | 2 |
请完成以下Java代码 | public class MInvoiceBatch extends X_C_InvoiceBatch
{
/**
*
*/
private static final long serialVersionUID = 3449653049236263604L;
/**
* Standard Constructor
* @param ctx context
* @param C_InvoiceBatch_ID id
* @param trxName trx
*/
public MInvoiceBatch (Properties ctx, int C_InvoiceBatch_ID, String trxName)
{
super (ctx, C_InvoiceBatch_ID, trxName);
if (C_InvoiceBatch_ID == 0)
{
// setDocumentNo (null);
// setC_Currency_ID (0); // @$C_Currency_ID@
setControlAmt (Env.ZERO); // 0
setDateDoc (new Timestamp(System.currentTimeMillis())); // @#Date@
setDocumentAmt (Env.ZERO);
setIsSOTrx (false); // N
setProcessed (false);
// setSalesRep_ID (0);
}
} // MInvoiceBatch
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
public MInvoiceBatch (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MInvoiceBatch
/** The Lines */
private MInvoiceBatchLine[] m_lines = null;
/**
* Get Lines
* @param reload reload data
* @return array of lines
*/
public MInvoiceBatchLine[] getLines (boolean reload)
{
if (m_lines != null && !reload) {
set_TrxName(m_lines, get_TrxName());
return m_lines;
}
String sql = "SELECT * FROM C_InvoiceBatchLine WHERE C_InvoiceBatch_ID=? ORDER BY Line";
ArrayList<MInvoiceBatchLine> list = new ArrayList<MInvoiceBatchLine>();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getC_InvoiceBatch_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
{
list.add (new MInvoiceBatchLine (getCtx(), rs, get_TrxName())); | }
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
log.error(sql, e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
//
m_lines = new MInvoiceBatchLine[list.size ()];
list.toArray (m_lines);
return m_lines;
} // getLines
/**
* Set Processed
* @param processed processed
*/
public void setProcessed (boolean processed)
{
super.setProcessed (processed);
if (get_ID() == 0)
return;
String set = "SET Processed='"
+ (processed ? "Y" : "N")
+ "' WHERE C_InvoiceBatch_ID=" + getC_InvoiceBatch_ID();
int noLine = DB.executeUpdateAndSaveErrorOnFail("UPDATE C_InvoiceBatchLine " + set, get_TrxName());
m_lines = null;
log.debug(processed + " - Lines=" + noLine);
} // setProcessed
} // MInvoiceBatch | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MInvoiceBatch.java | 1 |
请完成以下Java代码 | public void lifecycleEvent(LifecycleEvent event) {
if (Lifecycle.START_EVENT.equals(event.getType())) {
// the Apache Tomcat integration uses the Jmx Container for managing process engines and applications.
containerDelegate = (RuntimeContainerDelegateImpl) RuntimeContainerDelegate.INSTANCE.get();
deployBpmPlatform(event);
}
else if (Lifecycle.STOP_EVENT.equals(event.getType())) {
undeployBpmPlatform(event);
}
}
protected void deployBpmPlatform(LifecycleEvent event) {
final StandardServer server = (StandardServer) event.getSource();
containerDelegate.getServiceContainer().createDeploymentOperation("deploy BPM platform")
.addAttachment(TomcatAttachments.SERVER, server)
.addStep(new TomcatParseBpmPlatformXmlStep())
.addStep(new DiscoverBpmPlatformPluginsStep())
.addStep(new StartManagedThreadPoolStep())
.addStep(new StartJobExecutorStep())
.addStep(new PlatformXmlStartProcessEnginesStep())
.execute();
LOG.camundaBpmPlatformSuccessfullyStarted(server.getServerInfo()); | }
protected void undeployBpmPlatform(LifecycleEvent event) {
final StandardServer server = (StandardServer) event.getSource();
containerDelegate.getServiceContainer().createUndeploymentOperation("undeploy BPM platform")
.addAttachment(TomcatAttachments.SERVER, server)
.addStep(new StopJobExecutorStep())
.addStep(new StopManagedThreadPoolStep())
.addStep(new StopProcessApplicationsStep())
.addStep(new StopProcessEnginesStep())
.addStep(new UnregisterBpmPlatformPluginsStep())
.execute();
LOG.camundaBpmPlatformStopped(server.getServerInfo());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\tomcat\TomcatBpmPlatformBootstrap.java | 1 |
请完成以下Java代码 | 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代码 | protected void initializeOnPart(CaseFileItemOnPart onPart, Sentry sentry, CmmnHandlerContext context) {
// not yet implemented
String id = sentry.getId();
LOG.ignoredUnsupportedAttribute("onPart", "CaseFileItem", id);
}
protected void initializeIfPart(IfPart ifPart, CmmnSentryDeclaration sentryDeclaration, CmmnHandlerContext context) {
if (ifPart == null) {
return;
}
Collection<ConditionExpression> conditions = ifPart.getConditions();
if (conditions.size() > 1) {
String id = sentryDeclaration.getId();
LOG.multipleIgnoredConditions(id);
}
ExpressionManager expressionManager = context.getExpressionManager();
ConditionExpression condition = conditions.iterator().next();
Expression conditionExpression = expressionManager.createExpression(condition.getText());
CmmnIfPartDeclaration ifPartDeclaration = new CmmnIfPartDeclaration();
ifPartDeclaration.setCondition(conditionExpression);
sentryDeclaration.setIfPart(ifPartDeclaration);
}
protected void initializeVariableOnParts(CmmnElement element, CmmnSentryDeclaration sentryDeclaration,
CmmnHandlerContext context, List<CamundaVariableOnPart> variableOnParts) {
for(CamundaVariableOnPart variableOnPart: variableOnParts) {
initializeVariableOnPart(variableOnPart, sentryDeclaration, context);
}
}
protected void initializeVariableOnPart(CamundaVariableOnPart variableOnPart, CmmnSentryDeclaration sentryDeclaration, CmmnHandlerContext context) {
VariableTransition variableTransition;
try {
variableTransition = variableOnPart.getVariableEvent();
} catch(IllegalArgumentException illegalArgumentexception) {
throw LOG.nonMatchingVariableEvents(sentryDeclaration.getId());
} catch(NullPointerException nullPointerException) {
throw LOG.nonMatchingVariableEvents(sentryDeclaration.getId());
}
String variableName = variableOnPart.getVariableName();
String variableEventName = variableTransition.name(); | if (variableName != null) {
if (!sentryDeclaration.hasVariableOnPart(variableEventName, variableName)) {
CmmnVariableOnPartDeclaration variableOnPartDeclaration = new CmmnVariableOnPartDeclaration();
variableOnPartDeclaration.setVariableEvent(variableEventName);
variableOnPartDeclaration.setVariableName(variableName);
sentryDeclaration.addVariableOnParts(variableOnPartDeclaration);
}
} else {
throw LOG.emptyVariableName(sentryDeclaration.getId());
}
}
protected <V extends ModelElementInstance> List<V> queryExtensionElementsByClass(CmmnElement element, Class<V> cls) {
ExtensionElements extensionElements = element.getExtensionElements();
if (extensionElements != null) {
Query<ModelElementInstance> query = extensionElements.getElementsQuery();
return query.filterByType(cls).list();
} else {
return new ArrayList<V>();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\SentryHandler.java | 1 |
请完成以下Java代码 | public Token createNewToken(String tokenId) {
TokenEntity tokenEntity = create();
tokenEntity.setId(tokenId);
tokenEntity.setRevision(0); // needed as tokens can be transient
return tokenEntity;
}
@Override
public void updateToken(Token updatedToken) {
super.update((TokenEntity) updatedToken);
}
@Override
public boolean isNewToken(Token token) {
return ((TokenEntity) token).getRevision() == 0;
}
@Override
public List<Token> findTokenByQueryCriteria(TokenQueryImpl query) {
return dataManager.findTokenByQueryCriteria(query);
}
@Override | public long findTokenCountByQueryCriteria(TokenQueryImpl query) {
return dataManager.findTokenCountByQueryCriteria(query);
}
@Override
public TokenQuery createNewTokenQuery() {
return new TokenQueryImpl(getCommandExecutor());
}
@Override
public List<Token> findTokensByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findTokensByNativeQuery(parameterMap);
}
@Override
public long findTokenCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findTokenCountByNativeQuery(parameterMap);
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\TokenEntityManagerImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
public static class Packages {
/**
* Whether to trust all packages.
*/
private @Nullable Boolean trustAll;
/**
* List of specific packages to trust (when not trusting all packages).
*/ | private List<String> trusted = new ArrayList<>();
public @Nullable Boolean getTrustAll() {
return this.trustAll;
}
public void setTrustAll(@Nullable Boolean trustAll) {
this.trustAll = trustAll;
}
public List<String> getTrusted() {
return this.trusted;
}
public void setTrusted(List<String> trusted) {
this.trusted = trusted;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQProperties.java | 2 |
请完成以下Java代码 | public boolean isRequisition(final DocTypeId docTypeId)
{
final I_C_DocType dt = docTypesRepo.getById(docTypeId);
return X_C_DocType.DOCSUBTYPE_Requisition.equals(dt.getDocSubType())
&& X_C_DocType.DOCBASETYPE_PurchaseOrder.equals(dt.getDocBaseType());
}
@Override
public boolean isMediated(@NonNull final DocTypeId docTypeId)
{
final I_C_DocType dt = docTypesRepo.getById(docTypeId);
return X_C_DocType.DOCSUBTYPE_Mediated.equals(dt.getDocSubType())
&& X_C_DocType.DOCBASETYPE_PurchaseOrder.equals(dt.getDocBaseType());
}
@Override
public boolean isCallOrder(@NonNull final DocTypeId docTypeId)
{
final I_C_DocType dt = docTypesRepo.getById(docTypeId);
return (X_C_DocType.DOCBASETYPE_SalesOrder.equals(dt.getDocBaseType()) || X_C_DocType.DOCBASETYPE_PurchaseOrder.equals(dt.getDocBaseType()))
&& X_C_DocType.DOCSUBTYPE_CallOrder.equals(dt.getDocSubType());
}
@Override
public void save(@NonNull final I_C_DocType dt)
{
docTypesRepo.save(dt);
} | @NonNull
public ImmutableList<I_C_DocType> retrieveForSelection(@NonNull final PInstanceId pinstanceId)
{
return docTypesRepo.retrieveForSelection(pinstanceId);
}
public DocTypeId cloneToOrg(@NonNull final I_C_DocType fromDocType, @NonNull final OrgId toOrgId)
{
final String newName = fromDocType.getName() + "_cloned";
final I_C_DocType newDocType = InterfaceWrapperHelper.copy()
.setFrom(fromDocType)
.setSkipCalculatedColumns(true)
.copyToNew(I_C_DocType.class);
newDocType.setAD_Org_ID(toOrgId.getRepoId());
// dev-note: unique index (ad_client_id, name)
newDocType.setName(newName);
final DocSequenceId fromDocSequenceId = DocSequenceId.ofRepoIdOrNull(fromDocType.getDocNoSequence_ID());
if (fromDocType.isDocNoControlled() && fromDocSequenceId != null)
{
final DocSequenceId clonedDocSequenceId = sequenceDAO.cloneToOrg(fromDocSequenceId, toOrgId);
newDocType.setDocNoSequence_ID(clonedDocSequenceId.getRepoId());
newDocType.setIsDocNoControlled(true);
}
save(newDocType);
return DocTypeId.ofRepoId(newDocType.getC_DocType_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\impl\DocTypeBL.java | 1 |
请完成以下Java代码 | public ListenerContainerFactoryResolver.Configuration forContainerFactoryResolver() {
return this.factoryResolverConfig;
}
public @Nullable EndpointHandlerMethod getDltHandlerMethod() {
return this.dltHandlerMethod;
}
public List<DestinationTopic.Properties> getDestinationTopicProperties() {
return this.destinationTopicProperties;
}
@Nullable
public Integer getConcurrency() {
return this.concurrency;
}
static class TopicCreation {
private final boolean shouldCreateTopics;
private final int numPartitions;
private final short replicationFactor;
TopicCreation(@Nullable Boolean shouldCreate, @Nullable Integer numPartitions, @Nullable Short replicationFactor) {
this.shouldCreateTopics = shouldCreate == null || shouldCreate;
this.numPartitions = numPartitions == null ? 1 : numPartitions;
this.replicationFactor = replicationFactor == null ? -1 : replicationFactor;
}
TopicCreation() {
this.shouldCreateTopics = true; | this.numPartitions = 1;
this.replicationFactor = -1;
}
TopicCreation(boolean shouldCreateTopics) {
this.shouldCreateTopics = shouldCreateTopics;
this.numPartitions = 1;
this.replicationFactor = -1;
}
public int getNumPartitions() {
return this.numPartitions;
}
public short getReplicationFactor() {
return this.replicationFactor;
}
public boolean shouldCreateTopics() {
return this.shouldCreateTopics;
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\RetryTopicConfiguration.java | 1 |
请完成以下Java代码 | public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
} | public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<String> getPhones() {
return phones;
}
public void setPhones(List<String> phones) {
this.phones = phones;
}
} | repos\tutorials-master\json-modules\json-3\src\main\java\com\baeldung\pojomapping\User.java | 1 |
请完成以下Java代码 | public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(this.id, user.id) &&
Objects.equals(this.username, user.username) &&
Objects.equals(this.firstName, user.firstName) &&
Objects.equals(this.lastName, user.lastName) &&
Objects.equals(this.email, user.email) &&
Objects.equals(this.password, user.password) &&
Objects.equals(this.phone, user.phone) &&
Objects.equals(this.userStatus, user.userStatus);
}
@Override
public int hashCode() {
return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class User {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n");
sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" password: ").append(toIndentedString(password)).append("\n"); | sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\User.java | 1 |
请完成以下Java代码 | public class LoadBankStatement extends JavaProcess
{
public LoadBankStatement()
{
super();
log.info("LoadBankStatement");
} // LoadBankStatement
/** Client to be imported to */
private int m_AD_Client_ID = 0;
/** Organization to be imported to */
private int m_AD_Org_ID = 0;
/** Ban Statement Loader */
private int m_C_BankStmtLoader_ID = 0;
/** File to be imported */
private String fileName = "";
/** Current context */
private Properties m_ctx;
/** Current context */
private MBankStatementLoader m_controller = null;
/**
* Prepare - e.g., get Parameters.
*/
protected void prepare()
{
log.info("");
m_ctx = Env.getCtx();
ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (name.equals("C_BankStatementLoader_ID"))
m_C_BankStmtLoader_ID = ((BigDecimal)para[i].getParameter()).intValue();
else if (name.equals("FileName"))
fileName = (String)para[i].getParameter();
else | log.error("Unknown Parameter: " + name);
}
m_AD_Client_ID = Env.getAD_Client_ID(m_ctx);
log.info("AD_Client_ID=" + m_AD_Client_ID);
m_AD_Org_ID = Env.getAD_Org_ID(m_ctx);
log.info("AD_Org_ID=" + m_AD_Org_ID);
log.info("C_BankStatementLoader_ID=" + m_C_BankStmtLoader_ID);
} // prepare
/**
* Perform process.
* @return Message
* @throws Exception
*/
protected String doIt() throws java.lang.Exception
{
log.info("LoadBankStatement.doIt");
String message = "@Error@";
m_controller = new MBankStatementLoader(m_ctx, m_C_BankStmtLoader_ID, fileName, get_TrxName());
log.info(m_controller.toString());
if (m_controller == null || m_controller.get_ID() == 0)
log.error("Invalid Loader");
// Start loading bank statement lines
else if (!m_controller.loadLines())
log.error(m_controller.getErrorMessage() + " - " + m_controller.getErrorDescription());
else
{
log.info("Imported=" + m_controller.getImportCount());
addLog (0, null, new BigDecimal (m_controller.getImportCount()), "@Loaded@");
message = "@OK@";
}
return message;
} // doIt
} // LoadBankStatement | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\process\LoadBankStatement.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.