index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/TransactionTypeRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface TransactionTypeRepository extends JpaRepository<TransactionTypeEntity, Long> { Page<TransactionTypeEntity> findByIdentifierContainingOrNameContaining(final String identifier, final String name, final Pageable pageable); Optional<TransactionTypeEntity> findByIdentifier(final String identifier); }
4,800
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/LedgerRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface LedgerRepository extends JpaRepository<LedgerEntity, Long>, JpaSpecificationExecutor<LedgerEntity> { List<LedgerEntity> findByParentLedgerIsNull(); List<LedgerEntity> findByParentLedgerIsNullAndType(final String type); List<LedgerEntity> findByParentLedgerOrderByIdentifier(final LedgerEntity parentLedger); LedgerEntity findByIdentifier(final String identifier); }
4,801
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/TransactionTypeEntity.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @SuppressWarnings("unused") @Entity @Table(name = "thoth_tx_types") public class TransactionTypeEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) private Long id; @Column(name = "identifier", nullable = false, length = 32) private String identifier; @Column(name = "a_name", nullable = false, length = 256) private String name; @SuppressWarnings("DefaultAnnotationParam") @Column(name = "description", nullable = true, length = 2048) private String description; public TransactionTypeEntity() { super(); } public Long getId() { return this.id; } public void setId(final Long id) { this.id = id; } public String getIdentifier() { return this.identifier; } public void setIdentifier(final String identifier) { this.identifier = identifier; } public String getName() { return this.name; } public void setName(final String name) { this.name = name; } public String getDescription() { return this.description; } public void setDescription(final String description) { this.description = description; } }
4,802
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/JournalEntryEntity.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import java.time.LocalDateTime; import java.util.Set; @SuppressWarnings({"unused", "WeakerAccess"}) @Table(name = "thoth_journal_entries") public class JournalEntryEntity { @SuppressWarnings("DefaultAnnotationParam") @PartitionKey(value = 0) @Column(name = "date_bucket") private String dateBucket; @SuppressWarnings("DefaultAnnotationParam") @ClusteringColumn(value = 0) @Column(name = "transaction_identifier") private String transactionIdentifier; @Column(name = "transaction_date") private LocalDateTime transactionDate; @Column(name = "transaction_type") private String transactionType; @Column(name = "clerk") private String clerk; @Column(name = "note") private String note; @Frozen @Column(name = "debtors") private Set<DebtorType> debtors; @Frozen @Column(name = "creditors") private Set<CreditorType> creditors; @Column(name = "state") private String state; @Column(name = "message") private String message; @Column(name = "created_on") private LocalDateTime createdOn; @Column(name = "created_by") private String createdBy; public JournalEntryEntity() { super(); } public String getDateBucket() { return this.dateBucket; } public void setDateBucket(final String dateBucket) { this.dateBucket = dateBucket; } public String getTransactionIdentifier() { return this.transactionIdentifier; } public void setTransactionIdentifier(final String transactionIdentifier) { this.transactionIdentifier = transactionIdentifier; } public LocalDateTime getTransactionDate() { return this.transactionDate; } public void setTransactionDate(final LocalDateTime transactionDate) { this.transactionDate = transactionDate; } public String getTransactionType() { return this.transactionType; } public void setTransactionType(final String transactionType) { this.transactionType = transactionType; } public String getClerk() { return this.clerk; } public void setClerk(final String clerk) { this.clerk = clerk; } public String getNote() { return this.note; } public void setNote(final String note) { this.note = note; } public Set<DebtorType> getDebtors() { return this.debtors; } public void setDebtors(final Set<DebtorType> debtors) { this.debtors = debtors; } public Set<CreditorType> getCreditors() { return this.creditors; } public void setCreditors(final Set<CreditorType> creditors) { this.creditors = creditors; } public String getState() { return this.state; } public void setState(final String state) { this.state = state; } public String getMessage() { return this.message; } public void setMessage(final String message) { this.message = message; } public LocalDateTime getCreatedOn() { return this.createdOn; } public void setCreatedOn(final LocalDateTime createdOn) { this.createdOn = createdOn; } public String getCreatedBy() { return this.createdBy; } public void setCreatedBy(final String createdBy) { this.createdBy = createdBy; } }
4,803
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/AccountEntryEntity.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.apache.fineract.cn.postgresql.util.LocalDateTimeConverter; @SuppressWarnings({"unused"}) @Entity @Table(name = "thoth_account_entries") public class AccountEntryEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "account_id") private AccountEntity account; @Column(name = "a_type") private String type; @Column(name = "transaction_date") @Convert(converter = LocalDateTimeConverter.class) private LocalDateTime transactionDate; @Column(name = "message") private String message; @Column(name = "amount") private Double amount; @Column(name = "balance") private Double balance; public AccountEntryEntity() { super(); } public Long getId() { return this.id; } public void setId(final Long id) { this.id = id; } public AccountEntity getAccount() { return this.account; } public void setAccount(final AccountEntity account) { this.account = account; } public String getType() { return this.type; } public void setType(final String type) { this.type = type; } public LocalDateTime getTransactionDate() { return this.transactionDate; } public void setTransactionDate(final LocalDateTime transactionDate) { this.transactionDate = transactionDate; } public String getMessage() { return this.message; } public void setMessage(final String message) { this.message = message; } public Double getAmount() { return this.amount; } public void setAmount(final Double amount) { this.amount = amount; } public Double getBalance() { return this.balance; } public void setBalance(final Double balance) { this.balance = balance; } }
4,804
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/JournalEntryRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Session; import com.datastax.driver.core.SimpleStatement; import com.datastax.driver.core.Statement; import com.datastax.driver.core.querybuilder.QueryBuilder; import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.Result; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider; import org.apache.fineract.cn.cassandra.core.TenantAwareCassandraMapperProvider; import org.apache.fineract.cn.cassandra.core.TenantAwareEntityTemplate; import org.apache.fineract.cn.lang.DateConverter; import org.apache.fineract.cn.lang.DateRange; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @SuppressWarnings({"unused"}) @Repository public class JournalEntryRepository { private final CassandraSessionProvider cassandraSessionProvider; private final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider; private final TenantAwareEntityTemplate tenantAwareEntityTemplate; @Autowired public JournalEntryRepository(final CassandraSessionProvider cassandraSessionProvider, final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider, final TenantAwareEntityTemplate tenantAwareEntityTemplate) { super(); this.cassandraSessionProvider = cassandraSessionProvider; this.tenantAwareCassandraMapperProvider = tenantAwareCassandraMapperProvider; this.tenantAwareEntityTemplate = tenantAwareEntityTemplate; } public void saveJournalEntry(final JournalEntryEntity journalEntryEntity) { this.tenantAwareEntityTemplate.save(journalEntryEntity); final JournalEntryLookup journalEntryLookup = new JournalEntryLookup(); journalEntryLookup.setTransactionIdentifier(journalEntryEntity.getTransactionIdentifier()); journalEntryLookup.setDateBucket(journalEntryEntity.getDateBucket()); this.tenantAwareEntityTemplate.save(journalEntryLookup); } public List<JournalEntryEntity> fetchJournalEntries(final DateRange range) { final Session tenantSession = this.cassandraSessionProvider.getTenantSession(); final List<String> datesInBetweenRange = range.stream() .map(DateConverter::toIsoString) .collect(Collectors.toList()); final Statement stmt = new SimpleStatement( QueryBuilder .select().all() .from("thoth_journal_entries") .where(QueryBuilder.in("date_bucket", datesInBetweenRange)).getQueryString(), datesInBetweenRange.toArray() ); final ResultSet resultSet = tenantSession.execute(stmt); final Mapper<JournalEntryEntity> mapper = this.tenantAwareCassandraMapperProvider.getMapper(JournalEntryEntity.class); final Result<JournalEntryEntity> journalEntryEntities = mapper.map(resultSet); return journalEntryEntities.all(); } public Optional<JournalEntryEntity> findJournalEntry(final String transactionIdentifier) { final Optional<JournalEntryLookup> optionalJournalEntryLookup = this.tenantAwareEntityTemplate.findById(JournalEntryLookup.class, transactionIdentifier); if (optionalJournalEntryLookup.isPresent()) { final JournalEntryLookup journalEntryLookup = optionalJournalEntryLookup.get(); final List<JournalEntryEntity> journalEntryEntities = this.tenantAwareEntityTemplate.fetchByKeys(JournalEntryEntity.class, journalEntryLookup.getDateBucket(), journalEntryLookup.getTransactionIdentifier()); return Optional.of(journalEntryEntities.get(0)); } else { return Optional.empty(); } } }
4,805
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/AccountRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; import java.util.stream.Stream; @Repository public interface AccountRepository extends JpaRepository<AccountEntity, Long>, JpaSpecificationExecutor<AccountEntity> { List<AccountEntity> findByLedger(final LedgerEntity ledgerEntity); Page<AccountEntity> findByLedger(final LedgerEntity ledgerEntity, final Pageable pageable); AccountEntity findByIdentifier(final String identifier); @Query("SELECT CASE WHEN count(a) > 0 THEN true ELSE false END FROM AccountEntity a where a.referenceAccount = :accountEntity") Boolean existsByReference(@Param("accountEntity") final AccountEntity accountEntity); Stream<AccountEntity> findByBalanceIsNot(final Double value); }
4,806
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/CommandRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface CommandRepository extends JpaRepository<CommandEntity, Long> { List<CommandEntity> findByAccount(final AccountEntity accountEntity); }
4,807
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/AccountEntryRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import java.time.LocalDateTime; import javax.persistence.Convert; import org.apache.fineract.cn.postgresql.util.LocalDateTimeConverter; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; @Repository public interface AccountEntryRepository extends JpaRepository<AccountEntryEntity, Long> { @Convert(converter = LocalDateTimeConverter.class) Page<AccountEntryEntity> findByAccountAndTransactionDateBetween(final AccountEntity accountEntity, final LocalDateTime dateFrom, final LocalDateTime dateTo, final Pageable pageable); @Convert(converter = LocalDateTimeConverter.class) Page<AccountEntryEntity> findByAccountAndTransactionDateBetweenAndMessageEquals(final AccountEntity accountEntity, final LocalDateTime dateFrom, final LocalDateTime dateTo, final String message, final Pageable pageable); @Query("SELECT CASE WHEN count(a) > 0 THEN true ELSE false END FROM AccountEntryEntity a where a.account = :accountEntity") Boolean existsByAccount(@Param("accountEntity") final AccountEntity accountEntity); }
4,808
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/JournalEntryLookup.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; @SuppressWarnings({"unused", "WeakerAccess"}) @Table(name = "thoth_journal_entry_lookup") public class JournalEntryLookup { @PartitionKey @Column(name = "transaction_identifier") private String transactionIdentifier; @Column(name = "date_bucket") private String dateBucket; public JournalEntryLookup() { super(); } public String getTransactionIdentifier() { return this.transactionIdentifier; } public void setTransactionIdentifier(final String transactionIdentifier) { this.transactionIdentifier = transactionIdentifier; } public String getDateBucket() { return this.dateBucket; } public void setDateBucket(final String dateBucket) { this.dateBucket = dateBucket; } }
4,809
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/CreditorType.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import com.datastax.driver.mapping.annotations.Field; import com.datastax.driver.mapping.annotations.UDT; @SuppressWarnings({"unused"}) @UDT(name = "thoth_creditor") public class CreditorType { @Field(name = "account_number") private String accountNumber; @Field(name = "amount") private Double amount; public CreditorType() { super(); } public String getAccountNumber() { return this.accountNumber; } public void setAccountNumber(final String accountNumber) { this.accountNumber = accountNumber; } public Double getAmount() { return this.amount; } public void setAmount(final Double amount) { this.amount = amount; } }
4,810
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/AccountEntity.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import java.time.LocalDateTime; import javax.persistence.*; import org.apache.fineract.cn.postgresql.util.LocalDateTimeConverter; @SuppressWarnings({"unused"}) @Entity @Table(name = "thoth_accounts") public class AccountEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "a_type") private String type; @Column(name = "identifier") private String identifier; @Column(name = "a_name") private String name; @Column(name = "holders") private String holders; @Column(name = "signature_authorities") private String signatureAuthorities; @Column(name = "balance") private Double balance; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "reference_account_id") private AccountEntity referenceAccount; @OneToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "ledger_id") private LedgerEntity ledger; @Column(name = "a_state") private String state; @Column(name = "alternative_account_number", length = 256, nullable = true) private String alternativeAccountNumber; @Column(name = "created_on") @Convert(converter = LocalDateTimeConverter.class) private LocalDateTime createdOn; @Column(name = "created_by") private String createdBy; @Column(name = "last_modified_on") @Convert(converter = LocalDateTimeConverter.class) private LocalDateTime lastModifiedOn; @Column(name = "last_modified_by") private String lastModifiedBy; public AccountEntity() { super(); } public Long getId() { return this.id; } public void setId(final Long id) { this.id = id; } public String getType() { return this.type; } public void setType(final String type) { this.type = type; } public String getIdentifier() { return this.identifier; } public void setIdentifier(final String identifier) { this.identifier = identifier; } public String getName() { return this.name; } public void setName(final String name) { this.name = name; } public String getHolders() { return this.holders; } public void setHolders(final String holders) { this.holders = holders; } public String getSignatureAuthorities() { return this.signatureAuthorities; } public void setSignatureAuthorities(final String signatureAuthorities) { this.signatureAuthorities = signatureAuthorities; } public Double getBalance() { return this.balance; } public void setBalance(final Double balance) { this.balance = balance; } public AccountEntity getReferenceAccount() { return this.referenceAccount; } public void setReferenceAccount(final AccountEntity referenceAccount) { this.referenceAccount = referenceAccount; } public LedgerEntity getLedger() { return this.ledger; } public void setLedger(final LedgerEntity ledger) { this.ledger = ledger; } public String getState() { return this.state; } public void setState(final String state) { this.state = state; } public String getAlternativeAccountNumber() { return this.alternativeAccountNumber; } public void setAlternativeAccountNumber(final String alternativeAccountNumber) { this.alternativeAccountNumber = alternativeAccountNumber; } public LocalDateTime getCreatedOn() { return this.createdOn; } public void setCreatedOn(final LocalDateTime createdOn) { this.createdOn = createdOn; } public String getCreatedBy() { return this.createdBy; } public void setCreatedBy(final String createdBy) { this.createdBy = createdBy; } public LocalDateTime getLastModifiedOn() { return this.lastModifiedOn; } public void setLastModifiedOn(final LocalDateTime lastModifiedOn) { this.lastModifiedOn = lastModifiedOn; } public String getLastModifiedBy() { return this.lastModifiedBy; } public void setLastModifiedBy(final String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final AccountEntity that = (AccountEntity) o; return identifier.equals(that.identifier); } @Override public int hashCode() { return identifier.hashCode(); } }
4,811
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/LedgerEntity.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import java.math.BigDecimal; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.apache.fineract.cn.postgresql.util.LocalDateTimeConverter; @SuppressWarnings({"unused"}) @Entity @Table(name = "thoth_ledgers") public class LedgerEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "a_type") private String type; @Column(name = "identifier") private String identifier; @Column(name = "a_name") private String name; @Column(name = "description") private String description; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "parent_ledger_id") private LedgerEntity parentLedger; @Column(name = "total_value") private BigDecimal totalValue; @Column(name = "created_on") @Convert(converter = LocalDateTimeConverter.class) private LocalDateTime createdOn; @Column(name = "created_by") private String createdBy; @Column(name = "last_modified_on") @Convert(converter = LocalDateTimeConverter.class) private LocalDateTime lastModifiedOn; @Column(name = "last_modified_by") private String lastModifiedBy; @Column(name = "show_accounts_in_chart") private Boolean showAccountsInChart; public LedgerEntity() { super(); } public Long getId() { return this.id; } public void setId(final Long id) { this.id = id; } public String getType() { return this.type; } public void setType(final String type) { this.type = type; } public String getIdentifier() { return this.identifier; } public void setIdentifier(final String identifier) { this.identifier = identifier; } public String getName() { return this.name; } public void setName(final String name) { this.name = name; } public String getDescription() { return this.description; } public void setDescription(final String description) { this.description = description; } public LedgerEntity getParentLedger() { return this.parentLedger; } public void setParentLedger(final LedgerEntity parentLedger) { this.parentLedger = parentLedger; } public BigDecimal getTotalValue() { return this.totalValue; } public void setTotalValue(final BigDecimal totalValue) { this.totalValue = totalValue; } public LocalDateTime getCreatedOn() { return this.createdOn; } public void setCreatedOn(final LocalDateTime createdOn) { this.createdOn = createdOn; } public String getCreatedBy() { return this.createdBy; } public void setCreatedBy(final String createdBy) { this.createdBy = createdBy; } public LocalDateTime getLastModifiedOn() { return this.lastModifiedOn; } public void setLastModifiedOn(final LocalDateTime lastModifiedOn) { this.lastModifiedOn = lastModifiedOn; } public String getLastModifiedBy() { return this.lastModifiedBy; } public void setLastModifiedBy(final String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public Boolean getShowAccountsInChart() { return this.showAccountsInChart; } public void setShowAccountsInChart(final Boolean showAccountsInChart) { this.showAccountsInChart = showAccountsInChart; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final LedgerEntity that = (LedgerEntity) o; return identifier.equals(that.identifier); } @Override public int hashCode() { return identifier.hashCode(); } }
4,812
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/CommandEntity.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import org.apache.fineract.cn.postgresql.util.LocalDateTimeConverter; @SuppressWarnings("unused") @Entity @Table(name = "thoth_commands") public class CommandEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @OneToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "account_id") private AccountEntity account; @Column(name = "a_type") private String type; @Column(name = "a_comment") private String comment; @Column(name = "created_by") private String createdBy; @Column(name = "created_on") @Convert(converter = LocalDateTimeConverter.class) private LocalDateTime createdOn; public CommandEntity() { super(); } public Long getId() { return this.id; } public void setId(final Long id) { this.id = id; } public AccountEntity getAccount() { return this.account; } public void setAccount(final AccountEntity account) { this.account = account; } public String getType() { return this.type; } public void setType(final String type) { this.type = type; } public String getComment() { return this.comment; } public void setComment(final String comment) { this.comment = comment; } public String getCreatedBy() { return this.createdBy; } public void setCreatedBy(final String createdBy) { this.createdBy = createdBy; } public LocalDateTime getCreatedOn() { return this.createdOn; } public void setCreatedOn(final LocalDateTime createdOn) { this.createdOn = createdOn; } }
4,813
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/DebtorType.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository; import com.datastax.driver.mapping.annotations.Field; import com.datastax.driver.mapping.annotations.UDT; @SuppressWarnings({"unused"}) @UDT(name = "thoth_debtor") public class DebtorType { @Field(name = "account_number") private String accountNumber; @Field(name = "amount") private Double amount; public DebtorType() { super(); } public String getAccountNumber() { return this.accountNumber; } public void setAccountNumber(final String accountNumber) { this.accountNumber = accountNumber; } public Double getAmount() { return this.amount; } public void setAmount(final Double amount) { this.amount = amount; } }
4,814
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/specification/LedgerSpecification.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository.specification; import org.apache.fineract.cn.accounting.service.internal.repository.LedgerEntity; import org.springframework.data.jpa.domain.Specification; import javax.persistence.criteria.Predicate; import java.util.ArrayList; public class LedgerSpecification { private LedgerSpecification() { super(); } public static Specification<LedgerEntity> createSpecification( final boolean includeSubLedger, final String term, final String type) { return (root, query, cb) -> { final ArrayList<Predicate> predicates = new ArrayList<>(); if (!includeSubLedger) { predicates.add( cb.isNull(root.get("parentLedger")) ); } if (term != null) { final String likeExpression = "%" + term + "%"; predicates.add( cb.or( cb.like(root.get("identifier"), likeExpression), cb.like(root.get("name"), likeExpression) ) ); } if (type != null) { predicates.add(cb.equal(root.get("type"), type)); } return cb.and(predicates.toArray(new Predicate[predicates.size()])); }; } }
4,815
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/repository/specification/AccountSpecification.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.repository.specification; import org.apache.fineract.cn.accounting.api.v1.domain.Account; import org.apache.fineract.cn.accounting.service.internal.repository.AccountEntity; import org.springframework.data.jpa.domain.Specification; import javax.persistence.criteria.Predicate; import java.util.ArrayList; public class AccountSpecification { private AccountSpecification() { super(); } public static Specification<AccountEntity> createSpecification( final boolean includeClosed, final String term, final String type, final boolean includeCustomerAccounts) { return (root, query, cb) -> { final ArrayList<Predicate> predicates = new ArrayList<>(); if (!includeClosed) { predicates.add( root.get("state").in( Account.State.OPEN.name(), Account.State.LOCKED.name() ) ); } if (term != null) { final String likeExpression = "%" + term + "%"; predicates.add( cb.or( cb.like(root.get("identifier"), likeExpression), cb.like(root.get("name"), likeExpression), cb.like(root.get("alternativeAccountNumber"), likeExpression) ) ); } if (type != null) { predicates.add(cb.equal(root.get("type"), type)); } if (!includeCustomerAccounts) { predicates.add( cb.or( cb.equal(root.get("holders"), ""), cb.isNull(root.get("holders")) ) ); } return cb.and(predicates.toArray(new Predicate[predicates.size()])); }; } }
4,816
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/mapper/LedgerMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.mapper; import org.apache.fineract.cn.accounting.api.v1.domain.Ledger; import org.apache.fineract.cn.accounting.service.internal.repository.LedgerEntity; import java.math.BigDecimal; import org.apache.fineract.cn.lang.DateConverter; public class LedgerMapper { private LedgerMapper() { super(); } public static Ledger map(final LedgerEntity ledgerEntity) { final Ledger ledger = new Ledger(); ledger.setType(ledgerEntity.getType()); ledger.setIdentifier(ledgerEntity.getIdentifier()); ledger.setName(ledgerEntity.getName()); ledger.setDescription(ledgerEntity.getDescription()); if (ledgerEntity.getParentLedger() != null) { ledger.setParentLedgerIdentifier(ledgerEntity.getParentLedger().getIdentifier()); } ledger.setCreatedBy(ledgerEntity.getCreatedBy()); ledger.setCreatedOn(DateConverter.toIsoString(ledgerEntity.getCreatedOn())); if (ledgerEntity.getLastModifiedBy() != null) { ledger.setLastModifiedBy(ledgerEntity.getLastModifiedBy()); ledger.setLastModifiedOn(DateConverter.toIsoString(ledgerEntity.getLastModifiedOn())); } ledger.setShowAccountsInChart(ledgerEntity.getShowAccountsInChart()); final BigDecimal totalValue = ledgerEntity.getTotalValue() != null ? ledgerEntity.getTotalValue() : BigDecimal.ZERO; ledger.setTotalValue(totalValue); return ledger; } }
4,817
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/mapper/AccountMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.mapper; import org.apache.fineract.cn.accounting.api.v1.domain.Account; import org.apache.fineract.cn.accounting.service.internal.repository.AccountEntity; import java.util.Arrays; import java.util.HashSet; import org.apache.commons.lang.StringUtils; import org.apache.fineract.cn.lang.DateConverter; public class AccountMapper { private AccountMapper() { super(); } public static Account map(final AccountEntity accountEntity) { final Account account = new Account(); account.setIdentifier(accountEntity.getIdentifier()); account.setName(accountEntity.getName()); account.setType(accountEntity.getType()); account.setLedger(accountEntity.getLedger().getIdentifier()); if (accountEntity.getHolders() != null) { account.setHolders( new HashSet<>(Arrays.asList(StringUtils.split(accountEntity.getHolders(), ","))) ); } if (accountEntity.getSignatureAuthorities() != null) { account.setSignatureAuthorities( new HashSet<>(Arrays.asList(StringUtils.split(accountEntity.getSignatureAuthorities(), ","))) ); } if (accountEntity.getReferenceAccount() != null) { account.setReferenceAccount(accountEntity.getReferenceAccount().getIdentifier()); } account.setBalance(accountEntity.getBalance()); account.setAlternativeAccountNumber(accountEntity.getAlternativeAccountNumber()); account.setCreatedBy(accountEntity.getCreatedBy()); account.setCreatedOn(DateConverter.toIsoString(accountEntity.getCreatedOn())); if (accountEntity.getLastModifiedBy() != null) { account.setLastModifiedBy(accountEntity.getLastModifiedBy()); account.setLastModifiedOn(DateConverter.toIsoString(accountEntity.getLastModifiedOn())); } account.setState(accountEntity.getState()); return account; } }
4,818
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/mapper/AccountCommandMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.mapper; import org.apache.fineract.cn.accounting.api.v1.domain.AccountCommand; import org.apache.fineract.cn.accounting.service.internal.repository.CommandEntity; import org.apache.fineract.cn.lang.DateConverter; public class AccountCommandMapper { public AccountCommandMapper() { super(); } public static AccountCommand map(final CommandEntity commandEntity){ final AccountCommand command = new AccountCommand(); command.setAction(commandEntity.getType()); command.setComment(commandEntity.getComment()); command.setCreatedBy(commandEntity.getCreatedBy()); command.setCreatedOn(DateConverter.toIsoString(commandEntity.getCreatedOn())); return command; } }
4,819
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/mapper/JournalEntryMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.mapper; import org.apache.fineract.cn.accounting.api.v1.domain.Creditor; import org.apache.fineract.cn.accounting.api.v1.domain.Debtor; import org.apache.fineract.cn.accounting.api.v1.domain.JournalEntry; import org.apache.fineract.cn.accounting.service.internal.repository.JournalEntryEntity; import java.util.stream.Collectors; import org.apache.fineract.cn.lang.DateConverter; public class JournalEntryMapper { private JournalEntryMapper() { super(); } public static JournalEntry map(final JournalEntryEntity journalEntryEntity) { final JournalEntry journalEntry = new JournalEntry(); journalEntry.setTransactionIdentifier(journalEntryEntity.getTransactionIdentifier()); journalEntry.setTransactionDate(DateConverter.toIsoString(journalEntryEntity.getTransactionDate())); journalEntry.setTransactionType(journalEntryEntity.getTransactionType()); journalEntry.setClerk(journalEntryEntity.getClerk()); journalEntry.setNote(journalEntryEntity.getNote()); journalEntry.setDebtors( journalEntryEntity.getDebtors() .stream() .map(debtorType -> { final Debtor debtor = new Debtor(); debtor.setAccountNumber(debtorType.getAccountNumber()); debtor.setAmount(Double.toString(debtorType.getAmount())); return debtor; }) .collect(Collectors.toSet()) ); journalEntry.setCreditors( journalEntryEntity.getCreditors() .stream() .map(creditorType -> { final Creditor creditor = new Creditor(); creditor.setAccountNumber(creditorType.getAccountNumber()); creditor.setAmount(Double.toString(creditorType.getAmount())); return creditor; }) .collect(Collectors.toSet()) ); journalEntry.setMessage(journalEntryEntity.getMessage()); journalEntry.setState(journalEntryEntity.getState()); return journalEntry; } }
4,820
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/mapper/AccountEntryMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.mapper; import org.apache.fineract.cn.accounting.api.v1.domain.AccountEntry; import org.apache.fineract.cn.accounting.service.internal.repository.AccountEntryEntity; import org.apache.fineract.cn.lang.DateConverter; public class AccountEntryMapper { private AccountEntryMapper() { super(); } public static AccountEntry map(final AccountEntryEntity accountEntity) { final AccountEntry entry = new AccountEntry(); entry.setType(accountEntity.getType()); entry.setBalance(accountEntity.getBalance()); entry.setAmount(accountEntity.getAmount()); entry.setMessage(accountEntity.getMessage()); entry.setTransactionDate(DateConverter.toIsoString(accountEntity.getTransactionDate())); return entry; } }
4,821
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/mapper/TransactionTypeMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.mapper; import org.apache.fineract.cn.accounting.api.v1.domain.TransactionType; import org.apache.fineract.cn.accounting.service.internal.repository.TransactionTypeEntity; public class TransactionTypeMapper { private TransactionTypeMapper() { super(); } public static TransactionType map(final TransactionTypeEntity transactionTypeEntity) { final TransactionType transactionType = new TransactionType(); transactionType.setCode(transactionTypeEntity.getIdentifier()); transactionType.setName(transactionTypeEntity.getName()); transactionType.setDescription(transactionTypeEntity.getDescription()); return transactionType; } public static TransactionTypeEntity map(final TransactionType transactionType) { final TransactionTypeEntity transactionTypeEntity = new TransactionTypeEntity(); transactionTypeEntity.setIdentifier(transactionType.getCode()); transactionTypeEntity.setName(transactionType.getName()); transactionTypeEntity.setDescription(transactionType.getDescription()); return transactionTypeEntity; } }
4,822
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/CloseAccountCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; public class CloseAccountCommand { private final String identifier; private final String comment; public CloseAccountCommand(final String identifier, final String comment) { super(); this.identifier = identifier; this.comment = comment; } public String identifier() { return this.identifier; } public String comment() { return this.comment; } @Override public String toString() { return "CloseAccountCommand{" + "identifier='" + identifier + '\'' + '}'; } }
4,823
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/DeleteLedgerCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; public class DeleteLedgerCommand { private final String identifier; public DeleteLedgerCommand(final String identifier) { super(); this.identifier = identifier; } public String identifier() { return this.identifier; } @Override public String toString() { return "DeleteLedgerCommand{" + "identifier='" + identifier + '\'' + '}'; } }
4,824
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/BookJournalEntryCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; public class BookJournalEntryCommand { private final String transactionIdentifier; public BookJournalEntryCommand(final String transactionIdentifier) { super(); this.transactionIdentifier = transactionIdentifier; } public String transactionIdentifier() { return this.transactionIdentifier; } @Override public String toString() { return "BookJournalEntryCommand{" + "transactionIdentifier='" + transactionIdentifier + '\'' + '}'; } }
4,825
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/ReopenAccountCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; public class ReopenAccountCommand { private final String identifier; private final String comment; public ReopenAccountCommand(final String identifier, final String comment) { super(); this.identifier = identifier; this.comment = comment; } public String identifier() { return this.identifier; } public String comment() { return this.comment; } @Override public String toString() { return "ReopenAccountCommand{" + "identifier='" + identifier + '\'' + '}'; } }
4,826
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/CreateJournalEntryCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; import org.apache.fineract.cn.accounting.api.v1.domain.JournalEntry; public class CreateJournalEntryCommand { private final JournalEntry journalEntry; public CreateJournalEntryCommand(final JournalEntry journalEntry) { this.journalEntry = journalEntry; } public JournalEntry journalEntry() { return this.journalEntry; } @Override public String toString() { return "CreateJournalEntryCommand{" + "journalEntry=" + journalEntry.getTransactionIdentifier() + '}'; } }
4,827
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/LockAccountCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; public class LockAccountCommand { private final String identifier; private final String comment; public LockAccountCommand(final String identifier, final String comment) { super(); this.identifier = identifier; this.comment = comment; } public String identifier() { return this.identifier; } public String comment() { return this.comment; } @Override public String toString() { return "LockAccountCommand{" + "identifier='" + identifier + '\'' + '}'; } }
4,828
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/CreateTransactionTypeCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; import org.apache.fineract.cn.accounting.api.v1.domain.TransactionType; public class CreateTransactionTypeCommand { private final TransactionType transactionType; public CreateTransactionTypeCommand(final TransactionType transactionType) { super(); this.transactionType = transactionType; } public TransactionType transactionType() { return this.transactionType; } @Override public String toString() { return "CreateTransactionTypeCommand{" + "transactionType=" + transactionType.getCode() + '}'; } }
4,829
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/ReleaseJournalEntryCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; public class ReleaseJournalEntryCommand { private final String transactionIdentifier; public ReleaseJournalEntryCommand(final String transactionIdentifier) { super(); this.transactionIdentifier = transactionIdentifier; } public String transactionIdentifier() { return this.transactionIdentifier; } @Override public String toString() { return "ReleaseJournalEntryCommand{" + "transactionIdentifier='" + transactionIdentifier + '\'' + '}'; } }
4,830
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/CreateAccountCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; import org.apache.fineract.cn.accounting.api.v1.domain.Account; public class CreateAccountCommand { private final Account account; public CreateAccountCommand(final Account account) { super(); this.account = account; } public Account account() { return this.account; } @Override public String toString() { return "CreateAccountCommand{" + "account=" + account.getIdentifier() + '}'; } }
4,831
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/CreateLedgerCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; import org.apache.fineract.cn.accounting.api.v1.domain.Ledger; public class CreateLedgerCommand { private final Ledger ledger; public CreateLedgerCommand(final Ledger ledger) { super(); this.ledger = ledger; } public Ledger ledger() { return this.ledger; } @Override public String toString() { return "CreateLedgerCommand{" + "ledger=" + ledger.getIdentifier() + '}'; } }
4,832
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/DeleteAccountCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; public class DeleteAccountCommand { private final String identifier; public DeleteAccountCommand(final String identifier) { super(); this.identifier = identifier; } public String identifier() { return this.identifier; } @Override public String toString() { return "DeleteAccountCommand{" + "identifier='" + identifier + '\'' + '}'; } }
4,833
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/ModifyAccountCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; import org.apache.fineract.cn.accounting.api.v1.domain.Account; public class ModifyAccountCommand { private final Account account; public ModifyAccountCommand(final Account account) { super(); this.account = account; } public Account account() { return this.account; } @Override public String toString() { return "ModifyAccountCommand{" + "account=" + account.getIdentifier() + '}'; } }
4,834
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/UnlockAccountCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; public class UnlockAccountCommand { private final String identifier; private final String comment; public UnlockAccountCommand(final String identifier, final String comment) { super(); this.identifier = identifier; this.comment = comment; } public String identifier() { return this.identifier; } public String comment() { return this.comment; } @Override public String toString() { return "UnlockAccountCommand{" + "identifier='" + identifier + '\'' + '}'; } }
4,835
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/ModifyLedgerCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; import org.apache.fineract.cn.accounting.api.v1.domain.Ledger; public class ModifyLedgerCommand { private final Ledger ledger; public ModifyLedgerCommand(final Ledger ledger) { super(); this.ledger = ledger; } public Ledger ledger() { return this.ledger; } @Override public String toString() { return "ModifyLedgerCommand{" + "ledger=" + ledger.getIdentifier() + '}'; } }
4,836
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/ChangeTransactionTypeCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; import org.apache.fineract.cn.accounting.api.v1.domain.TransactionType; public class ChangeTransactionTypeCommand { private final TransactionType transactionType; public ChangeTransactionTypeCommand(final TransactionType transactionType) { super(); this.transactionType = transactionType; } public TransactionType transactionType() { return this.transactionType; } @Override public String toString() { return "ChangeTransactionTypeCommand{" + "transactionType=" + transactionType.getCode() + '}'; } }
4,837
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/AddSubLedgerCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; import org.apache.fineract.cn.accounting.api.v1.domain.Ledger; public class AddSubLedgerCommand { private final String parentLedgerIdentifier; private final Ledger subLedger; public AddSubLedgerCommand(final String parentLedgerIdentifier, final Ledger subLedger) { super(); this.parentLedgerIdentifier = parentLedgerIdentifier; this.subLedger = subLedger; } public String parentLedgerIdentifier() { return this.parentLedgerIdentifier; } public Ledger subLedger() { return this.subLedger; } @Override public String toString() { return "AddSubLedgerCommand{" + "parentLedgerIdentifier='" + parentLedgerIdentifier + '\'' + ", subLedger=" + subLedger.getIdentifier() + '}'; } }
4,838
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/InitializeServiceCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command; public class InitializeServiceCommand { public InitializeServiceCommand() { super(); } @Override public String toString() { return "InitializeServiceCommand{}"; } }
4,839
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/handler/LedgerCommandHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command.handler; import org.apache.fineract.cn.accounting.api.v1.EventConstants; import org.apache.fineract.cn.accounting.api.v1.domain.Ledger; import org.apache.fineract.cn.accounting.service.ServiceConstants; import org.apache.fineract.cn.accounting.service.internal.command.AddSubLedgerCommand; import org.apache.fineract.cn.accounting.service.internal.command.CreateLedgerCommand; import org.apache.fineract.cn.accounting.service.internal.command.DeleteLedgerCommand; import org.apache.fineract.cn.accounting.service.internal.command.ModifyLedgerCommand; import org.apache.fineract.cn.accounting.service.internal.repository.LedgerEntity; import org.apache.fineract.cn.accounting.service.internal.repository.LedgerRepository; import java.time.Clock; import java.time.LocalDateTime; import java.util.Collections; import java.util.List; import org.apache.fineract.cn.api.util.UserContextHolder; import org.apache.fineract.cn.command.annotation.Aggregate; import org.apache.fineract.cn.command.annotation.CommandHandler; import org.apache.fineract.cn.command.annotation.CommandLogLevel; import org.apache.fineract.cn.command.annotation.EventEmitter; import org.apache.fineract.cn.command.gateway.CommandGateway; import org.apache.fineract.cn.lang.ServiceException; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.transaction.annotation.Transactional; @SuppressWarnings({"unused", "WeakerAccess"}) @Aggregate public class LedgerCommandHandler { private final Logger logger; private final LedgerRepository ledgerRepository; private final CommandGateway commandGateway; @Autowired public LedgerCommandHandler(@Qualifier(ServiceConstants.LOGGER_NAME) final Logger logger, final LedgerRepository ledgerRepository, final CommandGateway commandGateway) { super(); this.logger = logger; this.ledgerRepository = ledgerRepository; this.commandGateway = commandGateway; } @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.POST_LEDGER) public String createLedger(final CreateLedgerCommand createLedgerCommand) { final Ledger ledger = createLedgerCommand.ledger(); this.logger.debug("Received create ledger command with identifier {}.", ledger.getIdentifier()); final LedgerEntity parentLedgerEntity = new LedgerEntity(); parentLedgerEntity.setIdentifier(ledger.getIdentifier()); parentLedgerEntity.setType(ledger.getType()); parentLedgerEntity.setName(ledger.getName()); parentLedgerEntity.setDescription(ledger.getDescription()); parentLedgerEntity.setCreatedBy(UserContextHolder.checkedGetUser()); parentLedgerEntity.setCreatedOn(LocalDateTime.now(Clock.systemUTC())); parentLedgerEntity.setShowAccountsInChart(ledger.getShowAccountsInChart()); final LedgerEntity savedParentLedger = this.ledgerRepository.save(parentLedgerEntity); this.addSubLedgersInternal(ledger.getSubLedgers(), savedParentLedger); this.logger.debug("Ledger {} created.", ledger.getIdentifier()); return ledger.getIdentifier(); } @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.POST_LEDGER) public String addSubLedger(final AddSubLedgerCommand addSubLedgerCommand) { final LedgerEntity parentLedger = this.ledgerRepository.findByIdentifier(addSubLedgerCommand.parentLedgerIdentifier()); final Ledger subLedger = addSubLedgerCommand.subLedger(); final LedgerEntity subLedgerEntity = this.ledgerRepository.findByIdentifier(subLedger.getIdentifier()); if (subLedgerEntity == null) { this.addSubLedgersInternal(Collections.singletonList(subLedger), parentLedger); } else { subLedgerEntity.setParentLedger(parentLedger); subLedgerEntity.setLastModifiedBy(UserContextHolder.checkedGetUser()); subLedgerEntity.setLastModifiedOn(LocalDateTime.now(Clock.systemUTC())); this.ledgerRepository.save(subLedgerEntity); } parentLedger.setLastModifiedBy(UserContextHolder.checkedGetUser()); parentLedger.setLastModifiedOn(LocalDateTime.now(Clock.systemUTC())); this.ledgerRepository.save(parentLedger); return subLedger.getIdentifier(); } @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.PUT_LEDGER) public String modifyLedger(final ModifyLedgerCommand modifyLedgerCommand) { final Ledger ledger2modify = modifyLedgerCommand.ledger(); final LedgerEntity ledgerEntity = this.ledgerRepository.findByIdentifier(ledger2modify.getIdentifier()); ledgerEntity.setName(ledger2modify.getName()); ledgerEntity.setDescription(ledger2modify.getDescription()); ledgerEntity.setLastModifiedBy(UserContextHolder.checkedGetUser()); ledgerEntity.setLastModifiedOn(LocalDateTime.now(Clock.systemUTC())); ledgerEntity.setShowAccountsInChart(ledger2modify.getShowAccountsInChart()); this.ledgerRepository.save(ledgerEntity); return ledger2modify.getIdentifier(); } @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.DELETE_LEDGER) public String deleteLedger(final DeleteLedgerCommand deleteLedgerCommand) { this.ledgerRepository.delete(this.ledgerRepository.findByIdentifier(deleteLedgerCommand.identifier())); return deleteLedgerCommand.identifier(); } @Transactional public void addSubLedgersInternal(final List<Ledger> subLedgers, final LedgerEntity parentLedgerEntity) { if (subLedgers != null) { this.logger.debug( "Add {} sub ledger(s) to parent ledger {}.", subLedgers.size(), parentLedgerEntity.getIdentifier() ); for (final Ledger subLedger : subLedgers) { if (!subLedger.getType().equals(parentLedgerEntity.getType())) { this.logger.error( "Type of sub ledger {} must match parent ledger {}. Expected {}, was {}", subLedger.getIdentifier(), parentLedgerEntity.getIdentifier(), parentLedgerEntity.getType(), subLedger.getType() ); throw ServiceException.badRequest( "Type of sub ledger {0} must match parent ledger {1}. Expected {2}, was {3}", subLedger.getIdentifier(), parentLedgerEntity.getIdentifier(), parentLedgerEntity.getType(), subLedger.getType() ); } final LedgerEntity subLedgerEntity = new LedgerEntity(); subLedgerEntity.setIdentifier(subLedger.getIdentifier()); subLedgerEntity.setType(subLedger.getType()); subLedgerEntity.setName(subLedger.getName()); subLedgerEntity.setDescription(subLedger.getDescription()); subLedgerEntity.setCreatedBy(UserContextHolder.checkedGetUser()); subLedgerEntity.setCreatedOn(LocalDateTime.now(Clock.systemUTC())); subLedgerEntity.setShowAccountsInChart(subLedger.getShowAccountsInChart()); subLedgerEntity.setParentLedger(parentLedgerEntity); final LedgerEntity savedSubLedger = this.ledgerRepository.save(subLedgerEntity); this.addSubLedgersInternal(subLedger.getSubLedgers(), savedSubLedger); this.logger.debug("Sub ledger {} created.", subLedger.getIdentifier()); } } } }
4,840
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/handler/MigrationCommandHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command.handler; import com.datastax.driver.core.DataType; import com.datastax.driver.core.schemabuilder.SchemaBuilder; import org.apache.fineract.cn.accounting.api.v1.EventConstants; import org.apache.fineract.cn.accounting.service.ServiceConstants; import org.apache.fineract.cn.accounting.service.internal.command.InitializeServiceCommand; import org.apache.fineract.cn.accounting.service.internal.repository.AccountRepository; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import javax.sql.DataSource; import org.apache.fineract.cn.cassandra.core.CassandraJourney; import org.apache.fineract.cn.cassandra.core.CassandraJourneyFactory; import org.apache.fineract.cn.cassandra.core.CassandraJourneyRoute; import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider; import org.apache.fineract.cn.command.annotation.Aggregate; import org.apache.fineract.cn.command.annotation.CommandHandler; import org.apache.fineract.cn.command.annotation.CommandLogLevel; import org.apache.fineract.cn.command.annotation.EventEmitter; import org.apache.fineract.cn.postgresql.domain.FlywayFactoryBean; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationInfo; import org.flywaydb.core.api.MigrationInfoService; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.transaction.annotation.Transactional; @SuppressWarnings({ "unused" }) @Aggregate public class MigrationCommandHandler { private final Logger logger; private final DataSource dataSource; private final FlywayFactoryBean flywayFactoryBean; private final CassandraSessionProvider cassandraSessionProvider; private final CassandraJourneyFactory cassandraJourneyFactory; private final AccountRepository accountRepository; private final AccountCommandHandler accountCommandHandler; @SuppressWarnings("SpringJavaAutowiringInspection") @Autowired public MigrationCommandHandler(@Qualifier(ServiceConstants.LOGGER_NAME) final Logger logger, final DataSource dataSource, final FlywayFactoryBean flywayFactoryBean, final CassandraSessionProvider cassandraSessionProvider, final CassandraJourneyFactory cassandraJourneyFactory, final AccountRepository accountRepository, final AccountCommandHandler accountCommandHandler) { super(); this.logger = logger; this.dataSource = dataSource; this.flywayFactoryBean = flywayFactoryBean; this.cassandraSessionProvider = cassandraSessionProvider; this.cassandraJourneyFactory = cassandraJourneyFactory; this.accountRepository = accountRepository; this.accountCommandHandler = accountCommandHandler; } @Transactional @CommandHandler(logStart = CommandLogLevel.DEBUG, logFinish = CommandLogLevel.DEBUG) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.INITIALIZE) public String initialize(final InitializeServiceCommand initializeServiceCommand) { final Flyway flyway = this.flywayFactoryBean.create(this.dataSource); final MigrationInfoService migrationInfoService = flyway.info(); final List<MigrationInfo> migrationInfoList = Arrays.asList(migrationInfoService.applied()); final boolean shouldMigrateLedgerTotals = migrationInfoList .stream() .noneMatch(migrationInfo -> migrationInfo.getVersion().getVersion().equals("9")); flyway.migrate(); final String versionNumber = "1"; final CassandraJourneyRoute initialRoute = CassandraJourneyRoute .plan("1") .addWaypoint( SchemaBuilder .createType("thoth_debtor") .addColumn("account_number", DataType.text()) .addColumn("amount", DataType.cdouble()) .buildInternal()) .addWaypoint( SchemaBuilder .createType("thoth_creditor") .addColumn("account_number", DataType.text()) .addColumn("amount", DataType.cdouble()) .buildInternal()) .addWaypoint( SchemaBuilder .createTable("thoth_journal_entries") .addPartitionKey("date_bucket", DataType.text()) .addClusteringColumn("transaction_identifier", DataType.text()) .addColumn("transaction_date", DataType.timestamp()) .addColumn("clerk", DataType.text()) .addColumn("note", DataType.text()) .addUDTSetColumn("debtors", SchemaBuilder.frozen("thoth_debtor")) .addUDTSetColumn("creditors", SchemaBuilder.frozen("thoth_creditor")) .addColumn("state", DataType.text()) .addColumn("message", DataType.text()) .buildInternal()) .addWaypoint(SchemaBuilder .createTable("thoth_journal_entry_lookup") .addPartitionKey("transaction_identifier", DataType.text()) .addColumn("date_bucket", DataType.text()) .buildInternal()) .build(); final CassandraJourneyRoute updateRouteVersion2 = CassandraJourneyRoute .plan("2") .addWaypoint( SchemaBuilder .alterTable("thoth_journal_entries") .addColumn("transaction_type").type(DataType.text()) .getQueryString() ) .build(); final CassandraJourneyRoute updateRouteVersion3 = CassandraJourneyRoute .plan("3") .addWaypoint( SchemaBuilder .alterTable("thoth_journal_entries") .addColumn("created_by").type(DataType.text()) .getQueryString() ) .addWaypoint( SchemaBuilder .alterTable("thoth_journal_entries") .addColumn("created_on").type(DataType.timestamp()) .getQueryString() ) .build(); final CassandraJourney cassandraJourney = this.cassandraJourneyFactory.create(this.cassandraSessionProvider); cassandraJourney.start(initialRoute); cassandraJourney.start(updateRouteVersion2); cassandraJourney.start(updateRouteVersion3); if (shouldMigrateLedgerTotals) { this.migrateLedgerTotals(); } return versionNumber; } public void migrateLedgerTotals() { this.logger.info("Start ledger total migration ..."); this.accountRepository.findByBalanceIsNot(0.00D).forEach(accountEntity -> this.accountCommandHandler.adjustLedgerTotals(accountEntity.getLedger().getIdentifier(), BigDecimal.valueOf(accountEntity.getBalance())) ); } }
4,841
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/handler/TransactionTypeAggregate.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command.handler; import org.apache.fineract.cn.accounting.api.v1.EventConstants; import org.apache.fineract.cn.accounting.api.v1.domain.TransactionType; import org.apache.fineract.cn.accounting.service.internal.command.ChangeTransactionTypeCommand; import org.apache.fineract.cn.accounting.service.internal.command.CreateTransactionTypeCommand; import org.apache.fineract.cn.accounting.service.internal.mapper.TransactionTypeMapper; import org.apache.fineract.cn.accounting.service.internal.repository.TransactionTypeEntity; import org.apache.fineract.cn.accounting.service.internal.repository.TransactionTypeRepository; import java.util.Optional; import org.apache.fineract.cn.command.annotation.Aggregate; import org.apache.fineract.cn.command.annotation.CommandHandler; import org.apache.fineract.cn.command.annotation.CommandLogLevel; import org.apache.fineract.cn.command.annotation.EventEmitter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; @SuppressWarnings("unused") @Aggregate public class TransactionTypeAggregate { private final TransactionTypeRepository transactionTypeRepository; @Autowired public TransactionTypeAggregate(final TransactionTypeRepository transactionTypeRepository) { super(); this.transactionTypeRepository = transactionTypeRepository; } @Transactional @CommandHandler(logStart = CommandLogLevel.DEBUG, logFinish = CommandLogLevel.DEBUG) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.POST_TX_TYPE) public String createTransactionType(final CreateTransactionTypeCommand createTransactionTypeCommand) { final TransactionType transactionType = createTransactionTypeCommand.transactionType(); this.transactionTypeRepository.save(TransactionTypeMapper.map(transactionType)); return transactionType.getCode(); } @Transactional @CommandHandler(logStart = CommandLogLevel.DEBUG, logFinish = CommandLogLevel.DEBUG) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.PUT_TX_TYPE) public String changeTransactionType(final ChangeTransactionTypeCommand changeTransactionTypeCommand) { final TransactionType transactionType = changeTransactionTypeCommand.transactionType(); final Optional<TransactionTypeEntity> optionalTransactionTypeEntity = this.transactionTypeRepository.findByIdentifier(transactionType.getCode()); optionalTransactionTypeEntity.ifPresent(transactionTypeEntity -> { transactionTypeEntity.setName(transactionType.getName()); transactionTypeEntity.setDescription(transactionType.getDescription()); this.transactionTypeRepository.save(transactionTypeEntity); }); return transactionType.getCode(); } }
4,842
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/handler/JournalEntryCommandHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command.handler; import org.apache.fineract.cn.accounting.api.v1.EventConstants; import org.apache.fineract.cn.accounting.api.v1.domain.Creditor; import org.apache.fineract.cn.accounting.api.v1.domain.Debtor; import org.apache.fineract.cn.accounting.api.v1.domain.JournalEntry; import org.apache.fineract.cn.accounting.service.internal.command.BookJournalEntryCommand; import org.apache.fineract.cn.accounting.service.internal.command.CreateJournalEntryCommand; import org.apache.fineract.cn.accounting.service.internal.command.ReleaseJournalEntryCommand; import org.apache.fineract.cn.accounting.service.internal.repository.CreditorType; import org.apache.fineract.cn.accounting.service.internal.repository.DebtorType; import org.apache.fineract.cn.accounting.service.internal.repository.JournalEntryEntity; import org.apache.fineract.cn.accounting.service.internal.repository.JournalEntryRepository; import java.time.Clock; import java.time.LocalDateTime; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.apache.fineract.cn.api.util.UserContextHolder; import org.apache.fineract.cn.command.annotation.Aggregate; import org.apache.fineract.cn.command.annotation.CommandHandler; import org.apache.fineract.cn.command.annotation.CommandLogLevel; import org.apache.fineract.cn.command.annotation.EventEmitter; import org.apache.fineract.cn.command.gateway.CommandGateway; import org.apache.fineract.cn.lang.DateConverter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; @SuppressWarnings("unused") @Aggregate public class JournalEntryCommandHandler { private final CommandGateway commandGateway; private final JournalEntryRepository journalEntryRepository; @Autowired public JournalEntryCommandHandler(final CommandGateway commandGateway, final JournalEntryRepository journalEntryRepository) { this.commandGateway = commandGateway; this.journalEntryRepository = journalEntryRepository; } @Transactional @CommandHandler(logStart = CommandLogLevel.NONE, logFinish = CommandLogLevel.NONE) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.POST_JOURNAL_ENTRY) public String createJournalEntry(final CreateJournalEntryCommand createJournalEntryCommand) { final JournalEntry journalEntry = createJournalEntryCommand.journalEntry(); final Set<Debtor> debtors = journalEntry.getDebtors(); final Set<DebtorType> debtorTypes = debtors .stream() .map(debtor -> { final DebtorType debtorType = new DebtorType(); debtorType.setAccountNumber(debtor.getAccountNumber()); debtorType.setAmount(Double.valueOf(debtor.getAmount())); return debtorType; }) .collect(Collectors.toSet()); final Set<Creditor> creditors = journalEntry.getCreditors(); final Set<CreditorType> creditorTypes = creditors .stream() .map(creditor -> { final CreditorType creditorType = new CreditorType(); creditorType.setAccountNumber(creditor.getAccountNumber()); creditorType.setAmount(Double.valueOf(creditor.getAmount())); return creditorType; }) .collect(Collectors.toSet()); final JournalEntryEntity journalEntryEntity = new JournalEntryEntity(); journalEntryEntity.setTransactionIdentifier(journalEntry.getTransactionIdentifier()); final LocalDateTime transactionDate = DateConverter.fromIsoString(journalEntry.getTransactionDate()); journalEntryEntity.setDateBucket(DateConverter.toIsoString(DateConverter.toLocalDate(transactionDate))); journalEntryEntity.setTransactionDate(transactionDate); journalEntryEntity.setTransactionType(journalEntry.getTransactionType()); journalEntryEntity.setClerk(journalEntry.getClerk() != null ? journalEntry.getClerk() : UserContextHolder.checkedGetUser()); journalEntryEntity.setNote(journalEntry.getNote()); journalEntryEntity.setDebtors(debtorTypes); journalEntryEntity.setCreditors(creditorTypes); journalEntryEntity.setMessage(journalEntry.getMessage()); journalEntryEntity.setState(JournalEntry.State.PENDING.name()); journalEntryEntity.setCreatedBy(UserContextHolder.checkedGetUser()); journalEntryEntity.setCreatedOn(LocalDateTime.now(Clock.systemUTC())); journalEntryRepository.saveJournalEntry(journalEntryEntity); this.commandGateway.process(new BookJournalEntryCommand(journalEntry.getTransactionIdentifier())); return journalEntry.getTransactionIdentifier(); } @Transactional @CommandHandler(logStart = CommandLogLevel.NONE, logFinish = CommandLogLevel.NONE) public void releaseJournalEntry(final ReleaseJournalEntryCommand releaseJournalEntryCommand) { final String transactionIdentifier = releaseJournalEntryCommand.transactionIdentifier(); final Optional<JournalEntryEntity> optionalJournalEntry = this.journalEntryRepository.findJournalEntry(transactionIdentifier); if (optionalJournalEntry.isPresent()) { final JournalEntryEntity journalEntryEntity = optionalJournalEntry.get(); journalEntryEntity.setState(JournalEntry.State.PROCESSED.name()); this.journalEntryRepository.saveJournalEntry(journalEntryEntity); } } }
4,843
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/command/handler/AccountCommandHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.command.handler; import org.apache.fineract.cn.accounting.api.v1.EventConstants; import org.apache.fineract.cn.accounting.api.v1.domain.Account; import org.apache.fineract.cn.accounting.api.v1.domain.AccountCommand; import org.apache.fineract.cn.accounting.api.v1.domain.AccountEntry; import org.apache.fineract.cn.accounting.api.v1.domain.AccountType; import org.apache.fineract.cn.accounting.api.v1.domain.JournalEntry; import org.apache.fineract.cn.accounting.service.ServiceConstants; import org.apache.fineract.cn.accounting.service.internal.command.BookJournalEntryCommand; import org.apache.fineract.cn.accounting.service.internal.command.CloseAccountCommand; import org.apache.fineract.cn.accounting.service.internal.command.CreateAccountCommand; import org.apache.fineract.cn.accounting.service.internal.command.DeleteAccountCommand; import org.apache.fineract.cn.accounting.service.internal.command.LockAccountCommand; import org.apache.fineract.cn.accounting.service.internal.command.ModifyAccountCommand; import org.apache.fineract.cn.accounting.service.internal.command.ReleaseJournalEntryCommand; import org.apache.fineract.cn.accounting.service.internal.command.ReopenAccountCommand; import org.apache.fineract.cn.accounting.service.internal.command.UnlockAccountCommand; import org.apache.fineract.cn.accounting.service.internal.repository.AccountEntity; import org.apache.fineract.cn.accounting.service.internal.repository.AccountEntryEntity; import org.apache.fineract.cn.accounting.service.internal.repository.AccountEntryRepository; import org.apache.fineract.cn.accounting.service.internal.repository.AccountRepository; import org.apache.fineract.cn.accounting.service.internal.repository.CommandEntity; import org.apache.fineract.cn.accounting.service.internal.repository.CommandRepository; import org.apache.fineract.cn.accounting.service.internal.repository.JournalEntryEntity; import org.apache.fineract.cn.accounting.service.internal.repository.JournalEntryRepository; import org.apache.fineract.cn.accounting.service.internal.repository.LedgerEntity; import org.apache.fineract.cn.accounting.service.internal.repository.LedgerRepository; import java.math.BigDecimal; import java.time.Clock; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.apache.fineract.cn.api.util.UserContextHolder; import org.apache.fineract.cn.command.annotation.Aggregate; import org.apache.fineract.cn.command.annotation.CommandHandler; import org.apache.fineract.cn.command.annotation.CommandLogLevel; import org.apache.fineract.cn.command.annotation.EventEmitter; import org.apache.fineract.cn.command.gateway.CommandGateway; import org.apache.fineract.cn.lang.ServiceException; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.transaction.annotation.Transactional; @SuppressWarnings("unused") @Aggregate public class AccountCommandHandler { private final Logger logger; private final CommandGateway commandGateway; private final AccountRepository accountRepository; private final AccountEntryRepository accountEntryRepository; private final LedgerRepository ledgerRepository; private final JournalEntryRepository journalEntryRepository; private final CommandRepository commandRepository; @Autowired public AccountCommandHandler(@Qualifier(ServiceConstants.LOGGER_NAME) final Logger logger, final CommandGateway commandGateway, final AccountRepository accountRepository, final AccountEntryRepository accountEntryRepository, final LedgerRepository ledgerRepository, final JournalEntryRepository journalEntryRepository, final CommandRepository commandRepository) { super(); this.logger = logger; this.commandGateway = commandGateway; this.accountRepository = accountRepository; this.accountEntryRepository = accountEntryRepository; this.ledgerRepository = ledgerRepository; this.journalEntryRepository = journalEntryRepository; this.commandRepository = commandRepository; } @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.POST_ACCOUNT) public String createAccount(final CreateAccountCommand createAccountCommand) { final Account account = createAccountCommand.account(); final AccountEntity accountEntity = new AccountEntity(); accountEntity.setIdentifier(account.getIdentifier()); accountEntity.setName(account.getName()); accountEntity.setType(account.getType()); final LedgerEntity ledger = this.ledgerRepository.findByIdentifier(account.getLedger()); accountEntity.setLedger(ledger); AccountEntity referenceAccount = null; if (account.getReferenceAccount() != null) { referenceAccount = this.accountRepository.findByIdentifier(account.getReferenceAccount()); if (referenceAccount.getState().equals(Account.State.OPEN.name())) { accountEntity.setReferenceAccount(referenceAccount); } else { throw ServiceException.badRequest("Reference account {0} is not valid.", referenceAccount.getIdentifier()); } } if (account.getHolders() != null) { accountEntity.setHolders( account.getHolders() .stream() .collect(Collectors.joining(",")) ); } if (account.getSignatureAuthorities() != null) { accountEntity.setSignatureAuthorities( account.getSignatureAuthorities() .stream() .collect(Collectors.joining(",")) ); } accountEntity.setBalance(account.getBalance()); accountEntity.setState(Account.State.OPEN.name()); accountEntity.setAlternativeAccountNumber(account.getAlternativeAccountNumber()); accountEntity.setCreatedBy(UserContextHolder.checkedGetUser()); accountEntity.setCreatedOn(LocalDateTime.now(Clock.systemUTC())); final AccountEntity savedAccountEntity = this.accountRepository.save(accountEntity); if (referenceAccount != null) { referenceAccount.setLastModifiedBy(UserContextHolder.checkedGetUser()); referenceAccount.setLastModifiedOn(LocalDateTime.now(Clock.systemUTC())); this.accountRepository.save(referenceAccount); } this.ledgerRepository.save(ledger); if (savedAccountEntity.getBalance() != null && savedAccountEntity.getBalance() != 0.00D) { this.adjustLedgerTotals( savedAccountEntity.getLedger().getIdentifier(), BigDecimal.valueOf(savedAccountEntity.getBalance())); } return account.getIdentifier(); } @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.PUT_ACCOUNT) public String modifyAccount(final ModifyAccountCommand modifyAccountCommand) { final Account account = modifyAccountCommand.account(); final AccountEntity accountEntity = this.accountRepository.findByIdentifier(account.getIdentifier()); if (account.getName() != null) { accountEntity.setName(account.getName()); } LedgerEntity ledger = null; if (!account.getLedger().equals(accountEntity.getLedger().getIdentifier())) { ledger = this.ledgerRepository.findByIdentifier(account.getLedger()); accountEntity.setLedger(ledger); } AccountEntity referenceAccount = null; if (account.getReferenceAccount() != null) { if (!account.getReferenceAccount().equals(accountEntity.getReferenceAccount().getIdentifier())) { referenceAccount = this.accountRepository.findByIdentifier(account.getReferenceAccount()); accountEntity.setReferenceAccount(referenceAccount); } } else { accountEntity.setReferenceAccount(null); } if (account.getHolders() != null) { accountEntity.setHolders( account.getHolders() .stream() .collect(Collectors.joining(",")) ); } else { accountEntity.setHolders(null); } if (account.getSignatureAuthorities() != null) { accountEntity.setSignatureAuthorities( account.getSignatureAuthorities() .stream() .collect(Collectors.joining(",")) ); } else { accountEntity.setSignatureAuthorities(null); } accountEntity.setLastModifiedBy(UserContextHolder.checkedGetUser()); accountEntity.setLastModifiedOn(LocalDateTime.now(Clock.systemUTC())); this.accountRepository.save(accountEntity); if (referenceAccount != null) { referenceAccount.setLastModifiedBy(UserContextHolder.checkedGetUser()); referenceAccount.setLastModifiedOn(LocalDateTime.now(Clock.systemUTC())); this.accountRepository.save(referenceAccount); } if (ledger != null) { this.ledgerRepository.save(ledger); } return account.getIdentifier(); } @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.CLOSE_ACCOUNT) public String closeAccount(final CloseAccountCommand closeAccountCommand) { final String modifyingUser = SecurityContextHolder.getContext().getAuthentication().getName(); final LocalDateTime now = LocalDateTime.now(Clock.systemUTC()); final String identifier = closeAccountCommand.identifier(); final AccountEntity accountEntity = this.accountRepository.findByIdentifier(identifier); accountEntity.setState(Account.State.CLOSED.name()); accountEntity.setLastModifiedBy(modifyingUser); accountEntity.setLastModifiedOn(now); this.accountRepository.save(accountEntity); final CommandEntity commandEntity = new CommandEntity(); commandEntity.setType(AccountCommand.Action.CLOSE.name()); commandEntity.setAccount(accountEntity); commandEntity.setComment(closeAccountCommand.comment()); commandEntity.setCreatedBy(modifyingUser); commandEntity.setCreatedOn(now); this.commandRepository.save(commandEntity); return identifier; } @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.LOCK_ACCOUNT) public String lockAccount(final LockAccountCommand lockAccountCommand) { final String modifyingUser = SecurityContextHolder.getContext().getAuthentication().getName(); final LocalDateTime now = LocalDateTime.now(Clock.systemUTC()); final String identifier = lockAccountCommand.identifier(); final AccountEntity accountEntity = this.accountRepository.findByIdentifier(identifier); accountEntity.setState(Account.State.LOCKED.name()); accountEntity.setLastModifiedBy(modifyingUser); accountEntity.setLastModifiedOn(now); this.accountRepository.save(accountEntity); final CommandEntity commandEntity = new CommandEntity(); commandEntity.setType(AccountCommand.Action.LOCK.name()); commandEntity.setAccount(accountEntity); commandEntity.setComment(lockAccountCommand.comment()); commandEntity.setCreatedBy(modifyingUser); commandEntity.setCreatedOn(now); this.commandRepository.save(commandEntity); return identifier; } @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.UNLOCK_ACCOUNT) public String unlockAccount(final UnlockAccountCommand unlockAccountCommand) { final String modifyingUser = SecurityContextHolder.getContext().getAuthentication().getName(); final LocalDateTime now = LocalDateTime.now(Clock.systemUTC()); final String identifier = unlockAccountCommand.identifier(); final AccountEntity accountEntity = this.accountRepository.findByIdentifier(identifier); accountEntity.setState(Account.State.OPEN.name()); accountEntity.setLastModifiedBy(modifyingUser); accountEntity.setLastModifiedOn(now); this.accountRepository.save(accountEntity); final CommandEntity commandEntity = new CommandEntity(); commandEntity.setType(AccountCommand.Action.UNLOCK.name()); commandEntity.setAccount(accountEntity); commandEntity.setComment(unlockAccountCommand.comment()); commandEntity.setCreatedBy(modifyingUser); commandEntity.setCreatedOn(now); this.commandRepository.save(commandEntity); return identifier; } @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.REOPEN_ACCOUNT) public String reopenAccount(final ReopenAccountCommand reopenAccountCommand) { final String modifyingUser = SecurityContextHolder.getContext().getAuthentication().getName(); final LocalDateTime now = LocalDateTime.now(Clock.systemUTC()); final String identifier = reopenAccountCommand.identifier(); final AccountEntity accountEntity = this.accountRepository.findByIdentifier(identifier); accountEntity.setState(Account.State.OPEN.name()); accountEntity.setLastModifiedBy(modifyingUser); accountEntity.setLastModifiedOn(now); this.accountRepository.save(accountEntity); final CommandEntity commandEntity = new CommandEntity(); commandEntity.setType(AccountCommand.Action.REOPEN.name()); commandEntity.setAccount(accountEntity); commandEntity.setComment(reopenAccountCommand.comment()); commandEntity.setCreatedBy(modifyingUser); commandEntity.setCreatedOn(now); this.commandRepository.save(commandEntity); return identifier; } @Transactional @CommandHandler(logStart = CommandLogLevel.NONE, logFinish = CommandLogLevel.NONE) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.RELEASE_JOURNAL_ENTRY) public String bookJournalEntry(final BookJournalEntryCommand bookJournalEntryCommand) { final String transactionIdentifier = bookJournalEntryCommand.transactionIdentifier(); final Optional<JournalEntryEntity> optionalJournalEntry = this.journalEntryRepository.findJournalEntry(transactionIdentifier); if (optionalJournalEntry.isPresent()) { final JournalEntryEntity journalEntryEntity = optionalJournalEntry.get(); if (!journalEntryEntity.getState().equals(JournalEntry.State.PENDING.name())) { return null; } // process all debtors journalEntryEntity.getDebtors() .forEach(debtor -> { final String accountNumber = debtor.getAccountNumber(); final AccountEntity accountEntity = this.accountRepository.findByIdentifier(accountNumber); final AccountType accountType = AccountType.valueOf(accountEntity.getType()); final BigDecimal amount; switch (accountType) { case ASSET: case EXPENSE: accountEntity.setBalance(accountEntity.getBalance() + debtor.getAmount()); amount = BigDecimal.valueOf(debtor.getAmount()); break; case LIABILITY: case EQUITY: case REVENUE: accountEntity.setBalance(accountEntity.getBalance() - debtor.getAmount()); amount = BigDecimal.valueOf(debtor.getAmount()).negate(); break; default: amount = BigDecimal.ZERO; } final AccountEntity savedAccountEntity = this.accountRepository.save(accountEntity); final AccountEntryEntity accountEntryEntity = new AccountEntryEntity(); accountEntryEntity.setType(AccountEntry.Type.DEBIT.name()); accountEntryEntity.setAccount(savedAccountEntity); accountEntryEntity.setBalance(savedAccountEntity.getBalance()); accountEntryEntity.setAmount(debtor.getAmount()); accountEntryEntity.setMessage(journalEntryEntity.getMessage()); accountEntryEntity.setTransactionDate(journalEntryEntity.getTransactionDate()); this.accountEntryRepository.save(accountEntryEntity); this.adjustLedgerTotals(savedAccountEntity.getLedger().getIdentifier(), amount); }); // process all creditors journalEntryEntity.getCreditors() .forEach(creditor -> { final String accountNumber = creditor.getAccountNumber(); final AccountEntity accountEntity = this.accountRepository.findByIdentifier(accountNumber); final AccountType accountType = AccountType.valueOf(accountEntity.getType()); final BigDecimal amount; switch (accountType) { case ASSET: case EXPENSE: accountEntity.setBalance(accountEntity.getBalance() - creditor.getAmount()); amount = BigDecimal.valueOf(creditor.getAmount()).negate(); break; case LIABILITY: case EQUITY: case REVENUE: accountEntity.setBalance(accountEntity.getBalance() + creditor.getAmount()); amount = BigDecimal.valueOf(creditor.getAmount()); break; default: amount = BigDecimal.ZERO; } final AccountEntity savedAccountEntity = this.accountRepository.save(accountEntity); final AccountEntryEntity accountEntryEntity = new AccountEntryEntity(); accountEntryEntity.setType(AccountEntry.Type.CREDIT.name()); accountEntryEntity.setAccount(savedAccountEntity); accountEntryEntity.setBalance(savedAccountEntity.getBalance()); accountEntryEntity.setAmount(creditor.getAmount()); accountEntryEntity.setMessage(journalEntryEntity.getMessage()); accountEntryEntity.setTransactionDate(journalEntryEntity.getTransactionDate()); this.accountEntryRepository.save(accountEntryEntity); this.adjustLedgerTotals(savedAccountEntity.getLedger().getIdentifier(), amount); }); this.commandGateway.process(new ReleaseJournalEntryCommand(transactionIdentifier)); return transactionIdentifier; } else { return null; } } @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.DELETE_ACCOUNT) public String deleteAccount(final DeleteAccountCommand deleteAccountCommand) { final String accountIdentifier = deleteAccountCommand.identifier(); final AccountEntity accountEntity = this.accountRepository.findByIdentifier(accountIdentifier); final List<CommandEntity> commandEntities = this.commandRepository.findByAccount(accountEntity); this.commandRepository.delete(commandEntities); this.accountRepository.delete(accountEntity); return accountIdentifier; } @Transactional public void adjustLedgerTotals(final String ledgerIdentifier, final BigDecimal amount) { final LedgerEntity ledger = this.ledgerRepository.findByIdentifier(ledgerIdentifier); final BigDecimal currentTotal = ledger.getTotalValue() != null ? ledger.getTotalValue() : BigDecimal.ZERO; ledger.setTotalValue(currentTotal.add(amount)); final LedgerEntity savedLedger = this.ledgerRepository.save(ledger); if (savedLedger.getParentLedger() != null) { this.adjustLedgerTotals(savedLedger.getParentLedger().getIdentifier(), amount); } } }
4,844
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/service/FinancialConditionService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.service; import org.apache.fineract.cn.accounting.api.v1.domain.AccountType; import org.apache.fineract.cn.accounting.api.v1.domain.financial.statement.FinancialCondition; import org.apache.fineract.cn.accounting.api.v1.domain.financial.statement.FinancialConditionEntry; import org.apache.fineract.cn.accounting.api.v1.domain.financial.statement.FinancialConditionSection; import org.apache.fineract.cn.accounting.service.internal.repository.LedgerRepository; import java.math.BigDecimal; import java.time.Clock; import java.time.LocalDateTime; import java.util.EnumSet; import org.apache.fineract.cn.lang.DateConverter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class FinancialConditionService { private final LedgerRepository ledgerRepository; @Autowired public FinancialConditionService(final LedgerRepository ledgerRepository) { super(); this.ledgerRepository = ledgerRepository; } public FinancialCondition getFinancialCondition() { final FinancialCondition financialCondition = new FinancialCondition(); financialCondition.setDate(DateConverter.toIsoString(LocalDateTime.now(Clock.systemUTC()))); this.createFinancialConditionSection(financialCondition, AccountType.ASSET, FinancialConditionSection.Type.ASSET); this.createFinancialConditionSection(financialCondition, AccountType.EQUITY, FinancialConditionSection.Type.EQUITY); this.createFinancialConditionSection(financialCondition, AccountType.LIABILITY, FinancialConditionSection.Type.LIABILITY); financialCondition.setTotalAssets( this.calculateTotal(financialCondition, EnumSet.of(FinancialConditionSection.Type.ASSET)) ); financialCondition.setTotalEquitiesAndLiabilities( this.calculateTotal(financialCondition, EnumSet.of(FinancialConditionSection.Type.EQUITY, FinancialConditionSection.Type.LIABILITY)) ); return financialCondition; } private void createFinancialConditionSection(final FinancialCondition financialCondition, final AccountType accountType, final FinancialConditionSection.Type financialConditionType) { this.ledgerRepository.findByParentLedgerIsNullAndType(accountType.name()).forEach(ledgerEntity -> { final FinancialConditionSection financialConditionSection = new FinancialConditionSection(); financialConditionSection.setType(financialConditionType.name()); financialConditionSection.setDescription(ledgerEntity.getName()); financialCondition.add(financialConditionSection); this.ledgerRepository.findByParentLedgerOrderByIdentifier(ledgerEntity).forEach(subLedgerEntity -> { final FinancialConditionEntry financialConditionEntry = new FinancialConditionEntry(); financialConditionEntry.setDescription(subLedgerEntity.getName()); final BigDecimal totalValue = subLedgerEntity.getTotalValue() != null ? subLedgerEntity.getTotalValue() : BigDecimal.ZERO; financialConditionEntry.setValue(totalValue); financialConditionSection.add(financialConditionEntry); }); }); } private BigDecimal calculateTotal(final FinancialCondition financialCondition, final EnumSet<FinancialConditionSection.Type> financialConditionTypes) { return financialCondition.getFinancialConditionSections() .stream() .filter(financialConditionSection -> financialConditionTypes.contains(FinancialConditionSection.Type.valueOf(financialConditionSection.getType()))) .map(FinancialConditionSection::getSubtotal) .reduce(BigDecimal.ZERO, BigDecimal::add); } }
4,845
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/service/AccountService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.service; import org.apache.fineract.cn.accounting.api.v1.domain.Account; import org.apache.fineract.cn.accounting.api.v1.domain.AccountCommand; import org.apache.fineract.cn.accounting.api.v1.domain.AccountEntry; import org.apache.fineract.cn.accounting.api.v1.domain.AccountEntryPage; import org.apache.fineract.cn.accounting.api.v1.domain.AccountPage; import org.apache.fineract.cn.accounting.service.internal.mapper.AccountCommandMapper; import org.apache.fineract.cn.accounting.service.internal.mapper.AccountEntryMapper; import org.apache.fineract.cn.accounting.service.internal.mapper.AccountMapper; import org.apache.fineract.cn.accounting.service.internal.repository.AccountEntity; import org.apache.fineract.cn.accounting.service.internal.repository.AccountEntryEntity; import org.apache.fineract.cn.accounting.service.internal.repository.AccountEntryRepository; import org.apache.fineract.cn.accounting.service.internal.repository.AccountRepository; import org.apache.fineract.cn.accounting.service.internal.repository.CommandEntity; import org.apache.fineract.cn.accounting.service.internal.repository.CommandRepository; import org.apache.fineract.cn.accounting.service.internal.repository.specification.AccountSpecification; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.apache.fineract.cn.lang.DateRange; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @Service public class AccountService { private final AccountRepository accountRepository; private final AccountEntryRepository accountEntryRepository; private final CommandRepository commandRepository; @Autowired public AccountService(final AccountRepository accountRepository, final AccountEntryRepository accountEntryRepository, final CommandRepository commandRepository) { super(); this.accountRepository = accountRepository; this.accountEntryRepository = accountEntryRepository; this.commandRepository = commandRepository; } public Optional<Account> findAccount(final String identifier) { final AccountEntity accountEntity = this.accountRepository.findByIdentifier(identifier); if (accountEntity == null) { return Optional.empty(); } else { return Optional.of(AccountMapper.map(accountEntity)); } } public AccountPage fetchAccounts( final boolean includeClosed, final String term, final String type, final boolean includeCustomerAccounts, final Pageable pageable) { final Page<AccountEntity> accountEntities = this.accountRepository.findAll( AccountSpecification.createSpecification(includeClosed, term, type, includeCustomerAccounts), pageable ); final AccountPage accountPage = new AccountPage(); accountPage.setTotalPages(accountEntities.getTotalPages()); accountPage.setTotalElements(accountEntities.getTotalElements()); if(accountEntities.getSize() > 0){ final List<Account> accounts = new ArrayList<>(accountEntities.getSize()); accountEntities.forEach(accountEntity -> accounts.add(AccountMapper.map(accountEntity))); accountPage.setAccounts(accounts); } return accountPage; } public AccountEntryPage fetchAccountEntries(final String identifier, final DateRange range, final @Nullable String message, final Pageable pageable){ final AccountEntity accountEntity = this.accountRepository.findByIdentifier(identifier); final Page<AccountEntryEntity> accountEntryEntities; if (message == null) { accountEntryEntities = this.accountEntryRepository.findByAccountAndTransactionDateBetween( accountEntity, range.getStartDateTime(), range.getEndDateTime(), pageable); } else { accountEntryEntities = this.accountEntryRepository.findByAccountAndTransactionDateBetweenAndMessageEquals( accountEntity, range.getStartDateTime(), range.getEndDateTime(), message, pageable); } final AccountEntryPage accountEntryPage = new AccountEntryPage(); accountEntryPage.setTotalPages(accountEntryEntities.getTotalPages()); accountEntryPage.setTotalElements(accountEntryEntities.getTotalElements()); if(accountEntryEntities.getSize() > 0){ final List<AccountEntry> accountEntries = new ArrayList<>(accountEntryEntities.getSize()); accountEntryEntities.forEach(accountEntryEntity -> accountEntries.add(AccountEntryMapper.map(accountEntryEntity))); accountEntryPage.setAccountEntries(accountEntries); } return accountEntryPage; } public final List<AccountCommand> fetchCommandsByAccount(final String identifier) { final AccountEntity accountEntity = this.accountRepository.findByIdentifier(identifier); final List<CommandEntity> commands = this.commandRepository.findByAccount(accountEntity); if (commands != null) { return commands.stream().map(AccountCommandMapper::map).collect(Collectors.toList()); } else { return Collections.emptyList(); } } public Boolean hasEntries(final String identifier) { final AccountEntity accountEntity = this.accountRepository.findByIdentifier(identifier); return this.accountEntryRepository.existsByAccount(accountEntity); } public Boolean hasReferenceAccounts(final String identifier) { final AccountEntity accountEntity = this.accountRepository.findByIdentifier(identifier); return this.accountRepository.existsByReference(accountEntity); } public List<AccountCommand> getActions(final String identifier) { final AccountEntity accountEntity = this.accountRepository.findByIdentifier(identifier); final ArrayList<AccountCommand> commands = new ArrayList<>(); final Account.State state = Account.State.valueOf(accountEntity.getState()); switch (state) { case OPEN: commands.add(this.buildCommand(AccountCommand.Action.LOCK)); commands.add(this.buildCommand(AccountCommand.Action.CLOSE)); break; case LOCKED: commands.add(this.buildCommand(AccountCommand.Action.UNLOCK)); commands.add(this.buildCommand(AccountCommand.Action.CLOSE)); break; case CLOSED: commands.add(this.buildCommand(AccountCommand.Action.REOPEN)); break; } return commands; } private AccountCommand buildCommand(final AccountCommand.Action action) { final AccountCommand accountCommand = new AccountCommand(); accountCommand.setAction(action.name()); return accountCommand; } }
4,846
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/service/TransactionTypeService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.service; import org.apache.fineract.cn.accounting.api.v1.domain.TransactionType; import org.apache.fineract.cn.accounting.api.v1.domain.TransactionTypePage; import org.apache.fineract.cn.accounting.service.internal.mapper.TransactionTypeMapper; import org.apache.fineract.cn.accounting.service.internal.repository.TransactionTypeEntity; import org.apache.fineract.cn.accounting.service.internal.repository.TransactionTypeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Optional; @Service public class TransactionTypeService { private final TransactionTypeRepository transactionTypeRepository; @Autowired public TransactionTypeService(final TransactionTypeRepository transactionTypeRepository) { super(); this.transactionTypeRepository = transactionTypeRepository; } public TransactionTypePage fetchTransactionTypes(final String term, final Pageable pageable) { final Page<TransactionTypeEntity> transactionTypeEntityPage; if (term != null) { transactionTypeEntityPage = this.transactionTypeRepository.findByIdentifierContainingOrNameContaining(term, term, pageable); } else { transactionTypeEntityPage = this.transactionTypeRepository.findAll(pageable); } final TransactionTypePage transactionTypePage = new TransactionTypePage(); transactionTypePage.setTotalElements(transactionTypeEntityPage.getTotalElements()); transactionTypePage.setTotalPages(transactionTypeEntityPage.getTotalPages()); transactionTypePage.setTransactionTypes(new ArrayList<>(transactionTypeEntityPage.getSize())); transactionTypeEntityPage.forEach(transactionTypeEntity -> transactionTypePage.add(TransactionTypeMapper.map(transactionTypeEntity))); return transactionTypePage; } public Optional<TransactionType> findByIdentifier(final String identifier) { return this.transactionTypeRepository.findByIdentifier(identifier).map(TransactionTypeMapper::map); } }
4,847
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/service/ChartOfAccountsService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.service; import org.apache.fineract.cn.accounting.api.v1.domain.ChartOfAccountEntry; import org.apache.fineract.cn.accounting.service.internal.repository.AccountEntity; import org.apache.fineract.cn.accounting.service.internal.repository.AccountRepository; import org.apache.fineract.cn.accounting.service.internal.repository.LedgerEntity; import org.apache.fineract.cn.accounting.service.internal.repository.LedgerRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @Service public class ChartOfAccountsService { private final LedgerRepository ledgerRepository; private final AccountRepository accountRepository; @Autowired public ChartOfAccountsService(final LedgerRepository ledgerRepository, final AccountRepository accountRepository) { super(); this.ledgerRepository = ledgerRepository; this.accountRepository = accountRepository; } @Transactional(readOnly = true) public List<ChartOfAccountEntry> getChartOfAccounts() { final ArrayList<ChartOfAccountEntry> chartOfAccountEntries = new ArrayList<>(); final List<LedgerEntity> parentLedgers = this.ledgerRepository.findByParentLedgerIsNull(); parentLedgers.sort(Comparator.comparing(LedgerEntity::getIdentifier)); final int level = 0; parentLedgers.forEach(ledgerEntity -> { final ChartOfAccountEntry chartOfAccountEntry = new ChartOfAccountEntry(); chartOfAccountEntries.add(chartOfAccountEntry); chartOfAccountEntry.setCode(ledgerEntity.getIdentifier()); chartOfAccountEntry.setName(ledgerEntity.getName()); chartOfAccountEntry.setDescription(ledgerEntity.getDescription()); chartOfAccountEntry.setType(ledgerEntity.getType()); chartOfAccountEntry.setLevel(level); final int nextLevel = level + 1; this.traverseHierarchy(chartOfAccountEntries, nextLevel, ledgerEntity); }); return chartOfAccountEntries; } private void traverseHierarchy(final List<ChartOfAccountEntry> chartOfAccountEntries, final int level, final LedgerEntity ledgerEntity) { if (ledgerEntity.getShowAccountsInChart()) { final List<AccountEntity> accountEntities = this.accountRepository.findByLedger(ledgerEntity); accountEntities.sort(Comparator.comparing(AccountEntity::getIdentifier)); accountEntities.forEach(accountEntity -> { final ChartOfAccountEntry chartOfAccountEntry = new ChartOfAccountEntry(); chartOfAccountEntries.add(chartOfAccountEntry); chartOfAccountEntry.setCode(accountEntity.getIdentifier()); chartOfAccountEntry.setName(accountEntity.getName()); chartOfAccountEntry.setType(accountEntity.getType()); chartOfAccountEntry.setLevel(level); }); } final List<LedgerEntity> subLedgers = this.ledgerRepository.findByParentLedgerOrderByIdentifier(ledgerEntity); if (subLedgers != null && subLedgers.size() > 0) { subLedgers.sort(Comparator.comparing(LedgerEntity::getIdentifier)); subLedgers.forEach(subLedger -> { final ChartOfAccountEntry chartOfAccountEntry = new ChartOfAccountEntry(); chartOfAccountEntries.add(chartOfAccountEntry); chartOfAccountEntry.setCode(subLedger.getIdentifier()); chartOfAccountEntry.setName(subLedger.getName()); chartOfAccountEntry.setType(subLedger.getType()); chartOfAccountEntry.setLevel(level); final int nextLevel = level + 1; this.traverseHierarchy(chartOfAccountEntries, nextLevel, subLedger); }); } } }
4,848
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/service/JournalEntryService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.service; import org.apache.fineract.cn.accounting.api.v1.domain.JournalEntry; import org.apache.fineract.cn.accounting.service.ServiceConstants; import org.apache.fineract.cn.accounting.service.internal.mapper.JournalEntryMapper; import org.apache.fineract.cn.accounting.service.internal.repository.DebtorType; import org.apache.fineract.cn.accounting.service.internal.repository.JournalEntryEntity; import org.apache.fineract.cn.accounting.service.internal.repository.JournalEntryRepository; import org.apache.fineract.cn.accounting.service.internal.repository.TransactionTypeEntity; import org.apache.fineract.cn.accounting.service.internal.repository.TransactionTypeRepository; import java.math.BigDecimal; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.apache.fineract.cn.lang.DateRange; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service public class JournalEntryService { private Logger logger; private final JournalEntryRepository journalEntryRepository; private final TransactionTypeRepository transactionTypeRepository; @Autowired public JournalEntryService(@Qualifier(ServiceConstants.LOGGER_NAME) final Logger logger, final JournalEntryRepository journalEntryRepository, final TransactionTypeRepository transactionTypeRepository) { super(); this.logger = logger; this.journalEntryRepository = journalEntryRepository; this.transactionTypeRepository = transactionTypeRepository; } public List<JournalEntry> fetchJournalEntries(final DateRange range, final String accountNumber, final BigDecimal amount) { final List<JournalEntryEntity> journalEntryEntities = this.journalEntryRepository.fetchJournalEntries(range); if (journalEntryEntities != null) { final List<JournalEntryEntity> filteredList = journalEntryEntities .stream() .filter(journalEntryEntity -> accountNumber == null || journalEntryEntity.getDebtors().stream() .anyMatch(debtorType -> debtorType.getAccountNumber().equals(accountNumber)) || journalEntryEntity.getCreditors().stream() .anyMatch(creditorType -> creditorType.getAccountNumber().equals(accountNumber)) ) .filter(journalEntryEntity -> amount == null || amount.compareTo( BigDecimal.valueOf( journalEntryEntity.getDebtors().stream().mapToDouble(DebtorType::getAmount).sum() ) ) == 0 ) .sorted(Comparator.comparing(JournalEntryEntity::getTransactionDate)) .collect(Collectors.toList()); final List<TransactionTypeEntity> transactionTypes = this.transactionTypeRepository.findAll(); final HashMap<String, String> mappedTransactionTypes = new HashMap<>(transactionTypes.size()); transactionTypes.forEach(transactionTypeEntity -> mappedTransactionTypes.put(transactionTypeEntity.getIdentifier(), transactionTypeEntity.getName()) ); return filteredList .stream() .map(journalEntryEntity -> { final JournalEntry journalEntry = JournalEntryMapper.map(journalEntryEntity); journalEntry.setTransactionType(mappedTransactionTypes.get(journalEntry.getTransactionType())); return journalEntry; }) .collect(Collectors.toList()); } else { return Collections.emptyList(); } } public Optional<JournalEntry> findJournalEntry(final String transactionIdentifier) { final Optional<JournalEntryEntity> optionalJournalEntryEntity = this.journalEntryRepository.findJournalEntry(transactionIdentifier); return optionalJournalEntryEntity.map(JournalEntryMapper::map); } }
4,849
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/service/TrialBalanceService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.service; import org.apache.fineract.cn.accounting.api.v1.domain.AccountType; import org.apache.fineract.cn.accounting.api.v1.domain.financial.statement.TrialBalance; import org.apache.fineract.cn.accounting.api.v1.domain.financial.statement.TrialBalanceEntry; import org.apache.fineract.cn.accounting.service.internal.mapper.LedgerMapper; import org.apache.fineract.cn.accounting.service.internal.repository.LedgerRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.Comparator; @Service public class TrialBalanceService { private final LedgerRepository ledgerRepository; @Autowired public TrialBalanceService(final LedgerRepository ledgerRepository) { super(); this.ledgerRepository = ledgerRepository; } public TrialBalance getTrialBalance(final boolean includeEmptyEntries) { final TrialBalance trialBalance = new TrialBalance(); this.ledgerRepository.findByParentLedgerIsNull().forEach(ledgerEntity -> this.ledgerRepository.findByParentLedgerOrderByIdentifier(ledgerEntity).forEach(subLedger -> { final BigDecimal totalValue = subLedger.getTotalValue() != null ? subLedger.getTotalValue() : BigDecimal.ZERO; if (!includeEmptyEntries && totalValue.compareTo(BigDecimal.ZERO) == 0) { return; } final TrialBalanceEntry trialBalanceEntry = new TrialBalanceEntry(); trialBalanceEntry.setLedger(LedgerMapper.map(subLedger)); switch (AccountType.valueOf(subLedger.getType())) { case ASSET: case EXPENSE: trialBalanceEntry.setType(TrialBalanceEntry.Type.DEBIT.name()); break; case LIABILITY: case EQUITY: case REVENUE: trialBalanceEntry.setType(TrialBalanceEntry.Type.CREDIT.name()); break; } trialBalanceEntry.setAmount(totalValue); trialBalance.getTrialBalanceEntries().add(trialBalanceEntry); }) ); trialBalance.setDebitTotal( trialBalance.getTrialBalanceEntries() .stream() .filter(trialBalanceEntry -> trialBalanceEntry.getType().equals(TrialBalanceEntry.Type.DEBIT.name())) .map(TrialBalanceEntry::getAmount) .reduce(BigDecimal.ZERO, BigDecimal::add) ); trialBalance.setCreditTotal( trialBalance.getTrialBalanceEntries() .stream() .filter(trialBalanceEntry -> trialBalanceEntry.getType().equals(TrialBalanceEntry.Type.CREDIT.name())) .map(TrialBalanceEntry::getAmount) .reduce(BigDecimal.ZERO, BigDecimal::add) ); // Sort by ledger identifier ASC trialBalance.getTrialBalanceEntries().sort(Comparator.comparing(trailBalanceEntry -> trailBalanceEntry.getLedger().getIdentifier())); return trialBalance; } }
4,850
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/service/LedgerService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.service; import org.apache.fineract.cn.accounting.api.v1.domain.Account; import org.apache.fineract.cn.accounting.api.v1.domain.AccountPage; import org.apache.fineract.cn.accounting.api.v1.domain.Ledger; import org.apache.fineract.cn.accounting.api.v1.domain.LedgerPage; import org.apache.fineract.cn.accounting.service.internal.mapper.AccountMapper; import org.apache.fineract.cn.accounting.service.internal.mapper.LedgerMapper; import org.apache.fineract.cn.accounting.service.internal.repository.AccountEntity; import org.apache.fineract.cn.accounting.service.internal.repository.AccountRepository; import org.apache.fineract.cn.accounting.service.internal.repository.LedgerEntity; import org.apache.fineract.cn.accounting.service.internal.repository.LedgerRepository; import org.apache.fineract.cn.accounting.service.internal.repository.specification.LedgerSpecification; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class LedgerService { private final LedgerRepository ledgerRepository; private final AccountRepository accountRepository; @Autowired public LedgerService(final LedgerRepository ledgerRepository, final AccountRepository accountRepository) { super(); this.ledgerRepository = ledgerRepository; this.accountRepository = accountRepository; } public LedgerPage fetchLedgers(final boolean includeSubLedgers, final String term, final String type, final Pageable pageable) { final LedgerPage ledgerPage = new LedgerPage(); final Page<LedgerEntity> ledgerEntities = this.ledgerRepository.findAll( LedgerSpecification.createSpecification(includeSubLedgers, term, type), pageable ); ledgerPage.setTotalPages(ledgerEntities.getTotalPages()); ledgerPage.setTotalElements(ledgerEntities.getTotalElements()); ledgerPage.setLedgers(this.mapToLedger(ledgerEntities.getContent())); return ledgerPage; } private List<Ledger> mapToLedger(List<LedgerEntity> ledgerEntities) { final List<Ledger> result = new ArrayList<>(ledgerEntities.size()); if(!ledgerEntities.isEmpty()) { ledgerEntities.forEach(ledgerEntity -> { final Ledger ledger = LedgerMapper.map(ledgerEntity); this.addSubLedgers(ledger, this.ledgerRepository.findByParentLedgerOrderByIdentifier(ledgerEntity)); result.add(ledger); }); } return result; } public Optional<Ledger> findLedger(final String identifier) { final LedgerEntity ledgerEntity = this.ledgerRepository.findByIdentifier(identifier); if (ledgerEntity != null) { final Ledger ledger = LedgerMapper.map(ledgerEntity); this.addSubLedgers(ledger, this.ledgerRepository.findByParentLedgerOrderByIdentifier(ledgerEntity)); return Optional.of(ledger); } else { return Optional.empty(); } } public AccountPage fetchAccounts(final String ledgerIdentifier, final Pageable pageable) { final LedgerEntity ledgerEntity = this.ledgerRepository.findByIdentifier(ledgerIdentifier); final Page<AccountEntity> accountEntities = this.accountRepository.findByLedger(ledgerEntity, pageable); final AccountPage accountPage = new AccountPage(); accountPage.setTotalPages(accountEntities.getTotalPages()); accountPage.setTotalElements(accountEntities.getTotalElements()); if(accountEntities.getSize() > 0){ final List<Account> accounts = new ArrayList<>(accountEntities.getSize()); accountEntities.forEach(accountEntity -> accounts.add(AccountMapper.map(accountEntity))); accountPage.setAccounts(accounts); } return accountPage; } public boolean hasAccounts(final String ledgerIdentifier) { final LedgerEntity ledgerEntity = this.ledgerRepository.findByIdentifier(ledgerIdentifier); final List<AccountEntity> ledgerAccounts = this.accountRepository.findByLedger(ledgerEntity); return ledgerAccounts.size() > 0; } private void addSubLedgers(final Ledger parentLedger, final List<LedgerEntity> subLedgerEntities) { if (subLedgerEntities != null) { final List<Ledger> subLedgers = new ArrayList<>(subLedgerEntities.size()); subLedgerEntities.forEach(subLedgerEntity -> subLedgers.add(LedgerMapper.map(subLedgerEntity))); parentLedger.setSubLedgers(subLedgers); } } }
4,851
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/internal/service/IncomeStatementService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.internal.service; import org.apache.fineract.cn.accounting.api.v1.domain.AccountType; import org.apache.fineract.cn.accounting.api.v1.domain.financial.statement.IncomeStatement; import org.apache.fineract.cn.accounting.api.v1.domain.financial.statement.IncomeStatementEntry; import org.apache.fineract.cn.accounting.api.v1.domain.financial.statement.IncomeStatementSection; import org.apache.fineract.cn.accounting.service.internal.repository.LedgerRepository; import java.math.BigDecimal; import java.time.Clock; import java.time.LocalDateTime; import org.apache.fineract.cn.lang.DateConverter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class IncomeStatementService { private final LedgerRepository ledgerRepository; @Autowired public IncomeStatementService(final LedgerRepository ledgerRepository) { super(); this.ledgerRepository = ledgerRepository; } public IncomeStatement getIncomeStatement() { final IncomeStatement incomeStatement = new IncomeStatement(); incomeStatement.setDate(DateConverter.toIsoString(LocalDateTime.now(Clock.systemUTC()))); this.createIncomeStatementSection(incomeStatement, AccountType.REVENUE, IncomeStatementSection.Type.INCOME); this.createIncomeStatementSection(incomeStatement, AccountType.EXPENSE, IncomeStatementSection.Type.EXPENSES); incomeStatement.setGrossProfit(this.calculateTotal(incomeStatement, IncomeStatementSection.Type.INCOME)); incomeStatement.setTotalExpenses(this.calculateTotal(incomeStatement, IncomeStatementSection.Type.EXPENSES)); incomeStatement.setNetIncome(incomeStatement.getGrossProfit().subtract(incomeStatement.getTotalExpenses())); return incomeStatement; } private void createIncomeStatementSection(final IncomeStatement incomeStatement, final AccountType accountType, final IncomeStatementSection.Type incomeStatementType) { this.ledgerRepository.findByParentLedgerIsNullAndType(accountType.name()).forEach(ledgerEntity -> { final IncomeStatementSection incomeStatementSection = new IncomeStatementSection(); incomeStatementSection.setType(incomeStatementType.name()); incomeStatementSection.setDescription(ledgerEntity.getName()); incomeStatement.add(incomeStatementSection); this.ledgerRepository.findByParentLedgerOrderByIdentifier(ledgerEntity).forEach(subLedgerEntity -> { final IncomeStatementEntry incomeStatementEntry = new IncomeStatementEntry(); incomeStatementEntry.setDescription(subLedgerEntity.getName()); final BigDecimal totalValue = subLedgerEntity.getTotalValue() != null ? subLedgerEntity.getTotalValue() : BigDecimal.ZERO; incomeStatementEntry.setValue(totalValue); incomeStatementSection.add(incomeStatementEntry); }); }); } private BigDecimal calculateTotal(final IncomeStatement incomeStatement, final IncomeStatementSection.Type incomeStatementType) { return incomeStatement.getIncomeStatementSections() .stream() .filter(incomeStatementSection -> incomeStatementSection.getType().equals(incomeStatementType.name())) .map(IncomeStatementSection::getSubtotal) .reduce(BigDecimal.ZERO, BigDecimal::add); } }
4,852
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/rest/LedgerRestController.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.rest; import org.apache.fineract.cn.accounting.api.v1.PermittableGroupIds; import org.apache.fineract.cn.accounting.api.v1.domain.AccountPage; import org.apache.fineract.cn.accounting.api.v1.domain.Ledger; import org.apache.fineract.cn.accounting.api.v1.domain.LedgerPage; import org.apache.fineract.cn.accounting.service.internal.command.AddSubLedgerCommand; import org.apache.fineract.cn.accounting.service.internal.command.CreateLedgerCommand; import org.apache.fineract.cn.accounting.service.internal.command.DeleteLedgerCommand; import org.apache.fineract.cn.accounting.service.internal.command.ModifyLedgerCommand; import org.apache.fineract.cn.accounting.service.internal.service.LedgerService; import org.apache.fineract.cn.accounting.service.rest.paging.PageableBuilder; import java.util.Optional; import javax.validation.Valid; import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType; import org.apache.fineract.cn.anubis.annotation.Permittable; import org.apache.fineract.cn.command.gateway.CommandGateway; import org.apache.fineract.cn.lang.ServiceException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @SuppressWarnings({"unused"}) @RestController @RequestMapping("/ledgers") public class LedgerRestController { private final CommandGateway commandGateway; private final LedgerService ledgerService; @Autowired public LedgerRestController(final CommandGateway commandGateway, final LedgerService ledgerService) { super(); this.commandGateway = commandGateway; this.ledgerService = ledgerService; } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_LEDGER) @RequestMapping( method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) @ResponseBody ResponseEntity<Void> createLedger(@RequestBody @Valid final Ledger ledger) { if (ledger.getParentLedgerIdentifier() != null) { throw ServiceException.badRequest("Ledger {0} is not a root.", ledger.getIdentifier()); } if (this.ledgerService.findLedger(ledger.getIdentifier()).isPresent()) { throw ServiceException.conflict("Ledger {0} already exists.", ledger.getIdentifier()); } this.commandGateway.process(new CreateLedgerCommand(ledger)); return ResponseEntity.accepted().build(); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_LEDGER) @RequestMapping( method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody ResponseEntity<LedgerPage> fetchLedgers(@RequestParam(value = "includeSubLedgers", required = false, defaultValue = "false") final boolean includeSubLedgers, @RequestParam(value = "term", required = false) final String term, @RequestParam(value = "type", required = false) final String type, @RequestParam(value = "pageIndex", required = false) final Integer pageIndex, @RequestParam(value = "size", required = false) final Integer size, @RequestParam(value = "sortColumn", required = false) final String sortColumn, @RequestParam(value = "sortDirection", required = false) final String sortDirection) { return ResponseEntity.ok( this.ledgerService.fetchLedgers( includeSubLedgers, term, type, PageableBuilder.create(pageIndex, size, sortColumn, sortDirection) ) ); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_LEDGER) @RequestMapping( value = "/{identifier}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody ResponseEntity<Ledger> findLedger(@PathVariable("identifier") final String identifier) { final Optional<Ledger> optionalLedger = this.ledgerService.findLedger(identifier); if (optionalLedger.isPresent()) { return ResponseEntity.ok(optionalLedger.get()); } else { throw ServiceException.notFound("Ledger {0} not found.", identifier); } } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_LEDGER) @RequestMapping( value = "/{identifier}", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) @ResponseBody ResponseEntity<Void> addSubLedger(@PathVariable("identifier") final String identifier, @RequestBody @Valid final Ledger subLedger) { final Optional<Ledger> optionalParentLedger = this.ledgerService.findLedger(identifier); if (optionalParentLedger.isPresent()) { final Ledger parentLedger = optionalParentLedger.get(); if (!parentLedger.getType().equals(subLedger.getType())) { throw ServiceException.badRequest("Ledger type must be the same."); } } else { throw ServiceException.notFound("Parent ledger {0} not found.", identifier); } if (this.ledgerService.findLedger(subLedger.getIdentifier()).isPresent()) { throw ServiceException.conflict("Ledger {0} already exists.", subLedger.getIdentifier()); } this.commandGateway.process(new AddSubLedgerCommand(identifier, subLedger)); return ResponseEntity.accepted().build(); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_LEDGER) @RequestMapping( value = "/{identifier}", method = RequestMethod.PUT, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) @ResponseBody ResponseEntity<Void> modifyLedger(@PathVariable("identifier") final String identifier, @RequestBody @Valid final Ledger ledger) { if (!identifier.equals(ledger.getIdentifier())) { throw ServiceException.badRequest("Addressed resource {0} does not match ledger {1}", identifier, ledger.getIdentifier()); } if (!this.ledgerService.findLedger(identifier).isPresent()) { throw ServiceException.notFound("Ledger {0} not found.", identifier); } this.commandGateway.process(new ModifyLedgerCommand(ledger)); return ResponseEntity.accepted().build(); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_LEDGER) @RequestMapping( value = "/{identifier}", method = RequestMethod.DELETE, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody ResponseEntity<Void> deleteLedger(@PathVariable("identifier") final String identifier) { final Optional<Ledger> optionalLedger = this.ledgerService.findLedger(identifier); if (optionalLedger.isPresent()) { final Ledger ledger = optionalLedger.get(); if (!ledger.getSubLedgers().isEmpty()) { throw ServiceException.conflict("Ledger {0} holds sub ledgers.", identifier); } } else { throw ServiceException.notFound("Ledger {0} not found.", identifier); } if (this.ledgerService.hasAccounts(identifier)) { throw ServiceException.conflict("Ledger {0} has assigned accounts.", identifier); } this.commandGateway.process(new DeleteLedgerCommand(identifier)); return ResponseEntity.accepted().build(); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_LEDGER) @RequestMapping( value = "/{identifier}/accounts", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody ResponseEntity<AccountPage> fetchAccountsOfLedger(@PathVariable("identifier") final String identifier, @RequestParam(value = "pageIndex", required = false) final Integer pageIndex, @RequestParam(value = "size", required = false) final Integer size, @RequestParam(value = "sortColumn", required = false) final String sortColumn, @RequestParam(value = "sortDirection", required = false) final String sortDirection) { if (!this.ledgerService.findLedger(identifier).isPresent()) { throw ServiceException.notFound("Ledger {0} not found.", identifier); } return ResponseEntity.ok(this.ledgerService.fetchAccounts(identifier, PageableBuilder.create(pageIndex, size, sortColumn, sortDirection))); } }
4,853
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/rest/FinancialConditionController.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.rest; import org.apache.fineract.cn.accounting.api.v1.PermittableGroupIds; import org.apache.fineract.cn.accounting.api.v1.domain.financial.statement.FinancialCondition; import org.apache.fineract.cn.accounting.service.internal.service.FinancialConditionService; import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType; import org.apache.fineract.cn.anubis.annotation.Permittable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/financialcondition") public class FinancialConditionController { private final FinancialConditionService financialConditionService; @Autowired public FinancialConditionController(final FinancialConditionService financialConditionService) { super(); this.financialConditionService = financialConditionService; } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_FIN_CONDITION) @RequestMapping( method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody public ResponseEntity<FinancialCondition> getFinancialCondition() { return ResponseEntity.ok(this.financialConditionService.getFinancialCondition()); } }
4,854
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/rest/MigrationRestController.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.rest; import org.apache.fineract.cn.accounting.service.internal.command.InitializeServiceCommand; import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType; import org.apache.fineract.cn.anubis.annotation.Permittable; import org.apache.fineract.cn.command.gateway.CommandGateway; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @SuppressWarnings("unused") @RestController @RequestMapping("/") public class MigrationRestController { private final CommandGateway commandGateway; @Autowired public MigrationRestController(final CommandGateway commandGateway) { super(); this.commandGateway = commandGateway; } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "/initialize", method = RequestMethod.POST, consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_VALUE ) public @ResponseBody ResponseEntity<Void> initialize() throws InterruptedException { this.commandGateway.process(new InitializeServiceCommand()); return ResponseEntity.accepted().build(); } }
4,855
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/rest/TransactionTypeRestController.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.rest; import org.apache.fineract.cn.accounting.api.v1.PermittableGroupIds; import org.apache.fineract.cn.accounting.api.v1.domain.TransactionType; import org.apache.fineract.cn.accounting.api.v1.domain.TransactionTypePage; import org.apache.fineract.cn.accounting.service.internal.command.ChangeTransactionTypeCommand; import org.apache.fineract.cn.accounting.service.internal.command.CreateTransactionTypeCommand; import org.apache.fineract.cn.accounting.service.internal.service.TransactionTypeService; import org.apache.fineract.cn.accounting.service.rest.paging.PageableBuilder; import javax.validation.Valid; import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType; import org.apache.fineract.cn.anubis.annotation.Permittable; import org.apache.fineract.cn.command.gateway.CommandGateway; import org.apache.fineract.cn.lang.ServiceException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @SuppressWarnings("unused") @RestController @RequestMapping("/transactiontypes") public class TransactionTypeRestController { private final CommandGateway commandGateway; private final TransactionTypeService transactionTypeService; @Autowired public TransactionTypeRestController(final CommandGateway commandGateway, final TransactionTypeService transactionTypeService) { super(); this.commandGateway = commandGateway; this.transactionTypeService = transactionTypeService; } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_TX_TYPES) @RequestMapping( value = "", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) @ResponseBody ResponseEntity<Void> createTransactionType(@RequestBody @Valid final TransactionType transactionType) { if (this.transactionTypeService.findByIdentifier(transactionType.getCode()).isPresent()) { throw ServiceException.conflict("Transaction type '{0}' already exists.", transactionType.getCode()); } this.commandGateway.process(new CreateTransactionTypeCommand(transactionType)); return ResponseEntity.accepted().build(); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_TX_TYPES) @RequestMapping( value = "", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody ResponseEntity<TransactionTypePage> fetchTransactionTypes(@RequestParam(value = "term", required = false) final String term, @RequestParam(value = "pageIndex", required = false) final Integer pageIndex, @RequestParam(value = "size", required = false) final Integer size, @RequestParam(value = "sortColumn", required = false) final String sortColumn, @RequestParam(value = "sortDirection", required = false) final String sortDirection) { final String column2sort = "code".equalsIgnoreCase(sortColumn) ? "identifier" : sortColumn; return ResponseEntity.ok( this.transactionTypeService.fetchTransactionTypes(term, PageableBuilder.create(pageIndex, size, column2sort, sortDirection))); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_TX_TYPES) @RequestMapping( value = "/{code}", method = RequestMethod.PUT, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) @ResponseBody ResponseEntity<Void> changeTransactionType(@PathVariable("code") final String code, @RequestBody @Valid final TransactionType transactionType) { if (!code.equals(transactionType.getCode())) { throw ServiceException.badRequest("Given transaction type {0} must match request path.", code); } if (!this.transactionTypeService.findByIdentifier(code).isPresent()) { throw ServiceException.notFound("Transaction type '{0}' not found.", code); } this.commandGateway.process(new ChangeTransactionTypeCommand(transactionType)); return ResponseEntity.accepted().build(); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_TX_TYPES) @RequestMapping( value = "/{code}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody ResponseEntity<TransactionType> findTransactionType(@PathVariable("code") final String code) { return ResponseEntity.ok( this.transactionTypeService.findByIdentifier(code) .orElseThrow(() -> ServiceException.notFound("Transaction type '{0}' not found.", code)) ); } }
4,856
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/rest/JournalRestController.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.rest; import org.apache.fineract.cn.accounting.api.v1.PermittableGroupIds; import org.apache.fineract.cn.accounting.api.v1.domain.Account; import org.apache.fineract.cn.accounting.api.v1.domain.JournalEntry; import org.apache.fineract.cn.accounting.service.internal.command.CreateJournalEntryCommand; import org.apache.fineract.cn.accounting.service.internal.service.AccountService; import org.apache.fineract.cn.accounting.service.internal.service.JournalEntryService; import java.math.BigDecimal; import java.util.List; import java.util.Optional; import javax.validation.Valid; import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType; import org.apache.fineract.cn.anubis.annotation.Permittable; import org.apache.fineract.cn.command.gateway.CommandGateway; import org.apache.fineract.cn.lang.DateRange; import org.apache.fineract.cn.lang.ServiceException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @SuppressWarnings({"unused"}) @RestController @RequestMapping("/journal") public class JournalRestController { private final CommandGateway commandGateway; private final JournalEntryService journalEntryService; private final AccountService accountService; @Autowired public JournalRestController(final CommandGateway commandGateway, final JournalEntryService journalEntryService, final AccountService accountService) { super(); this.commandGateway = commandGateway; this.journalEntryService = journalEntryService; this.accountService = accountService; } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_JOURNAL) @RequestMapping( method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) @ResponseBody ResponseEntity<Void> createJournalEntry(@RequestBody @Valid final JournalEntry journalEntry) { if (this.journalEntryService.findJournalEntry(journalEntry.getTransactionIdentifier()).isPresent()) { throw ServiceException.conflict("Journal entry {0} already exists.", journalEntry.getTransactionIdentifier()); } if (journalEntry.getDebtors().size() == 0) { throw ServiceException.badRequest("Debtors must be given."); } if (journalEntry.getCreditors().size() == 0) { throw ServiceException.badRequest("Creditors must be given."); } final Double debtorAmountSum = journalEntry.getDebtors() .stream() .peek(debtor -> { final Optional<Account> accountOptional = this.accountService.findAccount(debtor.getAccountNumber()); if (!accountOptional.isPresent()) { throw ServiceException.badRequest("Unknown debtor account{0}.", debtor.getAccountNumber()); } if (!accountOptional.get().getState().equals(Account.State.OPEN.name())) { throw ServiceException.conflict("Debtor account{0} must be in state open.", debtor.getAccountNumber()); } }) .map(debtor -> Double.valueOf(debtor.getAmount())) .reduce(0.0D, (x, y) -> x + y); final Double creditorAmountSum = journalEntry.getCreditors() .stream() .peek(creditor -> { final Optional<Account> accountOptional = this.accountService.findAccount(creditor.getAccountNumber()); if (!accountOptional.isPresent()) { throw ServiceException.badRequest("Unknown creditor account{0}.", creditor.getAccountNumber()); } if (!accountOptional.get().getState().equals(Account.State.OPEN.name())) { throw ServiceException.conflict("Creditor account{0} must be in state open.", creditor.getAccountNumber()); } }) .map(creditor -> Double.valueOf(creditor.getAmount())) .reduce(0.0D, (x, y) -> x + y); if (!debtorAmountSum.equals(creditorAmountSum)) { throw ServiceException.conflict( "Sum of debtor and sum of creditor amounts must be equals."); } this.commandGateway.process(new CreateJournalEntryCommand(journalEntry)); return ResponseEntity.accepted().build(); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_JOURNAL) @RequestMapping( method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody ResponseEntity<List<JournalEntry>> fetchJournalEntries( @RequestParam(value = "dateRange", required = false) final String dateRange, @RequestParam(value = "account", required = false) final String accountNumber, @RequestParam(value = "amount", required = false) final BigDecimal amount ) { final DateRange range = DateRange.fromIsoString(dateRange); return ResponseEntity.ok(this.journalEntryService.fetchJournalEntries(range, accountNumber, amount)); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_JOURNAL) @RequestMapping( value = "/{transactionIdentifier}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody ResponseEntity<JournalEntry> findJournalEntry( @PathVariable("transactionIdentifier") final String transactionIdentifier ) { final Optional<JournalEntry> optionalJournalEntry = this.journalEntryService.findJournalEntry(transactionIdentifier); if (optionalJournalEntry.isPresent()) { return ResponseEntity.ok(optionalJournalEntry.get()); } else { throw ServiceException.notFound("Journal entry {0} not found.", transactionIdentifier); } } }
4,857
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/rest/TrialBalanceController.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.rest; import org.apache.fineract.cn.accounting.api.v1.PermittableGroupIds; import org.apache.fineract.cn.accounting.api.v1.domain.financial.statement.TrialBalance; import org.apache.fineract.cn.accounting.service.internal.service.TrialBalanceService; import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType; import org.apache.fineract.cn.anubis.annotation.Permittable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @SuppressWarnings("unused") @RestController @RequestMapping("/trialbalance") public class TrialBalanceController { private final TrialBalanceService trialBalanceService; @Autowired public TrialBalanceController(final TrialBalanceService trialBalanceService) { super(); this.trialBalanceService = trialBalanceService; } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_LEDGER) @RequestMapping( method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody public ResponseEntity<TrialBalance> getTrialBalance( @RequestParam(value = "includeEmptyEntries", required = false) final boolean includeEmptyEntries) { return ResponseEntity.ok(this.trialBalanceService.getTrialBalance(includeEmptyEntries)); } }
4,858
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/rest/ChartOfAccountsController.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.rest; import org.apache.fineract.cn.accounting.api.v1.PermittableGroupIds; import org.apache.fineract.cn.accounting.api.v1.domain.ChartOfAccountEntry; import org.apache.fineract.cn.accounting.service.internal.service.ChartOfAccountsService; import java.util.List; import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType; import org.apache.fineract.cn.anubis.annotation.Permittable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @SuppressWarnings("unused") @RestController @RequestMapping("/chartofaccounts") public class ChartOfAccountsController { private final ChartOfAccountsService chartOfAccountsService; @Autowired public ChartOfAccountsController(final ChartOfAccountsService chartOfAccountsService) { super(); this.chartOfAccountsService = chartOfAccountsService; } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_LEDGER) @RequestMapping( method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody public ResponseEntity<List<ChartOfAccountEntry>> getChartOfAccounts() { return ResponseEntity.ok(this.chartOfAccountsService.getChartOfAccounts()); } }
4,859
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/rest/AccountRestController.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.rest; import org.apache.fineract.cn.accounting.api.v1.PermittableGroupIds; import org.apache.fineract.cn.accounting.api.v1.client.AccountNotFoundException; import org.apache.fineract.cn.accounting.api.v1.domain.Account; import org.apache.fineract.cn.accounting.api.v1.domain.AccountCommand; import org.apache.fineract.cn.accounting.api.v1.domain.AccountEntryPage; import org.apache.fineract.cn.accounting.api.v1.domain.AccountPage; import org.apache.fineract.cn.accounting.api.v1.domain.Ledger; import org.apache.fineract.cn.accounting.service.internal.command.CloseAccountCommand; import org.apache.fineract.cn.accounting.service.internal.command.CreateAccountCommand; import org.apache.fineract.cn.accounting.service.internal.command.DeleteAccountCommand; import org.apache.fineract.cn.accounting.service.internal.command.LockAccountCommand; import org.apache.fineract.cn.accounting.service.internal.command.ModifyAccountCommand; import org.apache.fineract.cn.accounting.service.internal.command.ReopenAccountCommand; import org.apache.fineract.cn.accounting.service.internal.command.UnlockAccountCommand; import org.apache.fineract.cn.accounting.service.internal.service.AccountService; import org.apache.fineract.cn.accounting.service.internal.service.LedgerService; import org.apache.fineract.cn.accounting.service.rest.paging.PageableBuilder; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; import javax.validation.Valid; import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType; import org.apache.fineract.cn.anubis.annotation.Permittable; import org.apache.fineract.cn.api.annotation.ThrowsException; import org.apache.fineract.cn.command.gateway.CommandGateway; import org.apache.fineract.cn.lang.DateRange; import org.apache.fineract.cn.lang.ServiceException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @SuppressWarnings({"unused"}) @RestController @RequestMapping("/accounts") public class AccountRestController { private final CommandGateway commandGateway; private final AccountService accountService; private final LedgerService ledgerService; @Autowired public AccountRestController(final CommandGateway commandGateway, final AccountService accountService, final LedgerService ledgerService) { super(); this.commandGateway = commandGateway; this.accountService = accountService; this.ledgerService = ledgerService; } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_ACCOUNT) @RequestMapping( method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) @ResponseBody ResponseEntity<Void> createAccount(@RequestBody @Valid final Account account) { if (this.accountService.findAccount(account.getIdentifier()).isPresent()) { throw ServiceException.conflict("Account {0} already exists.", account.getIdentifier()); } if (account.getReferenceAccount() != null && !this.accountService.findAccount(account.getReferenceAccount()).isPresent()) { throw ServiceException.badRequest("Reference account {0} not available.", account.getReferenceAccount()); } validateLedger(account); this.commandGateway.process(new CreateAccountCommand(account)); return ResponseEntity.accepted().build(); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_ACCOUNT) @RequestMapping( method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody ResponseEntity<AccountPage> fetchAccounts( @RequestParam(value = "includeClosed", required = false, defaultValue = "false") final boolean includeClosed, @RequestParam(value = "term", required = false) final String term, @RequestParam(value = "type", required = false) final String type, @RequestParam(value = "includeCustomerAccounts", required = false, defaultValue = "false") final boolean includeCustomerAccounts, @RequestParam(value = "pageIndex", required = false) final Integer pageIndex, @RequestParam(value = "size", required = false) final Integer size, @RequestParam(value = "sortColumn", required = false) final String sortColumn, @RequestParam(value = "sortDirection", required = false) final String sortDirection ) { return ResponseEntity.ok( this.accountService.fetchAccounts( includeClosed, term, type, includeCustomerAccounts, PageableBuilder.create(pageIndex, size, sortColumn, sortDirection) ) ); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_ACCOUNT) @RequestMapping( value = "/{identifier}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody ResponseEntity<Account> findAccount(@PathVariable("identifier") final String identifier) { final Optional<Account> optionalAccount = this.accountService.findAccount(identifier); if (optionalAccount.isPresent()) { return ResponseEntity.ok(optionalAccount.get()); } else { throw ServiceException.notFound("Account {0} not found.", identifier); } } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_ACCOUNT) @RequestMapping( value = "/{identifier}", method = RequestMethod.PUT, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) @ResponseBody ResponseEntity<Void> modifyAccount(@PathVariable("identifier") final String identifier, @RequestBody @Valid final Account account) { if (!identifier.equals(account.getIdentifier())) { throw ServiceException.badRequest("Addressed resource {0} does not match account {1}", identifier, account.getIdentifier()); } if (!this.accountService.findAccount(identifier).isPresent()) { throw ServiceException.notFound("Account {0} not found.", identifier); } if (account.getReferenceAccount() != null && !this.accountService.findAccount(account.getReferenceAccount()).isPresent()) { throw ServiceException.badRequest("Reference account {0} not available.", account.getReferenceAccount()); } validateLedger(account); this.commandGateway.process(new ModifyAccountCommand(account)); return ResponseEntity.accepted().build(); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_ACCOUNT) @RequestMapping( value = "/{identifier}/entries", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody ResponseEntity<AccountEntryPage> fetchAccountEntries( @PathVariable("identifier") final String identifier, @RequestParam(value = "dateRange", required = false) @Nullable final String dateRange, @RequestParam(value = "message", required = false) @Nullable final String message, @RequestParam(value = "pageIndex", required = false) @Nullable final Integer pageIndex, @RequestParam(value = "size", required = false) @Nullable final Integer size, @RequestParam(value = "sortColumn", required = false) @Nullable final String sortColumn, @RequestParam(value = "sortDirection", required = false) @Nullable final String sortDirection ) { final DateRange range = DateRange.fromIsoString(dateRange); return ResponseEntity.ok(this.accountService.fetchAccountEntries( identifier, range, message, PageableBuilder.create(pageIndex, size, sortColumn == null ? "transactionDate" : sortColumn, sortDirection))); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_ACCOUNT) @RequestMapping( value = "/{identifier}/commands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.ALL_VALUE ) @ThrowsException(status = HttpStatus.NOT_FOUND, exception = AccountNotFoundException.class) ResponseEntity<List<AccountCommand>> fetchAccountCommands(@PathVariable("identifier") final String identifier){ final Optional<Account> optionalAccount = this.accountService.findAccount(identifier); if (optionalAccount.isPresent()) { return ResponseEntity.ok(this.accountService.fetchCommandsByAccount(identifier)); } else { throw ServiceException.notFound("Account {0} not found.", identifier); } } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_ACCOUNT) @RequestMapping( value = "/{identifier}/commands", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) @ResponseBody ResponseEntity<Void> accountCommand(@PathVariable("identifier") final String identifier, @RequestBody @Valid final AccountCommand accountCommand) { final Optional<Account> optionalAccount = this.accountService.findAccount(identifier); if (optionalAccount.isPresent()) { final Account account = optionalAccount.get(); final Account.State state = Account.State.valueOf(account.getState()); switch (AccountCommand.Action.valueOf(accountCommand.getAction())) { case CLOSE: if (account.getBalance() != 0.00D) { throw ServiceException.conflict("Account {0} has remaining balance.", identifier); } if (state.equals(Account.State.OPEN) || state.equals(Account.State.LOCKED)) { this.commandGateway.process(new CloseAccountCommand(identifier, accountCommand.getComment())); } break; case LOCK: if (state.equals(Account.State.OPEN)) { this.commandGateway.process(new LockAccountCommand(identifier, accountCommand.getComment())); } break; case UNLOCK: if (state.equals(Account.State.LOCKED)) { this.commandGateway.process(new UnlockAccountCommand(identifier, accountCommand.getComment())); } break; case REOPEN: if (state.equals(Account.State.CLOSED)) { this.commandGateway.process(new ReopenAccountCommand(identifier, accountCommand.getComment())); } break; default: throw ServiceException.badRequest("Invalid state change."); } return ResponseEntity.accepted().build(); } else { throw ServiceException.notFound("Account {0} not found.", identifier); } } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_ACCOUNT) @RequestMapping( value = "/{identifier}", method = RequestMethod.DELETE, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody ResponseEntity<Void> deleteAccount(@PathVariable("identifier") final String identifier) { final Optional<Account> optionalAccount = this.accountService.findAccount(identifier); final Account account = optionalAccount.orElseThrow(() -> ServiceException.notFound("Account {0} not found", identifier)); if (!account.getState().equals(Account.State.CLOSED.name())) { throw ServiceException.conflict("Account {0} is not closed.", identifier); } if (this.accountService.hasEntries(identifier)) { throw ServiceException.conflict("Account {0} has valid entries.", identifier); } if (this.accountService.hasReferenceAccounts(identifier)) { throw ServiceException.conflict("Account {0} is referenced.", identifier); } this.commandGateway.process(new DeleteAccountCommand(identifier)); return ResponseEntity.accepted().build(); } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_ACCOUNT) @RequestMapping( value = "/{identifier}/actions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.ALL_VALUE ) public @ResponseBody ResponseEntity<List<AccountCommand>> fetchActions(@PathVariable(value = "identifier") final String identifier) { if (!this.accountService.findAccount(identifier).isPresent()) { throw ServiceException.notFound("Account {0} not found", identifier); } return ResponseEntity.ok(this.accountService.getActions(identifier)); } private void validateLedger(final @RequestBody @Valid Account account) { final Optional<Ledger> optionalLedger = this.ledgerService.findLedger(account.getLedger()); if (!optionalLedger.isPresent()) { throw ServiceException.badRequest("Ledger {0} not available.", account.getLedger()); } else { final Ledger ledger = optionalLedger.get(); if (!ledger.getType().equals(account.getType())) { throw ServiceException.badRequest("Account type {0} must match ledger type {1}.", account.getType(), ledger.getIdentifier()); } } } }
4,860
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/rest/IncomeStatementController.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.rest; import org.apache.fineract.cn.accounting.api.v1.PermittableGroupIds; import org.apache.fineract.cn.accounting.api.v1.domain.financial.statement.IncomeStatement; import org.apache.fineract.cn.accounting.service.internal.service.IncomeStatementService; import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType; import org.apache.fineract.cn.anubis.annotation.Permittable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/incomestatement") public class IncomeStatementController { private final IncomeStatementService incomeStatementService; @Autowired public IncomeStatementController(final IncomeStatementService incomeStatementService) { super(); this.incomeStatementService = incomeStatementService; } @Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.THOTH_INCOME_STMT) @RequestMapping( method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.ALL_VALUE} ) @ResponseBody public ResponseEntity<IncomeStatement> getIncomeStatement() { return ResponseEntity.ok(this.incomeStatementService.getIncomeStatement()); } }
4,861
0
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/rest
Create_ds/fineract-cn-accounting/service/src/main/java/org/apache/fineract/cn/accounting/service/rest/paging/PageableBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.accounting.service.rest.paging; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import javax.annotation.Nullable; public final class PageableBuilder { public static Pageable create( @Nullable final Integer pageIndex, @Nullable final Integer size, @Nullable final String sortColumn, @Nullable final String sortDirection) { final Integer pageIndexToUse = pageIndex != null ? pageIndex : 0; final Integer sizeToUse = size != null ? size : 20; final String sortColumnToUse = sortColumn != null ? sortColumn : "identifier"; final Sort.Direction direction = sortDirection != null ? Sort.Direction.valueOf(sortDirection.toUpperCase()) : Sort.Direction.ASC; return new PageRequest(pageIndexToUse, sizeToUse, direction, sortColumnToUse); } }
4,862
0
Create_ds/cordova-plugin-whitelist/tests/src
Create_ds/cordova-plugin-whitelist/tests/src/android/WhitelistAPI.java
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.cordova.test; import org.apache.cordova.Whitelist; import org.apache.cordova.Config; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.apache.cordova.PluginManager; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class WhitelistAPI extends CordovaPlugin { /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return True if the action was valid, false if not. */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("URLMatchesPatterns")) { String url = args.getString(0); JSONArray patterns = args.getJSONArray(1); Whitelist whitelist = new Whitelist(); for (int i=0; i < patterns.length(); i++) { String pattern = patterns.getString(i); whitelist.addWhiteListEntry(pattern, false); } boolean isAllowed = whitelist.isUrlWhiteListed(url); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, isAllowed)); return true; } else if (action.equals("URLIsAllowed")) { String url = args.getString(0); /* This code exists for compatibility between 3.x and 4.x versions of Cordova. * Previously the CordovaWebView class had a method, getWhitelist, which would * return a Whitelist object. Since the fixed whitelist is removed in Cordova 4.x, * the correct call now is to shouldAllowRequest from the plugin manager. */ Boolean isAllowed = null; try { Method isUrlWhiteListed = Config.class.getDeclaredMethod("isUrlWhitelisted", String.class); isAllowed = (Boolean)isUrlWhiteListed.invoke(url); } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } if (isAllowed == null) { try { Method gpm = webView.getClass().getMethod("getPluginManager"); PluginManager pm = (PluginManager)gpm.invoke(webView); Method isAllowedMethod = pm.getClass().getMethod("shouldAllowRequest", String.class); isAllowed = (Boolean)isAllowedMethod.invoke(pm, url); if (isAllowed == null) { isAllowed = false; } } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, isAllowed)); return true; } return false; } }
4,863
0
Create_ds/cordova-plugin-whitelist/src
Create_ds/cordova-plugin-whitelist/src/android/WhitelistPlugin.java
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.cordova.whitelist; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.ConfigXmlParser; import org.apache.cordova.LOG; import org.apache.cordova.Whitelist; import org.xmlpull.v1.XmlPullParser; import android.content.Context; public class WhitelistPlugin extends CordovaPlugin { private static final String LOG_TAG = "WhitelistPlugin"; private Whitelist allowedNavigations; private Whitelist allowedIntents; private Whitelist allowedRequests; // Used when instantiated via reflection by PluginManager public WhitelistPlugin() { } // These can be used by embedders to allow Java-configuration of whitelists. public WhitelistPlugin(Context context) { this(new Whitelist(), new Whitelist(), null); new CustomConfigXmlParser().parse(context); } public WhitelistPlugin(XmlPullParser xmlParser) { this(new Whitelist(), new Whitelist(), null); new CustomConfigXmlParser().parse(xmlParser); } public WhitelistPlugin(Whitelist allowedNavigations, Whitelist allowedIntents, Whitelist allowedRequests) { if (allowedRequests == null) { allowedRequests = new Whitelist(); allowedRequests.addWhiteListEntry("file:///*", false); allowedRequests.addWhiteListEntry("data:*", false); } this.allowedNavigations = allowedNavigations; this.allowedIntents = allowedIntents; this.allowedRequests = allowedRequests; } @Override public void pluginInitialize() { if (allowedNavigations == null) { allowedNavigations = new Whitelist(); allowedIntents = new Whitelist(); allowedRequests = new Whitelist(); new CustomConfigXmlParser().parse(webView.getContext()); } } private class CustomConfigXmlParser extends ConfigXmlParser { @Override public void handleStartTag(XmlPullParser xml) { String strNode = xml.getName(); if (strNode.equals("content")) { String startPage = xml.getAttributeValue(null, "src"); allowedNavigations.addWhiteListEntry(startPage, false); } else if (strNode.equals("allow-navigation")) { String origin = xml.getAttributeValue(null, "href"); if ("*".equals(origin)) { allowedNavigations.addWhiteListEntry("http://*/*", false); allowedNavigations.addWhiteListEntry("https://*/*", false); allowedNavigations.addWhiteListEntry("data:*", false); } else { allowedNavigations.addWhiteListEntry(origin, false); } } else if (strNode.equals("allow-intent")) { String origin = xml.getAttributeValue(null, "href"); allowedIntents.addWhiteListEntry(origin, false); } else if (strNode.equals("access")) { String origin = xml.getAttributeValue(null, "origin"); String subdomains = xml.getAttributeValue(null, "subdomains"); boolean external = (xml.getAttributeValue(null, "launch-external") != null); if (origin != null) { if (external) { LOG.w(LOG_TAG, "Found <access launch-external> within config.xml. Please use <allow-intent> instead."); allowedIntents.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0)); } else { if ("*".equals(origin)) { allowedRequests.addWhiteListEntry("http://*/*", false); allowedRequests.addWhiteListEntry("https://*/*", false); } else { allowedRequests.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0)); } } } } } @Override public void handleEndTag(XmlPullParser xml) { } } @Override public Boolean shouldAllowNavigation(String url) { if (allowedNavigations.isUrlWhiteListed(url)) { return true; } return null; // Default policy } @Override public Boolean shouldAllowRequest(String url) { if (Boolean.TRUE == shouldAllowNavigation(url)) { return true; } if (allowedRequests.isUrlWhiteListed(url)) { return true; } return null; // Default policy } @Override public Boolean shouldOpenExternalUrl(String url) { if (allowedIntents.isUrlWhiteListed(url)) { return true; } return null; // Default policy } public Whitelist getAllowedNavigations() { return allowedNavigations; } public void setAllowedNavigations(Whitelist allowedNavigations) { this.allowedNavigations = allowedNavigations; } public Whitelist getAllowedIntents() { return allowedIntents; } public void setAllowedIntents(Whitelist allowedIntents) { this.allowedIntents = allowedIntents; } public Whitelist getAllowedRequests() { return allowedRequests; } public void setAllowedRequests(Whitelist allowedRequests) { this.allowedRequests = allowedRequests; } }
4,864
0
Create_ds/workflow-kotlin/workflow-ui/core-android/src/androidTest/java/com/squareup/workflow1
Create_ds/workflow-kotlin/workflow-ui/core-android/src/androidTest/java/com/squareup/workflow1/ui/OnBackPressedDispatcherSpy.java
package androidx.activity; import java.util.ArrayDeque; public class OnBackPressedDispatcherSpy { private final OnBackPressedDispatcher dispatcher; public OnBackPressedDispatcherSpy(OnBackPressedDispatcher dispatcher) { this.dispatcher = dispatcher; } public ArrayDeque<OnBackPressedCallback> callbacks() { return dispatcher.mOnBackPressedCallbacks; } }
4,865
0
Create_ds/workflow-kotlin/workflow-core/src/jvmTest/java/com/squareup
Create_ds/workflow-kotlin/workflow-core/src/jvmTest/java/com/squareup/workflow1/NullFlowWorker.java
package com.squareup.workflow1; import kotlinx.coroutines.flow.Flow; import org.jetbrains.annotations.NotNull; /** * Worker that incorrectly returns null from {@link #run}, to simulate the default behavior of some * mocking libraries. * * See <a href="https://github.com/square/workflow/issues/842">#842</a>. */ class NullFlowWorker implements Worker { @NotNull @Override public Flow run() { //noinspection ConstantConditions return null; } @Override public boolean doesSameWorkAs(@NotNull Worker otherWorker) { //noinspection unchecked return Worker.DefaultImpls.doesSameWorkAs(this, otherWorker); } /** * Override this to make writing assertions on exception messages easier. */ @Override public String toString() { return "NullFlowWorker.toString"; } }
4,866
0
Create_ds/continuum/continuum-data-management/data-management-cli/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-data-management/data-management-cli/src/main/java/org/apache/maven/continuum/management/DataManagementCli.java
package org.apache.maven.continuum.management; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.sampullara.cli.Args; import com.sampullara.cli.Argument; import edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.manager.WagonManager; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.resolver.ArtifactResolutionResult; import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.artifact.resolver.DebugResolutionListener; import org.apache.maven.artifact.resolver.ResolutionListener; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter; import org.apache.maven.artifact.resolver.filter.TypeArtifactFilter; import org.apache.maven.continuum.management.util.PlexusFileSystemXmlApplicationContext; import org.apache.maven.settings.MavenSettingsBuilder; import org.apache.maven.settings.Mirror; import org.apache.maven.settings.Profile; import org.apache.maven.settings.Proxy; import org.apache.maven.settings.Repository; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.apache.maven.wagon.repository.RepositoryPermissions; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.PlexusContainerException; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.spring.PlexusClassPathXmlApplicationContext; import org.codehaus.plexus.spring.PlexusContainerAdapter; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; /** * An application for performing database upgrades from old Continuum and Redback versions. A suitable tool until it * is natively incorporated into Continuum itself. */ public class DataManagementCli { private static final Logger LOGGER = Logger.getLogger( DataManagementCli.class ); private static final String JAR_FILE_PREFIX = "jar:file:"; private static final String FILE_PREFIX = "file:"; private static final String SPRING_CONTEXT_LOC = "!/**/META-INF/spring-context.xml"; private static final String PLEXUS_XML_LOC = "!/**/META-INF/plexus/components.xml"; public static void main( String[] args ) throws Exception { Commands command = new Commands(); DatabaseFormat databaseFormat; OperationMode mode; SupportedDatabase databaseType; try { Args.parse( command, args ); if ( command.help ) { Args.usage( command ); return; } if ( command.version ) { System.out.print( "continuum-data-management version " + getVersion() ); return; } databaseFormat = DatabaseFormat.valueOf( command.databaseFormat ); mode = OperationMode.valueOf( command.mode ); databaseType = SupportedDatabase.valueOf( command.databaseType ); } catch ( IllegalArgumentException e ) { System.err.println( e.getMessage() ); Args.usage( command ); return; } if ( command.directory.exists() && !command.directory.isDirectory() ) { System.err.println( command.directory + " already exists and is not a directory." ); Args.usage( command ); return; } if ( !command.overwrite && mode == OperationMode.EXPORT && command.directory.exists() ) { System.err.println( command.directory + " already exists and will not be overwritten unless the -overwrite flag is used." ); Args.usage( command ); return; } if ( command.buildsJdbcUrl == null && command.usersJdbcUrl == null ) { System.err.println( "You must specify one of -buildsJdbcUrl and -usersJdbcUrl" ); Args.usage( command ); return; } if ( command.usersJdbcUrl != null && databaseFormat == DatabaseFormat.CONTINUUM_103 ) { System.err.println( "The -usersJdbcUrl option can not be used with Continuum 1.0.3 databases" ); Args.usage( command ); return; } if ( SupportedDatabase.OTHER.equals( databaseType ) ) { if ( command.driverClass == null || command.artifactId == null || command.groupId == null || command.artifactVersion == null || command.password == null || command.username == null ) { System.err.println( "If OTHER databaseType is selected, -driverClass, -artifactId, -groupId, -artifactVersion, -username and -password must be provided together" ); Args.usage( command ); return; } databaseType.defaultParams = new DatabaseParams( command.driverClass, command.groupId, command.artifactId, command.artifactVersion, command.username, command.password ); } BasicConfigurator.configure(); if ( command.debug ) { Logger.getRootLogger().setLevel( Level.DEBUG ); Logger.getLogger( "JPOX" ).setLevel( Level.DEBUG ); } else { Logger.getRootLogger().setLevel( Level.INFO ); Logger.getLogger( "JPOX" ).setLevel( Level.WARN ); } if ( command.settings != null && !command.settings.isFile() ) { System.err.println( command.settings + " not exists or is not a file." ); Args.usage( command ); return; } if ( command.buildsJdbcUrl != null ) { LOGGER.info( "Processing Continuum database..." ); processDatabase( databaseType, databaseFormat, mode, command.buildsJdbcUrl, command.directory, command.settings, databaseFormat.getContinuumToolRoleHint(), "data-management-jdo", "continuum", command.strict ); } if ( command.usersJdbcUrl != null ) { LOGGER.info( "Processing Redback database..." ); processDatabase( databaseType, databaseFormat, mode, command.usersJdbcUrl, command.directory, command.settings, databaseFormat.getRedbackToolRoleHint(), "data-management-redback-jdo", "redback", command.strict ); } LOGGER.info( "Export complete. Shutting down..." ); } private static void shutdownResolverThreadPool( PlexusContainerAdapter container ) { try { ArtifactResolver resolver = (ArtifactResolver) container.lookup( ArtifactResolver.ROLE ); Field f = resolver.getClass().getDeclaredField( "resolveArtifactPool" ); f.setAccessible( true ); ThreadPoolExecutor executor = (ThreadPoolExecutor) f.get( resolver ); executor.shutdownNow(); } catch ( Exception e ) { LOGGER.error( "failed to shutdown resolver thread pool", e ); } } private static void processDatabase( SupportedDatabase databaseType, DatabaseFormat databaseFormat, OperationMode mode, String jdbcUrl, File directory, File setting, String toolRoleHint, String managementArtifactId, String configRoleHint, boolean strict ) throws PlexusContainerException, ComponentLookupException, ComponentLifecycleException, ArtifactNotFoundException, ArtifactResolutionException, IOException { String applicationVersion = getVersion(); DatabaseParams params = new DatabaseParams( databaseType.defaultParams ); params.setUrl( jdbcUrl ); PlexusClassPathXmlApplicationContext classPathApplicationContext = null; PlexusFileSystemXmlApplicationContext fileSystemApplicationContext = null; ClassLoader origContextClassLoader = Thread.currentThread().getContextClassLoader(); try { classPathApplicationContext = new PlexusClassPathXmlApplicationContext( new String[] { "classpath*:/META-INF/spring-context.xml", "classpath*:/META-INF/plexus/components.xml", "classpath*:/META-INF/plexus/plexus.xml" } ); PlexusContainerAdapter container = new PlexusContainerAdapter(); container.setApplicationContext( classPathApplicationContext ); initializeWagon( container, setting ); List<Artifact> artifacts = new ArrayList<Artifact>(); try { artifacts.addAll( downloadArtifact( container, params.getGroupId(), params.getArtifactId(), params.getVersion(), setting ) ); artifacts.addAll( downloadArtifact( container, "org.apache.continuum", managementArtifactId, applicationVersion, setting ) ); artifacts.addAll( downloadArtifact( container, "jpox", "jpox", databaseFormat.getJpoxVersion(), setting ) ); } finally { shutdownResolverThreadPool( container ); } // Filter the list so we only use jars TypeArtifactFilter jarFilter = new TypeArtifactFilter( "jar" ); Iterator<Artifact> iter = artifacts.iterator(); while ( iter.hasNext() ) { if ( !jarFilter.include( iter.next() ) ) { iter.remove(); } } List<String> jars = new ArrayList<String>(); // Little hack to make it work more nicely in the IDE List<String> exclusions = new ArrayList<String>(); URLClassLoader cp = (URLClassLoader) DataManagementCli.class.getClassLoader(); List<URL> jarUrls = new ArrayList<URL>(); for ( URL url : cp.getURLs() ) { String urlEF = url.toExternalForm(); if ( urlEF.endsWith( "target/classes/" ) ) { int idEndIdx = urlEF.length() - 16; String id = urlEF.substring( urlEF.lastIndexOf( '/', idEndIdx - 1 ) + 1, idEndIdx ); // continuum-legacy included because the IDE doesn't do the proper assembly of enhanced classes and JDO metadata if ( !"data-management-api".equals( id ) && !"data-management-cli".equals( id ) && !"continuum-legacy".equals( id ) && !"continuum-model".equals( id ) && !"redback-legacy".equals( id ) ) { LOGGER.debug( "[IDE Help] Adding '" + id + "' as an exclusion and using one from classpath" ); exclusions.add( "org.apache.continuum:" + id ); jars.add( url.getPath() ); jarUrls.add( url ); } } // Sometimes finds its way into the IDE. Make sure it is loaded in the extra classloader too if ( urlEF.contains( "jpox-enhancer" ) ) { LOGGER.debug( "[IDE Help] Adding 'jpox-enhancer' as an exclusion and using one from classpath" ); jars.add( url.getPath() ); jarUrls.add( url ); } } ArtifactFilter filter = new ExcludesArtifactFilter( exclusions ); for ( Artifact a : artifacts ) { if ( "jpox".equals( a.getGroupId() ) && "jpox".equals( a.getArtifactId() ) ) { if ( a.getVersion().equals( databaseFormat.getJpoxVersion() ) ) { LOGGER.debug( "Adding artifact: " + a.getFile() ); jars.add( JAR_FILE_PREFIX + a.getFile().getAbsolutePath() + SPRING_CONTEXT_LOC ); jars.add( JAR_FILE_PREFIX + a.getFile().getAbsolutePath() + PLEXUS_XML_LOC ); jarUrls.add( new URL( FILE_PREFIX + a.getFile().getAbsolutePath() ) ); } } else if ( filter.include( a ) ) { LOGGER.debug( "Adding artifact: " + a.getFile() ); jars.add( JAR_FILE_PREFIX + a.getFile().getAbsolutePath() + SPRING_CONTEXT_LOC ); jars.add( JAR_FILE_PREFIX + a.getFile().getAbsolutePath() + PLEXUS_XML_LOC ); jarUrls.add( new URL( FILE_PREFIX + a.getFile().getAbsolutePath() ) ); } } URLClassLoader newClassLoader = new URLClassLoader( (URL[]) jarUrls.toArray( new URL[jarUrls.size()] ), cp ); Thread.currentThread().setContextClassLoader( newClassLoader ); classPathApplicationContext.setClassLoader( newClassLoader ); fileSystemApplicationContext = new PlexusFileSystemXmlApplicationContext( (String[]) jars.toArray( new String[jars.size()] ), classPathApplicationContext ); fileSystemApplicationContext.setClassLoader( newClassLoader ); container.setApplicationContext( fileSystemApplicationContext ); DatabaseFactoryConfigurator configurator = (DatabaseFactoryConfigurator) container.lookup( DatabaseFactoryConfigurator.class.getName(), configRoleHint ); configurator.configure( params ); DataManagementTool manager = (DataManagementTool) container.lookup( DataManagementTool.class.getName(), toolRoleHint ); if ( mode == OperationMode.EXPORT ) { manager.backupDatabase( directory ); } else if ( mode == OperationMode.IMPORT ) { manager.eraseDatabase(); manager.restoreDatabase( directory, strict ); } } finally { if ( fileSystemApplicationContext != null ) fileSystemApplicationContext.close(); if ( classPathApplicationContext != null ) classPathApplicationContext.close(); Thread.currentThread().setContextClassLoader( origContextClassLoader ); } } private static void initializeWagon( PlexusContainerAdapter container, File setting ) throws ComponentLookupException, ComponentLifecycleException, IOException { WagonManager wagonManager = (WagonManager) container.lookup( WagonManager.ROLE ); Settings settings = getSettings( container, setting ); try { Proxy proxy = settings.getActiveProxy(); if ( proxy != null ) { if ( proxy.getHost() == null ) { throw new IOException( "Proxy in settings.xml has no host" ); } wagonManager.addProxy( proxy.getProtocol(), proxy.getHost(), proxy.getPort(), proxy.getUsername(), proxy.getPassword(), proxy.getNonProxyHosts() ); } for ( Iterator i = settings.getServers().iterator(); i.hasNext(); ) { Server server = (Server) i.next(); wagonManager.addAuthenticationInfo( server.getId(), server.getUsername(), server.getPassword(), server.getPrivateKey(), server.getPassphrase() ); wagonManager.addPermissionInfo( server.getId(), server.getFilePermissions(), server.getDirectoryPermissions() ); if ( server.getConfiguration() != null ) { wagonManager.addConfiguration( server.getId(), (Xpp3Dom) server.getConfiguration() ); } } RepositoryPermissions defaultPermissions = new RepositoryPermissions(); defaultPermissions.setDirectoryMode( "775" ); defaultPermissions.setFileMode( "664" ); wagonManager.setDefaultRepositoryPermissions( defaultPermissions ); for ( Iterator i = settings.getMirrors().iterator(); i.hasNext(); ) { Mirror mirror = (Mirror) i.next(); wagonManager.addMirror( mirror.getId(), mirror.getMirrorOf(), mirror.getUrl() ); } } finally { container.release( wagonManager ); } } private static Collection<Artifact> downloadArtifact( PlexusContainer container, String groupId, String artifactId, String version, File setting ) throws ComponentLookupException, ArtifactNotFoundException, ArtifactResolutionException, IOException { ArtifactRepositoryFactory factory = (ArtifactRepositoryFactory) container.lookup( ArtifactRepositoryFactory.ROLE ); DefaultRepositoryLayout layout = (DefaultRepositoryLayout) container.lookup( ArtifactRepositoryLayout.ROLE, "default" ); ArtifactRepository localRepository = factory.createArtifactRepository( "local", getLocalRepositoryURL( container, setting ), layout, null, null ); List<ArtifactRepository> remoteRepositories = new ArrayList<ArtifactRepository>(); remoteRepositories.add( factory.createArtifactRepository( "central", "http://repo1.maven.org/maven2", layout, null, null ) ); //Load extra repositories from active profile Settings settings = getSettings( container, setting ); List<String> profileIds = settings.getActiveProfiles(); Map<String, Profile> profilesAsMap = settings.getProfilesAsMap(); if ( profileIds != null && !profileIds.isEmpty() ) { for ( String profileId : profileIds ) { Profile profile = profilesAsMap.get( profileId ); if ( profile != null ) { List<Repository> repos = profile.getRepositories(); if ( repos != null && !repos.isEmpty() ) { for ( Repository repo : repos ) { remoteRepositories.add( factory.createArtifactRepository( repo.getId(), repo.getUrl(), layout, null, null ) ); } } } } } ArtifactFactory artifactFactory = (ArtifactFactory) container.lookup( ArtifactFactory.ROLE ); Artifact artifact = artifactFactory.createArtifact( groupId, artifactId, version, Artifact.SCOPE_RUNTIME, "jar" ); Artifact dummyArtifact = artifactFactory.createProjectArtifact( "dummy", "dummy", "1.0" ); if ( artifact.isSnapshot() ) { remoteRepositories.add( factory.createArtifactRepository( "apache.snapshots", "http://people.apache.org/repo/m2-snapshot-repository", layout, null, null ) ); } ArtifactResolver resolver = (ArtifactResolver) container.lookup( ArtifactResolver.ROLE ); List<String> exclusions = new ArrayList<String>(); exclusions.add( "org.apache.continuum:data-management-api" ); exclusions.add( "org.codehaus.plexus:plexus-component-api" ); exclusions.add( "org.codehaus.plexus:plexus-container-default" ); exclusions.add( "org.slf4j:slf4j-api" ); exclusions.add( "log4j:log4j" ); ArtifactFilter filter = new ExcludesArtifactFilter( exclusions ); List<? extends ResolutionListener> listeners; if ( LOGGER.isDebugEnabled() ) { listeners = Collections.singletonList( new DebugResolutionListener( container.getLogger() ) ); } else { listeners = Collections.emptyList(); } ArtifactMetadataSource source = (ArtifactMetadataSource) container.lookup( ArtifactMetadataSource.ROLE, "maven" ); ArtifactResolutionResult result = resolver.resolveTransitively( Collections.singleton( artifact ), dummyArtifact, Collections.emptyMap(), localRepository, remoteRepositories, source, filter, listeners ); return result.getArtifacts(); } private static String getLocalRepositoryURL( PlexusContainer container, File setting ) throws ComponentLookupException, IOException { String repositoryPath; File settingsFile = new File( System.getProperty( "user.home" ), ".m2/settings.xml" ); if ( setting != null ) { Settings settings = getSettings( container, setting ); repositoryPath = new File( settings.getLocalRepository() ).toURL().toString(); } else if ( !settingsFile.exists() ) { repositoryPath = new File( System.getProperty( "user.home" ), ".m2/repository" ).toURL().toString(); } else { Settings settings = getSettings( container, null ); repositoryPath = new File( settings.getLocalRepository() ).toURL().toString(); } return repositoryPath; } private static Settings getSettings( PlexusContainer container, File setting ) throws ComponentLookupException, IOException { MavenSettingsBuilder mavenSettingsBuilder = (MavenSettingsBuilder) container.lookup( MavenSettingsBuilder.class.getName() ); try { if ( setting != null ) { return mavenSettingsBuilder.buildSettings( setting, false ); } else { return mavenSettingsBuilder.buildSettings( false ); } } catch ( XmlPullParserException e ) { e.printStackTrace(); throw new IOException( "Can't read settings.xml. " + e.getMessage() ); } } private static String getVersion() throws IOException { Properties properties = new Properties(); properties.load( DataManagementCli.class.getResourceAsStream( "/META-INF/maven/org.apache.continuum/data-management-api/pom.properties" ) ); return properties.getProperty( "version" ); } private static class Commands { @Argument( description = "Display help information", value = "help", alias = "h" ) private boolean help; @Argument( description = "Display version information", value = "version", alias = "v" ) private boolean version; @Argument( description = "The JDBC URL for the Continuum database that contains the data to convert, or to import the data into", value = "buildsJdbcUrl" ) private String buildsJdbcUrl; @Argument( description = "The JDBC URL for the Redback database that contains the data to convert, or to import the data into", value = "usersJdbcUrl" ) private String usersJdbcUrl; // TODO: ability to use the enum directly would be nice @Argument( description = "Format of the database. Valid values are CONTINUUM_103, CONTINUUM_109, CONTINUUM_11. Default is CONTINUUM_11." ) private String databaseFormat = DatabaseFormat.CONTINUUM_11.toString(); /* TODO: not yet supported @Argument( description = "Format of the backup directory. Valid values are CONTINUUM_103, CONTINUUM_109, CONTINUUM_11. Default is CONTINUUM_11.") private String dataFileFormat = DatabaseFormat.CONTINUUM_11.toString(); */ @Argument( description = "The directory to export the data to, or import the data from. Default is 'backups' in the current working directory.", value = "directory" ) private File directory = new File( "backups" ); @Argument( description = "Mode of operation. Valid values are IMPORT and EXPORT. Default is EXPORT.", value = "mode" ) private String mode = OperationMode.EXPORT.toString(); @Argument( description = "Whether to overwrite the designated directory if it already exists in export mode. Default is false.", value = "overwrite" ) private boolean overwrite; @Argument( description = "The type of database to use. Currently supported values are DERBY_10_1. The default value is DERBY_10_1.", value = "databaseType" ) private String databaseType = SupportedDatabase.DERBY_10_1.toString(); @Argument( description = "JDBC driver class", value = "driverClass", required = false ) private String driverClass; @Argument( description = "JDBC driver groupId", value = "groupId", required = false ) private String groupId; @Argument( description = "JDBC driver artifactId", value = "artifactId", required = false ) private String artifactId; @Argument( description = "Artifact version of the JDBC driver class", value = "artifactVersion", required = false ) private String artifactVersion; @Argument( description = "Username", value = "username", required = false ) private String username; @Argument( description = "Password", value = "password", required = false ) private String password; @Argument( description = "Turn on debugging information. Default is off.", value = "debug" ) private boolean debug; @Argument( description = "Alternate path for the user settings file", value = "settings", required = false, alias = "s" ) private File settings; @Argument( description = "Run on strict mode. Default is false.", value = "strict" ) private boolean strict; } private enum OperationMode { IMPORT, EXPORT } private enum SupportedDatabase { DERBY_10_1( new DatabaseParams( "org.apache.derby.jdbc.EmbeddedDriver", "org.apache.derby", "derby", "10.1.3.1", "sa", "" ) ), OTHER( new DatabaseParams( null, null, null, null, null, null ) ); private DatabaseParams defaultParams; SupportedDatabase( DatabaseParams defaultParams ) { this.defaultParams = defaultParams; } } }
4,867
0
Create_ds/continuum/continuum-data-management/data-management-cli/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-data-management/data-management-cli/src/main/java/org/apache/maven/continuum/management/DatabaseFormat.java
package org.apache.maven.continuum.management; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Enumeration of known database formats. */ public enum DatabaseFormat { /** * Continuum 1.0.3 build database. * * @todo this hasn't been completed/tested - the model needs to be annotated with 1.0.3 metadata and converters written. */ CONTINUUM_103( "1.1.1", "legacy-continuum-jdo" ) { public boolean isConvertibleFrom( DatabaseFormat sourceFormat ) { return false; } }, /** * Continuum pre-alpha build database. Plexus Security 1.0-alpha-5. */ CONTINUUM_109( "1.1.1", "legacy-continuum-jdo", "legacy-redback-jdo" ) { public boolean isConvertibleFrom( DatabaseFormat sourceFormat ) { return false; } }, /** * Continuum 1.1+ build database. */ CONTINUUM_11( "1.1.6", "continuum-jdo", "redback-jdo" ) { public boolean isConvertibleFrom( DatabaseFormat sourceFormat ) { return sourceFormat == CONTINUUM_103 || sourceFormat == CONTINUUM_109; } }; private final String jpoxVersion; private final String continuumToolRoleHint; private final String redbackToolRoleHint; DatabaseFormat( String jpoxVersion, String continuumToolRoleHint ) { this.jpoxVersion = jpoxVersion; this.continuumToolRoleHint = continuumToolRoleHint; this.redbackToolRoleHint = null; } DatabaseFormat( String jpoxVersion, String continuumToolRoleHint, String redbackToolRoleHint ) { this.jpoxVersion = jpoxVersion; this.continuumToolRoleHint = continuumToolRoleHint; this.redbackToolRoleHint = redbackToolRoleHint; } /** * Whether a database can be converted from the given format to this format. * * @param sourceFormat the database format to convert from * @return whether it can be successfully converted from that format */ public abstract boolean isConvertibleFrom( DatabaseFormat sourceFormat ); public String getJpoxVersion() { return jpoxVersion; } public String getContinuumToolRoleHint() { return continuumToolRoleHint; } public String getRedbackToolRoleHint() { return redbackToolRoleHint; } }
4,868
0
Create_ds/continuum/continuum-data-management/data-management-cli/src/main/java/org/apache/maven/continuum/management
Create_ds/continuum/continuum-data-management/data-management-cli/src/main/java/org/apache/maven/continuum/management/util/PlexusFileSystemXmlApplicationContext.java
package org.apache.maven.continuum.management.util; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.codehaus.plexus.spring.PlexusXmlBeanDefinitionReader; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.ResourceEntityResolver; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import java.io.IOException; public class PlexusFileSystemXmlApplicationContext extends FileSystemXmlApplicationContext { private static PlexusApplicationContextDelegate delegate = new PlexusApplicationContextDelegate(); public PlexusFileSystemXmlApplicationContext( String configLocation ) { super( configLocation ); } public PlexusFileSystemXmlApplicationContext( String[] configLocations ) { super( configLocations ); } public PlexusFileSystemXmlApplicationContext( String[] configLocations, ApplicationContext parent ) { super( configLocations, parent ); } public PlexusFileSystemXmlApplicationContext( String[] configLocations, boolean refresh ) { super( configLocations, refresh ); } public PlexusFileSystemXmlApplicationContext( String[] configLocations, boolean refresh, ApplicationContext parent ) { super( configLocations, refresh, parent ); } /** * {@inheritDoc} * * @see org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.xml.XmlBeanDefinitionReader) */ protected void loadBeanDefinitions( XmlBeanDefinitionReader reader ) throws BeansException, IOException { delegate.loadBeanDefinitions( reader ); super.loadBeanDefinitions( reader ); } /** * Copied from {@link AbstractXmlApplicationContext} * Loads the bean definitions via an XmlBeanDefinitionReader. * * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader * @see #initBeanDefinitionReader * @see #loadBeanDefinitions */ protected void loadBeanDefinitions( DefaultListableBeanFactory beanFactory ) throws IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. XmlBeanDefinitionReader beanDefinitionReader = new PlexusXmlBeanDefinitionReader( beanFactory ); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setResourceLoader( this ); beanDefinitionReader.setEntityResolver( new ResourceEntityResolver( this ) ); // Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. initBeanDefinitionReader( beanDefinitionReader ); loadBeanDefinitions( beanDefinitionReader ); } /** * {@inheritDoc} * * @see org.springframework.context.support.AbstractApplicationContext#postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) */ protected void postProcessBeanFactory( ConfigurableListableBeanFactory beanFactory ) { delegate.postProcessBeanFactory( beanFactory, this ); } /** * {@inheritDoc} * * @see org.springframework.context.support.AbstractApplicationContext#doClose() */ protected void doClose() { delegate.doClose(); super.doClose(); } }
4,869
0
Create_ds/continuum/continuum-data-management/data-management-cli/src/main/java/org/apache/maven/continuum/management
Create_ds/continuum/continuum-data-management/data-management-cli/src/main/java/org/apache/maven/continuum/management/util/PlexusApplicationContextDelegate.java
package org.apache.maven.continuum.management.util; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.codehaus.plexus.spring.PlexusBeanDefinitionDocumentReader; import org.codehaus.plexus.spring.PlexusConfigurationPropertyEditor; import org.codehaus.plexus.spring.PlexusContainerAdapter; import org.codehaus.plexus.spring.PlexusLifecycleBeanPostProcessor; import org.codehaus.plexus.spring.editors.CollectionPropertyEditor; import org.codehaus.plexus.spring.editors.MapPropertyEditor; import org.codehaus.plexus.spring.editors.PropertiesPropertyEditor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ApplicationContext; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class PlexusApplicationContextDelegate { /** * Logger used by this class. */ protected Logger logger = LoggerFactory.getLogger( getClass() ); private PlexusLifecycleBeanPostProcessor lifecycleBeanPostProcessor; /** * @see org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.xml.XmlBeanDefinitionReader) */ protected void loadBeanDefinitions( XmlBeanDefinitionReader reader ) throws BeansException, IOException { logger.info( "Registering Plexus to Spring XML translation" ); reader.setDocumentReaderClass( PlexusBeanDefinitionDocumentReader.class ); } /** * @see org.springframework.context.support.AbstractApplicationContext#postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) */ protected void postProcessBeanFactory( ConfigurableListableBeanFactory beanFactory, ApplicationContext context ) { // Register a PlexusContainerAdapter bean to allow context lookups using plexus API PlexusContainerAdapter plexus = new PlexusContainerAdapter(); plexus.setApplicationContext( context ); beanFactory.registerSingleton( "plexusContainer", plexus ); // Register a beanPostProcessor to handle plexus interface-based lifecycle management lifecycleBeanPostProcessor = new PlexusLifecycleBeanPostProcessor(); lifecycleBeanPostProcessor.setBeanFactory( context ); beanFactory.addBeanPostProcessor( lifecycleBeanPostProcessor ); // Register a PropertyEditor to support plexus XML <configuration> set as CDATA in // a spring context XML file. beanFactory.addPropertyEditorRegistrar( new PlexusConfigurationPropertyEditor() ); beanFactory.addPropertyEditorRegistrar( new PropertiesPropertyEditor() ); beanFactory.addPropertyEditorRegistrar( new CollectionPropertyEditor( List.class, ArrayList.class ) ); beanFactory.addPropertyEditorRegistrar( new CollectionPropertyEditor( Set.class, HashSet.class ) ); beanFactory.addPropertyEditorRegistrar( new MapPropertyEditor( Map.class, HashMap.class ) ); } /** * @see org.springframework.context.support.AbstractApplicationContext#doClose() */ protected void doClose() { try { lifecycleBeanPostProcessor.destroy(); } catch ( Throwable ex ) { logger.error( "Exception thrown from PlexusLifecycleBeanPostProcessor handling ContextClosedEvent", ex ); } } }
4,870
0
Create_ds/continuum/continuum-data-management/redback-legacy/src/main/java/org/codehaus/plexus/security/user/jdo
Create_ds/continuum/continuum-data-management/redback-legacy/src/main/java/org/codehaus/plexus/security/user/jdo/v0_9_0/UserManagementModelloMetadata.java
package org.codehaus.plexus.security.user.jdo.v0_9_0; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public class UserManagementModelloMetadata { private String modelVersion; public String getModelVersion() { return modelVersion; } public void setModelVersion( String modelVersion ) { this.modelVersion = modelVersion; } }
4,871
0
Create_ds/continuum/continuum-data-management/redback-legacy/src/main/java/org/codehaus/plexus/security/keys/jdo
Create_ds/continuum/continuum-data-management/redback-legacy/src/main/java/org/codehaus/plexus/security/keys/jdo/v0_9_0/PlexusSecurityKeyManagementJdoModelloMetadata.java
package org.codehaus.plexus.security.keys.jdo.v0_9_0; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public class PlexusSecurityKeyManagementJdoModelloMetadata { private String modelVersion; public String getModelVersion() { return modelVersion; } public void setModelVersion( String modelVersion ) { this.modelVersion = modelVersion; } }
4,872
0
Create_ds/continuum/continuum-data-management/redback-legacy/src/main/java/org/codehaus/plexus/security/authorization/rbac/jdo
Create_ds/continuum/continuum-data-management/redback-legacy/src/main/java/org/codehaus/plexus/security/authorization/rbac/jdo/v0_9_0/RbacJdoModelModelloMetadata.java
package org.codehaus.plexus.security.authorization.rbac.jdo.v0_9_0; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public class RbacJdoModelModelloMetadata { private String modelVersion; public String getModelVersion() { return modelVersion; } public void setModelVersion( String modelVersion ) { this.modelVersion = modelVersion; } }
4,873
0
Create_ds/continuum/continuum-data-management/data-management-jdo/src/test/java/org/apache/maven/continuum
Create_ds/continuum/continuum-data-management/data-management-jdo/src/test/java/org/apache/maven/continuum/management/DataManagementToolTest.java
package org.apache.maven.continuum.management; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.utils.file.FileSystemManager; import org.apache.maven.continuum.store.AbstractContinuumStoreTestCase; import org.codehaus.plexus.util.IOUtil; import org.custommonkey.xmlunit.Diff; import org.jdom.Document; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileWriter; import java.io.StringReader; import java.io.StringWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import static org.junit.Assert.assertTrue; /** * Test the database management tool. */ public class DataManagementToolTest extends AbstractContinuumStoreTestCase { private DataManagementTool dataManagementTool; private FileSystemManager fsManager; private File targetDirectory; private static final String BUILDS_XML = "builds.xml"; @Before public void setUp() throws Exception { dataManagementTool = lookup( DataManagementTool.class, "continuum-jdo" ); fsManager = lookup( FileSystemManager.class ); targetDirectory = createBackupDirectory(); } @After public void tearDown() throws Exception { Connection connection = DriverManager.getConnection( "jdbc:hsqldb:mem:." ); Statement stmt = connection.createStatement(); try { stmt.execute( "TRUNCATE SCHEMA PUBLIC RESTART IDENTITY AND COMMIT NO CHECK" ); connection.commit(); } finally { stmt.close(); connection.close(); } } @Test public void testBackupBuilds() throws Exception { createBuildDatabase( true ); // test sanity check assertBuildDatabase(); dataManagementTool.backupDatabase( targetDirectory ); File backupFile = new File( targetDirectory, BUILDS_XML ); assertTrue( "Check database exists", backupFile.exists() ); StringWriter sw = new StringWriter(); IOUtil.copy( getClass().getResourceAsStream( "/expected.xml" ), sw ); assertXmlSimilar( removeTimestampVariance( sw.toString() ), removeTimestampVariance( fsManager.fileContents( backupFile ) ) ); } @Test public void testEraseBuilds() throws Exception { createBuildDatabase( false ); dataManagementTool.eraseDatabase(); assertEmpty( false ); } @Test public void testRestoreBuilds() throws Exception { createBuildDatabase( false, true ); assertEmpty( true ); File backupFile = new File( targetDirectory, BUILDS_XML ); IOUtil.copy( getClass().getResourceAsStream( "/expected.xml" ), new FileWriter( backupFile ) ); dataManagementTool.restoreDatabase( targetDirectory, true ); /* // TODO: why is this wrong? assertBuildDatabase(); // Test that it worked. Relies on BackupBuilds having worked dataManagementTool.backupDatabase( targetDirectory ); StringWriter sw = new StringWriter(); IOUtil.copy( getClass().getResourceAsStream( "/expected.xml" ), sw ); //assertEquals( "Check database content", removeTimestampVariance( sw.toString() ), // removeTimestampVariance( FileUtils.fileRead( backupFile ) ) ); assertXmlSimilar( removeTimestampVariance( sw.toString() ), removeTimestampVariance( FileUtils .fileRead( backupFile ) ) ); */ } private static File createBackupDirectory() { String timestamp = new SimpleDateFormat( "yyyyMMdd.HHmmss", Locale.US ).format( new Date() ); File targetDirectory = getTestFile( "target/backups/" + timestamp ); targetDirectory.mkdirs(); return targetDirectory; } private static String removeTimestampVariance( String content ) { return removeTagContent( removeTagContent( removeTagContent( removeTagContent( content, "startTime" ), "endTime" ), "date" ), "id" ); } public void assertXmlIdentical( String expected, String test ) throws Exception { String expectedXml = prettyXmlPrint( expected ); String testXml = prettyXmlPrint( test ); Diff diff = new Diff( expectedXml, testXml ); StringBuffer diffMessage = new StringBuffer(); assertTrue( " xml diff not identical " + diff.appendMessage( diffMessage ).toString(), diff.identical() ); } public void assertXmlSimilar( String expected, String test ) throws Exception { String expectedXml = prettyXmlPrint( expected ); String testXml = prettyXmlPrint( test ); Diff diff = new Diff( expectedXml, testXml ); StringBuffer diffMessage = new StringBuffer(); assertTrue( " xml diff not similar " + diff.appendMessage( diffMessage ).toString(), diff.similar() ); } public String prettyXmlPrint( String xml ) throws Exception { SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build( new StringReader( xml ) ); XMLOutputter outp = new XMLOutputter(); outp.setFormat( Format.getPrettyFormat() ); StringWriter sw = new StringWriter(); outp.output( document, sw ); return sw.getBuffer().toString(); } private static String removeTagContent( String content, String field ) { return content.replaceAll( "<" + field + ">.*</" + field + ">", "<" + field + "></" + field + ">" ); } }
4,874
0
Create_ds/continuum/continuum-data-management/data-management-jdo/src/main/java/org/jpox
Create_ds/continuum/continuum-data-management/data-management-jdo/src/main/java/org/jpox/store/OID.java
/********************************************************************** Copyright (c) 2002 Kelly Grizzle (TJDO) and others. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: 2003 Erik Bengtson - Refactored OID 2003 Andy Jefferson - fixed OID(String) 2003 Andy Jefferson - coding standards 2004 Andy Jefferson - fixes to allow full use of long or String OIDs 2005 Erik Bengtson - removed oidType 2007 Brett Porter - changed hashcode algorithm to avoid collisions (see CORE-3297) ... **********************************************************************/ package org.jpox.store; import org.jpox.ClassNameConstants; import org.jpox.util.Localiser; /** * An object identifier. OIDs are normally used as object identifiers for * persistent objects that use datastore identity. They're also used for * view objects, which actually use non-datastore identity. The behaviour of * this class is governed by JDO spec 5.4.3. * * @version $Revision: 1.17 $ */ public class OID implements java.io.Serializable { private transient static final Localiser LOCALISER = Localiser.getInstance( "org.jpox.store.Localisation" ); /** * Separator to use between fields. */ private transient static final String oidSeparator = "[OID]"; // JDO spec 5.4.3 - serializable fields required to be public. /** * The identity. */ public final Object oid; /** * The PersistenceCapable class name */ public final String pcClass; /** * pre-created toString to improve performance * */ public final String toString; /** * pre-created hasCode to improve performance * */ public final int hashCode; /** * Creates an OID with the no value. * Required by the JDO spec */ public OID() { oid = null; pcClass = null; toString = null; hashCode = -1; } /** * Create a string datastore identity * * @param pcClass The PersistenceCapable class that this represents * @param object The value */ public OID( String pcClass, Object object ) { this.pcClass = pcClass; this.oid = object; StringBuffer s = new StringBuffer(); s.append( this.oid.toString() ); s.append( oidSeparator ); s.append( this.pcClass ); toString = s.toString(); hashCode = this.oid.hashCode() * 39 + pcClass.hashCode(); } /** * Constructs an OID from its string representation that is * consistent with the output of toString(). * * @param str the string representation of an OID. * @throws IllegalArgumentException if the given string representation is not valid. * @see #toString */ public OID( String str ) throws IllegalArgumentException { if ( str.length() < 2 ) { throw new IllegalArgumentException( LOCALISER.msg( "OID.InvalidValue", str ) ); } int start = 0; int end = str.indexOf( oidSeparator, start ); String oidStr = str.substring( start, end ); Object oidValue = null; try { // Use Long if possible, else String oidValue = new Long( oidStr ); } catch ( NumberFormatException nfe ) { oidValue = oidStr; } oid = oidValue; start = end + oidSeparator.length(); this.pcClass = str.substring( start, str.length() ); toString = str; hashCode = this.oid.hashCode() * 39 + pcClass.hashCode(); } /** * Returns copy of the requested oid to be accessed by the user. * * @return Copy of the OID. */ public Object getNewObjectIdCopy() { return new OID( this.pcClass, this.oid ); } /** * Provides the OID in a form that can be used by the database as a key. * * @return The key value */ public Object keyValue() { return oid; } /** * Equality operator. * * @param obj Object to compare against * @return Whether they are equal */ public boolean equals( Object obj ) { if ( obj == null ) { return false; } if ( obj == this ) { return true; } if ( !( obj.getClass().getName().equals( ClassNameConstants.OID ) ) ) { return false; } if ( hashCode() != obj.hashCode() ) { return false; } return true; } /** * Accessor for the hashcode * * @return Hashcode for this object */ public int hashCode() { return hashCode; } /** * Returns the string representation of the OID. * Will be a string such as "1[OID]org.jpox.samples.MyClass" * where * <UL> * <LI>1 is the identity "id"</LI> * <LI>class name is the name of the PersistenceCapable class that it represents</LI> * </UL> * * @return the string representation of the OID. */ public String toString() { return toString; } /** * Accessor for the PC class name * * @return the PC Class */ public String getPcClass() { return pcClass; } }
4,875
0
Create_ds/continuum/continuum-data-management/data-management-jdo/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-data-management/data-management-jdo/src/main/java/org/apache/maven/continuum/management/JdoDataManagementTool.java
package org.apache.maven.continuum.management; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.BuildDefinitionDao; import org.apache.continuum.dao.BuildDefinitionTemplateDao; import org.apache.continuum.dao.BuildQueueDao; import org.apache.continuum.dao.ContinuumReleaseResultDao; import org.apache.continuum.dao.DaoUtils; import org.apache.continuum.dao.DirectoryPurgeConfigurationDao; import org.apache.continuum.dao.DistributedDirectoryPurgeConfigurationDao; import org.apache.continuum.dao.InstallationDao; import org.apache.continuum.dao.LocalRepositoryDao; import org.apache.continuum.dao.ProfileDao; import org.apache.continuum.dao.ProjectGroupDao; import org.apache.continuum.dao.ProjectScmRootDao; import org.apache.continuum.dao.RepositoryPurgeConfigurationDao; import org.apache.continuum.dao.ScheduleDao; import org.apache.continuum.dao.SystemConfigurationDao; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.continuum.model.release.ContinuumReleaseResult; import org.apache.continuum.model.repository.DirectoryPurgeConfiguration; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.utils.ProjectSorter; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildDefinitionTemplate; import org.apache.maven.continuum.model.project.BuildQueue; import org.apache.maven.continuum.model.project.ContinuumDatabase; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.Schedule; import org.apache.maven.continuum.model.project.io.stax.ContinuumStaxReader; import org.apache.maven.continuum.model.project.io.stax.ContinuumStaxWriter; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.jdo.ConfigurableJdoFactory; import org.codehaus.plexus.jdo.PlexusJdoUtils; import org.codehaus.plexus.util.IOUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManagerFactory; import javax.xml.stream.XMLStreamException; /** * JDO implementation the database management tool API. */ @Component( role = org.apache.maven.continuum.management.DataManagementTool.class, hint = "continuum-jdo" ) public class JdoDataManagementTool implements DataManagementTool { private Logger log = LoggerFactory.getLogger( JdoDataManagementTool.class ); @Requirement private DaoUtils daoUtils; @Requirement private LocalRepositoryDao localRepositoryDao; @Requirement private DirectoryPurgeConfigurationDao directoryPurgeConfigurationDao; @Requirement private RepositoryPurgeConfigurationDao repositoryPurgeConfigurationDao; @Requirement private DistributedDirectoryPurgeConfigurationDao distributedDirectoryPurgeConfigurationDao; @Requirement private InstallationDao installationDao; @Requirement private ProfileDao profileDao; @Requirement private ProjectGroupDao projectGroupDao; @Requirement private ScheduleDao scheduleDao; @Requirement private SystemConfigurationDao systemConfigurationDao; @Requirement private ProjectScmRootDao projectScmRootDao; @Requirement private BuildDefinitionTemplateDao buildDefinitionTemplateDao; @Requirement private ContinuumReleaseResultDao releaseResultDao; @Requirement private BuildQueueDao buildQueueDao; @Requirement private BuildDefinitionDao buildDefinitionDao; protected static final String BUILDS_XML = "builds.xml"; @Requirement( role = org.codehaus.plexus.jdo.JdoFactory.class, hint = "continuum" ) protected ConfigurableJdoFactory factory; public void backupDatabase( File backupDirectory ) throws IOException { ContinuumDatabase database = new ContinuumDatabase(); try { database.setSystemConfiguration( systemConfigurationDao.getSystemConfiguration() ); } catch ( ContinuumStoreException e ) { throw new DataManagementException( e ); } // TODO: need these to lazy load to conserve memory while we stream out the model Collection projectGroups = projectGroupDao.getAllProjectGroupsWithTheLot(); database.setProjectGroups( new ArrayList( projectGroups ) ); try { database.setInstallations( installationDao.getAllInstallations() ); database.setBuildDefinitionTemplates( buildDefinitionTemplateDao.getAllBuildDefinitionTemplate() ); database.setBuildQueues( buildQueueDao.getAllBuildQueues() ); database.setBuildDefinitions( buildDefinitionDao.getAllTemplates() ); } catch ( ContinuumStoreException e ) { throw new DataManagementException( e ); } database.setSchedules( scheduleDao.getAllSchedulesByName() ); database.setProfiles( profileDao.getAllProfilesByName() ); database.setLocalRepositories( localRepositoryDao.getAllLocalRepositories() ); database.setRepositoryPurgeConfigurations( repositoryPurgeConfigurationDao.getAllRepositoryPurgeConfigurations() ); database.setDirectoryPurgeConfigurations( directoryPurgeConfigurationDao.getAllDirectoryPurgeConfigurations() ); database.setDistributedDirectoryPurgeConfigurations( distributedDirectoryPurgeConfigurationDao.getAllDistributedDirectoryPurgeConfigurations() ); database.setProjectScmRoots( projectScmRootDao.getAllProjectScmRoots() ); database.setContinuumReleaseResults( releaseResultDao.getAllContinuumReleaseResults() ); ContinuumStaxWriter writer = new ContinuumStaxWriter(); File backupFile = new File( backupDirectory, BUILDS_XML ); File parentFile = backupFile.getParentFile(); parentFile.mkdirs(); OutputStream out = new FileOutputStream( backupFile ); Writer fileWriter = new OutputStreamWriter( out, Charset.forName( database.getModelEncoding() ) ); try { writer.write( fileWriter, database ); } catch ( XMLStreamException e ) { throw new DataManagementException( "Modello failure: unable to write data to StAX writer", e ); } finally { IOUtil.close( fileWriter ); } } public void eraseDatabase() { daoUtils.eraseDatabase(); } public void restoreDatabase( File backupDirectory, boolean strict ) throws IOException { ContinuumStaxReader reader = new ContinuumStaxReader(); FileReader fileReader = new FileReader( new File( backupDirectory, BUILDS_XML ) ); ContinuumDatabase database; try { database = reader.read( fileReader, strict ); } catch ( XMLStreamException e ) { throw new DataManagementException( e ); } finally { IOUtil.close( fileReader ); } // Take control of the JDO instead of using the store, and configure a new persistence factory // that won't generate new object IDs. Properties properties = new Properties(); properties.putAll( factory.getProperties() ); properties.setProperty( "org.jpox.metadata.jdoFileExtension", "jdorepl" ); PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory( properties ); PlexusJdoUtils.addObject( pmf.getPersistenceManager(), database.getSystemConfiguration() ); Map<Integer, BuildQueue> buildQueues = new HashMap<Integer, BuildQueue>(); for ( BuildQueue buildQueue : (List<BuildQueue>) database.getBuildQueues() ) { buildQueue = (BuildQueue) PlexusJdoUtils.addObject( pmf.getPersistenceManager(), buildQueue ); buildQueues.put( buildQueue.getId(), buildQueue ); } Map<Integer, Schedule> schedules = new HashMap<Integer, Schedule>(); for ( Iterator i = database.getSchedules().iterator(); i.hasNext(); ) { Schedule schedule = (Schedule) i.next(); schedule.setBuildQueues( getBuildQueuesBySchedule( buildQueues, schedule ) ); schedule = (Schedule) PlexusJdoUtils.addObject( pmf.getPersistenceManager(), schedule ); schedules.put( Integer.valueOf( schedule.getId() ), schedule ); } Map<Integer, Installation> installations = new HashMap<Integer, Installation>(); for ( Iterator i = database.getInstallations().iterator(); i.hasNext(); ) { Installation installation = (Installation) i.next(); installation = (Installation) PlexusJdoUtils.addObject( pmf.getPersistenceManager(), installation ); installations.put( Integer.valueOf( installation.getInstallationId() ), installation ); } Map<Integer, Profile> profiles = new HashMap<Integer, Profile>(); for ( Iterator i = database.getProfiles().iterator(); i.hasNext(); ) { Profile profile = (Profile) i.next(); // process installations if ( profile.getJdk() != null ) { profile.setJdk( installations.get( profile.getJdk().getInstallationId() ) ); } if ( profile.getBuilder() != null ) { profile.setBuilder( installations.get( profile.getBuilder().getInstallationId() ) ); } List environmentVariables = new ArrayList(); for ( Iterator envIt = profile.getEnvironmentVariables().listIterator(); envIt.hasNext(); ) { Installation installation = (Installation) envIt.next(); environmentVariables.add( installations.get( installation.getInstallationId() ) ); envIt.remove(); } profile.setEnvironmentVariables( environmentVariables ); profile = (Profile) PlexusJdoUtils.addObject( pmf.getPersistenceManager(), profile ); profiles.put( Integer.valueOf( profile.getId() ), profile ); } Map<Integer, BuildDefinition> buildDefinitions = new HashMap<Integer, BuildDefinition>(); for ( BuildDefinition buildDefinition : (List<BuildDefinition>) database.getBuildDefinitions() ) { if ( buildDefinition.getSchedule() != null ) { buildDefinition.setSchedule( schedules.get( Integer.valueOf( buildDefinition.getSchedule().getId() ) ) ); } if ( buildDefinition.getProfile() != null ) { buildDefinition.setProfile( profiles.get( Integer.valueOf( buildDefinition.getProfile().getId() ) ) ); } buildDefinition = (BuildDefinition) PlexusJdoUtils.addObject( pmf.getPersistenceManager(), buildDefinition ); buildDefinitions.put( Integer.valueOf( buildDefinition.getId() ), buildDefinition ); } Map<Integer, LocalRepository> localRepositories = new HashMap<Integer, LocalRepository>(); for ( LocalRepository localRepository : (List<LocalRepository>) database.getLocalRepositories() ) { localRepository = (LocalRepository) PlexusJdoUtils.addObject( pmf.getPersistenceManager(), localRepository ); localRepositories.put( Integer.valueOf( localRepository.getId() ), localRepository ); } Map<Integer, ProjectGroup> projectGroups = new HashMap<Integer, ProjectGroup>(); for ( Iterator i = database.getProjectGroups().iterator(); i.hasNext(); ) { ProjectGroup projectGroup = (ProjectGroup) i.next(); // first, we must map up any schedules, etc. projectGroup.setBuildDefinitions( processBuildDefinitions( projectGroup.getBuildDefinitions(), schedules, profiles, buildDefinitions ) ); for ( Iterator j = projectGroup.getProjects().iterator(); j.hasNext(); ) { Project project = (Project) j.next(); project.setBuildDefinitions( processBuildDefinitions( project.getBuildDefinitions(), schedules, profiles, buildDefinitions ) ); } if ( projectGroup.getLocalRepository() != null ) { projectGroup.setLocalRepository( localRepositories.get( Integer.valueOf( projectGroup.getLocalRepository().getId() ) ) ); } projectGroup = (ProjectGroup) PlexusJdoUtils.addObject( pmf.getPersistenceManager(), projectGroup ); projectGroups.put( Integer.valueOf( projectGroup.getId() ), projectGroup ); } // create project scm root data (CONTINUUM-2040) Map<Integer, ProjectScmRoot> projectScmRoots = new HashMap<Integer, ProjectScmRoot>(); Set<Integer> keys = projectGroups.keySet(); int id = 1; for ( Integer key : keys ) { ProjectGroup projectGroup = projectGroups.get( key ); String url = " "; List<Project> projects = ProjectSorter.getSortedProjects( getProjectsByGroupIdWithDependencies( pmf, projectGroup.getId() ), log ); for ( Iterator j = projects.iterator(); j.hasNext(); ) { Project project = (Project) j.next(); if ( !project.getScmUrl().trim().startsWith( url ) ) { url = project.getScmUrl(); ProjectScmRoot projectScmRoot = new ProjectScmRoot(); projectScmRoot.setId( id ); projectScmRoot.setProjectGroup( projectGroup ); projectScmRoot.setScmRootAddress( url ); projectScmRoot.setState( project.getState() ); projectScmRoot = (ProjectScmRoot) PlexusJdoUtils.addObject( pmf.getPersistenceManager(), projectScmRoot ); projectScmRoots.put( Integer.valueOf( projectScmRoot.getId() ), projectScmRoot ); id++; } } } /* for ( RepositoryPurgeConfiguration repoPurge : (List<RepositoryPurgeConfiguration>) database.getRepositoryPurgeConfigurations() ) { repoPurge.setRepository( localRepositories.get( Integer.valueOf( repoPurge.getRepository().getId() ) ) ); if ( repoPurge.getSchedule() != null ) { repoPurge.setSchedule( schedules.get( Integer.valueOf( repoPurge.getSchedule().getId() ) ) ); } repoPurge = (RepositoryPurgeConfiguration) PlexusJdoUtils.addObject( pmf.getPersistenceManager(), repoPurge ); }*/ for ( DirectoryPurgeConfiguration dirPurge : (List<DirectoryPurgeConfiguration>) database.getDirectoryPurgeConfigurations() ) { if ( dirPurge.getSchedule() != null ) { dirPurge.setSchedule( schedules.get( Integer.valueOf( dirPurge.getSchedule().getId() ) ) ); } dirPurge = (DirectoryPurgeConfiguration) PlexusJdoUtils.addObject( pmf.getPersistenceManager(), dirPurge ); } for ( ContinuumReleaseResult releaseResult : (List<ContinuumReleaseResult>) database.getContinuumReleaseResults() ) { releaseResult.setProjectGroup( projectGroups.get( Integer.valueOf( releaseResult.getProjectGroup().getId() ) ) ); ProjectGroup group = releaseResult.getProjectGroup(); for ( Project project : (List<Project>) group.getProjects() ) { if ( project.getId() == releaseResult.getProject().getId() ) { try { Project proj = (Project) PlexusJdoUtils.getObjectById( pmf.getPersistenceManager(), Project.class, project.getId(), null ); releaseResult.setProject( proj ); } catch ( Exception e ) { throw new DataManagementException( e ); } } } releaseResult = (ContinuumReleaseResult) PlexusJdoUtils.addObject( pmf.getPersistenceManager(), releaseResult ); } for ( BuildDefinitionTemplate template : (List<BuildDefinitionTemplate>) database.getBuildDefinitionTemplates() ) { template.setBuildDefinitions( processBuildDefinitions( template.getBuildDefinitions(), buildDefinitions ) ); template = (BuildDefinitionTemplate) PlexusJdoUtils.addObject( pmf.getPersistenceManager(), template ); } } private List<Project> getProjectsByGroupIdWithDependencies( PersistenceManagerFactory pmf, int projectGroupId ) { List<Project> allProjects = PlexusJdoUtils.getAllObjectsDetached( pmf.getPersistenceManager(), Project.class, "name ascending", "project-dependencies" ); List<Project> groupProjects = new ArrayList<Project>(); for ( Project project : allProjects ) { if ( project.getProjectGroup().getId() == projectGroupId ) { groupProjects.add( project ); } } return groupProjects; } private List<BuildDefinition> processBuildDefinitions( List<BuildDefinition> buildDefinitions, Map<Integer, Schedule> schedules, Map<Integer, Profile> profiles, Map<Integer, BuildDefinition> buildDefs ) { List<BuildDefinition> buildDefsList = new ArrayList<BuildDefinition>(); for ( BuildDefinition def : buildDefinitions ) { if ( buildDefs.get( Integer.valueOf( def.getId() ) ) != null ) { buildDefsList.add( buildDefs.get( Integer.valueOf( def.getId() ) ) ); } else { if ( def.getSchedule() != null ) { def.setSchedule( schedules.get( Integer.valueOf( def.getSchedule().getId() ) ) ); } if ( def.getProfile() != null ) { def.setProfile( profiles.get( Integer.valueOf( def.getProfile().getId() ) ) ); } buildDefsList.add( def ); } } return buildDefsList; } private List<BuildDefinition> processBuildDefinitions( List<BuildDefinition> buildDefinitions, Map<Integer, BuildDefinition> buildDefs ) { List<BuildDefinition> buildDefsList = new ArrayList<BuildDefinition>(); for ( BuildDefinition buildDefinition : buildDefinitions ) { buildDefsList.add( buildDefs.get( Integer.valueOf( buildDefinition.getId() ) ) ); } return buildDefsList; } private List<BuildQueue> getBuildQueuesBySchedule( Map<Integer, BuildQueue> allBuildQueues, Schedule schedule ) { List<BuildQueue> buildQueues = new ArrayList<BuildQueue>(); for ( BuildQueue buildQueue : (List<BuildQueue>) schedule.getBuildQueues() ) { buildQueues.add( allBuildQueues.get( Integer.valueOf( buildQueue.getId() ) ) ); } return buildQueues; } }
4,876
0
Create_ds/continuum/continuum-data-management/data-management-jdo/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-data-management/data-management-jdo/src/main/java/org/apache/maven/continuum/management/LegacyJdoDataManagementTool.java
package org.apache.maven.continuum.management; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.v1_0_9.BuildDefinition; import org.apache.maven.continuum.model.project.v1_0_9.BuildResult; import org.apache.maven.continuum.model.project.v1_0_9.ContinuumDatabase; import org.apache.maven.continuum.model.project.v1_0_9.Project; import org.apache.maven.continuum.model.project.v1_0_9.ProjectDependency; import org.apache.maven.continuum.model.project.v1_0_9.ProjectDeveloper; import org.apache.maven.continuum.model.project.v1_0_9.ProjectGroup; import org.apache.maven.continuum.model.project.v1_0_9.ProjectNotifier; import org.apache.maven.continuum.model.project.v1_0_9.Schedule; import org.apache.maven.continuum.model.project.v1_0_9.io.stax.ContinuumStaxReader; import org.apache.maven.continuum.model.project.v1_0_9.io.stax.ContinuumStaxWriter; import org.apache.maven.continuum.model.scm.v1_0_9.ChangeFile; import org.apache.maven.continuum.model.scm.v1_0_9.ChangeSet; import org.apache.maven.continuum.model.scm.v1_0_9.ScmResult; import org.apache.maven.continuum.model.scm.v1_0_9.SuiteResult; import org.apache.maven.continuum.model.scm.v1_0_9.TestCaseFailure; import org.apache.maven.continuum.model.scm.v1_0_9.TestResult; import org.apache.maven.continuum.model.system.v1_0_9.SystemConfiguration; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory; import org.codehaus.plexus.jdo.PlexusJdoUtils; import org.codehaus.plexus.util.IOUtil; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import javax.jdo.FetchPlan; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.xml.stream.XMLStreamException; /** * JDO implementation the database management tool API. */ @Component( role = org.apache.maven.continuum.management.DataManagementTool.class, hint = "legacy-continuum-jdo" ) public class LegacyJdoDataManagementTool implements DataManagementTool { protected static final String BUILDS_XML = "builds.xml"; @Requirement( role = org.codehaus.plexus.jdo.JdoFactory.class, hint = "continuum" ) protected DefaultConfigurableJdoFactory factory; public void backupDatabase( File backupDirectory ) throws IOException { PersistenceManagerFactory pmf = getPersistenceManagerFactory( "jdo109" ); ContinuumDatabase database = new ContinuumDatabase(); try { database.setSystemConfiguration( retrieveSystemConfiguration( pmf ) ); } catch ( ContinuumStoreException e ) { throw new DataManagementException( e ); } Collection<ProjectGroup> projectGroups = retrieveAllProjectGroups( pmf ); database.setProjectGroups( new ArrayList<ProjectGroup>( projectGroups ) ); database.setSchedules( retrieveAllSchedules( pmf ) ); ContinuumStaxWriter writer = new ContinuumStaxWriter(); backupDirectory.mkdirs(); OutputStream out = new FileOutputStream( new File( backupDirectory, BUILDS_XML ) ); Writer fileWriter = new OutputStreamWriter( out, Charset.forName( database.getModelEncoding() ) ); try { writer.write( fileWriter, database ); } catch ( XMLStreamException e ) { throw new DataManagementException( "Modello failure: unable to write data to StAX writer", e ); } finally { IOUtil.close( fileWriter ); } } private List retrieveAllSchedules( PersistenceManagerFactory pmf ) { return PlexusJdoUtils.getAllObjectsDetached( getPersistenceManager( pmf ), Schedule.class, "name ascending", (String) null ); } private Collection<ProjectGroup> retrieveAllProjectGroups( PersistenceManagerFactory pmf ) { List<String> fetchGroups = Arrays.asList( "project-with-builds", "projectgroup-projects", "build-result-with-details", "project-with-checkout-result", "project-all-details", "project-build-details" ); return PlexusJdoUtils.getAllObjectsDetached( getPersistenceManager( pmf ), ProjectGroup.class, "name ascending", fetchGroups ); } private SystemConfiguration retrieveSystemConfiguration( PersistenceManagerFactory pmf ) throws ContinuumStoreException { SystemConfiguration result; List systemConfs = PlexusJdoUtils.getAllObjectsDetached( getPersistenceManager( pmf ), SystemConfiguration.class, null, (String) null ); if ( systemConfs == null || systemConfs.isEmpty() ) { result = null; } else if ( systemConfs.size() > 1 ) { throw new ContinuumStoreException( "Database is corrupted. There are more than one systemConfiguration object." ); } else { result = (SystemConfiguration) systemConfs.get( 0 ); } return result; } @SuppressWarnings( { "OverlyCoupledMethod" } ) public void eraseDatabase() { PersistenceManagerFactory pmf = getPersistenceManagerFactory( "jdo109" ); PersistenceManager persistenceManager = getPersistenceManager( pmf ); PlexusJdoUtils.removeAll( persistenceManager, ProjectGroup.class ); PlexusJdoUtils.removeAll( persistenceManager, Project.class ); PlexusJdoUtils.removeAll( persistenceManager, Schedule.class ); PlexusJdoUtils.removeAll( persistenceManager, ScmResult.class ); PlexusJdoUtils.removeAll( persistenceManager, BuildResult.class ); PlexusJdoUtils.removeAll( persistenceManager, TestResult.class ); PlexusJdoUtils.removeAll( persistenceManager, SuiteResult.class ); PlexusJdoUtils.removeAll( persistenceManager, TestCaseFailure.class ); PlexusJdoUtils.removeAll( persistenceManager, SystemConfiguration.class ); PlexusJdoUtils.removeAll( persistenceManager, ProjectNotifier.class ); PlexusJdoUtils.removeAll( persistenceManager, ProjectDeveloper.class ); PlexusJdoUtils.removeAll( persistenceManager, ProjectDependency.class ); PlexusJdoUtils.removeAll( persistenceManager, ChangeSet.class ); PlexusJdoUtils.removeAll( persistenceManager, ChangeFile.class ); PlexusJdoUtils.removeAll( persistenceManager, BuildDefinition.class ); } private PersistenceManager getPersistenceManager( PersistenceManagerFactory pmf ) { PersistenceManager pm = pmf.getPersistenceManager(); pm.getFetchPlan().setMaxFetchDepth( -1 ); pm.getFetchPlan().setDetachmentOptions( FetchPlan.DETACH_LOAD_FIELDS ); return pm; } public void restoreDatabase( File backupDirectory, boolean strict ) throws IOException { ContinuumStaxReader reader = new ContinuumStaxReader(); FileReader fileReader = new FileReader( new File( backupDirectory, BUILDS_XML ) ); ContinuumDatabase database; try { database = reader.read( fileReader, strict ); } catch ( XMLStreamException e ) { throw new DataManagementException( e ); } finally { IOUtil.close( fileReader ); } PersistenceManagerFactory pmf = getPersistenceManagerFactory( "jdorepl109" ); PlexusJdoUtils.addObject( pmf.getPersistenceManager(), database.getSystemConfiguration() ); Map<Integer, Schedule> schedules = new HashMap<Integer, Schedule>(); for ( Iterator i = database.getSchedules().iterator(); i.hasNext(); ) { Schedule schedule = (Schedule) i.next(); schedule = (Schedule) PlexusJdoUtils.addObject( pmf.getPersistenceManager(), schedule ); schedules.put( Integer.valueOf( schedule.getId() ), schedule ); } for ( Iterator i = database.getProjectGroups().iterator(); i.hasNext(); ) { ProjectGroup projectGroup = (ProjectGroup) i.next(); // first, we must map up any schedules, etc. processBuildDefinitions( projectGroup.getBuildDefinitions(), schedules ); for ( Iterator j = projectGroup.getProjects().iterator(); j.hasNext(); ) { Project project = (Project) j.next(); processBuildDefinitions( project.getBuildDefinitions(), schedules ); } PlexusJdoUtils.addObject( pmf.getPersistenceManager(), projectGroup ); } pmf.close(); } private PersistenceManagerFactory getPersistenceManagerFactory( String ext ) { // Take control of the JDO instead of using the store, and configure a new persistence factory // that won't generate new object IDs. Properties properties = new Properties(); //noinspection UseOfPropertiesAsHashtable properties.putAll( factory.getProperties() ); properties.setProperty( "org.jpox.metadata.jdoFileExtension", ext ); return JDOHelper.getPersistenceManagerFactory( properties ); } private static void processBuildDefinitions( List buildDefinitions, Map<Integer, Schedule> schedules ) { for ( Iterator i = buildDefinitions.iterator(); i.hasNext(); ) { BuildDefinition def = (BuildDefinition) i.next(); if ( def.getSchedule() != null ) { def.setSchedule( schedules.get( Integer.valueOf( def.getSchedule().getId() ) ) ); } } } }
4,877
0
Create_ds/continuum/continuum-data-management/data-management-jdo/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-data-management/data-management-jdo/src/main/java/org/apache/maven/continuum/management/DefaultDatabaseFactoryConfigurator.java
package org.apache.maven.continuum.management; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory; import java.util.Iterator; import java.util.Properties; @Component( role = org.apache.maven.continuum.management.DatabaseFactoryConfigurator.class, hint = "continuum" ) public class DefaultDatabaseFactoryConfigurator implements DatabaseFactoryConfigurator { @Requirement( role = org.codehaus.plexus.jdo.JdoFactory.class, hint = "continuum" ) protected DefaultConfigurableJdoFactory factory; public void configure( DatabaseParams params ) { // Must occur before store is looked up factory.setDriverName( params.getDriverClass() ); factory.setUserName( params.getUsername() ); factory.setPassword( params.getPassword() ); factory.setUrl( params.getUrl() ); Properties properties = params.getProperties(); for ( Iterator i = properties.keySet().iterator(); i.hasNext(); ) { String key = (String) i.next(); factory.setProperty( key, properties.getProperty( key ) ); } } }
4,878
0
Create_ds/continuum/continuum-data-management/data-management-redback-jdo/src/main/java/org/apache/maven/continuum/management
Create_ds/continuum/continuum-data-management/data-management-redback-jdo/src/main/java/org/apache/maven/continuum/management/redback/JdoDataManagementTool.java
package org.apache.maven.continuum.management.redback; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.management.DataManagementException; import org.apache.maven.continuum.management.DataManagementTool; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.redback.keys.KeyManager; import org.codehaus.plexus.redback.rbac.RBACManager; import org.codehaus.plexus.redback.rbac.RbacManagerException; import org.codehaus.plexus.redback.users.UserManager; import java.io.File; import java.io.IOException; import javax.xml.stream.XMLStreamException; /** * JDO implementation the database management tool API. */ @Component( role = org.apache.maven.continuum.management.DataManagementTool.class, hint = "redback-jdo" ) public class JdoDataManagementTool implements DataManagementTool { @Requirement( hint = "jdo" ) private org.codehaus.plexus.redback.management.DataManagementTool toolDelegate; @Requirement( hint = "jdo" ) private RBACManager rbacManager; @Requirement( hint = "jdo" ) private UserManager userManager; @Requirement( hint = "jdo" ) private KeyManager keyManager; public void backupDatabase( File backupDirectory ) throws IOException { try { toolDelegate.backupKeyDatabase( keyManager, backupDirectory ); toolDelegate.backupRBACDatabase( rbacManager, backupDirectory ); toolDelegate.backupUserDatabase( userManager, backupDirectory ); } catch ( XMLStreamException e ) { throw new DataManagementException( e ); } catch ( RbacManagerException e ) { throw new DataManagementException( e ); } } public void eraseDatabase() { toolDelegate.eraseKeysDatabase( keyManager ); toolDelegate.eraseRBACDatabase( rbacManager ); toolDelegate.eraseUsersDatabase( userManager ); } public void restoreDatabase( File backupDirectory, boolean strict ) throws IOException { try { toolDelegate.restoreKeysDatabase( keyManager, backupDirectory ); toolDelegate.restoreRBACDatabase( rbacManager, backupDirectory ); toolDelegate.restoreUsersDatabase( userManager, backupDirectory ); } catch ( XMLStreamException e ) { throw new DataManagementException( e ); } catch ( RbacManagerException e ) { throw new DataManagementException( e ); } } }
4,879
0
Create_ds/continuum/continuum-data-management/data-management-redback-jdo/src/main/java/org/apache/maven/continuum/management
Create_ds/continuum/continuum-data-management/data-management-redback-jdo/src/main/java/org/apache/maven/continuum/management/redback/LegacyJdoDataManagementTool.java
package org.apache.maven.continuum.management.redback; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.management.DataManagementException; import org.apache.maven.continuum.management.DataManagementTool; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.jdo.JdoFactory; import org.codehaus.plexus.jdo.PlexusJdoUtils; import org.codehaus.plexus.jdo.PlexusStoreException; import org.codehaus.plexus.security.authorization.rbac.jdo.v0_9_0.JdoOperation; import org.codehaus.plexus.security.authorization.rbac.jdo.v0_9_0.JdoPermission; import org.codehaus.plexus.security.authorization.rbac.jdo.v0_9_0.JdoResource; import org.codehaus.plexus.security.authorization.rbac.jdo.v0_9_0.JdoRole; import org.codehaus.plexus.security.authorization.rbac.jdo.v0_9_0.JdoUserAssignment; import org.codehaus.plexus.security.authorization.rbac.jdo.v0_9_0.RbacDatabase; import org.codehaus.plexus.security.authorization.rbac.jdo.v0_9_0.RbacJdoModelModelloMetadata; import org.codehaus.plexus.security.authorization.rbac.jdo.v0_9_0.io.stax.RbacJdoModelStaxReader; import org.codehaus.plexus.security.authorization.rbac.jdo.v0_9_0.io.stax.RbacJdoModelStaxWriter; import org.codehaus.plexus.security.keys.jdo.v0_9_0.AuthenticationKeyDatabase; import org.codehaus.plexus.security.keys.jdo.v0_9_0.JdoAuthenticationKey; import org.codehaus.plexus.security.keys.jdo.v0_9_0.PlexusSecurityKeyManagementJdoModelloMetadata; import org.codehaus.plexus.security.keys.jdo.v0_9_0.io.stax.PlexusSecurityKeyManagementJdoStaxReader; import org.codehaus.plexus.security.keys.jdo.v0_9_0.io.stax.PlexusSecurityKeyManagementJdoStaxWriter; import org.codehaus.plexus.security.rbac.RBACObjectAssertions; import org.codehaus.plexus.security.rbac.RbacManagerException; import org.codehaus.plexus.security.user.Messages; import org.codehaus.plexus.security.user.UserManagerException; import org.codehaus.plexus.security.user.jdo.v0_9_0.JdoUser; import org.codehaus.plexus.security.user.jdo.v0_9_0.UserDatabase; import org.codehaus.plexus.security.user.jdo.v0_9_0.UserManagementModelloMetadata; import org.codehaus.plexus.security.user.jdo.v0_9_0.io.stax.UserManagementStaxReader; import org.codehaus.plexus.security.user.jdo.v0_9_0.io.stax.UserManagementStaxWriter; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManager; import javax.xml.stream.XMLStreamException; /** * JDO implementation the database management tool API. */ @Component( role = org.apache.maven.continuum.management.DataManagementTool.class, hint = "legacy-redback-jdo" ) public class LegacyJdoDataManagementTool implements DataManagementTool { private static final String USERS_XML_NAME = "users.xml"; private static final String KEYS_XML_NAME = "keys.xml"; private static final String RBAC_XML_NAME = "rbac.xml"; @Requirement( hint = "users" ) private JdoFactory jdoFactory; public void backupDatabase( File backupDirectory ) throws IOException { try { backupKeyDatabase( backupDirectory ); backupRBACDatabase( backupDirectory ); backupUserDatabase( backupDirectory ); } catch ( XMLStreamException e ) { throw new DataManagementException( e ); } catch ( RbacManagerException e ) { throw new DataManagementException( e ); } } public void restoreDatabase( File backupDirectory, boolean strict ) throws IOException, DataManagementException { try { restoreKeysDatabase( backupDirectory ); restoreRBACDatabase( backupDirectory ); restoreUsersDatabase( backupDirectory ); } catch ( XMLStreamException e ) { throw new DataManagementException( e ); } catch ( PlexusStoreException e ) { throw new DataManagementException( e ); } catch ( RbacManagerException e ) { throw new DataManagementException( e ); } } public void eraseDatabase() { eraseKeysDatabase(); eraseRBACDatabase(); eraseUsersDatabase(); } public void backupRBACDatabase( File backupDirectory ) throws RbacManagerException, IOException, XMLStreamException { RbacDatabase database = new RbacDatabase(); database.setRoles( PlexusJdoUtils.getAllObjectsDetached( getPersistenceManager(), JdoRole.class ) ); database.setUserAssignments( PlexusJdoUtils.getAllObjectsDetached( getPersistenceManager(), JdoUserAssignment.class ) ); database.setPermissions( PlexusJdoUtils.getAllObjectsDetached( getPersistenceManager(), JdoPermission.class ) ); database.setOperations( PlexusJdoUtils.getAllObjectsDetached( getPersistenceManager(), JdoOperation.class ) ); database.setResources( PlexusJdoUtils.getAllObjectsDetached( getPersistenceManager(), JdoResource.class ) ); RbacJdoModelStaxWriter writer = new RbacJdoModelStaxWriter(); FileWriter fileWriter = new FileWriter( new File( backupDirectory, RBAC_XML_NAME ) ); try { writer.write( fileWriter, database ); } finally { IOUtil.close( fileWriter ); } } public void backupUserDatabase( File backupDirectory ) throws IOException, XMLStreamException { UserDatabase database = new UserDatabase(); database.setUsers( PlexusJdoUtils.getAllObjectsDetached( getPersistenceManager(), JdoUser.class ) ); UserManagementStaxWriter writer = new UserManagementStaxWriter(); FileWriter fileWriter = new FileWriter( new File( backupDirectory, USERS_XML_NAME ) ); try { writer.write( fileWriter, database ); } finally { IOUtil.close( fileWriter ); } } public void backupKeyDatabase( File backupDirectory ) throws IOException, XMLStreamException { AuthenticationKeyDatabase database = new AuthenticationKeyDatabase(); List keys = PlexusJdoUtils.getAllObjectsDetached( getPersistenceManager(), JdoAuthenticationKey.class ); database.setKeys( keys ); PlexusSecurityKeyManagementJdoStaxWriter writer = new PlexusSecurityKeyManagementJdoStaxWriter(); FileWriter fileWriter = new FileWriter( new File( backupDirectory, KEYS_XML_NAME ) ); try { writer.write( fileWriter, database ); } finally { IOUtil.close( fileWriter ); } } private PersistenceManager getPersistenceManager() { PersistenceManager pm = jdoFactory.getPersistenceManagerFactory().getPersistenceManager(); pm.getFetchPlan().setMaxFetchDepth( 5 ); return pm; } public void restoreRBACDatabase( File backupDirectory ) throws IOException, XMLStreamException, RbacManagerException, PlexusStoreException { RbacJdoModelStaxReader reader = new RbacJdoModelStaxReader(); FileReader fileReader = new FileReader( new File( backupDirectory, RBAC_XML_NAME ) ); RbacDatabase database; try { database = reader.read( fileReader ); } finally { IOUtil.close( fileReader ); } Map<String, JdoPermission> permissionMap = new HashMap<String, JdoPermission>(); Map<String, JdoResource> resources = new HashMap<String, JdoResource>(); Map<String, JdoOperation> operations = new HashMap<String, JdoOperation>(); for ( Iterator i = database.getRoles().iterator(); i.hasNext(); ) { JdoRole role = (JdoRole) i.next(); // TODO: this could be generally useful and put into saveRole itself as long as the performance penalty isn't too harsh. // Currently it always saves everything where it could pull pack the existing permissions, etc if they exist List<JdoPermission> permissions = new ArrayList<JdoPermission>(); for ( Iterator j = role.getPermissions().iterator(); j.hasNext(); ) { JdoPermission permission = (JdoPermission) j.next(); if ( permissionMap.containsKey( permission.getName() ) ) { permission = permissionMap.get( permission.getName() ); } else if ( objectExists( permission ) ) { permission = (JdoPermission) PlexusJdoUtils.getObjectById( getPersistenceManager(), JdoPermission.class, permission.getName() ); permissionMap.put( permission.getName(), permission ); } else { JdoOperation operation = (JdoOperation) permission.getOperation(); if ( operations.containsKey( operation.getName() ) ) { operation = operations.get( operation.getName() ); } else if ( objectExists( operation ) ) { operation = (JdoOperation) PlexusJdoUtils.getObjectById( getPersistenceManager(), JdoOperation.class, operation.getName() ); operations.put( operation.getName(), operation ); } else { RBACObjectAssertions.assertValid( operation ); operation = (JdoOperation) PlexusJdoUtils.saveObject( getPersistenceManager(), operation, null ); operations.put( operation.getName(), operation ); } permission.setOperation( operation ); JdoResource resource = (JdoResource) permission.getResource(); if ( resources.containsKey( resource.getIdentifier() ) ) { resource = resources.get( resource.getIdentifier() ); } else if ( objectExists( resource ) ) { resource = (JdoResource) PlexusJdoUtils.getObjectById( getPersistenceManager(), JdoResource.class, resource.getIdentifier() ); resources.put( resource.getIdentifier(), resource ); } else { RBACObjectAssertions.assertValid( resource ); resource = (JdoResource) PlexusJdoUtils.saveObject( getPersistenceManager(), resource, null ); resources.put( resource.getIdentifier(), resource ); } permission.setResource( resource ); RBACObjectAssertions.assertValid( permission ); permission = (JdoPermission) PlexusJdoUtils.saveObject( getPersistenceManager(), permission, null ); permissionMap.put( permission.getName(), permission ); } permissions.add( permission ); } role.setPermissions( permissions ); RBACObjectAssertions.assertValid( role ); PlexusJdoUtils.saveObject( getPersistenceManager(), role, new String[] { null } ); } for ( Iterator i = database.getUserAssignments().iterator(); i.hasNext(); ) { JdoUserAssignment userAssignment = (JdoUserAssignment) i.next(); RBACObjectAssertions.assertValid( "Save User Assignment", userAssignment ); PlexusJdoUtils.saveObject( getPersistenceManager(), userAssignment, new String[] { null } ); } } private boolean objectExists( Object object ) { return JDOHelper.getObjectId( object ) != null; } public void restoreUsersDatabase( File backupDirectory ) throws IOException, XMLStreamException { UserManagementStaxReader reader = new UserManagementStaxReader(); FileReader fileReader = new FileReader( new File( backupDirectory, USERS_XML_NAME ) ); UserDatabase database; try { database = reader.read( fileReader ); } finally { IOUtil.close( fileReader ); } for ( Iterator i = database.getUsers().iterator(); i.hasNext(); ) { JdoUser user = (JdoUser) i.next(); if ( !( user instanceof JdoUser ) ) { throw new UserManagerException( "Unable to Add User. User object " + user.getClass().getName() + " is not an instance of " + JdoUser.class.getName() ); } if ( StringUtils.isEmpty( user.getUsername() ) ) { throw new IllegalStateException( Messages.getString( "user.manager.cannot.add.user.without.username" ) ); //$NON-NLS-1$ } PlexusJdoUtils.addObject( getPersistenceManager(), user ); } } public void restoreKeysDatabase( File backupDirectory ) throws IOException, XMLStreamException { PlexusSecurityKeyManagementJdoStaxReader reader = new PlexusSecurityKeyManagementJdoStaxReader(); FileReader fileReader = new FileReader( new File( backupDirectory, KEYS_XML_NAME ) ); AuthenticationKeyDatabase database; try { database = reader.read( fileReader ); } finally { IOUtil.close( fileReader ); } for ( Iterator i = database.getKeys().iterator(); i.hasNext(); ) { JdoAuthenticationKey key = (JdoAuthenticationKey) i.next(); PlexusJdoUtils.addObject( getPersistenceManager(), key ); } } public void eraseRBACDatabase() { // Must delete in order so that FK constraints don't get violated PlexusJdoUtils.removeAll( getPersistenceManager(), JdoRole.class ); PlexusJdoUtils.removeAll( getPersistenceManager(), JdoPermission.class ); PlexusJdoUtils.removeAll( getPersistenceManager(), JdoOperation.class ); PlexusJdoUtils.removeAll( getPersistenceManager(), JdoResource.class ); PlexusJdoUtils.removeAll( getPersistenceManager(), JdoUserAssignment.class ); PlexusJdoUtils.removeAll( getPersistenceManager(), RbacJdoModelModelloMetadata.class ); } public void eraseUsersDatabase() { PlexusJdoUtils.removeAll( getPersistenceManager(), JdoUser.class ); PlexusJdoUtils.removeAll( getPersistenceManager(), UserManagementModelloMetadata.class ); } public void eraseKeysDatabase() { PlexusJdoUtils.removeAll( getPersistenceManager(), JdoAuthenticationKey.class ); PlexusJdoUtils.removeAll( getPersistenceManager(), PlexusSecurityKeyManagementJdoModelloMetadata.class ); } }
4,880
0
Create_ds/continuum/continuum-data-management/data-management-redback-jdo/src/main/java/org/apache/maven/continuum/management
Create_ds/continuum/continuum-data-management/data-management-redback-jdo/src/main/java/org/apache/maven/continuum/management/redback/DefaultDatabaseFactoryConfigurator.java
package org.apache.maven.continuum.management.redback; import org.apache.maven.continuum.management.DatabaseFactoryConfigurator; import org.apache.maven.continuum.management.DatabaseParams; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory; import java.util.Iterator; import java.util.Properties; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @Component( role = org.apache.maven.continuum.management.DatabaseFactoryConfigurator.class, hint = "redback" ) public class DefaultDatabaseFactoryConfigurator implements DatabaseFactoryConfigurator { @Requirement( role = org.codehaus.plexus.jdo.JdoFactory.class, hint = "users" ) protected DefaultConfigurableJdoFactory factory; public void configure( DatabaseParams params ) { // Must occur before store is looked up factory.setDriverName( params.getDriverClass() ); factory.setUserName( params.getUsername() ); factory.setPassword( params.getPassword() ); factory.setUrl( params.getUrl() ); Properties properties = params.getProperties(); for ( Iterator i = properties.keySet().iterator(); i.hasNext(); ) { String key = (String) i.next(); factory.setProperty( key, properties.getProperty( key ) ); } } }
4,881
0
Create_ds/continuum/continuum-data-management/continuum-legacy/src/main/java/org/apache/maven/continuum/model/project
Create_ds/continuum/continuum-data-management/continuum-legacy/src/main/java/org/apache/maven/continuum/model/project/v1_0_9/ContinuumModelloMetadata.java
package org.apache.maven.continuum.model.project.v1_0_9; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public class ContinuumModelloMetadata { private String modelVersion; public String getModelVersion() { return modelVersion; } public void setModelVersion( String modelVersion ) { this.modelVersion = modelVersion; } }
4,882
0
Create_ds/continuum/continuum-data-management/data-management-api/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-data-management/data-management-api/src/main/java/org/apache/maven/continuum/management/DatabaseFactoryConfigurator.java
package org.apache.maven.continuum.management; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public interface DatabaseFactoryConfigurator { void configure( DatabaseParams params ); }
4,883
0
Create_ds/continuum/continuum-data-management/data-management-api/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-data-management/data-management-api/src/main/java/org/apache/maven/continuum/management/DataManagementTool.java
package org.apache.maven.continuum.management; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; import java.io.IOException; /** * Delegate to the correct data management tool. */ public interface DataManagementTool { /** * Backup the database. * * @param backupDirectory the directory to backup to * @throws java.io.IOException if there is a problem writing to the backup file * @throws DataManagementException if there is a problem reading from the database */ void backupDatabase( File backupDirectory ) throws IOException, DataManagementException; /** * Restore the database. * * @param backupDirectory the directory where the backup to restore from resides * @param strict * @throws java.io.IOException if there is a problem reading the backup file * @throws DataManagementException if there is a problem parsing the backup file */ void restoreDatabase( File backupDirectory, boolean strict ) throws IOException, DataManagementException; /** * Smoke the database. */ void eraseDatabase(); }
4,884
0
Create_ds/continuum/continuum-data-management/data-management-api/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-data-management/data-management-api/src/main/java/org/apache/maven/continuum/management/DatabaseParams.java
package org.apache.maven.continuum.management; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Properties; /** * Bean for storing database parameters. */ public class DatabaseParams { private final String driverClass; private String url; private final String groupId; private final String artifactId; private String version; private String username; private String password; private final Properties properties = new Properties(); DatabaseParams( String driverClass, String groupId, String artifactId, String version, String username, String password ) { this.driverClass = driverClass; this.groupId = groupId; this.artifactId = artifactId; this.version = version; this.username = username; this.password = password; } DatabaseParams( DatabaseParams params ) { this.driverClass = params.driverClass; this.groupId = params.groupId; this.artifactId = params.artifactId; this.version = params.version; this.username = params.username; this.password = params.password; this.url = params.url; } public String getUrl() { return url; } public String getGroupId() { return groupId; } public String getArtifactId() { return artifactId; } public String getVersion() { return version; } public String getUsername() { return username; } public String getPassword() { return password; } public String getDriverClass() { return driverClass; } public void setUrl( String url ) { this.url = url; } public Properties getProperties() { return properties; } }
4,885
0
Create_ds/continuum/continuum-data-management/data-management-api/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-data-management/data-management-api/src/main/java/org/apache/maven/continuum/management/DataManagementException.java
package org.apache.maven.continuum.management; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Exception wrapper for application errors that can't be recovered from. */ public class DataManagementException extends RuntimeException { public DataManagementException( Throwable nested ) { super( nested ); } public DataManagementException( String msg, Throwable nested ) { super( msg, nested ); } }
4,886
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/ContinuumPurgeConstants.java
package org.apache.continuum.purge; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * @author Maria Catherine Tan * @since 25 jul 07 */ public class ContinuumPurgeConstants { public static final String PURGE_REPOSITORY = "repository"; public static final String PURGE_DIRECTORY_RELEASES = "releases"; public static final String PURGE_DIRECTORY_WORKING = "working"; public static final String PURGE_DIRECTORY_BUILDOUTPUT = "buildOutput"; public static final String RELEASE_DIR_PATTERN = "releases-*"; public static final String PURGE = "PURGE"; public static final String PURGE_REPO_CONTENTS = "Purge All Repository Contents"; public static final String PURGE_DIR_CONTENTS = "Purge All Directory Contents"; public static final String PURGE_ARTIFACT = "Purge Artifact File"; public static final String PURGE_FILE = "Purge Support File"; public static final String PURGE_PROJECT = "Purge Project"; }
4,887
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository/content/ManagedDefaultRepositoryContent.java
package org.apache.continuum.purge.repository.content; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.StringUtils; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.purge.repository.utils.FileTypes; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.maven.archiva.common.utils.PathUtil; import org.apache.maven.archiva.common.utils.VersionUtil; import org.apache.maven.archiva.model.ArtifactReference; import org.apache.maven.archiva.model.ProjectReference; import org.apache.maven.archiva.model.VersionedReference; import org.apache.maven.archiva.repository.ContentNotFoundException; import org.apache.maven.archiva.repository.content.ArtifactExtensionMapping; import org.apache.maven.archiva.repository.content.DefaultPathParser; import org.apache.maven.archiva.repository.content.PathParser; import org.apache.maven.archiva.repository.layout.LayoutException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; /** * Taken from Archiva's ManagedDefaultRepositoryContent and made some few changes. */ @Component( role = RepositoryManagedContent.class, hint = "default", instantiationStrategy = "per-lookup" ) public class ManagedDefaultRepositoryContent implements RepositoryManagedContent { private static final String MAVEN_METADATA = "maven-metadata.xml"; private static final char PATH_SEPARATOR = '/'; private static final char GROUP_SEPARATOR = '.'; private static final char ARTIFACT_SEPARATOR = '-'; private final PathParser defaultPathParser = new DefaultPathParser(); @Requirement( hint = "file-types" ) private FileTypes filetypes; @Requirement private FileSystemManager fsManager; private LocalRepository repository; public void deleteVersion( VersionedReference reference ) throws ContentNotFoundException { String path = toMetadataPath( reference ); File projectPath = new File( getRepoRoot(), path ); File projectDir = projectPath.getParentFile(); if ( projectDir.exists() && projectDir.isDirectory() ) { try { fsManager.removeDir( projectDir ); } catch ( IOException e ) { // TODO: log this somewhere? } } } public int getId() { return repository.getId(); } public Set<ArtifactReference> getRelatedArtifacts( ArtifactReference reference ) throws ContentNotFoundException, LayoutException { File artifactFile = toFile( reference ); File repoDir = artifactFile.getParentFile(); if ( !repoDir.exists() ) { throw new ContentNotFoundException( "Unable to get related artifacts using a non-existant directory: " + repoDir.getAbsolutePath() ); } if ( !repoDir.isDirectory() ) { throw new ContentNotFoundException( "Unable to get related artifacts using a non-directory: " + repoDir.getAbsolutePath() ); } Set<ArtifactReference> foundArtifacts = new HashSet<ArtifactReference>(); // First gather up the versions found as artifacts in the managed repository. for ( File repoFile : repoDir.listFiles() ) { if ( repoFile.isDirectory() ) { // Skip it. it's a directory. continue; } String relativePath = PathUtil.getRelative( repository.getLocation(), repoFile ); if ( filetypes.matchesArtifactPattern( relativePath ) ) { ArtifactReference artifact = toArtifactReference( relativePath ); // Test for related, groupId / artifactId / version must match. if ( artifact.getGroupId().equals( reference.getGroupId() ) && artifact.getArtifactId().equals( reference.getArtifactId() ) && artifact.getVersion().equals( reference.getVersion() ) ) { foundArtifacts.add( artifact ); } } } return foundArtifacts; } public String getRepoRoot() { return repository.getLocation(); } public LocalRepository getRepository() { return repository; } /** * Gather the Available Versions (on disk) for a specific Project Reference, based on filesystem * information. * * @return the Set of available versions, based on the project reference. * @throws ContentNotFoundException * @throws LayoutException */ public Set<String> getVersions( ProjectReference reference ) throws ContentNotFoundException, LayoutException { String path = toMetadataPath( reference ); int idx = path.lastIndexOf( '/' ); if ( idx > 0 ) { path = path.substring( 0, idx ); } File repoDir = new File( repository.getLocation(), path ); if ( !repoDir.exists() ) { throw new ContentNotFoundException( "Unable to get Versions on a non-existant directory: " + repoDir.getAbsolutePath() ); } if ( !repoDir.isDirectory() ) { throw new ContentNotFoundException( "Unable to get Versions on a non-directory: " + repoDir.getAbsolutePath() ); } Set<String> foundVersions = new HashSet<String>(); VersionedReference versionRef = new VersionedReference(); versionRef.setGroupId( reference.getGroupId() ); versionRef.setArtifactId( reference.getArtifactId() ); for ( File repoFile : repoDir.listFiles() ) { if ( !repoFile.isDirectory() ) { // Skip it. not a directory. continue; } // Test if dir has an artifact, which proves to us that it is a valid version directory. String version = repoFile.getName(); versionRef.setVersion( version ); if ( hasArtifact( versionRef ) ) { // Found an artifact, must be a valid version. foundVersions.add( version ); } } return foundVersions; } public Set<String> getVersions( VersionedReference reference ) throws ContentNotFoundException, LayoutException { String path = toMetadataPath( reference ); int idx = path.lastIndexOf( '/' ); if ( idx > 0 ) { path = path.substring( 0, idx ); } File repoDir = new File( repository.getLocation(), path ); if ( !repoDir.exists() ) { throw new ContentNotFoundException( "Unable to get versions on a non-existant directory: " + repoDir.getAbsolutePath() ); } if ( !repoDir.isDirectory() ) { throw new ContentNotFoundException( "Unable to get versions on a non-directory: " + repoDir.getAbsolutePath() ); } Set<String> foundVersions = new HashSet<String>(); // First gather up the versions found as artifacts in the managed repository. for ( File repoFile : repoDir.listFiles() ) { if ( repoFile.isDirectory() ) { // Skip it. it's a directory. continue; } String relativePath = PathUtil.getRelative( repository.getLocation(), repoFile ); if ( filetypes.matchesDefaultExclusions( relativePath ) ) { // Skip it, it's metadata or similar continue; } if ( filetypes.matchesArtifactPattern( relativePath ) ) { ArtifactReference artifact = toArtifactReference( relativePath ); foundVersions.add( artifact.getVersion() ); } } return foundVersions; } public String toMetadataPath( ProjectReference reference ) { StringBuffer path = new StringBuffer(); path.append( formatAsDirectory( reference.getGroupId() ) ).append( PATH_SEPARATOR ); path.append( reference.getArtifactId() ).append( PATH_SEPARATOR ); path.append( MAVEN_METADATA ); return path.toString(); } public String toMetadataPath( VersionedReference reference ) { StringBuffer path = new StringBuffer(); path.append( formatAsDirectory( reference.getGroupId() ) ).append( PATH_SEPARATOR ); path.append( reference.getArtifactId() ).append( PATH_SEPARATOR ); if ( reference.getVersion() != null ) { // add the version only if it is present path.append( VersionUtil.getBaseVersion( reference.getVersion() ) ).append( PATH_SEPARATOR ); } path.append( MAVEN_METADATA ); return path.toString(); } public String toPath( ArtifactReference reference ) { if ( reference == null ) { throw new IllegalArgumentException( "Artifact reference cannot be null" ); } String baseVersion = VersionUtil.getBaseVersion( reference.getVersion() ); return toPath( reference.getGroupId(), reference.getArtifactId(), baseVersion, reference.getVersion(), reference.getClassifier(), reference.getType() ); } public void setRepository( LocalRepository repository ) { this.repository = repository; } /** * Convert a path to an artifact reference. * * @param path the path to convert. (relative or full location path) * @throws LayoutException if the path cannot be converted to an artifact reference. */ public ArtifactReference toArtifactReference( String path ) throws LayoutException { if ( ( path != null ) && path.startsWith( repository.getLocation() ) ) { return defaultPathParser.toArtifactReference( path.substring( repository.getLocation().length() ) ); } return defaultPathParser.toArtifactReference( path ); } public File toFile( ArtifactReference reference ) { return new File( repository.getLocation(), toPath( reference ) ); } /** * Get the first Artifact found in the provided VersionedReference location. * * @param reference the reference to the versioned reference to search within * @return the ArtifactReference to the first artifact located within the versioned reference. or null if * no artifact was found within the versioned reference. * @throws IOException if the versioned reference is invalid (example: doesn't exist, or isn't a directory) * @throws LayoutException if the path cannot be converted to an artifact reference. */ private ArtifactReference getFirstArtifact( VersionedReference reference ) throws LayoutException, IOException { String path = toMetadataPath( reference ); int idx = path.lastIndexOf( '/' ); if ( idx > 0 ) { path = path.substring( 0, idx ); } File repoDir = new File( repository.getLocation(), path ); if ( !repoDir.exists() ) { throw new IOException( "Unable to gather the list of snapshot versions on a non-existant directory: " + repoDir.getAbsolutePath() ); } if ( !repoDir.isDirectory() ) { throw new IOException( "Unable to gather the list of snapshot versions on a non-directory: " + repoDir.getAbsolutePath() ); } for ( File repoFile : repoDir.listFiles() ) { if ( repoFile.isDirectory() ) { // Skip it. it's a directory. continue; } String relativePath = PathUtil.getRelative( repository.getLocation(), repoFile ); if ( filetypes.matchesArtifactPattern( relativePath ) ) { return toArtifactReference( relativePath ); } } // No artifact was found. return null; } private boolean hasArtifact( VersionedReference reference ) throws LayoutException { try { return ( getFirstArtifact( reference ) != null ); } catch ( IOException e ) { return false; } } private String formatAsDirectory( String directory ) { return directory.replace( GROUP_SEPARATOR, PATH_SEPARATOR ); } private String toPath( String groupId, String artifactId, String baseVersion, String version, String classifier, String type ) { StringBuffer path = new StringBuffer(); path.append( formatAsDirectory( groupId ) ).append( PATH_SEPARATOR ); path.append( artifactId ).append( PATH_SEPARATOR ); if ( baseVersion != null ) { path.append( baseVersion ).append( PATH_SEPARATOR ); if ( ( version != null ) && ( type != null ) ) { path.append( artifactId ).append( ARTIFACT_SEPARATOR ).append( version ); if ( StringUtils.isNotBlank( classifier ) ) { path.append( ARTIFACT_SEPARATOR ).append( classifier ); } path.append( GROUP_SEPARATOR ).append( ArtifactExtensionMapping.getExtension( type ) ); } } return path.toString(); } }
4,888
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository/content/RepositoryManagedContentFactory.java
package org.apache.continuum.purge.repository.content; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.codehaus.plexus.component.repository.exception.ComponentLookupException; public interface RepositoryManagedContentFactory { RepositoryManagedContent create( String layout ) throws ComponentLookupException; }
4,889
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository/content/RepositoryManagedContentFactoryImpl.java
package org.apache.continuum.purge.repository.content; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Component( role = RepositoryManagedContentFactory.class ) public class RepositoryManagedContentFactoryImpl implements RepositoryManagedContentFactory, Contextualizable { private static final Logger log = LoggerFactory.getLogger( RepositoryManagedContentFactoryImpl.class ); private PlexusContainer container; @Configuration( "default" ) private String defaultLayout; public RepositoryManagedContent create( String layout ) throws ComponentLookupException { RepositoryManagedContent repoContent; try { log.debug( "attempting to find direct match for layout {}", layout ); repoContent = (RepositoryManagedContent) container.lookup( RepositoryManagedContent.ROLE, layout ); log.debug( "found direct match for layout '{}'", layout ); } catch ( ComponentLookupException e ) { log.warn( "layout '{}' not found, falling back to '{}'", layout, defaultLayout ); repoContent = (RepositoryManagedContent) container.lookup( RepositoryManagedContent.ROLE, defaultLayout ); } return repoContent; } public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } }
4,890
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository/content/ManagedLegacyRepositoryContent.java
package org.apache.continuum.purge.repository.content; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.StringUtils; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.purge.repository.utils.FileTypes; import org.apache.maven.archiva.common.utils.PathUtil; import org.apache.maven.archiva.model.ArtifactReference; import org.apache.maven.archiva.model.ProjectReference; import org.apache.maven.archiva.model.VersionedReference; import org.apache.maven.archiva.repository.ContentNotFoundException; import org.apache.maven.archiva.repository.content.ArtifactExtensionMapping; import org.apache.maven.archiva.repository.content.PathParser; import org.apache.maven.archiva.repository.layout.LayoutException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import java.io.File; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Taken from Archiva's ManagedLegacyRepositoryContent and made some few changes */ @Component( role = RepositoryManagedContent.class, hint = "legacy", instantiationStrategy = "per-lookup" ) public class ManagedLegacyRepositoryContent implements RepositoryManagedContent { private static final String PATH_SEPARATOR = "/"; private static final Map<String, String> typeToDirectoryMap; static { typeToDirectoryMap = new HashMap<String, String>(); typeToDirectoryMap.put( "ejb-client", "ejb" ); typeToDirectoryMap.put( ArtifactExtensionMapping.MAVEN_PLUGIN, "maven-plugin" ); typeToDirectoryMap.put( ArtifactExtensionMapping.MAVEN_ONE_PLUGIN, "plugin" ); typeToDirectoryMap.put( "distribution-tgz", "distribution" ); typeToDirectoryMap.put( "distribution-zip", "distribution" ); typeToDirectoryMap.put( "javadoc", "javadoc.jar" ); } @Requirement( hint = "legacy-parser" ) private PathParser legacyPathParser; @Requirement( hint = "file-types" ) private FileTypes filetypes; private LocalRepository repository; public void deleteVersion( VersionedReference reference ) throws ContentNotFoundException { File groupDir = new File( repository.getLocation(), reference.getGroupId() ); if ( !groupDir.exists() ) { throw new ContentNotFoundException( "Unable to get versions using a non-existant groupId directory: " + groupDir.getAbsolutePath() ); } if ( !groupDir.isDirectory() ) { throw new ContentNotFoundException( "Unable to get versions using a non-directory: " + groupDir.getAbsolutePath() ); } // First gather up the versions found as artifacts in the managed repository. File typeDirs[] = groupDir.listFiles(); for ( File typeDir : typeDirs ) { if ( !typeDir.isDirectory() ) { // Skip it, we only care about directories. continue; } if ( !typeDir.getName().endsWith( "s" ) ) { // Skip it, we only care about directories that end in "s". } deleteVersions( typeDir, reference ); } } private void deleteVersions( File typeDir, VersionedReference reference ) { File repoFiles[] = typeDir.listFiles(); for ( File repoFile : repoFiles ) { if ( repoFile.isDirectory() ) { // Skip it. it's a directory. continue; } String relativePath = PathUtil.getRelative( repository.getLocation(), repoFile ); if ( filetypes.matchesArtifactPattern( relativePath ) ) { try { ArtifactReference artifact = toArtifactReference( relativePath ); if ( StringUtils.equals( artifact.getArtifactId(), reference.getArtifactId() ) && StringUtils.equals( artifact.getVersion(), reference.getVersion() ) ) { repoFile.delete(); deleteSupportFiles( repoFile ); } } catch ( LayoutException e ) { /* don't fail the process if there is a bad artifact within the directory. */ } } } } private void deleteSupportFiles( File repoFile ) { deleteSupportFile( repoFile, ".sha1" ); deleteSupportFile( repoFile, ".md5" ); deleteSupportFile( repoFile, ".asc" ); deleteSupportFile( repoFile, ".gpg" ); } private void deleteSupportFile( File repoFile, String supportExtension ) { File supportFile = new File( repoFile.getAbsolutePath() + supportExtension ); if ( supportFile.exists() && supportFile.isFile() ) { supportFile.delete(); } } public int getId() { return repository.getId(); } public Set<ArtifactReference> getRelatedArtifacts( ArtifactReference reference ) throws ContentNotFoundException, LayoutException { File artifactFile = toFile( reference ); File repoDir = artifactFile.getParentFile(); if ( !repoDir.exists() ) { throw new ContentNotFoundException( "Unable to get related artifacts using a non-existant directory: " + repoDir.getAbsolutePath() ); } if ( !repoDir.isDirectory() ) { throw new ContentNotFoundException( "Unable to get related artifacts using a non-directory: " + repoDir.getAbsolutePath() ); } Set<ArtifactReference> foundArtifacts = new HashSet<ArtifactReference>(); // First gather up the versions found as artifacts in the managed repository. File projectParentDir = repoDir.getParentFile(); File typeDirs[] = projectParentDir.listFiles(); for ( File typeDir : typeDirs ) { if ( !typeDir.isDirectory() ) { // Skip it, we only care about directories. continue; } if ( !typeDir.getName().endsWith( "s" ) ) { // Skip it, we only care about directories that end in "s". } getRelatedArtifacts( typeDir, reference, foundArtifacts ); } return foundArtifacts; } public String getRepoRoot() { return repository.getLocation(); } public LocalRepository getRepository() { return repository; } public Set<String> getVersions( ProjectReference reference ) throws ContentNotFoundException { File groupDir = new File( repository.getLocation(), reference.getGroupId() ); if ( !groupDir.exists() ) { throw new ContentNotFoundException( "Unable to get versions using a non-existant groupId directory: " + groupDir.getAbsolutePath() ); } if ( !groupDir.isDirectory() ) { throw new ContentNotFoundException( "Unable to get versions using a non-directory: " + groupDir.getAbsolutePath() ); } Set<String> foundVersions = new HashSet<String>(); // First gather up the versions found as artifacts in the managed repository. File typeDirs[] = groupDir.listFiles(); for ( File typeDir : typeDirs ) { if ( !typeDir.isDirectory() ) { // Skip it, we only care about directories. continue; } if ( !typeDir.getName().endsWith( "s" ) ) { // Skip it, we only care about directories that end in "s". } getProjectVersions( typeDir, reference, foundVersions ); } return foundVersions; } public Set<String> getVersions( VersionedReference reference ) throws ContentNotFoundException { File groupDir = new File( repository.getLocation(), reference.getGroupId() ); if ( !groupDir.exists() ) { throw new ContentNotFoundException( "Unable to get versions using a non-existant groupId directory: " + groupDir.getAbsolutePath() ); } if ( !groupDir.isDirectory() ) { throw new ContentNotFoundException( "Unable to get versions using a non-directory: " + groupDir.getAbsolutePath() ); } Set<String> foundVersions = new HashSet<String>(); // First gather up the versions found as artifacts in the managed repository. File typeDirs[] = groupDir.listFiles(); for ( File typeDir : typeDirs ) { if ( !typeDir.isDirectory() ) { // Skip it, we only care about directories. continue; } if ( !typeDir.getName().endsWith( "s" ) ) { // Skip it, we only care about directories that end in "s". } getVersionedVersions( typeDir, reference, foundVersions ); } return foundVersions; } /** * Convert a path to an artifact reference. * * @param path the path to convert. (relative or full location path) * @throws LayoutException if the path cannot be converted to an artifact reference. */ public ArtifactReference toArtifactReference( String path ) throws LayoutException { if ( ( path != null ) && path.startsWith( repository.getLocation() ) ) { return legacyPathParser.toArtifactReference( path.substring( repository.getLocation().length() ) ); } return legacyPathParser.toArtifactReference( path ); } public File toFile( ArtifactReference reference ) { return new File( repository.getLocation(), toPath( reference ) ); } public String toMetadataPath( ProjectReference reference ) { // No metadata present in legacy repository. return null; } public String toMetadataPath( VersionedReference reference ) { // No metadata present in legacy repository. return null; } public String toPath( ArtifactReference reference ) { if ( reference == null ) { throw new IllegalArgumentException( "Artifact reference cannot be null" ); } return toPath( reference.getGroupId(), reference.getArtifactId(), reference.getVersion(), reference.getClassifier(), reference.getType() ); } public void setRepository( LocalRepository repo ) { this.repository = repo; } private void getProjectVersions( File typeDir, ProjectReference reference, Set<String> foundVersions ) { File repoFiles[] = typeDir.listFiles(); for ( File repoFile : repoFiles ) { if ( repoFile.isDirectory() ) { // Skip it. it's a directory. continue; } String relativePath = PathUtil.getRelative( repository.getLocation(), repoFile ); if ( filetypes.matchesArtifactPattern( relativePath ) ) { try { ArtifactReference artifact = toArtifactReference( relativePath ); if ( StringUtils.equals( artifact.getArtifactId(), reference.getArtifactId() ) ) { foundVersions.add( artifact.getVersion() ); } } catch ( LayoutException e ) { /* don't fail the process if there is a bad artifact within the directory. */ } } } } private void getRelatedArtifacts( File typeDir, ArtifactReference reference, Set<ArtifactReference> foundArtifacts ) { for ( File repoFile : typeDir.listFiles() ) { if ( repoFile.isDirectory() ) { // Skip it. it's a directory. continue; } String relativePath = PathUtil.getRelative( repository.getLocation(), repoFile ); if ( filetypes.matchesArtifactPattern( relativePath ) ) { try { ArtifactReference artifact = toArtifactReference( relativePath ); if ( StringUtils.equals( artifact.getArtifactId(), reference.getArtifactId() ) && artifact.getVersion().startsWith( reference.getVersion() ) ) { foundArtifacts.add( artifact ); } } catch ( LayoutException e ) { /* don't fail the process if there is a bad artifact within the directory. */ } } } } private void getVersionedVersions( File typeDir, VersionedReference reference, Set<String> foundVersions ) { for ( File repoFile : typeDir.listFiles() ) { if ( repoFile.isDirectory() ) { // Skip it. it's a directory. continue; } String relativePath = PathUtil.getRelative( repository.getLocation(), repoFile ); if ( filetypes.matchesArtifactPattern( relativePath ) ) { try { ArtifactReference artifact = toArtifactReference( relativePath ); if ( StringUtils.equals( artifact.getArtifactId(), reference.getArtifactId() ) && artifact.getVersion().startsWith( reference.getVersion() ) ) { foundVersions.add( artifact.getVersion() ); } } catch ( LayoutException e ) { /* don't fail the process if there is a bad artifact within the directory. */ } } } } private String toPath( String groupId, String artifactId, String version, String classifier, String type ) { StringBuffer path = new StringBuffer(); path.append( groupId ).append( PATH_SEPARATOR ); path.append( getDirectory( type ) ).append( PATH_SEPARATOR ); if ( version != null ) { path.append( artifactId ).append( '-' ).append( version ); if ( StringUtils.isNotBlank( classifier ) ) { path.append( '-' ).append( classifier ); } path.append( '.' ).append( ArtifactExtensionMapping.getExtension( type ) ); } return path.toString(); } private String getDirectory( String type ) { String dirname = typeToDirectoryMap.get( type ); if ( dirname != null ) { return dirname + "s"; } // Default process. return type + "s"; } }
4,891
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository/utils/LegacyPathParser.java
package org.apache.continuum.purge.repository.utils; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.StringUtils; import org.apache.maven.archiva.model.ArtifactReference; import org.apache.maven.archiva.repository.content.ArtifactClassifierMapping; import org.apache.maven.archiva.repository.content.ArtifactExtensionMapping; import org.apache.maven.archiva.repository.content.PathParser; import org.apache.maven.archiva.repository.layout.LayoutException; import org.codehaus.plexus.component.annotations.Component; /** * Codes were taken from Archiva's LegacyPathParser and made some few changes. */ @Component( role = org.apache.maven.archiva.repository.content.PathParser.class, hint = "legacy-parser" ) public class LegacyPathParser implements PathParser { private static final String INVALID_ARTIFACT_PATH = "Invalid path to Artifact: "; public ArtifactReference toArtifactReference( String path ) throws LayoutException { ArtifactReference artifact = new ArtifactReference(); String normalizedPath = StringUtils.replace( path, "\\", "/" ); String pathParts[] = StringUtils.split( normalizedPath, '/' ); /* Always 3 parts. (Never more or less) * * path = "commons-lang/jars/commons-lang-2.1.jar" * path[0] = "commons-lang"; // The Group ID * path[1] = "jars"; // The Directory Type * path[2] = "commons-lang-2.1.jar"; // The Filename. */ if ( pathParts.length != 3 ) { // Illegal Path Parts Length. throw new LayoutException( INVALID_ARTIFACT_PATH + "legacy paths should only have 3 parts [groupId]/[type]s/[artifactId]-[version].[type], found " + pathParts.length + " instead." ); } // The Group ID. artifact.setGroupId( pathParts[0] ); // The Expected Type. String expectedType = pathParts[1]; // Sanity Check: expectedType should end in "s". if ( !expectedType.endsWith( "s" ) ) { throw new LayoutException( INVALID_ARTIFACT_PATH + "legacy paths should have an expected type ending in [s] in the second part of the path." ); } // The Filename. String filename = pathParts[2]; FilenameParser parser = new FilenameParser( filename ); artifact.setArtifactId( parser.nextNonVersion() ); // Sanity Check: does it have an artifact id? if ( StringUtils.isEmpty( artifact.getArtifactId() ) ) { // Special Case: The filename might start with a version id (like "test-arch-1.0.jar"). int idx = filename.indexOf( '-' ); if ( idx > 0 ) { parser.reset(); // Take the first section regardless of content. String artifactId = parser.next(); // Is there anything more that is considered not a version id? String moreArtifactId = parser.nextNonVersion(); if ( StringUtils.isNotBlank( moreArtifactId ) ) { artifact.setArtifactId( artifactId + "-" + moreArtifactId ); } else { artifact.setArtifactId( artifactId ); } } // Sanity Check: still no artifact id? if ( StringUtils.isEmpty( artifact.getArtifactId() ) ) { throw new LayoutException( INVALID_ARTIFACT_PATH + "no artifact id present." ); } } artifact.setVersion( parser.remaining() ); // Sanity Check: does it have a version? if ( StringUtils.isEmpty( artifact.getVersion() ) ) { // Special Case: use last section of artifactId as version. String artifactId = artifact.getArtifactId(); int idx = artifactId.lastIndexOf( '-' ); if ( idx > 0 ) { artifact.setVersion( artifactId.substring( idx + 1 ) ); artifact.setArtifactId( artifactId.substring( 0, idx ) ); } else { throw new LayoutException( INVALID_ARTIFACT_PATH + "no version found." ); } } String classifier = ArtifactClassifierMapping.getClassifier( expectedType ); if ( classifier != null ) { String version = artifact.getVersion(); if ( !version.endsWith( "-" + classifier ) ) { throw new LayoutException( INVALID_ARTIFACT_PATH + expectedType + " artifacts must use the classifier " + classifier ); } version = version.substring( 0, version.length() - classifier.length() - 1 ); artifact.setVersion( version ); artifact.setClassifier( classifier ); } String extension = parser.getExtension(); // Set Type String defaultExtension = expectedType.substring( 0, expectedType.length() - 1 ); artifact.setType( ArtifactExtensionMapping.mapExtensionAndClassifierToType( classifier, extension, defaultExtension ) ); // Sanity Check: does it have an extension? if ( StringUtils.isEmpty( artifact.getType() ) ) { throw new LayoutException( INVALID_ARTIFACT_PATH + "no extension found." ); } // Special Case with Maven Plugins if ( StringUtils.equals( "jar", extension ) && StringUtils.equals( "plugins", expectedType ) ) { artifact.setType( ArtifactExtensionMapping.MAVEN_ONE_PLUGIN ); } else { // Sanity Check: does extension match pathType on path? String expectedExtension = ArtifactExtensionMapping.getExtension( artifact.getType() ); if ( !expectedExtension.equals( extension ) ) { throw new LayoutException( INVALID_ARTIFACT_PATH + "mismatch on extension [" + extension + "] and layout specified type [" + artifact.getType() + "] (which maps to extension: [" + expectedExtension + "]) on path [" + path + "]" ); } } return artifact; } }
4,892
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository/utils/FileTypes.java
package org.apache.continuum.purge.repository.utils; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.codehaus.plexus.util.SelectorUtils; import java.util.Arrays; import java.util.List; /** * Codes were taken from Archiva and made some changes. */ public class FileTypes { private List<String> artifactFileTypePatterns; private List<String> ignoredFileTypePatterns; public static final List<String> DEFAULT_EXCLUSIONS = Arrays.asList( "**/maven-metadata.xml", "**/maven-metadata-*.xml", "**/*.sha1", "**/*.asc", "**/*.md5", "**/*.pgp", "**/*.repositories", "**/resolver-status.properties" ); public List<String> getIgnoredFileTypePatterns() { if ( ignoredFileTypePatterns == null ) { ignoredFileTypePatterns = DEFAULT_EXCLUSIONS; } return ignoredFileTypePatterns; } public List<String> getArtifactFileTypePatterns() { return artifactFileTypePatterns; } public synchronized boolean matchesArtifactPattern( String relativePath ) { // Correct the slash pattern. relativePath = relativePath.replace( '\\', '/' ); if ( artifactFileTypePatterns == null ) { return false; } for ( String pattern : artifactFileTypePatterns ) { if ( SelectorUtils.matchPath( pattern, relativePath, false ) ) { // Found match return true; } } // No match. return false; } public boolean matchesDefaultExclusions( String relativePath ) { // Correct the slash pattern. relativePath = relativePath.replace( '\\', '/' ); for ( String pattern : DEFAULT_EXCLUSIONS ) { if ( SelectorUtils.matchPath( pattern, relativePath, false ) ) { // Found match return true; } } // No match. return false; } }
4,893
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository/utils/FilenameParser.java
package org.apache.continuum.purge.repository.utils; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.archiva.common.utils.VersionUtil; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Codes were taken from Archiva's FilenameParser */ public class FilenameParser { private String name; private String extension; private int offset; private static final Pattern mavenPluginPattern = Pattern.compile( "(maven-.*-plugin)|(.*-maven-plugin)" ); private static final Pattern extensionPattern = Pattern.compile( "(\\.tar\\.gz$)|(\\.tar\\.bz2$)|(\\.[\\-a-z0-9]*$)", Pattern.CASE_INSENSITIVE ); private static final Pattern section = Pattern.compile( "([^-]*)" ); private final Matcher matcher; public FilenameParser( String filename ) { this.name = filename; Matcher mat = extensionPattern.matcher( name ); if ( mat.find() ) { extension = filename.substring( mat.start() + 1 ); name = name.substring( 0, name.length() - extension.length() - 1 ); } matcher = section.matcher( name ); reset(); } public void reset() { offset = 0; } public String next() { // Past the end of the string. if ( offset > name.length() ) { return null; } // Return the next section. if ( matcher.find( offset ) ) { // Return found section. offset = matcher.end() + 1; return matcher.group(); } // Nothing to return. return null; } protected String remaining() { if ( offset >= name.length() ) { return null; } String end = name.substring( offset ); offset = name.length(); return end; } protected String nextNonVersion() { boolean done = false; StringBuffer ver = new StringBuffer(); // Any text upto the end of a special case is considered non-version. Matcher specialMat = mavenPluginPattern.matcher( name ); if ( specialMat.find() ) { ver.append( name.substring( offset, specialMat.end() ) ); offset = specialMat.end() + 1; } while ( !done ) { int initialOffset = offset; String section = next(); if ( section == null ) { done = true; } else if ( !VersionUtil.isVersion( section ) ) { if ( ver.length() > 0 ) { ver.append( '-' ); } ver.append( section ); } else { offset = initialOffset; done = true; } } return ver.toString(); } public String getExtension() { return extension; } }
4,894
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/repository/scanner/DefaultRepositoryScanner.java
package org.apache.continuum.purge.repository.scanner; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.collections.CollectionUtils; import org.apache.continuum.purge.executor.ContinuumPurgeExecutorException; import org.apache.continuum.purge.repository.utils.FileTypes; import org.apache.maven.archiva.common.utils.BaseFile; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.DirectoryWalkListener; import org.codehaus.plexus.util.DirectoryWalker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Codes were taken from Archiva and made some changes. */ @Component( role = RepositoryScanner.class, hint = "purge" ) public class DefaultRepositoryScanner implements RepositoryScanner { @Requirement( hint = "file-types" ) private FileTypes filetypes; public void scan( File repoLocation, ScannerHandler handler ) throws ContinuumPurgeExecutorException { List<String> ignoredPatterns = filetypes.getIgnoredFileTypePatterns(); scan( repoLocation, handler, ignoredPatterns ); } public void scan( File repositoryLocation, ScannerHandler handler, List<String> ignoredContentPatterns ) throws ContinuumPurgeExecutorException { if ( !repositoryLocation.exists() ) { throw new UnsupportedOperationException( "Unable to scan a repository, directory " + repositoryLocation.getAbsolutePath() + " does not exist." ); } if ( !repositoryLocation.isDirectory() ) { throw new UnsupportedOperationException( "Unable to scan a repository, path " + repositoryLocation.getAbsolutePath() + " is not a directory." ); } // Setup Includes / Excludes. List<String> allExcludes = new ArrayList<String>(); List<String> allIncludes = new ArrayList<String>(); if ( CollectionUtils.isNotEmpty( ignoredContentPatterns ) ) { allExcludes.addAll( ignoredContentPatterns ); } // Scan All Content. (intentional) allIncludes.add( "**/*" ); // Setup Directory Walker DirectoryWalker dirWalker = new DirectoryWalker(); dirWalker.setBaseDir( repositoryLocation ); dirWalker.setIncludes( allIncludes ); dirWalker.setExcludes( allExcludes ); ScanListener listener = new ScanListener( repositoryLocation, handler ); dirWalker.addDirectoryWalkListener( listener ); // Execute scan. dirWalker.scan(); } } class ScanListener implements DirectoryWalkListener { private static final Logger log = LoggerFactory.getLogger( ScanListener.class ); private final File repository; private final ScannerHandler handler; public ScanListener( File repoLocation, ScannerHandler handler ) { this.repository = repoLocation; this.handler = handler; } public void debug( String message ) { log.debug( "repo scan: {}", message ); } public void directoryWalkFinished() { log.debug( "finished walk: {}", repository ); } public void directoryWalkStarting( File file ) { log.debug( "starting walk: {}", repository ); } public void directoryWalkStep( int percentage, File file ) { BaseFile basefile = new BaseFile( repository, file ); handler.handle( basefile.getRelativePath() ); } }
4,895
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor/dir/DirectoryPurgeExecutorFactoryImpl.java
package org.apache.continuum.purge.executor.dir; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.purge.executor.ContinuumPurgeExecutor; import org.apache.continuum.purge.executor.ContinuumPurgeExecutorException; import org.apache.continuum.utils.file.FileSystemManager; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileFilter; import java.io.IOException; import static org.apache.commons.io.filefilter.DirectoryFileFilter.DIRECTORY; import static org.apache.continuum.purge.ContinuumPurgeConstants.*; @Component( role = DirectoryPurgeExecutorFactory.class ) public class DirectoryPurgeExecutorFactoryImpl implements DirectoryPurgeExecutorFactory { @Requirement private FileSystemManager fsManager; public ContinuumPurgeExecutor create( boolean deleteAll, int daysOld, int retentionCount, String dirType ) { if ( PURGE_DIRECTORY_RELEASES.equals( dirType ) ) { return new ReleasesPurgeExecutor( fsManager, deleteAll, daysOld, retentionCount, dirType ); } if ( PURGE_DIRECTORY_WORKING.equals( dirType ) ) { return new WorkingPurgeExecutor( fsManager, deleteAll, daysOld, retentionCount, dirType ); } if ( PURGE_DIRECTORY_BUILDOUTPUT.equals( dirType ) ) { return new BuildOutputPurgeExecutor( fsManager, deleteAll, daysOld, retentionCount, dirType ); } return new UnsupportedPurgeExecutor( dirType ); } } class UnsupportedPurgeExecutor implements ContinuumPurgeExecutor { private static Logger log = LoggerFactory.getLogger( UnsupportedPurgeExecutor.class ); private String dirType; UnsupportedPurgeExecutor( String dirType ) { this.dirType = dirType; } public void purge( String path ) throws ContinuumPurgeExecutorException { log.warn( "ignoring purge request, directory type {} not supported", dirType ); } } abstract class AbstractPurgeExecutor implements ContinuumPurgeExecutor { protected final FileSystemManager fsManager; protected boolean deleteAll; protected final int daysOlder; protected final int retentionCount; protected final String directoryType; AbstractPurgeExecutor( FileSystemManager fsManager, boolean deleteAll, int daysOlder, int retentionCount, String directoryType ) { this.fsManager = fsManager; this.deleteAll = deleteAll; this.daysOlder = daysOlder; this.retentionCount = retentionCount; this.directoryType = directoryType; } public void purge( String path ) throws ContinuumPurgeExecutorException { try { File dir = new File( path ); purge( dir ); } catch ( PurgeBuilderException e ) { throw new ContinuumPurgeExecutorException( "purge failed: " + e.getMessage() ); } } abstract void purge( File dir ) throws PurgeBuilderException; } class ReleasesPurgeExecutor extends AbstractPurgeExecutor { ReleasesPurgeExecutor( FileSystemManager fsManager, boolean deleteAll, int daysOlder, int retentionCount, String directoryType ) { super( fsManager, deleteAll, daysOlder, retentionCount, directoryType ); } @Override void purge( File dir ) throws PurgeBuilderException { if ( deleteAll ) { PurgeBuilder.purge( dir ) .dirs() .namedLike( RELEASE_DIR_PATTERN ) .executeWith( new RemoveDirHandler( fsManager ) ); } else { PurgeBuilder.purge( dir ) .dirs() .namedLike( RELEASE_DIR_PATTERN ) .olderThan( daysOlder ) .inAgeOrder() .retainLast( retentionCount ) .executeWith( new RemoveDirHandler( fsManager ) ); } } } class BuildOutputPurgeExecutor extends AbstractPurgeExecutor { BuildOutputPurgeExecutor( FileSystemManager fsManager, boolean deleteAll, int daysOlder, int retentionCount, String directoryType ) { super( fsManager, deleteAll, daysOlder, retentionCount, directoryType ); } @Override void purge( File dir ) throws PurgeBuilderException { if ( deleteAll ) { PurgeBuilder.purge( dir ) .dirs() .executeWith( new WipeDirHandler( fsManager ) ); } else { File[] projectDirs = dir.listFiles( (FileFilter) DIRECTORY ); if ( projectDirs == null ) return; for ( File projectDir : projectDirs ) { PurgeBuilder.purge( projectDir ) .dirs() .olderThan( daysOlder ) .inAgeOrder() .retainLast( retentionCount ) .executeWith( new BuildOutputHandler( fsManager ) ); } } } } class WorkingPurgeExecutor extends AbstractPurgeExecutor { WorkingPurgeExecutor( FileSystemManager fsManager, boolean deleteAll, int daysOlder, int retentionCount, String directoryType ) { super( fsManager, deleteAll, daysOlder, retentionCount, directoryType ); } @Override void purge( File dir ) throws PurgeBuilderException { if ( deleteAll ) { PurgeBuilder.purge( dir ) .dirs() .notNamedLike( RELEASE_DIR_PATTERN ) .executeWith( new RemoveDirHandler( fsManager ) ); } else { PurgeBuilder.purge( dir ) .dirs() .notNamedLike( RELEASE_DIR_PATTERN ) .olderThan( daysOlder ) .inAgeOrder() .retainLast( retentionCount ) .executeWith( new RemoveDirHandler( fsManager ) ); } } } abstract class AbstractFSHandler implements Handler { private Logger log = LoggerFactory.getLogger( getClass() ); protected FileSystemManager fsManager; AbstractFSHandler( FileSystemManager fsManager ) { this.fsManager = fsManager; } public void handle( File dir ) { try { handleFile( dir ); } catch ( IOException e ) { log.warn( "failed to purge file {}: {}", dir, e.getMessage() ); } } abstract void handleFile( File dir ) throws IOException; } class WipeDirHandler extends AbstractFSHandler { WipeDirHandler( FileSystemManager fsManager ) { super( fsManager ); } public void handleFile( File dir ) throws IOException { fsManager.wipeDir( dir ); } } class BuildOutputHandler extends AbstractFSHandler { BuildOutputHandler( FileSystemManager fsManager ) { super( fsManager ); } public void handleFile( File dir ) throws IOException { fsManager.removeDir( dir ); File logFile = new File( dir.getAbsoluteFile() + ".log.txt" ); if ( logFile.exists() ) { logFile.delete(); } } } class RemoveDirHandler extends AbstractFSHandler { RemoveDirHandler( FileSystemManager fsManager ) { super( fsManager ); } public void handleFile( File dir ) throws IOException { fsManager.removeDir( dir ); } }
4,896
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor/dir/DirectoryPurgeExecutorFactory.java
package org.apache.continuum.purge.executor.dir; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.purge.executor.ContinuumPurgeExecutor; public interface DirectoryPurgeExecutorFactory { ContinuumPurgeExecutor create( boolean deleteAll, int daysOld, int retentionCount, String dirType ); }
4,897
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor/dir/PurgeBuilder.java
package org.apache.continuum.purge.executor.dir; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.io.DirectoryWalker; import org.apache.commons.io.filefilter.AgeFileFilter; import org.apache.commons.io.filefilter.AndFileFilter; import org.apache.commons.io.filefilter.NotFileFilter; import org.apache.commons.io.filefilter.WildcardFileFilter; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import static java.util.Collections.EMPTY_LIST; import static org.apache.commons.io.comparator.LastModifiedFileComparator.LASTMODIFIED_COMPARATOR; import static org.apache.commons.io.filefilter.DirectoryFileFilter.DIRECTORY; import static org.apache.commons.io.filefilter.FileFileFilter.FILE; import static org.apache.commons.io.filefilter.TrueFileFilter.TRUE; public class PurgeBuilder { public static Purge purge( File dir ) { return new PurgeDelegate( dir ); } } interface Purge { Purge dirs(); Purge files(); Purge namedLike( String pattern ); Purge notNamedLike( String pattern ); Purge olderThan( int ageInDays ); Purge inAgeOrder(); Purge retainLast( int min ); void executeWith( Handler handler ) throws PurgeBuilderException; List<File> list() throws PurgeBuilderException; } interface Handler { void handle( File f ); } class PurgeBuilderException extends Exception { public PurgeBuilderException( String message ) { super( message ); } } class PurgeDelegate implements Purge { private static long MILLIS_IN_DAY = 24 * 60 * 26 * 1000; private File root; boolean recursive; private int maxScanDepth = -1; private AndFileFilter filter; private Comparator<File> ordering; private int retainMin; public PurgeDelegate( File root ) { this.root = root; filter = new AndFileFilter(); filter.addFileFilter( TRUE ); retainMin = 0; } public Purge dirs() { filter.addFileFilter( DIRECTORY ); return this; } public Purge files() { filter.addFileFilter( FILE ); return this; } public Purge namedLike( String pattern ) { filter.addFileFilter( new WildcardFileFilter( pattern ) ); return this; } public Purge notNamedLike( String pattern ) { filter.addFileFilter( new NotFileFilter( new WildcardFileFilter( pattern ) ) ); return this; } public Purge olderThan( int age ) { if ( age > 0 ) { filter.addFileFilter( new AgeFileFilter( System.currentTimeMillis() - age * MILLIS_IN_DAY ) ); } return this; } @SuppressWarnings( "unchecked" ) public Purge inAgeOrder() { ordering = LASTMODIFIED_COMPARATOR; return this; } public Purge retainLast( int min ) { if ( min > 0 ) { retainMin = min; } return this; } public void executeWith( Handler handler ) throws PurgeBuilderException { for ( File file : list() ) { handler.handle( file ); } } public List<File> list() throws PurgeBuilderException { List<File> files = listRoot(); if ( retainMin > 0 ) { sort( files ); int limit = files.size() - retainMin; return limit < 0 ? EMPTY_LIST : files.subList( 0, limit ); } return files; } private void sort( List<File> files ) { if ( ordering != null ) { Collections.sort( files, ordering ); } } private List<File> listRoot() throws PurgeBuilderException { if ( !root.exists() ) { throw new PurgeBuilderException( String.format( "purge root %s does not exist", root ) ); } if ( !root.isDirectory() ) { throw new PurgeBuilderException( String.format( "purge root %s is not a directory", root ) ); } if ( !root.canRead() ) { throw new PurgeBuilderException( String.format( "purge root %s is not readable", root ) ); } if ( !recursive ) { maxScanDepth = 1; } try { return new PurgeScanner( root, filter, maxScanDepth ).scan(); } catch ( IOException e ) { throw new PurgeBuilderException( "failure during scan: " + e.getMessage() ); } } } class PurgeScanner extends DirectoryWalker { private File root; private FileFilter filter; PurgeScanner( File root, FileFilter filter, int depth ) { super( null, depth ); this.root = root; this.filter = filter; } public List<File> scan() throws IOException { List<File> scanned = new ArrayList<File>(); walk( root, scanned ); return scanned; } @Override protected void handleFile( File file, int depth, Collection results ) throws IOException { if ( filter.accept( file ) ) { results.add( file ); } } @Override protected boolean handleDirectory( File directory, int depth, Collection results ) throws IOException { if ( !root.equals( directory ) && filter.accept( directory ) ) { results.add( directory ); } return true; } }
4,898
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor/repo/RepositoryPurgeExecutorFactoryImpl.java
package org.apache.continuum.purge.executor.repo; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.purge.executor.ContinuumPurgeExecutor; import org.apache.continuum.purge.executor.ContinuumPurgeExecutorException; import org.apache.continuum.purge.repository.content.RepositoryManagedContent; import org.apache.continuum.purge.repository.scanner.RepositoryScanner; import org.apache.continuum.utils.file.FileSystemManager; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import java.io.File; import java.io.IOException; @Component( role = RepositoryPurgeExecutorFactory.class ) public class RepositoryPurgeExecutorFactoryImpl implements RepositoryPurgeExecutorFactory { @Requirement( hint = "purge" ) private RepositoryScanner scanner; @Requirement private FileSystemManager fsManager; public ContinuumPurgeExecutor create( boolean deleteAll, int daysOld, int retentionCount, boolean deleteReleasedSnapshots, RepositoryManagedContent repoContent ) { if ( deleteAll ) { return new CleanAllPurgeExecutor( fsManager ); } ContinuumPurgeExecutor executor; if ( daysOld > 0 ) { executor = new DaysOldRepositoryPurgeExecutor( repoContent, daysOld, retentionCount ); } else { executor = new RetentionCountRepositoryPurgeExecutor( repoContent, retentionCount ); } if ( deleteReleasedSnapshots ) { ContinuumPurgeExecutor snapshots = new ReleasedSnapshotsRepositoryPurgeExecutor( repoContent ); executor = new MultiplexedPurgeExecutor( snapshots, executor ); } return new ScanningPurgeExecutor( scanner, executor ); } } class CleanAllPurgeExecutor implements ContinuumPurgeExecutor { FileSystemManager fsManager; CleanAllPurgeExecutor( FileSystemManager fsManager ) { this.fsManager = fsManager; } public void purge( String path ) throws ContinuumPurgeExecutorException { try { fsManager.wipeDir( new File( path ) ); } catch ( IOException e ) { throw new ContinuumPurgeExecutorException( "failed to remove repo" + path, e ); } } }
4,899