text,length,is_long_context,metric_val,label_metric "module Esterel.Lang.CanFunction.Plug where open import Data.Nat using (_+_ ; suc) open import Function using (_∋_ ; _∘_ ; id ; _$_) open import Data.Nat.Properties.Simple using ( +-comm ; +-assoc) open import utility open import Esterel.Lang open import Esterel.Lang.Properties open import Esterel.Lang.CanFunction open import Esterel.Environment as Env open import Esterel.Context open import Esterel.Context.Properties open import Data.Product open import Data.Sum open import Data.Bool open import Data.List using ([] ; [_] ; _∷_ ; List ; _++_) open import Relation.Nullary open import Relation.Binary.PropositionalEquality using (_≡_ ; refl ; sym ; subst ; cong ; trans ; module ≡-Reasoning ; cong₂ ; subst₂ ; inspect) open import Data.Empty open import Esterel.Lang.Binding open import Data.Maybe using ( nothing ; just ) open import Data.List.Any open import Data.List.Any.Properties renaming (++⁺ˡ to ++ˡ ; ++⁺ʳ to ++ʳ ) open import Esterel.Lang.CanFunction.SetSigMonotonic open ≡-Reasoning using (_≡⟨_⟩_ ; _≡⟨⟩_ ; _∎) open import Relation.Nullary.Decidable using (⌊_⌋) open import Data.FiniteMap import Data.OrderedListMap as OMap open import Data.Nat as Nat using (ℕ) open import Esterel.Variable.Signal as Signal using (Signal ; _ₛ ; _≟ₛₜ_) open import Esterel.Variable.Shared as SharedVar using (SharedVar ; _ₛₕ) open import Esterel.Variable.Sequential as SeqVar using (SeqVar ; _ᵥ) open import Esterel.CompletionCode as Code renaming (CompletionCode to Code) open import Data.OrderedListMap Signal Signal.unwrap Signal.Status as SigM open import Data.OrderedListMap SharedVar SharedVar.unwrap (Σ SharedVar.Status (λ _ → ℕ)) as ShrM open import Data.OrderedListMap SeqVar SeqVar.unwrap ℕ as SeqM open ListSet Code._≟_ module NSet = ListSet Nat._≟_ canθₖ-plug : ∀ S' sigs → ∀ C p q → (Canₖq⊆Canₖp : ∀ θ k → k ∈ (Canₖ q θ) → k ∈ (Canₖ p θ)) → (Canₛq⊆Canₛp : ∀ θ S → S ∈ (Canₛ q θ) → S ∈ (Canₛ p θ)) → (∀ θ k → k ∈ (Canθₖ sigs S' (C ⟦ q ⟧c) θ) → k ∈ (Canθₖ sigs S' (C ⟦ p ⟧c) θ)) canθₛ-plug : ∀ S' sigs → ∀ C p q → (Canₛq⊆Canₛp : ∀ θ S → S ∈ (Canₛ q θ) → S ∈ (Canₛ p θ)) → (Canₖq⊆Canₖp : ∀ θ k → k ∈ (Canₖ q θ) → k ∈ (Canₖ p θ)) → (∀ θ k → k ∈ (Canθₛ sigs S' (C ⟦ q ⟧c) θ) → k ∈ (Canθₛ sigs S' (C ⟦ p ⟧c) θ)) canθₛₕ-plug : ∀ S' sigs → ∀ C p q → (Canₛₕq⊆Canₛₕp : ∀ θ → (Canₛₕ q θ) ⊆¹ (Canₛₕ p θ)) → (Canₛq⊆Canₛp : ∀ θ k → k ∈ (Canₖ q θ) → k ∈ (Canₖ p θ)) → (Canₖq⊆Canₖp : ∀ θ S → S ∈ (Canₛ q θ) → S ∈ (Canₛ p θ)) → (∀ θ k → k ∈ (Canθₛₕ sigs S' (C ⟦ q ⟧c) θ) → k ∈ (Canθₛₕ sigs S' (C ⟦ p ⟧c) θ)) canₛₕ-plug : ∀ C p q → (Canₛₕq⊆Canₛₕp : ∀ θ → (Canₛₕ q θ) ⊆¹ (Canₛₕ p θ)) → (∀ θ k → k ∈ (Canₖ q θ) → k ∈ (Canₖ p θ)) → (Canₛq⊆Canₛp : ∀ θ → (Canₛ q θ) ⊆¹ (Canₛ p θ)) → (∀ θ → (Canₛₕ (C ⟦ q ⟧c) θ) ⊆¹ (Canₛₕ (C ⟦ p ⟧c) θ)) canₖ-plug : ∀ C p q → (Canₖq⊆Canₖp : ∀ θ k → k ∈ (Canₖ q θ) → k ∈ (Canₖ p θ)) → (Canₛq⊆Canₛp : ∀ θ S → S ∈ (Canₛ q θ) → S ∈ (Canₛ p θ)) → (∀ θ k → k ∈ (Canₖ (C ⟦ q ⟧c) θ) → k ∈ (Canₖ (C ⟦ p ⟧c) θ)) canₛ-plug : ∀ C p q → (Canₛq⊆Canₛp : ∀ θ → (Canₛ q θ) ⊆¹ (Canₛ p θ)) → (∀ θ k → k ∈ (Canₖ q θ) → k ∈ (Canₖ p θ)) → (∀ θ → (Canₛ (C ⟦ q ⟧c) θ) ⊆¹ (Canₛ (C ⟦ p ⟧c) θ)) canθₖ-plug S' [] C p q Canₖq⊆Canₖp Canₛq⊆Canₛp = canₖ-plug C p q Canₖq⊆Canₖp Canₛq⊆Canₛp canθₖ-plug S' (just Signal.present ∷ sigs) C p q Canₖq⊆Canₖp Canₛq⊆Canₛp θ = canθₖ-plug (suc S') sigs C p q Canₖq⊆Canₖp Canₛq⊆Canₛp (θ ← _) canθₖ-plug S' (just Signal.absent ∷ sigs) C p q Canₖq⊆Canₖp Canₛq⊆Canₛp θ = canθₖ-plug (suc S') sigs C p q Canₖq⊆Canₖp Canₛq⊆Canₛp (θ ← _) canθₖ-plug S' (nothing ∷ sigs) C p q Canₖq⊆Canₖp Canₛq⊆Canₛp = canθₖ-plug (suc S') sigs C p q Canₖq⊆Canₖp Canₛq⊆Canₛp canθₖ-plug S' (just Signal.unknown ∷ sigs) C p q Canₖq⊆Canₖp Canₛq⊆Canₛp θ with any (Nat._≟_ S') (Canθₛ sigs (suc S') (C ⟦ p ⟧c) (θ ← ([S]-env (S' ₛ)))) | any (Nat._≟_ S') (Canθₛ sigs (suc S') (C ⟦ q ⟧c) (θ ← ([S]-env (S' ₛ)))) canθₖ-plug S' (just Signal.unknown ∷ sigs) C p q Canₖq⊆Canₖp Canₛq⊆Canₛp θ | yes p₁ | (yes p₂) = canθₖ-plug (suc S') sigs C p q Canₖq⊆Canₖp Canₛq⊆Canₛp (θ ← _) canθₖ-plug S' (just Signal.unknown ∷ sigs) C p q Canₖq⊆Canₖp Canₛq⊆Canₛp θ | yes p₁ | (no ¬p) with sig-←-monoʳ (S' ₛ) ([S]-env (S' ₛ)) θ (sig-∈-single (S' ₛ) Signal.unknown) ... | S'∈θ←[S]env rewrite ((θ ← [S]-env-absent (S' ₛ)) ≡ (set-sig{S' ₛ} (θ ← [S]-env (S' ₛ)) S'∈θ←[S]env Signal.absent) ∋ (θ ← [S]-env-absent (S' ₛ)) ≡⟨ cong (θ ←_) (sym (←-single-overwrite-sig (S' ₛ) Signal.unknown ([S]-env-absent (S' ₛ)) ((sig-∈-single (S' ₛ) Signal.absent)))) ⟩ (θ ← (([S]-env (S' ₛ)) ← [S]-env-absent (S' ₛ))) ≡⟨ ←-assoc θ ([S]-env (S' ₛ)) ([S]-env-absent (S' ₛ)) ⟩ ((θ ← ([S]-env (S' ₛ))) ← ([S]-env-absent (S' ₛ))) ≡⟨ sym (sig-set=← (θ ← [S]-env (S' ₛ)) (S' ₛ) Signal.absent S'∈θ←[S]env) ⟩ (set-sig{S' ₛ} (θ ← [S]-env (S' ₛ)) S'∈θ←[S]env Signal.absent) ∎) with canθₖ-set-sig-monotonic sigs (suc S') (C ⟦ q ⟧c) (S' ₛ) (θ ← [S]-env (S' ₛ)) S'∈θ←[S]env Signal.absent (trans (sig-stats-←-right-irr' (S' ₛ) θ ([S]-env (S' ₛ)) (sig-∈-single (S' ₛ) Signal.unknown) S'∈θ←[S]env) (sig-stats-1map' (S' ₛ) Signal.unknown ((sig-∈-single (S' ₛ) Signal.unknown)))) (n∉map-suc-n-+ S' (SigM.Dom' sigs)) ... | Canabsq⊂Canunq = λ k x → (canθₖ-plug (suc S') sigs C p q Canₖq⊆Canₖp Canₛq⊆Canₛp (θ ← _)) k (Canabsq⊂Canunq k x) canθₖ-plug S' (just Signal.unknown ∷ sigs) C p q Canₖq⊆Canₖp Canₛq⊆Canₛp θ | no ¬p | (yes p₁) = ⊥-elim (¬p ((canθₛ-plug (suc S') sigs C p q Canₛq⊆Canₛp Canₖq⊆Canₖp (θ ← _)) _ p₁ )) canθₖ-plug S' (just Signal.unknown ∷ sigs) C p q Canₖq⊆Canₖp Canₛq⊆Canₛp θ | no ¬p | (no ¬p₁) = canθₖ-plug (suc S') sigs C p q Canₖq⊆Canₖp Canₛq⊆Canₛp (θ ← _) canθₛ-plug S' [] C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ = canₛ-plug C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ canθₛ-plug S' (nothing ∷ sigs) C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ = canθₛ-plug (suc S') sigs C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ canθₛ-plug S' (just Signal.present ∷ sigs) C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ = canθₛ-plug (suc S') sigs C p q Canₛq⊆Canₛp Canₖq⊆Canₖp (θ ← _) canθₛ-plug S' (just Signal.absent ∷ sigs) C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ = canθₛ-plug (suc S') sigs C p q Canₛq⊆Canₛp Canₖq⊆Canₖp (θ ← _) canθₛ-plug S' (just Signal.unknown ∷ sigs) C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ with any (Nat._≟_ S') (Canθₛ sigs (suc S') (C ⟦ p ⟧c) (θ ← ([S]-env (S' ₛ)))) | any (Nat._≟_ S') (Canθₛ sigs (suc S') (C ⟦ q ⟧c) (θ ← ([S]-env (S' ₛ)))) canθₛ-plug S' (just Signal.unknown ∷ sigs) C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ | yes p₁ | (yes p₂) = canθₛ-plug (suc S') sigs C p q Canₛq⊆Canₛp Canₖq⊆Canₖp (θ ← _) canθₛ-plug S' (just Signal.unknown ∷ sigs) C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ | yes p₁ | (no ¬p) with sig-←-monoʳ (S' ₛ) ([S]-env (S' ₛ)) θ (sig-∈-single (S' ₛ) Signal.unknown) ... | S'∈θ←[S]env rewrite ((θ ← [S]-env-absent (S' ₛ)) ≡ (set-sig{S' ₛ} (θ ← [S]-env (S' ₛ)) S'∈θ←[S]env Signal.absent) ∋ (θ ← [S]-env-absent (S' ₛ)) ≡⟨ cong (θ ←_) (sym (←-single-overwrite-sig (S' ₛ) Signal.unknown ([S]-env-absent (S' ₛ)) ((sig-∈-single (S' ₛ) Signal.absent)))) ⟩ (θ ← (([S]-env (S' ₛ)) ← [S]-env-absent (S' ₛ))) ≡⟨ ←-assoc θ ([S]-env (S' ₛ)) ([S]-env-absent (S' ₛ)) ⟩ ((θ ← ([S]-env (S' ₛ))) ← ([S]-env-absent (S' ₛ))) ≡⟨ sym (sig-set=← (θ ← [S]-env (S' ₛ)) (S' ₛ) Signal.absent S'∈θ←[S]env) ⟩ (set-sig{S' ₛ} (θ ← [S]-env (S' ₛ)) S'∈θ←[S]env Signal.absent) ∎) with canθₛ-set-sig-monotonic sigs (suc S') (C ⟦ q ⟧c) (S' ₛ) (θ ← [S]-env (S' ₛ)) S'∈θ←[S]env Signal.absent (trans (sig-stats-←-right-irr' (S' ₛ) θ ([S]-env (S' ₛ)) (sig-∈-single (S' ₛ) Signal.unknown) S'∈θ←[S]env) (sig-stats-1map' (S' ₛ) Signal.unknown ((sig-∈-single (S' ₛ) Signal.unknown)))) (n∉map-suc-n-+ S' (SigM.Dom' sigs)) ... | Canabsq⊂Canunq = λ k x → (canθₛ-plug (suc S') sigs C p q Canₛq⊆Canₛp Canₖq⊆Canₖp (θ ← _)) k (Canabsq⊂Canunq k x) canθₛ-plug S' (just Signal.unknown ∷ sigs) C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ | no ¬p | (yes p₁) = ⊥-elim (¬p ((canθₛ-plug (suc S') sigs) C p q Canₛq⊆Canₛp Canₖq⊆Canₖp (θ ← _) _ p₁)) canθₛ-plug S' (just Signal.unknown ∷ sigs) C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ | no ¬p | (no ¬p₁) = canθₛ-plug (suc S') sigs C p q Canₛq⊆Canₛp Canₖq⊆Canₖp (θ ← _) canθₛₕ-plug S' [] C p q Canₛₕq⊆Canₛₕp Canₛq⊆Canₛp Canₖq⊆Canₖp θ = canₛₕ-plug C p q Canₛₕq⊆Canₛₕp Canₛq⊆Canₛp Canₖq⊆Canₖp θ canθₛₕ-plug S' (nothing ∷ sigs) C p q Canₛₕq⊆Canₛₕp Canₛq⊆Canₛp Canₖq⊆Canₖp θ = canθₛₕ-plug (suc S') sigs C p q Canₛₕq⊆Canₛₕp Canₛq⊆Canₛp Canₖq⊆Canₖp θ canθₛₕ-plug S' (just Signal.present ∷ sigs) C p q Canₛₕq⊆Canₛₕp Canₛq⊆Canₛp Canₖq⊆Canₖp θ = canθₛₕ-plug (suc S') sigs C p q Canₛₕq⊆Canₛₕp Canₛq⊆Canₛp Canₖq⊆Canₖp (θ ← _) canθₛₕ-plug S' (just Signal.absent ∷ sigs) C p q Canₛₕq⊆Canₛₕp Canₛq⊆Canₛp Canₖq⊆Canₖp θ = canθₛₕ-plug (suc S') sigs C p q Canₛₕq⊆Canₛₕp Canₛq⊆Canₛp Canₖq⊆Canₖp (θ ← _) canθₛₕ-plug S' (just Signal.unknown ∷ sigs) C p q Canₛₕq⊆Canₛₕp Canₛq⊆Canₛp Canₖq⊆Canₖp θ with any (Nat._≟_ S') (Canθₛ sigs (suc S') (C ⟦ p ⟧c) (θ ← ([S]-env (S' ₛ)))) | any (Nat._≟_ S') (Canθₛ sigs (suc S') (C ⟦ q ⟧c) (θ ← ([S]-env (S' ₛ)))) canθₛₕ-plug S' (just Signal.unknown ∷ sigs) C p q Canₛₕq⊆Canₛₕp Canₛq⊆Canₛp Canₖq⊆Canₖp θ | yes p₁ | (yes p₂) = canθₛₕ-plug (suc S') sigs C p q Canₛₕq⊆Canₛₕp Canₛq⊆Canₛp Canₖq⊆Canₖp (θ ← _) canθₛₕ-plug S' (just Signal.unknown ∷ sigs) C p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp Canₛq⊆Canₛp θ | yes p₁ | (no ¬p) with sig-←-monoʳ (S' ₛ) ([S]-env (S' ₛ)) θ (sig-∈-single (S' ₛ) Signal.unknown) ... | S'∈θ←[S]env rewrite ((θ ← [S]-env-absent (S' ₛ)) ≡ (set-sig{S' ₛ} (θ ← [S]-env (S' ₛ)) S'∈θ←[S]env Signal.absent) ∋ (θ ← [S]-env-absent (S' ₛ)) ≡⟨ cong (θ ←_) (sym (←-single-overwrite-sig (S' ₛ) Signal.unknown ([S]-env-absent (S' ₛ)) ((sig-∈-single (S' ₛ) Signal.absent)))) ⟩ (θ ← (([S]-env (S' ₛ)) ← [S]-env-absent (S' ₛ))) ≡⟨ ←-assoc θ ([S]-env (S' ₛ)) ([S]-env-absent (S' ₛ)) ⟩ ((θ ← ([S]-env (S' ₛ))) ← ([S]-env-absent (S' ₛ))) ≡⟨ sym (sig-set=← (θ ← [S]-env (S' ₛ)) (S' ₛ) Signal.absent S'∈θ←[S]env) ⟩ (set-sig{S' ₛ} (θ ← [S]-env (S' ₛ)) S'∈θ←[S]env Signal.absent) ∎) with canθₛₕ-set-sig-monotonic sigs (suc S') (C ⟦ q ⟧c) (S' ₛ) (θ ← [S]-env (S' ₛ)) S'∈θ←[S]env Signal.absent (trans (sig-stats-←-right-irr' (S' ₛ) θ ([S]-env (S' ₛ)) (sig-∈-single (S' ₛ) Signal.unknown) S'∈θ←[S]env) (sig-stats-1map' (S' ₛ) Signal.unknown ((sig-∈-single (S' ₛ) Signal.unknown)))) (n∉map-suc-n-+ S' (SigM.Dom' sigs)) ... | Canabsq⊂Canunq = λ k x → (canθₛₕ-plug (suc S') sigs C p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp Canₛq⊆Canₛp (θ ← _)) k (Canabsq⊂Canunq k x) canθₛₕ-plug S' (just Signal.unknown ∷ sigs) C p q Canₛₕq⊆Canₛₕp Canₛq⊆Canₛp Canₖq⊆Canₖp θ | no ¬p | (yes p₁) = ⊥-elim (¬p (canθₛ-plug (suc S') sigs C p q Canₖq⊆Canₖp Canₛq⊆Canₛp (θ ← _) _ p₁)) canθₛₕ-plug S' (just Signal.unknown ∷ sigs) C p q Canₛₕq⊆Canₛₕp Canₛq⊆Canₛp Canₖq⊆Canₖp θ | no ¬p | (no ¬p₁) = canθₛₕ-plug (suc S') sigs C p q Canₛₕq⊆Canₛₕp Canₛq⊆Canₛp Canₖq⊆Canₖp (θ ← _) canₖ-plug [] p q Canₖq⊆Canₖp _ = Canₖq⊆Canₖp canₖ-plug (ceval (epar₁ q) ∷ C) p q₁ Canₖq⊆Canₖp ⊂s θ = map-mono² Code._⊔_ (canₖ-plug C p q₁ Canₖq⊆Canₖp ⊂s θ) (λ x y → y) canₖ-plug (ceval (epar₂ p) ∷ C) p₁ q Canₖq⊆Canₖp ⊂s θ = map-mono²{xs = Canₖ p θ} Code._⊔_ (λ x y → y) (canₖ-plug C p₁ q Canₖq⊆Canₖp ⊂s θ) canₖ-plug (ceval (eloopˢ q) ∷ C) p q₁ Canₖq⊆Canₖp ⊂s θ = canₖ-plug C p q₁ Canₖq⊆Canₖp ⊂s θ canₖ-plug (ceval (eseq q) ∷ C) p q₁ Canₖq⊆Canₖp ⊂s θ with any (Code.nothin Code.≟_) (Canₖ (C ⟦ p ⟧c) θ) | any (Code.nothin Code.≟_) (Canₖ (C ⟦ q₁ ⟧c) θ) ... | yes 0∈CanC⟦p⟧ | yes 0∈CanC⟦q⟧ = codesub++both ((codesub- Code.nothin (canₖ-plug C p q₁ Canₖq⊆Canₖp ⊂s θ))) (λ x y → y) ... | yes 0∈CanC⟦p⟧ | no 0∉CanC⟦q⟧ = λ k x → ++ˡ (set-remove-not-removed{Code.nothin}{k} (λ {refl → 0∉CanC⟦q⟧ x}) (canₖ-plug C p q₁ Canₖq⊆Canₖp ⊂s θ _ x)) ... | no 0∉CanC⟦p⟧ | yes 0∈CanC⟦q⟧ = ⊥-elim (0∉CanC⟦p⟧ (canₖ-plug C p q₁ Canₖq⊆Canₖp ⊂s θ _ 0∈CanC⟦q⟧)) ... | no 0∉CanC⟦p⟧ | no 0∉CanC⟦q⟧ = canₖ-plug C p q₁ Canₖq⊆Canₖp ⊂s θ canₖ-plug (ceval (esuspend S) ∷ C) p q Canₖq⊆Canₖp ⊂s = canₖ-plug C p q Canₖq⊆Canₖp ⊂s canₖ-plug (ceval etrap ∷ C) p q Canₖq⊆Canₖp ⊂s = λ θ → map-mono Code.↓* (canₖ-plug C p q Canₖq⊆Canₖp ⊂s θ) canₖ-plug (csignl S ∷ C) p q Canₖq⊆Canₖp ⊂s θ = canθₖ-plug 0 (sig ([S]-env S)) C p q Canₖq⊆Canₖp ⊂s θ canₖ-plug (cpresent₁ S q ∷ C) p q₁ Canₖq⊆Canₖp ⊂s θ with Sig∈ S θ ... | no S∉Domθ = codesub++both (canₖ-plug C p q₁ Canₖq⊆Canₖp ⊂s θ) (λ x y → y) ... | yes S∈Domθ with (Signal.present ≟ₛₜ (sig-stats{S} θ S∈Domθ)) ... | yes _ = canₖ-plug C p q₁ Canₖq⊆Canₖp ⊂s θ ... | no _ with (Signal.absent ≟ₛₜ (sig-stats{S} θ S∈Domθ)) ... | yes _ = λ k z → z ... | no _ = codesub++both (canₖ-plug C p q₁ Canₖq⊆Canₖp ⊂s θ) (λ x y → y) canₖ-plug (cpresent₂ S p₁ ∷ C) p q Canₖq⊆Canₖp ⊂s θ with Sig∈ S θ ... | no S∉Domθ = codesub++both{a = Canₖ p₁ θ} (λ x y → y) (canₖ-plug C p q Canₖq⊆Canₖp ⊂s θ) ... | yes S∈Domθ with (Signal.present ≟ₛₜ (sig-stats{S} θ S∈Domθ)) ... | yes _ = λ x y → y ... | no _ with (Signal.absent ≟ₛₜ (sig-stats{S} θ S∈Domθ)) ... | yes _ = canₖ-plug C p q Canₖq⊆Canₖp ⊂s θ ... | no _ = codesub++both{a = Canₖ p₁ θ} (λ x y → y) (canₖ-plug C p q Canₖq⊆Canₖp ⊂s θ) canₖ-plug (cloop ∷ C) p q Canₖq⊆Canₖp ⊂s = (canₖ-plug C p q Canₖq⊆Canₖp ⊂s) canₖ-plug (cloopˢ₂ p ∷ C) p₁ q Canₖq⊆Canₖp ⊂s θ = λ k z → z canₖ-plug (cseq₂ p ∷ C) p₁ q Canₖq⊆Canₖp ⊂s θ with any (Code.nothin Code.≟_) (Canₖ p θ) ... | yes 0∈Canp = codesub++both{a = set-remove (Canₖ p θ) Code.nothin } (λ x y → y) (canₖ-plug C p₁ q Canₖq⊆Canₖp ⊂s θ) ... | no 0∉Canp = λ x y → y canₖ-plug (cshared s e ∷ C) p q Canₖq⊆Canₖp ⊂s = (canₖ-plug C p q Canₖq⊆Canₖp ⊂s) canₖ-plug (cvar x e ∷ C) p q Canₖq⊆Canₖp ⊂s = (canₖ-plug C p q Canₖq⊆Canₖp ⊂s) canₖ-plug (cif₁ x q ∷ C) p q₁ Canₖq⊆Canₖp ⊂s θ = codesub++both (canₖ-plug C p q₁ Canₖq⊆Canₖp ⊂s θ) (λ x y → y) canₖ-plug (cif₂ x p ∷ C) p₁ q Canₖq⊆Canₖp ⊂s θ = codesub++both{a = Canₖ p θ} (λ x y → y) (canₖ-plug C p₁ q Canₖq⊆Canₖp ⊂s θ) canₖ-plug (cenv θ₁ A ∷ C) p q Canₖq⊆Canₖp ⊂s θ = canθₖ-plug 0 (sig θ₁) C p q Canₖq⊆Canₖp ⊂s θ canₛ-plug [] p q Canₛq⊆Canₛp Canₖq⊆Canₖp = Canₛq⊆Canₛp canₛ-plug (ceval (epar₁ q) ∷ C) p q₁ Canₛq⊆Canₛp Canₖq⊆Canₖp θ = ∪¹-respect-⊆¹-left (canₛ-plug C p q₁ Canₛq⊆Canₛp Canₖq⊆Canₖp θ) canₛ-plug (ceval (epar₂ p) ∷ C) p₁ q Canₛq⊆Canₛp Canₖq⊆Canₖp θ = ∪¹-respect-⊆¹-right (Canₛ p θ) (canₛ-plug C p₁ q Canₛq⊆Canₛp Canₖq⊆Canₖp θ) canₛ-plug (ceval (eloopˢ q) ∷ C) p q₁ Canₛq⊆Canₛp Canₖq⊆Canₖp θ = canₛ-plug C p q₁ Canₛq⊆Canₛp Canₖq⊆Canₖp θ canₛ-plug (ceval (eseq q) ∷ C) p q₁ Canₛq⊆Canₛp Canₖq⊆Canₖp θ with any (Code.nothin Code.≟_) (Canₖ (C ⟦ p ⟧c) θ) | any (Code.nothin Code.≟_) (Canₖ (C ⟦ q₁ ⟧c) θ) ... | yes 0∈CanC⟦p⟧ | yes 0∈CanC⟦q⟧ = ∪¹-respect-⊆¹-left (canₛ-plug C p q₁ Canₛq⊆Canₛp Canₖq⊆Canₖp θ) ... | yes 0∈CanC⟦p⟧ | no 0∉CanC⟦q⟧ = λ S x → (++ˡ (canₛ-plug C p q₁ Canₛq⊆Canₛp Canₖq⊆Canₖp θ S x)) ... | no 0∉CanC⟦p⟧ | yes 0∈CanC⟦q⟧ = ⊥-elim (0∉CanC⟦p⟧ (canₖ-plug C p q₁ Canₖq⊆Canₖp Canₛq⊆Canₛp θ _ 0∈CanC⟦q⟧)) ... | no 0∉CanC⟦p⟧ | no 0∉CanC⟦q⟧ = (canₛ-plug C p q₁ Canₛq⊆Canₛp Canₖq⊆Canₖp θ) -- set-subtract-merge : ∀ {xs ys z} → z ∈ set-subtract xs ys → (z ∈ xs) × (z ∉ ys) canₛ-plug (ceval (esuspend S) ∷ C) p q Canₛq⊆Canₛp Canₖq⊆Canₖp = (canₛ-plug C p q Canₛq⊆Canₛp Canₖq⊆Canₖp) canₛ-plug (ceval etrap ∷ C) p q Canₛq⊆Canₛp Canₖq⊆Canₖp = (canₛ-plug C p q Canₛq⊆Canₛp Canₖq⊆Canₖp) canₛ-plug (csignl (S ₛ) ∷ C) p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ S' S'∈CanC⟦q⟧ = NSet.set-remove-not-removed ((¬ S ≡ S') ∋ NSet.set-remove-not-eq{S'}{S}{Canθₛ (sig ([S]-env (S ₛ))) 0 (C ⟦ q ⟧c) θ} S'∈CanC⟦q⟧) ((canθₛ-plug 0 (sig ([S]-env (S ₛ))) C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ) S' ( (NSet.set-remove-mono-∈ S S'∈CanC⟦q⟧) )) canₛ-plug (cpresent₁ S q ∷ C) p q₁ Canₛq⊆Canₛp Canₖq⊆Canₖp θ with Sig∈ S θ ... | no S∉Domθ = ∪¹-respect-⊆¹-left (canₛ-plug C p q₁ Canₛq⊆Canₛp Canₖq⊆Canₖp θ) ... | yes S∈Domθ with (Signal.present ≟ₛₜ (sig-stats{S} θ S∈Domθ)) ... | yes _ = (canₛ-plug C p q₁ Canₛq⊆Canₛp Canₖq⊆Canₖp θ) ... | no _ with (Signal.absent ≟ₛₜ (sig-stats{S} θ S∈Domθ)) ... | yes _ = λ k z → z ... | no _ = ∪¹-respect-⊆¹-left (canₛ-plug C p q₁ Canₛq⊆Canₛp Canₖq⊆Canₖp θ) canₛ-plug (cpresent₂ S p₁ ∷ C) p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ with Sig∈ S θ ... | no S∉Domθ = ∪¹-respect-⊆¹-right (Canₛ p₁ θ) (canₛ-plug C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ) ... | yes S∈Domθ with (Signal.present ≟ₛₜ (sig-stats{S} θ S∈Domθ)) ... | yes _ = λ x y → y ... | no _ with (Signal.absent ≟ₛₜ (sig-stats{S} θ S∈Domθ)) ... | yes _ = (canₛ-plug C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ) ... | no _ = ∪¹-respect-⊆¹-right (Canₛ p₁ θ) (canₛ-plug C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ) canₛ-plug (cloop ∷ C) p q Canₛq⊆Canₛp Canₖq⊆Canₖp = (canₛ-plug C p q Canₛq⊆Canₛp Canₖq⊆Canₖp) canₛ-plug (cloopˢ₂ p ∷ C) p₁ q Canₛq⊆Canₛp Canₖq⊆Canₖp θ = λ x z → z canₛ-plug (cseq₂ p ∷ C) p₁ q Canₛq⊆Canₛp Canₖq⊆Canₖp θ with any (Code.nothin Code.≟_) (Canₖ p θ) ... | yes 0∈Canp = ∪¹-respect-⊆¹-right (Canₛ p θ) (canₛ-plug C p₁ q Canₛq⊆Canₛp Canₖq⊆Canₖp θ) ... | no 0∉Canp = λ x y → y canₛ-plug (cshared s e ∷ C) p q Canₛq⊆Canₛp Canₖq⊆Canₖp = (canₛ-plug C p q Canₛq⊆Canₛp Canₖq⊆Canₖp) canₛ-plug (cvar x e ∷ C) p q Canₛq⊆Canₛp Canₖq⊆Canₖp = (canₛ-plug C p q Canₛq⊆Canₛp Canₖq⊆Canₖp) canₛ-plug (cif₁ x q ∷ C) p q₁ Canₛq⊆Canₛp Canₖq⊆Canₖp θ = ∪¹-respect-⊆¹-left (canₛ-plug C p q₁ Canₛq⊆Canₛp Canₖq⊆Canₖp θ) canₛ-plug (cif₂ x p ∷ C) p₁ q Canₛq⊆Canₛp Canₖq⊆Canₖp θ = ∪¹-respect-⊆¹-right (Canₛ p θ) (canₛ-plug C p₁ q Canₛq⊆Canₛp Canₖq⊆Canₖp θ) canₛ-plug (cenv θ₁ A ∷ C) p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ = ⊆¹-respect-|¹ (fst $ Dom θ₁) (canθₛ-plug 0 (sig θ₁) C p q Canₛq⊆Canₛp Canₖq⊆Canₖp θ) canₛₕ-plug [] p q Canₛₕq⊆Canₛₕp Canₖₕq⊆Canₖₕp ⊂S = Canₛₕq⊆Canₛₕp canₛₕ-plug (ceval (epar₁ q) ∷ C) p q₁ Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ = ∪¹-respect-⊆¹-left (canₛₕ-plug C p q₁ Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ) canₛₕ-plug (ceval (epar₂ p) ∷ C) p₁ q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ = ∪¹-respect-⊆¹-right (Canₛₕ p θ) (canₛₕ-plug C p₁ q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ) canₛₕ-plug (ceval (eloopˢ q) ∷ C) p q₁ Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ = canₛₕ-plug C p q₁ Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ canₛₕ-plug (ceval (eseq q) ∷ C) p q₁ Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ with any (Code.nothin Code.≟_) (Canₖ (C ⟦ p ⟧c) θ) | any (Code.nothin Code.≟_) (Canₖ (C ⟦ q₁ ⟧c) θ) ... | yes 0∈CanC⟦p⟧ | yes 0∈CanC⟦q⟧ = ∪¹-respect-⊆¹-left (canₛₕ-plug C p q₁ Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ) ... | yes 0∈CanC⟦p⟧ | no 0∉CanC⟦q⟧ = λ S x → (++ˡ (canₛₕ-plug C p q₁ Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ S x)) ... | no 0∉CanC⟦p⟧ | yes 0∈CanC⟦q⟧ = ⊥-elim (0∉CanC⟦p⟧ (canₖ-plug C p q₁ Canₖq⊆Canₖp ⊂S θ _ 0∈CanC⟦q⟧)) ... | no 0∉CanC⟦p⟧ | no 0∉CanC⟦q⟧ = (canₛₕ-plug C p q₁ Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ) canₛₕ-plug (ceval (esuspend S) ∷ C) p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S = (canₛₕ-plug C p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S) canₛₕ-plug (ceval etrap ∷ C) p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S = (canₛₕ-plug C p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S) canₛₕ-plug (csignl S ∷ C) p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ = canθₛₕ-plug 0 (sig ([S]-env S)) C p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ canₛₕ-plug (cpresent₁ S q ∷ C) p q₁ Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ with Sig∈ S θ ... | no S∉Domθ = ∪¹-respect-⊆¹-left (canₛₕ-plug C p q₁ Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ) ... | yes S∈Domθ with (Signal.present ≟ₛₜ (sig-stats{S} θ S∈Domθ)) ... | yes _ = (canₛₕ-plug C p q₁ Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ) ... | no _ with (Signal.absent ≟ₛₜ (sig-stats{S} θ S∈Domθ)) ... | yes _ = λ k z → z ... | no _ = ∪¹-respect-⊆¹-left (canₛₕ-plug C p q₁ Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ) canₛₕ-plug (cpresent₂ S p₁ ∷ C) p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ with Sig∈ S θ ... | no S∉Domθ = ∪¹-respect-⊆¹-right (Canₛₕ p₁ θ) (canₛₕ-plug C p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ) ... | yes S∈Domθ with (Signal.present ≟ₛₜ (sig-stats{S} θ S∈Domθ)) ... | yes _ = λ x y → y ... | no _ with (Signal.absent ≟ₛₜ (sig-stats{S} θ S∈Domθ)) ... | yes _ = (canₛₕ-plug C p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ) ... | no _ = ∪¹-respect-⊆¹-right (Canₛₕ p₁ θ) (canₛₕ-plug C p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ) canₛₕ-plug (cloop ∷ C) p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S = (canₛₕ-plug C p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S) canₛₕ-plug (cloopˢ₂ p ∷ C) p₁ q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ = λ x z → z canₛₕ-plug (cseq₂ p ∷ C) p₁ q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ with any (Code.nothin Code.≟_) (Canₖ p θ) ... | yes 0∈Canp = ∪¹-respect-⊆¹-right (Canₛₕ p θ) (canₛₕ-plug C p₁ q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ) ... | no 0∉Canp = λ x y → y canₛₕ-plug (cshared (s ₛₕ) e ∷ C) p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ s' s'∈CanC⟦q⟧ = NSet.set-remove-not-removed ((¬ s ≡ s') ∋ NSet.set-remove-not-eq{s'}{s}{Canₛₕ (C ⟦ q ⟧c) θ} s'∈CanC⟦q⟧) (canₛₕ-plug C p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ s' (NSet.set-remove-mono-∈ s s'∈CanC⟦q⟧)) canₛₕ-plug (cvar x e ∷ C) p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S = (canₛₕ-plug C p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S) canₛₕ-plug (cif₁ x q ∷ C) p q₁ Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ = ∪¹-respect-⊆¹-left (canₛₕ-plug C p q₁ Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ) canₛₕ-plug (cif₂ x p ∷ C) p₁ q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ = ∪¹-respect-⊆¹-right (Canₛₕ p θ) (canₛₕ-plug C p₁ q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ) canₛₕ-plug (cenv θ₁ A ∷ C) p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ = ⊆¹-respect-|¹ (snd $ Dom θ₁) (canθₛₕ-plug 0 (sig θ₁) C p q Canₛₕq⊆Canₛₕp Canₖq⊆Canₖp ⊂S θ) canθₖ-plugE : ∀ S' sigs → ∀ E p q → (Canₖq⊆Canₖp : ∀ θ k → k ∈ (Canₖ q θ) → k ∈ (Canₖ p θ)) → (Canₛq⊆Canₛp : ∀ θ S → S ∈ (Canₛ q θ) → S ∈ (Canₛ p θ)) → (∀ θ k → k ∈ (Canθₖ sigs S' (E ⟦ q ⟧e) θ) → k ∈ (Canθₖ sigs S' (E ⟦ p ⟧e) θ)) canθₖ-plugE S' sigs E p q with canθₖ-plug S' sigs (Data.List.map ceval E) p q ... | r rewrite unplugc (⟦⟧e-to-⟦⟧c (Erefl{E}{q})) | unplugc (⟦⟧e-to-⟦⟧c (Erefl{E}{p})) = r canθₛ-plugE : ∀ S' sigs → ∀ E p q → (Canₛq⊆Canₛp : ∀ θ S → S ∈ (Canₛ q θ) → S ∈ (Canₛ p θ)) → (Canₖq⊆Canₖp : ∀ θ k → k ∈ (Canₖ q θ) → k ∈ (Canₖ p θ)) → (∀ θ k → k ∈ (Canθₛ sigs S' (E ⟦ q ⟧e) θ) → k ∈ (Canθₛ sigs S' (E ⟦ p ⟧e) θ)) canθₛ-plugE S' sigs E p q with canθₛ-plug S' sigs (Data.List.map ceval E) p q ... | r rewrite unplugc (⟦⟧e-to-⟦⟧c (Erefl{E}{q})) | unplugc (⟦⟧e-to-⟦⟧c (Erefl{E}{p})) = r canθₛₕ-plugE : ∀ S' sigs → ∀ E p q → (Canₛₕq⊆Canₛₕp : ∀ θ → (Canₛₕ q θ) ⊆¹ (Canₛₕ p θ)) → (Canₛq⊆Canₛp : ∀ θ k → k ∈ (Canₖ q θ) → k ∈ (Canₖ p θ)) → (Canₖq⊆Canₖp : ∀ θ S → S ∈ (Canₛ q θ) → S ∈ (Canₛ p θ)) → (∀ θ k → k ∈ (Canθₛₕ sigs S' (E ⟦ q ⟧e) θ) → k ∈ (Canθₛₕ sigs S' (E ⟦ p ⟧e) θ)) canθₛₕ-plugE S' sigs E p q with canθₛₕ-plug S' sigs (Data.List.map ceval E) p q ... | r rewrite unplugc (⟦⟧e-to-⟦⟧c (Erefl{E}{q})) | unplugc (⟦⟧e-to-⟦⟧c (Erefl{E}{p})) = r ",12421,True,3008.0102386974067,median "------------------------------------------------------------------------ -- A variant of the propositional truncation operator with an erased -- truncation constructor ------------------------------------------------------------------------ -- Partly following the HoTT book, but adapted for erasure. {-# OPTIONS --erased-cubical --safe #-} -- The module is parametrised by a notion of equality. The higher -- constructor of the HIT defining the propositional truncation -- operator uses path equality, but the supplied notion of equality is -- used for many other things. import Equality.Path as P module H-level.Truncation.Propositional.Erased {e⁺} (eq : ∀ {a p} → P.Equality-with-paths a p e⁺) where open P.Derived-definitions-and-properties eq hiding (elim) open import Prelude as P open import Logical-equivalence using (_⇔_) open import Bijection equality-with-J as Bijection using (_↔_) import Colimit.Sequential.Very-erased eq as C open import Embedding equality-with-J as Emb using (Is-embedding) open import Equality.Decidable-UIP equality-with-J open import Equality.Path.Isomorphisms eq open import Equivalence equality-with-J as Eq using (_≃_; Is-equivalence) open import Equivalence.Erased equality-with-J as EEq using (_≃ᴱ_; Is-equivalenceᴱ) open import Equivalence.Erased.Contractible-preimages equality-with-J as ECP using (Contractibleᴱ; _⁻¹ᴱ_) open import Equivalence-relation equality-with-J open import Erased.Cubical eq as Er using (Erased; [_]; erased; Very-stableᴱ-≡; Erased-singleton) open import Function-universe equality-with-J as F hiding (id; _∘_) open import H-level equality-with-J as H-level open import H-level.Closure equality-with-J open import H-level.Truncation.Propositional.One-step eq as O using (∥_∥¹-out-^) import H-level.Truncation.Propositional.Non-recursive.Erased eq as N open import Monad equality-with-J open import Preimage equality-with-J using (_⁻¹_) open import Surjection equality-with-J as S using (_↠_; Split-surjective) private variable a b ℓ p r : Level A A₁ A₂ B B₁ B₂ C : Type a P Q : A → Type p R : A → A → Type r f g k x y : A ------------------------------------------------------------------------ -- The type former -- A propositional truncation operator with an erased higher -- constructor. data ∥_∥ᴱ (A : Type a) : Type a where ∣_∣ : A → ∥ A ∥ᴱ @0 truncation-is-propositionᴾ : P.Is-proposition ∥ A ∥ᴱ -- The truncation produces propositions (in erased contexts). @0 truncation-is-proposition : Is-proposition ∥ A ∥ᴱ truncation-is-proposition = _↔_.from (H-level↔H-level 1) truncation-is-propositionᴾ ------------------------------------------------------------------------ -- Eliminators -- A dependent eliminator, expressed using paths. record Elimᴾ′ {A : Type a} (P : ∥ A ∥ᴱ → Type p) : Type (a ⊔ p) where no-eta-equality field ∣∣ʳ : (x : A) → P ∣ x ∣ @0 truncation-is-propositionʳ : (p : P x) (q : P y) → P.[ (λ i → P (truncation-is-propositionᴾ x y i)) ] p ≡ q open Elimᴾ′ public elimᴾ′ : Elimᴾ′ P → (x : ∥ A ∥ᴱ) → P x elimᴾ′ {A = A} {P = P} e = helper where module E = Elimᴾ′ e helper : (x : ∥ A ∥ᴱ) → P x helper ∣ x ∣ = E.∣∣ʳ x helper (truncation-is-propositionᴾ x y i) = E.truncation-is-propositionʳ (helper x) (helper y) i -- A possibly more useful dependent eliminator, expressed using paths. record Elimᴾ {A : Type a} (P : ∥ A ∥ᴱ → Type p) : Type (a ⊔ p) where no-eta-equality field ∣∣ʳ : (x : A) → P ∣ x ∣ @0 truncation-is-propositionʳ : (x : ∥ A ∥ᴱ) → P.Is-proposition (P x) open Elimᴾ public elimᴾ : Elimᴾ P → (x : ∥ A ∥ᴱ) → P x elimᴾ e = elimᴾ′ λ where .∣∣ʳ → E.∣∣ʳ .truncation-is-propositionʳ _ _ → P.heterogeneous-irrelevance E.truncation-is-propositionʳ where module E = Elimᴾ e -- A non-dependent eliminator, expressed using paths. record Recᴾ (A : Type a) (B : Type b) : Type (a ⊔ b) where no-eta-equality field ∣∣ʳ : A → B @0 truncation-is-propositionʳ : P.Is-proposition B open Recᴾ public recᴾ : Recᴾ A B → ∥ A ∥ᴱ → B recᴾ r = elimᴾ λ where .∣∣ʳ → R.∣∣ʳ .truncation-is-propositionʳ _ → R.truncation-is-propositionʳ where module R = Recᴾ r -- A dependently typed eliminator. record Elim {A : Type a} (P : ∥ A ∥ᴱ → Type p) : Type (a ⊔ p) where no-eta-equality field ∣∣ʳ : (x : A) → P ∣ x ∣ @0 truncation-is-propositionʳ : (x : ∥ A ∥ᴱ) → Is-proposition (P x) open Elim public elim : Elim P → (x : ∥ A ∥ᴱ) → P x elim e = elimᴾ λ where .∣∣ʳ → E.∣∣ʳ .truncation-is-propositionʳ → _↔_.to (H-level↔H-level 1) ∘ E.truncation-is-propositionʳ where module E = Elim e -- Primitive ""recursion"". record Rec (A : Type a) (B : Type b) : Type (a ⊔ b) where no-eta-equality field ∣∣ʳ : A → B @0 truncation-is-propositionʳ : Is-proposition B open Rec public rec : Rec A B → ∥ A ∥ᴱ → B rec r = recᴾ λ where .∣∣ʳ → R.∣∣ʳ .truncation-is-propositionʳ → _↔_.to (H-level↔H-level 1) R.truncation-is-propositionʳ where module R = Rec r ------------------------------------------------------------------------ -- Conversion functions -- ∥_∥ᴱ is pointwise equivalent to N.∥_∥ᴱ. ∥∥ᴱ≃∥∥ᴱ : ∥ A ∥ᴱ ≃ N.∥ A ∥ᴱ ∥∥ᴱ≃∥∥ᴱ = Eq.↔→≃ (rec λ where .∣∣ʳ → N.∣_∣ .truncation-is-propositionʳ → N.∥∥ᴱ-proposition) (N.elim λ where .N.∣∣ʳ → ∣_∣ .N.is-propositionʳ _ → truncation-is-proposition) (N.elim λ where .N.∣∣ʳ _ → refl _ .N.is-propositionʳ _ → mono₁ 1 N.∥∥ᴱ-proposition) (elim λ where .∣∣ʳ _ → refl _ .truncation-is-propositionʳ _ → mono₁ 1 truncation-is-proposition) ------------------------------------------------------------------------ -- Some preservation lemmas and related results -- A map function. ∥∥ᴱ-map : (A → B) → ∥ A ∥ᴱ → ∥ B ∥ᴱ ∥∥ᴱ-map f = rec λ where .∣∣ʳ → ∣_∣ ∘ f .truncation-is-propositionʳ → truncation-is-proposition mutual -- If A and B are logically equivalent, then there is an equivalence -- with erased proofs between ∥ A ∥ᴱ and ∥ B ∥ᴱ. ∥∥ᴱ-cong-⇔ : A ⇔ B → ∥ A ∥ᴱ ≃ᴱ ∥ B ∥ᴱ ∥∥ᴱ-cong-⇔ A⇔B = ∥∥ᴱ-cong-⇔′ (∣_∣ ∘ _⇔_.to A⇔B) (∣_∣ ∘ _⇔_.from A⇔B) -- A variant of the previous result. ∥∥ᴱ-cong-⇔′ : (A → ∥ B ∥ᴱ) → (B → ∥ A ∥ᴱ) → ∥ A ∥ᴱ ≃ᴱ ∥ B ∥ᴱ ∥∥ᴱ-cong-⇔′ A→∥B∥ B→∥A∥ = EEq.⇔→≃ᴱ truncation-is-proposition truncation-is-proposition (rec λ where .∣∣ʳ → A→∥B∥ .truncation-is-propositionʳ → truncation-is-proposition) (rec λ where .∣∣ʳ → B→∥A∥ .truncation-is-propositionʳ → truncation-is-proposition) -- If there is a split surjection from A to B, then there is a split -- surjection from ∥ A ∥ᴱ to ∥ B ∥ᴱ. ∥∥ᴱ-cong-↠ : A ↠ B → ∥ A ∥ᴱ ↠ ∥ B ∥ᴱ ∥∥ᴱ-cong-↠ A↠B = record { logical-equivalence = record { to = ∥∥ᴱ-map (_↠_.to A↠B) ; from = ∥∥ᴱ-map (_↠_.from A↠B) } ; right-inverse-of = elim λ where .∣∣ʳ x → ∣ _↠_.to A↠B (_↠_.from A↠B x) ∣ ≡⟨ cong ∣_∣ (_↠_.right-inverse-of A↠B x) ⟩∎ ∣ x ∣ ∎ .truncation-is-propositionʳ _ → mono₁ 1 truncation-is-proposition } private ∥∥ᴱ-cong-↔ : A ↔ B → ∥ A ∥ᴱ ↔ ∥ B ∥ᴱ ∥∥ᴱ-cong-↔ A↔B = record { surjection = ∥∥ᴱ-cong-↠ (_↔_.surjection A↔B) ; left-inverse-of = elim λ where .∣∣ʳ x → ∣ _↔_.from A↔B (_↔_.to A↔B x) ∣ ≡⟨ cong ∣_∣ (_↔_.left-inverse-of A↔B x) ⟩∎ ∣ x ∣ ∎ .truncation-is-propositionʳ _ → mono₁ 1 truncation-is-proposition } -- The truncation operator preserves ""symmetric"" functions. ∥∥ᴱ-cong : A ↝[ ⌊ k ⌋-sym ] B → ∥ A ∥ᴱ ↝[ ⌊ k ⌋-sym ] ∥ B ∥ᴱ ∥∥ᴱ-cong {k = logical-equivalence} = _≃ᴱ_.logical-equivalence ∘ ∥∥ᴱ-cong-⇔ ∥∥ᴱ-cong {k = bijection} = ∥∥ᴱ-cong-↔ ∥∥ᴱ-cong {k = equivalence} = from-isomorphism ∘ ∥∥ᴱ-cong-↔ ∘ from-isomorphism ∥∥ᴱ-cong {k = equivalenceᴱ} = ∥∥ᴱ-cong-⇔ ∘ _≃ᴱ_.logical-equivalence ------------------------------------------------------------------------ -- Some bijections/erased equivalences -- If the underlying type is a proposition, then truncations of the -- type are isomorphic to the type itself. ∥∥ᴱ↔ : @0 Is-proposition A → ∥ A ∥ᴱ ↔ A ∥∥ᴱ↔ A-prop = record { surjection = record { logical-equivalence = record { to = rec λ where .∣∣ʳ → id .truncation-is-propositionʳ → A-prop ; from = ∣_∣ } ; right-inverse-of = λ _ → refl _ } ; left-inverse-of = elim λ where .∣∣ʳ _ → refl _ .truncation-is-propositionʳ _ → mono₁ 1 truncation-is-proposition } -- If A is merely inhabited, then the truncation of A is equivalent -- (with erased proofs) to the unit type. inhabited⇒∥∥ᴱ≃ᴱ⊤ : ∥ A ∥ᴱ → ∥ A ∥ᴱ ≃ᴱ ⊤ inhabited⇒∥∥ᴱ≃ᴱ⊤ ∥a∥ = EEq.inhabited→Is-proposition→≃ᴱ⊤ ∥a∥ truncation-is-proposition -- If A is not inhabited, then the propositional truncation of A is -- isomorphic to the empty type. not-inhabited⇒∥∥ᴱ↔⊥ : ¬ A → ∥ A ∥ᴱ ↔ ⊥ {ℓ = ℓ} not-inhabited⇒∥∥ᴱ↔⊥ {A = A} = ¬ A ↝⟨ (λ ¬a → rec λ where .∣∣ʳ → ¬a .truncation-is-propositionʳ → ⊥-propositional) ⟩ ¬ ∥ A ∥ᴱ ↝⟨ inverse ∘ Bijection.⊥↔uninhabited ⟩□ ∥ A ∥ᴱ ↔ ⊥ □ -- The negation of the truncation of A is isomorphic to the negation -- of A. ¬∥∥ᴱ↔¬ : ¬ ∥ A ∥ᴱ ↔ ¬ A ¬∥∥ᴱ↔¬ {A = A} = record { surjection = record { logical-equivalence = record { to = λ f → f ∘ ∣_∣ ; from = λ ¬A → rec λ where .∣∣ʳ → ¬A .truncation-is-propositionʳ → ⊥-propositional } ; right-inverse-of = λ _ → ¬-propositional ext _ _ } ; left-inverse-of = λ _ → ¬-propositional ext _ _ } -- A form of idempotence for binary sums. idempotent : ∥ A ⊎ A ∥ᴱ ≃ᴱ ∥ A ∥ᴱ idempotent = ∥∥ᴱ-cong-⇔ (record { to = P.[ id , id ]; from = inj₁ }) ------------------------------------------------------------------------ -- The universal property, and some related results mutual -- The propositional truncation operator's universal property. -- -- See also Quotient.Erased.Σ→Erased-Constant≃∥∥ᴱ→. universal-property : @0 Is-proposition B → (∥ A ∥ᴱ → B) ≃ (A → B) universal-property B-prop = universal-property-Π (λ _ → B-prop) -- A generalisation of the universal property. universal-property-Π : @0 (∀ x → Is-proposition (P x)) → ((x : ∥ A ∥ᴱ) → P x) ≃ ((x : A) → P ∣ x ∣) universal-property-Π {A = A} {P = P} P-prop = ((x : ∥ A ∥ᴱ) → P x) ↝⟨ Eq.↔⇒≃ (record { surjection = record { logical-equivalence = record { to = λ f → ∣ f ∘ ∣_∣ ∣ ; from = rec λ where .∣∣ʳ f → elim λ where .∣∣ʳ → f .truncation-is-propositionʳ → P-prop .truncation-is-propositionʳ → Π-closure ext 1 λ _ → P-prop _ } ; right-inverse-of = elim λ where .∣∣ʳ _ → refl _ .truncation-is-propositionʳ _ → mono₁ 1 truncation-is-proposition } ; left-inverse-of = λ f → ⟨ext⟩ $ elim λ where .∣∣ʳ _ → refl _ .truncation-is-propositionʳ _ → mono₁ 1 (P-prop _) }) ⟩ ∥ ((x : A) → P ∣ x ∣) ∥ᴱ ↔⟨ ∥∥ᴱ↔ (Π-closure ext 1 λ _ → P-prop _) ⟩□ ((x : A) → P ∣ x ∣) □ -- The universal property computes in the ""right"" way. _ : (@0 B-prop : Is-proposition B) (f : ∥ A ∥ᴱ → B) → _≃_.to (universal-property B-prop) f ≡ f ∘ ∣_∣ _ = λ _ _ → refl _ _ : (@0 B-prop : Is-proposition B) (f : A → B) (x : A) → _≃_.from (universal-property B-prop) f ∣ x ∣ ≡ f x _ = λ _ _ _ → refl _ -- Functions from ∥ A ∥ᴱ can be expressed as functions from A along -- with some erased data. ∥∥ᴱ→≃ : (∥ A ∥ᴱ → B) ≃ (∃ λ (f : A → B) → Erased (∃ λ (g : ∀ n → ∥ A ∥¹-out-^ (suc n) → B) → (∀ x → g zero O.∣ x ∣ ≡ f x) × (∀ n x → g (suc n) O.∣ x ∣ ≡ g n x))) ∥∥ᴱ→≃ {A = A} {B = B} = (∥ A ∥ᴱ → B) ↝⟨ →-cong ext ∥∥ᴱ≃∥∥ᴱ F.id ⟩ (N.∥ A ∥ᴱ → B) ↝⟨ C.universal-property ⟩□ (∃ λ (f : A → B) → Erased (∃ λ (g : ∀ n → ∥ A ∥¹-out-^ (suc n) → B) → (∀ x → g zero O.∣ x ∣ ≡ f x) × (∀ n x → g (suc n) O.∣ x ∣ ≡ g n x))) □ -- A function of type (x : ∥ A ∥ᴱ) → P x, along with an erased proof -- showing that the function is equal to some erased function, is -- equivalent to a function of type (x : A) → P ∣ x ∣, along with an -- erased equality proof. Σ-Π-∥∥ᴱ-Erased-≡-≃ : {@0 g : (x : ∥ A ∥ᴱ) → P x} → (∃ λ (f : (x : ∥ A ∥ᴱ) → P x) → Erased (f ≡ g)) ≃ (∃ λ (f : (x : A) → P ∣ x ∣) → Erased (f ≡ g ∘ ∣_∣)) Σ-Π-∥∥ᴱ-Erased-≡-≃ {A = A} {P = P} {g = g} = (∃ λ (f : (x : ∥ A ∥ᴱ) → P x) → Erased (f ≡ g)) ↝⟨ (Σ-cong lemma λ _ → Er.Erased-cong (inverse $ Eq.≃-≡ lemma)) ⟩ (∃ λ (f : (x : N.∥ A ∥ᴱ) → P (_≃_.from ∥∥ᴱ≃∥∥ᴱ x)) → Erased (f ≡ g ∘ _≃_.from ∥∥ᴱ≃∥∥ᴱ)) ↝⟨ N.Σ-Π-∥∥ᴱ-Erased-≡-≃ ⟩□ (∃ λ (f : (x : A) → P ∣ x ∣) → Erased (f ≡ g ∘ ∣_∣)) □ where lemma = Π-cong-contra ext (inverse ∥∥ᴱ≃∥∥ᴱ) λ _ → Eq.id ------------------------------------------------------------------------ -- Some results based on ""Generalizations of Hedberg's Theorem"" by -- Kraus, Escardó, Coquand and Altenkirch -- Types with constant endofunctions are ""h-stable"" (meaning that -- ""mere inhabitance"" implies inhabitance). constant-endofunction⇒h-stable : {f : A → A} → @0 Constant f → ∥ A ∥ᴱ → A constant-endofunction⇒h-stable {A = A} {f = f} c = ∥ A ∥ᴱ ↝⟨ (rec λ where .∣∣ʳ x → f x , [ c (f x) x ] .truncation-is-propositionʳ → prop) ⟩ (∃ λ (x : A) → Erased (f x ≡ x)) ↝⟨ proj₁ ⟩□ A □ where @0 prop : _ prop = $⟨ fixpoint-lemma f c ⟩ Is-proposition (∃ λ x → f x ≡ x) ↝⟨ H-level-cong _ 1 (∃-cong λ _ → inverse $ Er.erased Er.Erased↔) ⦂ (_ → _) ⟩□ Is-proposition (∃ λ x → Erased (f x ≡ x)) □ -- Having a constant endofunction is logically equivalent to being -- h-stable. constant-endofunction⇔h-stable : (∃ λ (f : A → A) → Erased (Constant f)) ⇔ (∥ A ∥ᴱ → A) constant-endofunction⇔h-stable = record { to = λ (_ , [ c ]) → constant-endofunction⇒h-stable c ; from = λ f → f ∘ ∣_∣ , [ (λ x y → f ∣ x ∣ ≡⟨ cong f $ truncation-is-proposition _ _ ⟩∎ f ∣ y ∣ ∎) ] } ------------------------------------------------------------------------ -- Some results related to _×_ -- The cartesian product of the truncation of A and A is equivalent -- (with erased ""proofs"") to A. ∥∥ᴱ×≃ᴱ : (∥ A ∥ᴱ × A) ≃ᴱ A ∥∥ᴱ×≃ᴱ = EEq.↔→≃ᴱ proj₂ (λ x → ∣ x ∣ , x) refl (λ _ → cong (_, _) (truncation-is-proposition _ _)) -- The application _≃ᴱ_.right-inverse-of ∥∥ᴱ×≃ᴱ x computes in a -- certain way. _ : _≃ᴱ_.right-inverse-of ∥∥ᴱ×≃ᴱ x ≡ refl _ _ = refl _ -- ∥_∥ᴱ commutes with _×_. ∥∥ᴱ×∥∥ᴱ↔∥×∥ᴱ : (∥ A ∥ᴱ × ∥ B ∥ᴱ) ↔ ∥ A × B ∥ᴱ ∥∥ᴱ×∥∥ᴱ↔∥×∥ᴱ = record { surjection = record { logical-equivalence = record { from = λ p → ∥∥ᴱ-map proj₁ p , ∥∥ᴱ-map proj₂ p ; to = uncurry $ rec λ where .∣∣ʳ x → rec λ where .∣∣ʳ y → ∣ x , y ∣ .truncation-is-propositionʳ → truncation-is-proposition .truncation-is-propositionʳ → Π-closure ext 1 λ _ → truncation-is-proposition } ; right-inverse-of = elim λ where .∣∣ʳ _ → refl _ .truncation-is-propositionʳ _ → mono₁ 1 truncation-is-proposition } ; left-inverse-of = uncurry $ elim λ where .∣∣ʳ _ → elim λ where .∣∣ʳ _ → refl _ .truncation-is-propositionʳ _ → mono₁ 1 $ ×-closure 1 truncation-is-proposition truncation-is-proposition .truncation-is-propositionʳ _ → Π-closure ext 1 λ _ → mono₁ 1 $ ×-closure 1 truncation-is-proposition truncation-is-proposition } ------------------------------------------------------------------------ -- Some results related to h-levels -- Variants of proj₁-closure. private H-level-×₁-lemma : (A → ∥ B ∥ᴱ) → ∀ n → H-level (suc n) (A × B) → H-level (suc n) A H-level-×₁-lemma inhabited n h = [inhabited⇒+]⇒+ n λ a → flip rec (inhabited a) λ where .∣∣ʳ b → proj₁-closure (λ _ → b) (suc n) h .truncation-is-propositionʳ → H-level-propositional ext (suc n) H-level-×₁ : (A → ∥ B ∥ᴱ) → ∀ n → H-level n (A × B) → H-level n A H-level-×₁ inhabited zero h = propositional⇒inhabited⇒contractible (H-level-×₁-lemma inhabited 0 (mono₁ 0 h)) (proj₁ (proj₁ h)) H-level-×₁ inhabited (suc n) = H-level-×₁-lemma inhabited n H-level-×₂ : (B → ∥ A ∥ᴱ) → ∀ n → H-level n (A × B) → H-level n B H-level-×₂ {B = B} {A = A} inhabited n = H-level n (A × B) ↝⟨ H-level.respects-surjection (from-bijection ×-comm) n ⟩ H-level n (B × A) ↝⟨ H-level-×₁ inhabited n ⟩□ H-level n B □ ------------------------------------------------------------------------ -- Flattening -- A generalised flattening lemma. flatten′ : (F : (Type ℓ → Type ℓ) → Type f) (map : ∀ {G H} → (∀ {A} → G A → H A) → F G → F H) (f : F ∥_∥ᴱ → ∥ F id ∥ᴱ) → (∀ x → f (map ∣_∣ x) ≡ ∣ x ∣) → (∀ x → ∥∥ᴱ-map (map ∣_∣) (f x) ≡ ∣ x ∣) → ∥ F ∥_∥ᴱ ∥ᴱ ↔ ∥ F id ∥ᴱ flatten′ _ map f f-map map-f = record { surjection = record { logical-equivalence = record { to = rec λ where .∣∣ʳ → f .truncation-is-propositionʳ → truncation-is-proposition ; from = ∥∥ᴱ-map (map ∣_∣) } ; right-inverse-of = elim λ where .∣∣ʳ → f-map .truncation-is-propositionʳ _ → mono₁ 1 truncation-is-proposition } ; left-inverse-of = elim λ where .∣∣ʳ → map-f .truncation-is-propositionʳ _ → mono₁ 1 truncation-is-proposition } -- Nested truncations can be flattened. flatten : ∥ ∥ A ∥ᴱ ∥ᴱ ↔ ∥ A ∥ᴱ flatten {A = A} = flatten′ (λ F → F A) (λ f → f) id (λ _ → refl _) (elim λ where .∣∣ʳ _ → refl _ .truncation-is-propositionʳ _ → mono₁ 1 truncation-is-proposition) private -- Another flattening lemma, given as an example of how flatten′ can -- be used. ∥∃∥∥ᴱ∥ᴱ↔∥∃∥ᴱ : ∥ ∃ (∥_∥ᴱ ∘ P) ∥ᴱ ↔ ∥ ∃ P ∥ᴱ ∥∃∥∥ᴱ∥ᴱ↔∥∃∥ᴱ {P = P} = flatten′ (λ F → ∃ (F ∘ P)) (λ f → Σ-map id f) (uncurry λ x → ∥∥ᴱ-map (x ,_)) (λ _ → refl _) (uncurry λ _ → elim λ where .∣∣ʳ _ → refl _ .truncation-is-propositionʳ _ → mono₁ 1 truncation-is-proposition) -- A variant of flatten′ with _≃ᴱ_ instead of _↔_. flatten-≃ᴱ : (F : (Type ℓ → Type ℓ) → Type f) (map : ∀ {G H} → (∀ {A} → G A → H A) → F G → F H) (f : F ∥_∥ᴱ → ∥ F id ∥ᴱ) → @0 (∀ x → f (map ∣_∣ x) ≡ ∣ x ∣) → @0 (∀ x → ∥∥ᴱ-map (map ∣_∣) (f x) ≡ ∣ x ∣) → ∥ F ∥_∥ᴱ ∥ᴱ ≃ᴱ ∥ F id ∥ᴱ flatten-≃ᴱ _ map f f-map map-f = EEq.↔→≃ᴱ (rec λ where .∣∣ʳ → f .truncation-is-propositionʳ → truncation-is-proposition) (∥∥ᴱ-map (map ∣_∣)) (elim λ @0 where .∣∣ʳ → f-map .truncation-is-propositionʳ _ → mono₁ 1 truncation-is-proposition) (elim λ @0 where .∣∣ʳ → map-f .truncation-is-propositionʳ _ → mono₁ 1 truncation-is-proposition) ------------------------------------------------------------------------ -- The propositional truncation operator is a monad -- A universe-polymorphic variant of bind. infixl 5 _>>=′_ _>>=′_ : ∥ A ∥ᴱ → (A → ∥ B ∥ᴱ) → ∥ B ∥ᴱ x >>=′ f = _↔_.to flatten (∥∥ᴱ-map f x) -- The universe-polymorphic variant of bind is associative. >>=′-associative : (x : ∥ A ∥ᴱ) → x >>=′ (λ x → f x >>=′ g) ≡ x >>=′ f >>=′ g >>=′-associative = elim λ where .∣∣ʳ _ → refl _ .truncation-is-propositionʳ _ → ⇒≡ 1 truncation-is-proposition instance -- The propositional truncation operator is a monad. raw-monad : Raw-monad (∥_∥ᴱ {a = a}) Raw-monad.return raw-monad = ∣_∣ Raw-monad._>>=_ raw-monad = _>>=′_ monad : Monad (∥_∥ᴱ {a = a}) Monad.raw-monad monad = raw-monad Monad.left-identity monad _ _ = refl _ Monad.associativity monad x _ _ = >>=′-associative x Monad.right-identity monad = elim λ where .∣∣ʳ _ → refl _ .truncation-is-propositionʳ _ → ⇒≡ 1 truncation-is-proposition ------------------------------------------------------------------------ -- Surjectivity -- A variant of surjectivity with ""erased proofs"". Surjectiveᴱ : {A : Type a} {B : Type b} → (A → B) → Type (a ⊔ b) Surjectiveᴱ f = ∀ y → ∥ f ⁻¹ᴱ y ∥ᴱ -- The property Surjectiveᴱ f is a proposition (in erased contexts). @0 Surjectiveᴱ-propositional : Is-proposition (Surjectiveᴱ f) Surjectiveᴱ-propositional = Π-closure ext 1 λ _ → truncation-is-proposition -- The function ∣_∣ is surjective (with erased proofs). ∣∣-surjective : Surjectiveᴱ (∣_∣ {A = A}) ∣∣-surjective = elim λ where .∣∣ʳ x → ∣ x , [ refl _ ] ∣ .truncation-is-propositionʳ _ → truncation-is-proposition -- Split surjective functions are surjective (with erased proofs). Split-surjective→Surjectiveᴱ : Split-surjective f → Surjectiveᴱ f Split-surjective→Surjectiveᴱ s = λ y → ∣ ECP.⁻¹→⁻¹ᴱ (s y) ∣ -- Being both surjective (with erased proofs) and an embedding -- (completely erased) is equivalent to being an equivalence (with -- erased proofs). -- -- This result, without erasure, is Corollary 4.6.4 from the first -- edition of the HoTT book. Surjectiveᴱ×Erased-Is-embedding≃ᴱIs-equivalenceᴱ : (Surjectiveᴱ f × Erased (Is-embedding f)) ≃ᴱ Is-equivalenceᴱ f Surjectiveᴱ×Erased-Is-embedding≃ᴱIs-equivalenceᴱ {f = f} = EEq.⇔→≃ᴱ (×-closure 1 Surjectiveᴱ-propositional (Er.H-level-Erased 1 (Emb.Is-embedding-propositional ext))) (EEq.Is-equivalenceᴱ-propositional ext f) (λ (is-surj , is-emb) → _⇔_.from EEq.Is-equivalenceᴱ⇔Is-equivalenceᴱ-CP $ λ y → $⟨ is-surj y ⟩ ∥ f ⁻¹ᴱ y ∥ᴱ ↝⟨ (rec λ where .∣∣ʳ p → ECP.inhabited→Is-proposition→Contractibleᴱ p (H-level-cong _ 1 ECP.⁻¹≃⁻¹ᴱ (Emb.embedding→⁻¹-propositional (Er.erased is-emb) _)) .truncation-is-propositionʳ → ECP.Contractibleᴱ-propositional ext) ⟩□ Contractibleᴱ (f ⁻¹ᴱ y) □) (λ is-eq@(inv , [ r-inv , _ ]) → (λ y → $⟨ inv y , [ r-inv y ] ⟩ f ⁻¹ᴱ y ↝⟨ ∣_∣ ⟩ ∥ f ⁻¹ᴱ y ∥ᴱ □) , ($⟨ is-eq ⟩ Is-equivalenceᴱ f ↝⟨ Er.[_]→ ⟩ Erased (Is-equivalenceᴱ f) ↝⟨ Er.map EEq.Is-equivalenceᴱ→Is-equivalence ⟩ Erased (Is-equivalence f) ↝⟨ Er.map Emb.Is-equivalence→Is-embedding ⟩□ Erased (Is-embedding f) □)) ------------------------------------------------------------------------ -- Another lemma -- The function λ R x y → ∥ R x y ∥ᴱ preserves Is-equivalence-relation. ∥∥ᴱ-preserves-Is-equivalence-relation : Is-equivalence-relation R → Is-equivalence-relation (λ x y → ∥ R x y ∥ᴱ) ∥∥ᴱ-preserves-Is-equivalence-relation R-equiv = record { reflexive = ∣ reflexive ∣ ; symmetric = symmetric ⟨$⟩_ ; transitive = λ p q → transitive ⟨$⟩ p ⊛ q } where open Is-equivalence-relation R-equiv ------------------------------------------------------------------------ -- Definitions related to truncated binary sums -- Truncated binary sums. infixr 1 _∥⊎∥ᴱ_ _∥⊎∥ᴱ_ : Type a → Type b → Type (a ⊔ b) A ∥⊎∥ᴱ B = ∥ A ⊎ B ∥ᴱ -- Introduction rules. ∣inj₁∣ : A → A ∥⊎∥ᴱ B ∣inj₁∣ = ∣_∣ ∘ inj₁ ∣inj₂∣ : B → A ∥⊎∥ᴱ B ∣inj₂∣ = ∣_∣ ∘ inj₂ -- In erased contexts _∥⊎∥ᴱ_ is pointwise propositional. @0 ∥⊎∥ᴱ-propositional : Is-proposition (A ∥⊎∥ᴱ B) ∥⊎∥ᴱ-propositional = truncation-is-proposition -- The _∥⊎∥ᴱ_ operator preserves ""symmetric"" functions. infixr 1 _∥⊎∥ᴱ-cong_ _∥⊎∥ᴱ-cong_ : A₁ ↝[ ⌊ k ⌋-sym ] A₂ → B₁ ↝[ ⌊ k ⌋-sym ] B₂ → (A₁ ∥⊎∥ᴱ B₁) ↝[ ⌊ k ⌋-sym ] (A₂ ∥⊎∥ᴱ B₂) A₁↝A₂ ∥⊎∥ᴱ-cong B₁↝B₂ = ∥∥ᴱ-cong (A₁↝A₂ ⊎-cong B₁↝B₂) -- _∥⊎∥ᴱ_ is commutative. ∥⊎∥ᴱ-comm : A ∥⊎∥ᴱ B ↔ B ∥⊎∥ᴱ A ∥⊎∥ᴱ-comm = ∥∥ᴱ-cong ⊎-comm -- If one truncates the types to the left or right of _∥⊎∥ᴱ_, then one -- ends up with an isomorphic type. truncate-left-∥⊎∥ᴱ : A ∥⊎∥ᴱ B ↔ ∥ A ∥ᴱ ∥⊎∥ᴱ B truncate-left-∥⊎∥ᴱ = inverse $ flatten′ (λ F → F _ ⊎ _) (λ f → ⊎-map f id) P.[ ∥∥ᴱ-map inj₁ , ∣inj₂∣ ] P.[ (λ _ → refl _) , (λ _ → refl _) ] P.[ (elim λ where .∣∣ʳ _ → refl _ .truncation-is-propositionʳ _ → mono₁ 1 ∥⊎∥ᴱ-propositional) , (λ _ → refl _) ] truncate-right-∥⊎∥ᴱ : A ∥⊎∥ᴱ B ↔ A ∥⊎∥ᴱ ∥ B ∥ᴱ truncate-right-∥⊎∥ᴱ {A = A} {B = B} = A ∥⊎∥ᴱ B ↝⟨ ∥⊎∥ᴱ-comm ⟩ B ∥⊎∥ᴱ A ↝⟨ truncate-left-∥⊎∥ᴱ ⟩ ∥ B ∥ᴱ ∥⊎∥ᴱ A ↝⟨ ∥⊎∥ᴱ-comm ⟩□ A ∥⊎∥ᴱ ∥ B ∥ᴱ □ -- _∥⊎∥ᴱ_ is associative. ∥⊎∥ᴱ-assoc : A ∥⊎∥ᴱ (B ∥⊎∥ᴱ C) ↔ (A ∥⊎∥ᴱ B) ∥⊎∥ᴱ C ∥⊎∥ᴱ-assoc {A = A} {B = B} {C = C} = ∥ A ⊎ ∥ B ⊎ C ∥ᴱ ∥ᴱ ↝⟨ inverse truncate-right-∥⊎∥ᴱ ⟩ ∥ A ⊎ B ⊎ C ∥ᴱ ↝⟨ ∥∥ᴱ-cong ⊎-assoc ⟩ ∥ (A ⊎ B) ⊎ C ∥ᴱ ↝⟨ truncate-left-∥⊎∥ᴱ ⟩□ ∥ ∥ A ⊎ B ∥ᴱ ⊎ C ∥ᴱ □ -- ⊥ is a left and right identity of _∥⊎∥ᴱ_ if the other argument is a -- proposition. ∥⊎∥ᴱ-left-identity : @0 Is-proposition A → ⊥ {ℓ = ℓ} ∥⊎∥ᴱ A ↔ A ∥⊎∥ᴱ-left-identity {A = A} A-prop = ∥ ⊥ ⊎ A ∥ᴱ ↝⟨ ∥∥ᴱ-cong ⊎-left-identity ⟩ ∥ A ∥ᴱ ↝⟨ ∥∥ᴱ↔ A-prop ⟩□ A □ ∥⊎∥ᴱ-right-identity : @0 Is-proposition A → A ∥⊎∥ᴱ ⊥ {ℓ = ℓ} ↔ A ∥⊎∥ᴱ-right-identity {A = A} A-prop = A ∥⊎∥ᴱ ⊥ ↔⟨ ∥⊎∥ᴱ-comm ⟩ ⊥ ∥⊎∥ᴱ A ↔⟨ ∥⊎∥ᴱ-left-identity A-prop ⟩□ A □ -- _∥⊎∥ᴱ_ is idempotent for propositions (up to equivalences with -- erased proofs). ∥⊎∥ᴱ-idempotent : @0 Is-proposition A → (A ∥⊎∥ᴱ A) ≃ᴱ A ∥⊎∥ᴱ-idempotent {A = A} A-prop = ∥ A ⊎ A ∥ᴱ ↝⟨ idempotent ⟩ ∥ A ∥ᴱ ↔⟨ ∥∥ᴱ↔ A-prop ⟩□ A □ -- Sometimes a truncated binary sum is equivalent (with erased proofs) -- to one of its summands. drop-left-∥⊎∥ᴱ : @0 Is-proposition B → (A → B) → (A ∥⊎∥ᴱ B) ≃ᴱ B drop-left-∥⊎∥ᴱ B-prop A→B = EEq.⇔→≃ᴱ ∥⊎∥ᴱ-propositional B-prop (rec λ where .∣∣ʳ → P.[ A→B , id ] .truncation-is-propositionʳ → B-prop) ∣inj₂∣ drop-right-∥⊎∥ᴱ : @0 Is-proposition A → (B → A) → (A ∥⊎∥ᴱ B) ≃ᴱ A drop-right-∥⊎∥ᴱ {A = A} {B = B} A-prop B→A = A ∥⊎∥ᴱ B ↔⟨ ∥⊎∥ᴱ-comm ⟩ B ∥⊎∥ᴱ A ↝⟨ drop-left-∥⊎∥ᴱ A-prop B→A ⟩□ A □ -- Sometimes a truncated binary sum is isomorphic to one of its -- summands. drop-⊥-right-∥⊎∥ᴱ : @0 Is-proposition A → ¬ B → A ∥⊎∥ᴱ B ↔ A drop-⊥-right-∥⊎∥ᴱ A-prop ¬B = record { surjection = record { logical-equivalence = record { to = rec λ where .∣∣ʳ → P.[ id , ⊥-elim ∘ ¬B ] .truncation-is-propositionʳ → A-prop ; from = ∣inj₁∣ } ; right-inverse-of = refl } ; left-inverse-of = elim λ where .∣∣ʳ → P.[ (λ _ → refl _) , ⊥-elim ∘ ¬B ] .truncation-is-propositionʳ _ → mono₁ 1 ∥⊎∥ᴱ-propositional } drop-⊥-left-∥⊎∥ᴱ : @0 Is-proposition B → ¬ A → A ∥⊎∥ᴱ B ↔ B drop-⊥-left-∥⊎∥ᴱ B-prop ¬A = record { surjection = record { logical-equivalence = record { to = rec λ where .∣∣ʳ → P.[ ⊥-elim ∘ ¬A , id ] .truncation-is-propositionʳ → B-prop ; from = ∣inj₂∣ } ; right-inverse-of = refl } ; left-inverse-of = elim λ where .∣∣ʳ → P.[ ⊥-elim ∘ ¬A , (λ _ → refl _) ] .truncation-is-propositionʳ _ → mono₁ 1 ∥⊎∥ᴱ-propositional } -- A type of functions from a truncated binary sum to a family of -- propositions can be expressed as a binary product of function -- types. Π∥⊎∥ᴱ↔Π×Π : @0 (∀ x → Is-proposition (P x)) → ((x : A ∥⊎∥ᴱ B) → P x) ↔ ((x : A) → P (∣inj₁∣ x)) × ((y : B) → P (∣inj₂∣ y)) Π∥⊎∥ᴱ↔Π×Π {A = A} {B = B} {P = P} P-prop = ((x : A ∥⊎∥ᴱ B) → P x) ↔⟨ universal-property-Π P-prop ⟩ ((x : A ⊎ B) → P ∣ x ∣) ↝⟨ Π⊎↔Π×Π ext ⟩□ ((x : A) → P (∣inj₁∣ x)) × ((y : B) → P (∣inj₂∣ y)) □ -- Two distributivity laws for Σ and _∥⊎∥ᴱ_. Σ-∥⊎∥ᴱ-distrib-left : @0 Is-proposition A → Σ A (λ x → P x ∥⊎∥ᴱ Q x) ↔ Σ A P ∥⊎∥ᴱ Σ A Q Σ-∥⊎∥ᴱ-distrib-left {P = P} {Q = Q} A-prop = (∃ λ x → ∥ P x ⊎ Q x ∥ᴱ) ↝⟨ inverse $ ∥∥ᴱ↔ (Σ-closure 1 A-prop λ _ → ∥⊎∥ᴱ-propositional) ⟩ ∥ (∃ λ x → ∥ P x ⊎ Q x ∥ᴱ) ∥ᴱ ↝⟨ flatten′ (λ F → (∃ λ x → F (P x ⊎ Q x))) (λ f → Σ-map id f) (uncurry λ x → ∥∥ᴱ-map (x ,_)) (λ _ → refl _) (uncurry λ _ → elim λ where .∣∣ʳ _ → refl _ .truncation-is-propositionʳ _ → mono₁ 1 truncation-is-proposition) ⟩ ∥ (∃ λ x → P x ⊎ Q x) ∥ᴱ ↝⟨ ∥∥ᴱ-cong ∃-⊎-distrib-left ⟩□ ∥ ∃ P ⊎ ∃ Q ∥ᴱ □ Σ-∥⊎∥ᴱ-distrib-right : @0 (∀ x → Is-proposition (P x)) → Σ (A ∥⊎∥ᴱ B) P ↔ Σ A (P ∘ ∣inj₁∣) ∥⊎∥ᴱ Σ B (P ∘ ∣inj₂∣) Σ-∥⊎∥ᴱ-distrib-right {A = A} {B = B} {P = P} P-prop = record { surjection = record { logical-equivalence = record { to = uncurry $ elim λ where .∣∣ʳ → curry (∣_∣ ∘ _↔_.to ∃-⊎-distrib-right) .truncation-is-propositionʳ _ → Π-closure ext 1 λ _ → ∥⊎∥ᴱ-propositional ; from = rec λ where .∣∣ʳ → Σ-map ∣_∣ id ∘ _↔_.from ∃-⊎-distrib-right .truncation-is-propositionʳ → prop } ; right-inverse-of = elim λ where .∣∣ʳ → P.[ (λ _ → refl _) , (λ _ → refl _) ] .truncation-is-propositionʳ _ → mono₁ 1 ∥⊎∥ᴱ-propositional } ; left-inverse-of = uncurry $ elim λ where .∣∣ʳ → P.[ (λ _ _ → refl _) , (λ _ _ → refl _) ] .truncation-is-propositionʳ _ → Π-closure ext 1 λ _ → mono₁ 1 prop } where @0 prop : _ prop = Σ-closure 1 ∥⊎∥ᴱ-propositional P-prop -- A variant of one of De Morgan's laws. ¬∥⊎∥ᴱ¬↔¬× : Dec (¬ A) → Dec (¬ B) → (¬ A ∥⊎∥ᴱ ¬ B) ≃ᴱ (¬ (A × B)) ¬∥⊎∥ᴱ¬↔¬× {A = A} {B = B} dec-¬A dec-¬B = EEq.⇔→≃ᴱ ∥⊎∥ᴱ-propositional (¬-propositional ext) (rec λ where .∣∣ʳ → ¬⊎¬→׬ .truncation-is-propositionʳ → ¬-propositional ext) (∣_∣ ∘ _↠_.from (¬⊎¬↠¬× ext dec-¬A dec-¬B)) ------------------------------------------------------------------------ -- Code related to Erased-singleton -- A corollary of erased-singleton-with-erased-center-propositional. ↠→↠Erased-singleton : {@0 y : B} (A↠B : A ↠ B) → ∥ (∃ λ (x : A) → Erased (_↠_.to A↠B x ≡ y)) ∥ᴱ ↠ Erased-singleton y ↠→↠Erased-singleton {A = A} {y = y} A↠B = ∥ (∃ λ (x : A) → Erased (_↠_.to A↠B x ≡ y)) ∥ᴱ ↝⟨ ∥∥ᴱ-cong-↠ (S.Σ-cong A↠B λ _ → F.id) ⟩ ∥ Erased-singleton y ∥ᴱ ↔⟨ ∥∥ᴱ↔ (Er.erased-singleton-with-erased-center-propositional $ Er.Very-stable→Very-stableᴱ 1 $ Er.Very-stable→Very-stable-≡ 0 $ erased Er.Erased-Very-stable) ⟩□ Erased-singleton y □ -- Another corollary of -- erased-singleton-with-erased-center-propositional. ↠→≃ᴱErased-singleton : {@0 y : B} (A↠B : A ↠ B) → ∥ (∃ λ (x : A) → Erased (_↠_.to A↠B x ≡ y)) ∥ᴱ ≃ᴱ Erased-singleton y ↠→≃ᴱErased-singleton {A = A} {y = y} A↠B = ∥ (∃ λ (x : A) → Erased (_↠_.to A↠B x ≡ y)) ∥ᴱ ↝⟨ ∥∥ᴱ-cong-⇔ (S.Σ-cong-⇔ A↠B λ _ → F.id) ⟩ ∥ Erased-singleton y ∥ᴱ ↔⟨ ∥∥ᴱ↔ (Er.erased-singleton-with-erased-center-propositional $ Er.Very-stable→Very-stableᴱ 1 $ Er.Very-stable→Very-stable-≡ 0 $ erased Er.Erased-Very-stable) ⟩□ Erased-singleton y □ -- A corollary of Σ-Erased-Erased-singleton↔ and ↠→≃ᴱErased-singleton. Σ-Erased-∥-Σ-Erased-≡-∥≃ᴱ : (A↠B : A ↠ B) → (∃ λ (x : Erased B) → ∥ (∃ λ (y : A) → Erased (_↠_.to A↠B y ≡ erased x)) ∥ᴱ) ≃ᴱ B Σ-Erased-∥-Σ-Erased-≡-∥≃ᴱ {A = A} {B = B} A↠B = (∃ λ (x : Erased B) → ∥ (∃ λ (y : A) → Erased (_↠_.to A↠B y ≡ erased x)) ∥ᴱ) ↝⟨ (∃-cong λ _ → ↠→≃ᴱErased-singleton A↠B) ⟩ (∃ λ (x : Erased B) → Erased-singleton (erased x)) ↔⟨ Er.Σ-Erased-Erased-singleton↔ ⟩□ B □ -- In an erased context the left-to-right direction of -- Σ-Erased-∥-Σ-Erased-≡-∥≃ᴱ returns the erased first component. @0 to-Σ-Erased-∥-Σ-Erased-≡-∥≃ᴱ≡ : ∀ (A↠B : A ↠ B) x → _≃ᴱ_.to (Σ-Erased-∥-Σ-Erased-≡-∥≃ᴱ A↠B) x ≡ erased (proj₁ x) to-Σ-Erased-∥-Σ-Erased-≡-∥≃ᴱ≡ A↠B ([ x ] , y) = _≃ᴱ_.to (Σ-Erased-∥-Σ-Erased-≡-∥≃ᴱ A↠B) ([ x ] , y) ≡⟨⟩ proj₁ (_≃ᴱ_.to (↠→≃ᴱErased-singleton A↠B) y) ≡⟨ erased (proj₂ (_≃ᴱ_.to (↠→≃ᴱErased-singleton A↠B) y)) ⟩∎ x ∎ ",12501,True,2759.2217142265963,median "-- In this file we consider the special of localising at a single -- element f : R (or rather the set of powers of f). This is also -- known as inverting f. -- We then prove that localising first at an element f and at an element -- g (or rather the image g/1) is the same as localising at the product f·g -- This fact has an important application in algebraic geometry where it's -- used to define the structure sheaf of a commutative ring. {-# OPTIONS --safe --experimental-lossy-unification #-} module Cubical.Algebra.CommRing.Localisation.InvertingElements where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Function open import Cubical.Foundations.Equiv open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Univalence open import Cubical.Foundations.HLevels open import Cubical.Foundations.Powerset open import Cubical.Foundations.Transport open import Cubical.Functions.FunExtEquiv import Cubical.Data.Empty as ⊥ open import Cubical.Data.Bool open import Cubical.Data.Nat renaming ( _+_ to _+ℕ_ ; _·_ to _·ℕ_ ; _^_ to _^ℕ_ ; +-comm to +ℕ-comm ; +-assoc to +ℕ-assoc ; ·-assoc to ·ℕ-assoc ; ·-comm to ·ℕ-comm) open import Cubical.Data.Nat.Order open import Cubical.Data.Vec open import Cubical.Data.Sigma.Base open import Cubical.Data.Sigma.Properties open import Cubical.Data.FinData open import Cubical.Relation.Nullary open import Cubical.Relation.Binary open import Cubical.Algebra.Group open import Cubical.Algebra.AbGroup open import Cubical.Algebra.Monoid open import Cubical.Algebra.Ring open import Cubical.Algebra.CommRing open import Cubical.Algebra.CommRing.Localisation.Base open import Cubical.Algebra.CommRing.Localisation.UniversalProperty open import Cubical.Algebra.CommRing.Ideal open import Cubical.Algebra.CommRing.FGIdeal open import Cubical.Algebra.CommRing.RadicalIdeal open import Cubical.Algebra.CommRingSolver.Reflection open import Cubical.HITs.SetQuotients as SQ open import Cubical.HITs.PropositionalTruncation as PT open Iso private variable ℓ ℓ' : Level A : Type ℓ module InvertingElementsBase (R' : CommRing ℓ) where open isMultClosedSubset private R = fst R' open CommRingStr (snd R') open Exponentiation R' open RingTheory (CommRing→Ring R') [_ⁿ|n≥0] : R → ℙ R [ f ⁿ|n≥0] g = (∃[ n ∈ ℕ ] g ≡ f ^ n) , isPropPropTrunc -- Σ[ n ∈ ℕ ] (s ≡ f ^ n) × (∀ m → s ≡ f ^ m → n ≤ m) maybe better, this isProp: -- (n,s≡fⁿ,p) (m,s≡fᵐ,q) then n≤m by p and m≤n by q => n≡m powersFormMultClosedSubset : (f : R) → isMultClosedSubset R' [ f ⁿ|n≥0] powersFormMultClosedSubset f .containsOne = PT.∣ zero , refl ∣₁ powersFormMultClosedSubset f .multClosed = PT.map2 λ (m , p) (n , q) → (m +ℕ n) , (λ i → (p i) · (q i)) ∙ ·-of-^-is-^-of-+ f m n R[1/_] : R → Type ℓ R[1/ f ] = Loc.S⁻¹R R' [ f ⁿ|n≥0] (powersFormMultClosedSubset f) -- a quick fact isContrR[1/0] : isContr R[1/ 0r ] fst isContrR[1/0] = [ 1r , 0r , ∣ 1 , sym (·Rid 0r) ∣₁ ] -- everything is equal to 1/0 snd isContrR[1/0] = elimProp (λ _ → squash/ _ _) λ _ → eq/ _ _ ((0r , ∣ 1 , sym (·Rid 0r) ∣₁) , useSolver _ _) where useSolver : ∀ s r → 0r · 1r · s ≡ 0r · r · 0r useSolver = solve R' R[1/_]AsCommRing : R → CommRing ℓ R[1/ f ]AsCommRing = Loc.S⁻¹RAsCommRing R' [ f ⁿ|n≥0] (powersFormMultClosedSubset f) -- A useful lemma: (gⁿ/1)≡(g/1)ⁿ in R[1/f] ^-respects-/1 : {f g : R} (n : ℕ) → [ (g ^ n) , 1r , PT.∣ 0 , (λ _ → 1r) ∣₁ ] ≡ Exponentiation._^_ R[1/ f ]AsCommRing [ g , 1r , powersFormMultClosedSubset _ .containsOne ] n ^-respects-/1 zero = refl ^-respects-/1 {f} {g} (suc n) = eq/ _ _ ( (1r , powersFormMultClosedSubset f .containsOne) , cong (1r · (g · (g ^ n)) ·_) (·Lid 1r)) ∙ cong (CommRingStr._·_ (R[1/ f ]AsCommRing .snd) [ g , 1r , powersFormMultClosedSubset f .containsOne ]) (^-respects-/1 n) -- A slight improvement for eliminating into propositions invElPropElim : {f : R} {P : R[1/ f ] → Type ℓ'} → (∀ x → isProp (P x)) → (∀ (r : R) (n : ℕ) → P [ r , (f ^ n) , PT.∣ n , refl ∣₁ ]) -- ∀ r n → P (r/fⁿ) ---------------------------------------------------------- → ∀ x → P x invElPropElim {f = f} {P = P} PisProp base = elimProp (λ _ → PisProp _) []-case where S[f] = Loc.S R' [ f ⁿ|n≥0] (powersFormMultClosedSubset f) []-case : (a : R × S[f]) → P [ a ] []-case (r , s , s∈S[f]) = PT.rec (PisProp _) Σhelper s∈S[f] where Σhelper : Σ[ n ∈ ℕ ] s ≡ f ^ n → P [ r , s , s∈S[f] ] Σhelper (n , p) = subst P (cong [_] (≡-× refl (Σ≡Prop (λ _ → isPropPropTrunc) (sym p)))) (base r n) invElPropElim2 : {f g : R} {P : R[1/ f ] → R[1/ g ] → Type ℓ'} → (∀ x y → isProp (P x y)) → (∀ (r s : R) (n : ℕ) → P [ r , (f ^ n) , PT.∣ n , refl ∣₁ ] [ s , (g ^ n) , PT.∣ n , refl ∣₁ ]) ---------------------------------------------------------- → ∀ x y → P x y invElPropElim2 {f = f} {g = g} {P = P} PisProp base = invElPropElim (λ _ → isPropΠ (λ _ → PisProp _ _)) reduce1 where reduce1 : ∀ (r : R) (n : ℕ) (y : R[1/ g ]) → P [ r , f ^ n , ∣ n , refl ∣₁ ] y reduce1 r n = invElPropElim (λ _ → PisProp _ _) reduce2 where reduce2 : (s : R) (m : ℕ) → P [ r , f ^ n , ∣ n , refl ∣₁ ] [ s , g ^ m , ∣ m , refl ∣₁ ] reduce2 s m = subst2 P p q (base _ _ l) where l = max m n x : R[1/ f ] x = [ r , f ^ n , ∣ n , refl ∣₁ ] y : R[1/ g ] y = [ s , g ^ m , ∣ m , refl ∣₁ ] x' : R[1/ f ] x' = [ r · f ^ (l ∸ n) , f ^ l , ∣ l , refl ∣₁ ] y' : R[1/ g ] y' = [ s · g ^ (l ∸ m) , g ^ l , ∣ l , refl ∣₁ ] p : x' ≡ x p = eq/ _ _ ((1r , ∣ 0 , refl ∣₁) , path) where useSolver1 : ∀ a b c → 1r · (a · b) · c ≡ a · (b · c) useSolver1 = solve R' useSolver2 : ∀ a b → a · b ≡ 1r · a · b useSolver2 = solve R' path : 1r · (r · f ^ (l ∸ n)) · f ^ n ≡ 1r · r · f ^ l path = 1r · (r · f ^ (l ∸ n)) · f ^ n ≡⟨ useSolver1 _ _ _ ⟩ r · (f ^ (l ∸ n) · f ^ n) ≡⟨ cong (r ·_) (·-of-^-is-^-of-+ _ _ _) ⟩ r · f ^ (l ∸ n +ℕ n) ≡⟨ cong (λ k → r · f ^ k) (≤-∸-+-cancel right-≤-max) ⟩ r · f ^ l ≡⟨ useSolver2 _ _ ⟩ 1r · r · f ^ l ∎ q : y' ≡ y q = eq/ _ _ ((1r , ∣ 0 , refl ∣₁) , path) where useSolver1 : ∀ a b c → 1r · (a · b) · c ≡ a · (b · c) useSolver1 = solve R' useSolver2 : ∀ a b → a · b ≡ 1r · a · b useSolver2 = solve R' path : 1r · (s · g ^ (l ∸ m)) · g ^ m ≡ 1r · s · g ^ l path = 1r · (s · g ^ (l ∸ m)) · g ^ m ≡⟨ useSolver1 _ _ _ ⟩ s · (g ^ (l ∸ m) · g ^ m) ≡⟨ cong (s ·_) (·-of-^-is-^-of-+ _ _ _) ⟩ s · g ^ (l ∸ m +ℕ m) ≡⟨ cong (λ k → s · g ^ k) (≤-∸-+-cancel left-≤-max) ⟩ s · g ^ l ≡⟨ useSolver2 _ _ ⟩ 1r · s · g ^ l ∎ -- For predicates over the set of powers powersPropElim : {f : R} {P : R → Type ℓ'} → (∀ x → isProp (P x)) → (∀ n → P (f ^ n)) ------------------------------ → ∀ s → s ∈ [ f ⁿ|n≥0] → P s powersPropElim {f = f} {P = P} PisProp base s = PT.rec (PisProp s) λ (n , p) → subst P (sym p) (base n) module RadicalLemma (R' : CommRing ℓ) (f g : (fst R')) where open IsRingHom open isMultClosedSubset open CommRingTheory R' open RingTheory (CommRing→Ring R') open CommIdeal R' hiding (subst-∈) renaming (_∈_ to _∈ᵢ_) open RadicalIdeal R' open Exponentiation R' open InvertingElementsBase R' open S⁻¹RUniversalProp R' [ f ⁿ|n≥0] (powersFormMultClosedSubset f) hiding (S⁻¹RHasUniversalProp) open S⁻¹RUniversalProp R' [ g ⁿ|n≥0] (powersFormMultClosedSubset g) hiding (_/1 ; /1AsCommRingHom) open CommRingStr (R' .snd) private R = R' .fst ⟨_⟩ : R → CommIdeal ⟨ f ⟩ = ⟨ replicateFinVec 1 f ⟩[ R' ] unitHelper : f ∈ᵢ √ ⟨ g ⟩ → (g /1) ∈ R[1/ f ]AsCommRing ˣ unitHelper = PT.rec isPropGoal (uncurry ℕhelper) where isPropGoal = Units.inverseUniqueness _ (g /1) ℕhelper : (n : ℕ) → f ^ n ∈ᵢ ⟨ g ⟩ → (g /1) ∈ R[1/ f ]AsCommRing ˣ ℕhelper n = PT.rec isPropGoal -- fⁿ≡αg → g⁻¹≡α/fⁿ λ (α , p) → [ (α zero) , (f ^ n) , ∣ n , refl ∣₁ ] , eq/ _ _ ((1r , powersFormMultClosedSubset f .containsOne) , useSolver1 _ _ ∙ sym p ∙ useSolver2 _) where useSolver1 : ∀ x y → 1r · (x · y) · 1r ≡ y · x + 0r useSolver1 = solve R' useSolver2 : ∀ x → x ≡ 1r · 1r · (1r · x) useSolver2 = solve R' toUnit : f ∈ᵢ √ ⟨ g ⟩ → ∀ s → s ∈ [ g ⁿ|n≥0] → (s /1) ∈ R[1/ f ]AsCommRing ˣ toUnit f∈√⟨g⟩ = powersPropElim (λ x → Units.inverseUniqueness _ (x /1)) λ n → subst-∈ (R[1/ f ]AsCommRing ˣ) (sym (^-respects-/1 n)) (Exponentiation.^-presUnit _ _ n (unitHelper f∈√⟨g⟩)) module DoubleLoc (R' : CommRing ℓ) (f g : (fst R')) where open isMultClosedSubset open CommRingStr (snd R') open CommRingTheory R' open Exponentiation R' open InvertingElementsBase open RingTheory (CommRing→Ring R') open CommRingStr (snd (R[1/_]AsCommRing R' f)) renaming ( _·_ to _·ᶠ_ ; 1r to 1ᶠ ; _+_ to _+ᶠ_ ; 0r to 0ᶠ ; ·Lid to ·ᶠ-lid ; ·Rid to ·ᶠ-rid ; ·Assoc to ·ᶠ-assoc ; ·Comm to ·ᶠ-comm) open IsRingHom private R = fst R' R[1/f] = R[1/_] R' f R[1/f]AsCommRing = R[1/_]AsCommRing R' f R[1/fg] = R[1/_] R' (f · g) R[1/fg]AsCommRing = R[1/_]AsCommRing R' (f · g) R[1/f][1/g] = R[1/_] (R[1/_]AsCommRing R' f) [ g , 1r , powersFormMultClosedSubset R' f .containsOne ] R[1/f][1/g]AsCommRing = R[1/_]AsCommRing (R[1/_]AsCommRing R' f) [ g , 1r , powersFormMultClosedSubset R' f .containsOne ] R[1/f][1/g]ˣ = R[1/f][1/g]AsCommRing ˣ _/1/1 : R → R[1/f][1/g] r /1/1 = [ [ r , 1r , PT.∣ 0 , refl ∣₁ ] , 1ᶠ , PT.∣ 0 , refl ∣₁ ] /1/1AsCommRingHom : CommRingHom R' R[1/f][1/g]AsCommRing fst /1/1AsCommRingHom = _/1/1 snd /1/1AsCommRingHom = makeIsRingHom refl lem+ lem· where lem+ : _ lem+ r r' = cong [_] (≡-× (cong [_] (≡-× (cong₂ _+_ (sym (·Rid _) ∙ (λ i → (·Rid r (~ i)) · (·Rid 1r (~ i)))) (sym (·Rid _) ∙ (λ i → (·Rid r' (~ i)) · (·Rid 1r (~ i))))) (Σ≡Prop (λ _ → isPropPropTrunc) (sym (·Lid _) ∙ (λ i → (·Lid 1r (~ i)) · (·Lid 1r (~ i))))))) (Σ≡Prop (λ _ → isPropPropTrunc) (sym (·ᶠ-lid 1ᶠ)))) lem· : _ lem· r r' = cong [_] (≡-× (cong [_] (≡-× refl (Σ≡Prop (λ _ → isPropPropTrunc) (sym (·Lid _))))) (Σ≡Prop (λ _ → isPropPropTrunc) (sym (·ᶠ-lid 1ᶠ)))) -- this will give us a map R[1/fg] → R[1/f][1/g] by the universal property of localisation fⁿgⁿ/1/1∈R[1/f][1/g]ˣ : (s : R) → s ∈ ([_ⁿ|n≥0] R' (f · g)) → s /1/1 ∈ R[1/f][1/g]ˣ fⁿgⁿ/1/1∈R[1/f][1/g]ˣ = powersPropElim R' (λ s → R[1/f][1/g]ˣ (s /1/1) .snd) ℕcase where ℕcase : (n : ℕ) → ((f · g) ^ n) /1/1 ∈ R[1/f][1/g]ˣ ℕcase n = [ [ 1r , (f ^ n) , PT.∣ n , refl ∣₁ ] , [ (g ^ n) , 1r , PT.∣ 0 , refl ∣₁ ] --denominator , PT.∣ n , ^-respects-/1 _ n ∣₁ ] , eq/ _ _ ((1ᶠ , powersFormMultClosedSubset _ _ .containsOne) , eq/ _ _ ((1r , powersFormMultClosedSubset _ _ .containsOne) , path)) where eq1 : ∀ x → 1r · (1r · (x · 1r) · 1r) · (1r · 1r · (1r · 1r)) ≡ x eq1 = solve R' eq2 : ∀ x y → x · y ≡ 1r · (1r · 1r · (1r · y)) · (1r · (1r · x) · 1r) eq2 = solve R' path : 1r · (1r · ((f · g) ^ n · 1r) · 1r) · (1r · 1r · (1r · 1r)) ≡ 1r · (1r · 1r · (1r · g ^ n)) · (1r · (1r · f ^ n) · 1r) path = 1r · (1r · ((f · g) ^ n · 1r) · 1r) · (1r · 1r · (1r · 1r)) ≡⟨ eq1 ((f · g) ^ n) ⟩ (f · g) ^ n ≡⟨ ^-ldist-· _ _ _ ⟩ f ^ n · g ^ n ≡⟨ eq2 (f ^ n) (g ^ n) ⟩ 1r · (1r · 1r · (1r · g ^ n)) · (1r · (1r · f ^ n) · 1r) ∎ open PathToS⁻¹R pathtoR[1/fg] : PathToS⁻¹R R' ([_ⁿ|n≥0] R' (f · g)) (powersFormMultClosedSubset R' (f · g)) R[1/f][1/g]AsCommRing /1/1AsCommRingHom φS⊆Aˣ pathtoR[1/fg] = fⁿgⁿ/1/1∈R[1/f][1/g]ˣ kerφ⊆annS pathtoR[1/fg] r p = toGoal helperR[1/f] where open RingTheory (CommRing→Ring R[1/f]AsCommRing) renaming ( 0RightAnnihilates to 0ᶠRightAnnihilates ; 0LeftAnnihilates to 0ᶠ-leftNullifies) open Exponentiation R[1/f]AsCommRing renaming (_^_ to _^ᶠ_) hiding (·-of-^-is-^-of-+ ; ^-ldist-·) S[f] = Loc.S R' ([_ⁿ|n≥0] R' f) (powersFormMultClosedSubset R' f) S[fg] = Loc.S R' ([_ⁿ|n≥0] R' (f · g)) (powersFormMultClosedSubset R' (f · g)) g/1 : R[1/_] R' f g/1 = [ g , 1r , powersFormMultClosedSubset R' f .containsOne ] S[g/1] = Loc.S R[1/f]AsCommRing ([_ⁿ|n≥0] R[1/f]AsCommRing g/1) (powersFormMultClosedSubset R[1/f]AsCommRing g/1) r/1 : R[1/_] R' f r/1 = [ r , 1r , powersFormMultClosedSubset R' f .containsOne ] -- this is the crucial step, modulo truncation we can take p to be generated -- by the quotienting relation of localisation. Note that we wouldn't be able -- to prove our goal if kerφ⊆annS was formulated with a Σ instead of a ∃ ∥r/1,1/1≈0/1,1/1∥ : ∃[ u ∈ S[g/1] ] fst u ·ᶠ r/1 ·ᶠ 1ᶠ ≡ fst u ·ᶠ 0ᶠ ·ᶠ 1ᶠ ∥r/1,1/1≈0/1,1/1∥ = Iso.fun (SQ.isEquivRel→TruncIso (Loc.locIsEquivRel _ _ _) _ _) p helperR[1/f] : ∃[ n ∈ ℕ ] [ g ^ n · r , 1r , PT.∣ 0 , refl ∣₁ ] ≡ 0ᶠ helperR[1/f] = PT.rec isPropPropTrunc (uncurry (uncurry (powersPropElim R[1/f]AsCommRing (λ _ → isPropΠ (λ _ → isPropPropTrunc)) baseCase))) ∥r/1,1/1≈0/1,1/1∥ where baseCase : ∀ n → g/1 ^ᶠ n ·ᶠ r/1 ·ᶠ 1ᶠ ≡ g/1 ^ᶠ n ·ᶠ 0ᶠ ·ᶠ 1ᶠ → ∃[ n ∈ ℕ ] [ g ^ n · r , 1r , PT.∣ 0 , refl ∣₁ ] ≡ 0ᶠ baseCase n q = PT.∣ n , path ∣₁ where path : [ g ^ n · r , 1r , PT.∣ 0 , refl ∣₁ ] ≡ 0ᶠ path = [ g ^ n · r , 1r , PT.∣ 0 , refl ∣₁ ] ≡⟨ cong [_] (≡-× refl (Σ≡Prop (λ _ → isPropPropTrunc) (sym (·Rid _)))) ⟩ [ g ^ n , 1r , PT.∣ 0 , refl ∣₁ ] ·ᶠ r/1 ≡⟨ cong (_·ᶠ r/1) (^-respects-/1 _ n) ⟩ g/1 ^ᶠ n ·ᶠ r/1 ≡⟨ sym (·ᶠ-rid _) ⟩ g/1 ^ᶠ n ·ᶠ r/1 ·ᶠ 1ᶠ ≡⟨ q ⟩ g/1 ^ᶠ n ·ᶠ 0ᶠ ·ᶠ 1ᶠ ≡⟨ cong (_·ᶠ 1ᶠ) (0ᶠRightAnnihilates _) ∙ 0ᶠ-leftNullifies 1ᶠ ⟩ 0ᶠ ∎ toGoal : ∃[ n ∈ ℕ ] [ g ^ n · r , 1r , PT.∣ 0 , refl ∣₁ ] ≡ 0ᶠ → ∃[ u ∈ S[fg] ] fst u · r ≡ 0r toGoal = PT.rec isPropPropTrunc Σhelper where Σhelper : Σ[ n ∈ ℕ ] [ g ^ n · r , 1r , PT.∣ 0 , refl ∣₁ ] ≡ 0ᶠ → ∃[ u ∈ S[fg] ] fst u · r ≡ 0r Σhelper (n , q) = PT.map Σhelper2 helperR where -- now, repeat the above strategy with q ∥gⁿr≈0∥ : ∃[ u ∈ S[f] ] fst u · (g ^ n · r) · 1r ≡ fst u · 0r · 1r ∥gⁿr≈0∥ = Iso.fun (SQ.isEquivRel→TruncIso (Loc.locIsEquivRel _ _ _) _ _) q helperR : ∃[ m ∈ ℕ ] f ^ m · g ^ n · r ≡ 0r helperR = PT.rec isPropPropTrunc (uncurry (uncurry (powersPropElim R' (λ _ → isPropΠ (λ _ → isPropPropTrunc)) baseCase))) ∥gⁿr≈0∥ where baseCase : (m : ℕ) → f ^ m · (g ^ n · r) · 1r ≡ f ^ m · 0r · 1r → ∃[ m ∈ ℕ ] f ^ m · g ^ n · r ≡ 0r baseCase m q' = PT.∣ m , path ∣₁ where path : f ^ m · g ^ n · r ≡ 0r path = (λ i → ·Rid (·Assoc (f ^ m) (g ^ n) r (~ i)) (~ i)) ∙∙ q' ∙∙ (λ i → ·Rid (0RightAnnihilates (f ^ m) i) i) Σhelper2 : Σ[ m ∈ ℕ ] f ^ m · g ^ n · r ≡ 0r → Σ[ u ∈ S[fg] ] fst u · r ≡ 0r Σhelper2 (m , q') = (((f · g) ^ l) , PT.∣ l , refl ∣₁) , path where l = max m n path : (f · g) ^ l · r ≡ 0r path = (f · g) ^ l · r ≡⟨ cong (_· r) (^-ldist-· _ _ _) ⟩ f ^ l · g ^ l · r ≡⟨ cong₂ (λ x y → f ^ x · g ^ y · r) (sym (≤-∸-+-cancel {m = m} left-≤-max)) (sym (≤-∸-+-cancel {m = n} right-≤-max)) ⟩ f ^ (l ∸ m +ℕ m) · g ^ (l ∸ n +ℕ n) · r ≡⟨ cong₂ (λ x y → x · y · r) (sym (·-of-^-is-^-of-+ _ _ _)) (sym (·-of-^-is-^-of-+ _ _ _)) ⟩ f ^ (l ∸ m) · f ^ m · (g ^ (l ∸ n) · g ^ n) · r ≡⟨ cong (_· r) (·CommAssocSwap _ _ _ _) ⟩ f ^ (l ∸ m) · g ^ (l ∸ n) · (f ^ m · g ^ n) · r ≡⟨ sym (·Assoc _ _ _) ⟩ f ^ (l ∸ m) · g ^ (l ∸ n) · (f ^ m · g ^ n · r) ≡⟨ cong (f ^ (l ∸ m) · g ^ (l ∸ n) ·_) q' ⟩ f ^ (l ∸ m) · g ^ (l ∸ n) · 0r ≡⟨ 0RightAnnihilates _ ⟩ 0r ∎ surχ pathtoR[1/fg] = invElPropElim _ (λ _ → isPropPropTrunc) toGoal where open Exponentiation R[1/f]AsCommRing renaming (_^_ to _^ᶠ_) hiding (·-of-^-is-^-of-+ ; ^-ldist-·) open CommRingStr (snd R[1/f][1/g]AsCommRing) renaming (_·_ to _·R[1/f][1/g]_) hiding (1r ; ·Lid ; ·Rid ; ·Assoc) open Units R[1/f][1/g]AsCommRing g/1 : R[1/_] R' f g/1 = [ g , 1r , powersFormMultClosedSubset R' f .containsOne ] S[fg] = Loc.S R' ([_ⁿ|n≥0] R' (f · g)) (powersFormMultClosedSubset R' (f · g)) baseCase : (r : R) (m n : ℕ) → ∃[ x ∈ R × S[fg] ] (x .fst /1/1) ≡ [ [ r , f ^ m , PT.∣ m , refl ∣₁ ] , [ g ^ n , 1r , PT.∣ 0 , refl ∣₁ ] , PT.∣ n , ^-respects-/1 _ n ∣₁ ] ·R[1/f][1/g] (x .snd .fst /1/1) baseCase r m n = PT.∣ ((r · f ^ (l ∸ m) · g ^ (l ∸ n)) -- x .fst , (f · g) ^ l , PT.∣ l , refl ∣₁) -- x .snd , eq/ _ _ ((1ᶠ , PT.∣ 0 , refl ∣₁) , eq/ _ _ ((1r , PT.∣ 0 , refl ∣₁) , path)) ∣₁ -- reduce equality of double fractions into equality in R where eq1 : ∀ r flm gln gn fm → 1r · (1r · (r · flm · gln) · (gn · 1r)) · (1r · (fm · 1r) · 1r) ≡ r · flm · (gln · gn) · fm eq1 = solve R' eq2 : ∀ r flm gl fm → r · flm · gl · fm ≡ r · (flm · fm ) · gl eq2 = solve R' eq3 : ∀ r fgl → r · fgl ≡ 1r · (1r · (r · fgl) · 1r) · (1r · 1r · (1r · 1r)) eq3 = solve R' l = max m n path : 1r · (1r · (r · f ^ (l ∸ m) · g ^ (l ∸ n)) · (g ^ n · 1r)) · (1r · (f ^ m · 1r) · 1r) ≡ 1r · (1r · (r · (f · g) ^ l) · 1r) · (1r · 1r · (1r · 1r)) path = 1r · (1r · (r · f ^ (l ∸ m) · g ^ (l ∸ n)) · (g ^ n · 1r)) · (1r · (f ^ m · 1r) · 1r) ≡⟨ eq1 r (f ^ (l ∸ m)) (g ^ (l ∸ n)) (g ^ n) (f ^ m) ⟩ r · f ^ (l ∸ m) · (g ^ (l ∸ n) · g ^ n) · f ^ m ≡⟨ cong (λ x → r · f ^ (l ∸ m) · x · f ^ m) (·-of-^-is-^-of-+ _ _ _) ⟩ r · f ^ (l ∸ m) · g ^ (l ∸ n +ℕ n) · f ^ m ≡⟨ cong (λ x → r · f ^ (l ∸ m) · g ^ x · f ^ m) (≤-∸-+-cancel right-≤-max) ⟩ r · f ^ (l ∸ m) · g ^ l · f ^ m ≡⟨ eq2 r (f ^ (l ∸ m)) (g ^ l) (f ^ m) ⟩ r · (f ^ (l ∸ m) · f ^ m) · g ^ l ≡⟨ cong (λ x → r · x · g ^ l) (·-of-^-is-^-of-+ _ _ _) ⟩ r · f ^ (l ∸ m +ℕ m) · g ^ l ≡⟨ cong (λ x → r · f ^ x · g ^ l) (≤-∸-+-cancel left-≤-max) ⟩ r · f ^ l · g ^ l ≡⟨ sym (·Assoc _ _ _) ⟩ r · (f ^ l · g ^ l) ≡⟨ cong (r ·_) (sym (^-ldist-· _ _ _)) ⟩ r · (f · g) ^ l ≡⟨ eq3 r ((f · g) ^ l) ⟩ 1r · (1r · (r · (f · g) ^ l) · 1r) · (1r · 1r · (1r · 1r)) ∎ base-^ᶠ-helper : (r : R) (m n : ℕ) → ∃[ x ∈ R × S[fg] ] (x .fst /1/1) ≡ [ [ r , f ^ m , PT.∣ m , refl ∣₁ ] , g/1 ^ᶠ n , PT.∣ n , refl ∣₁ ] ·R[1/f][1/g] (x .snd .fst /1/1) base-^ᶠ-helper r m n = subst (λ y → ∃[ x ∈ R × S[fg] ] (x .fst /1/1) ≡ [ [ r , f ^ m , PT.∣ m , refl ∣₁ ] , y ] ·R[1/f][1/g] (x .snd .fst /1/1)) (Σ≡Prop (λ _ → isPropPropTrunc) (^-respects-/1 _ n)) (baseCase r m n) indStep : (r : R[1/_] R' f) (n : ℕ) → ∃[ x ∈ R × S[fg] ] (x .fst /1/1) ≡ [ r , g/1 ^ᶠ n , PT.∣ n , refl ∣₁ ] ·R[1/f][1/g] (x .snd .fst /1/1) indStep = invElPropElim _ (λ _ → isPropΠ λ _ → isPropPropTrunc) base-^ᶠ-helper toGoal : (r : R[1/_] R' f) (n : ℕ) → ∃[ x ∈ R × S[fg] ] (x .fst /1/1) ·R[1/f][1/g] ((x .snd .fst /1/1) ⁻¹) ⦃ φS⊆Aˣ pathtoR[1/fg] (x .snd .fst) (x .snd .snd) ⦄ ≡ [ r , g/1 ^ᶠ n , PT.∣ n , refl ∣₁ ] toGoal r n = PT.map Σhelper (indStep r n) where Σhelper : Σ[ x ∈ R × S[fg] ] (x .fst /1/1) ≡ [ r , g/1 ^ᶠ n , PT.∣ n , refl ∣₁ ] ·R[1/f][1/g] (x .snd .fst /1/1) → Σ[ x ∈ R × S[fg] ] (x .fst /1/1) ·R[1/f][1/g] ((x .snd .fst /1/1) ⁻¹) ⦃ φS⊆Aˣ pathtoR[1/fg] (x .snd .fst) (x .snd .snd) ⦄ ≡ [ r , g/1 ^ᶠ n , PT.∣ n , refl ∣₁ ] Σhelper ((r' , s , s∈S[fg]) , p) = (r' , s , s∈S[fg]) , ⁻¹-eq-elim ⦃ φS⊆Aˣ pathtoR[1/fg] s s∈S[fg] ⦄ p -- the main result: localising at one element and then at another is -- the same as localising at the product. -- takes forever to compute without experimental lossy unification R[1/fg]≡R[1/f][1/g] : R[1/fg]AsCommRing ≡ R[1/f][1/g]AsCommRing R[1/fg]≡R[1/f][1/g] = S⁻¹RChar R' ([_ⁿ|n≥0] R' (f · g)) (powersFormMultClosedSubset R' (f · g)) _ /1/1AsCommRingHom pathtoR[1/fg] -- In this module we construct the map R[1/fg]→R[1/f][1/g] directly -- and show that it is equal (although not judgementally) to the map induced -- by the universal property of localisation, i.e. transporting along the path -- constructed above. Given that this is the easier direction, we can see that -- it is pretty cumbersome to prove R[1/fg]≡R[1/f][1/g] directly, -- which illustrates the usefulness of S⁻¹RChar quite well. private module check where φ : R[1/fg] → R[1/f][1/g] φ = SQ.rec squash/ ϕ ϕcoh where S[fg] = Loc.S R' ([_ⁿ|n≥0] R' (f · g)) (powersFormMultClosedSubset R' (f · g)) curriedϕΣ : (r s : R) → Σ[ n ∈ ℕ ] s ≡ (f · g) ^ n → R[1/f][1/g] curriedϕΣ r s (n , s≡fg^n) = [ [ r , (f ^ n) , PT.∣ n , refl ∣₁ ] , [ (g ^ n) , 1r , PT.∣ 0 , refl ∣₁ ] --denominator , PT.∣ n , ^-respects-/1 R' n ∣₁ ] curriedϕ : (r s : R) → ∃[ n ∈ ℕ ] s ≡ (f · g) ^ n → R[1/f][1/g] curriedϕ r s = elim→Set (λ _ → squash/) (curriedϕΣ r s) coh where coh : (x y : Σ[ n ∈ ℕ ] s ≡ (f · g) ^ n) → curriedϕΣ r s x ≡ curriedϕΣ r s y coh (n , s≡fg^n) (m , s≡fg^m) = eq/ _ _ ((1ᶠ , PT.∣ 0 , refl ∣₁) , eq/ _ _ ( (1r , powersFormMultClosedSubset R' f .containsOne) , path)) where eq1 : ∀ r gm fm → 1r · (1r · r · gm) · (1r · fm · 1r) ≡ r · (gm · fm) eq1 = solve R' path : 1r · (1r · r · (g ^ m)) · (1r · (f ^ m) · 1r) ≡ 1r · (1r · r · (g ^ n)) · (1r · (f ^ n) · 1r) path = 1r · (1r · r · (g ^ m)) · (1r · (f ^ m) · 1r) ≡⟨ eq1 r (g ^ m) (f ^ m) ⟩ r · (g ^ m · f ^ m) ≡⟨ cong (r ·_) (sym (^-ldist-· g f m)) ⟩ r · ((g · f) ^ m) ≡⟨ cong (λ x → r · (x ^ m)) (·Comm _ _) ⟩ r · ((f · g) ^ m) ≡⟨ cong (r ·_) ((sym s≡fg^m) ∙ s≡fg^n) ⟩ r · ((f · g) ^ n) ≡⟨ cong (λ x → r · (x ^ n)) (·Comm _ _) ⟩ r · ((g · f) ^ n) ≡⟨ cong (r ·_) (^-ldist-· g f n) ⟩ r · (g ^ n · f ^ n) ≡⟨ sym (eq1 r (g ^ n) (f ^ n)) ⟩ 1r · (1r · r · (g ^ n)) · (1r · (f ^ n) · 1r) ∎ ϕ : R × S[fg] → R[1/f][1/g] ϕ = uncurry2 curriedϕ -- λ (r / (fg)ⁿ) → ((r / fⁿ) / gⁿ) curriedϕcohΣ : (r s r' s' u : R) → (p : u · r · s' ≡ u · r' · s) → (α : Σ[ n ∈ ℕ ] s ≡ (f · g) ^ n) → (β : Σ[ m ∈ ℕ ] s' ≡ (f · g) ^ m) → (γ : Σ[ l ∈ ℕ ] u ≡ (f · g) ^ l) → ϕ (r , s , PT.∣ α ∣₁) ≡ ϕ (r' , s' , PT.∣ β ∣₁) curriedϕcohΣ r s r' s' u p (n , s≡fgⁿ) (m , s'≡fgᵐ) (l , u≡fgˡ) = eq/ _ _ ( ( [ (g ^ l) , 1r , powersFormMultClosedSubset R' f .containsOne ] , PT.∣ l , ^-respects-/1 R' l ∣₁) , eq/ _ _ ((f ^ l , PT.∣ l , refl ∣₁) , path)) where eq1 : ∀ fl gl r gm fm → fl · (gl · r · gm) · (1r · fm · 1r) ≡ fl · gl · r · (gm · fm) eq1 = solve R' path : f ^ l · (g ^ l · transp (λ i → R) i0 r · transp (λ i → R) i0 (g ^ m)) · (1r · transp (λ i → R) i0 (f ^ m) · transp (λ i → R) i0 1r) ≡ f ^ l · (g ^ l · transp (λ i → R) i0 r' · transp (λ i → R) i0 (g ^ n)) · (1r · transp (λ i → R) i0 (f ^ n) · transp (λ i → R) i0 1r) path = f ^ l · (g ^ l · transp (λ i → R) i0 r · transp (λ i → R) i0 (g ^ m)) · (1r · transp (λ i → R) i0 (f ^ m) · transp (λ i → R) i0 1r) ≡⟨ (λ i → f ^ l · (g ^ l · transportRefl r i · transportRefl (g ^ m) i) · (1r · transportRefl (f ^ m) i · transportRefl 1r i)) ⟩ f ^ l · (g ^ l · r · g ^ m) · (1r · f ^ m · 1r) ≡⟨ eq1 (f ^ l) (g ^ l) r (g ^ m) (f ^ m) ⟩ f ^ l · g ^ l · r · (g ^ m · f ^ m) ≡⟨ (λ i → ^-ldist-· f g l (~ i) · r · ^-ldist-· g f m (~ i)) ⟩ (f · g) ^ l · r · (g · f) ^ m ≡⟨ cong (λ x → (f · g) ^ l · r · x ^ m) (·Comm _ _) ⟩ (f · g) ^ l · r · (f · g) ^ m ≡⟨ (λ i → u≡fgˡ (~ i) · r · s'≡fgᵐ (~ i)) ⟩ u · r · s' ≡⟨ p ⟩ u · r' · s ≡⟨ (λ i → u≡fgˡ i · r' · s≡fgⁿ i) ⟩ (f · g) ^ l · r' · (f · g) ^ n ≡⟨ cong (λ x → (f · g) ^ l · r' · x ^ n) (·Comm _ _) ⟩ (f · g) ^ l · r' · (g · f) ^ n ≡⟨ (λ i → ^-ldist-· f g l i · r' · ^-ldist-· g f n i) ⟩ f ^ l · g ^ l · r' · (g ^ n · f ^ n) ≡⟨ sym (eq1 (f ^ l) (g ^ l) r' (g ^ n) (f ^ n)) ⟩ f ^ l · (g ^ l · r' · g ^ n) · (1r · f ^ n · 1r) ≡⟨ (λ i → f ^ l · (g ^ l · transportRefl r' (~ i) · transportRefl (g ^ n) (~ i)) · (1r · transportRefl (f ^ n) (~ i) · transportRefl 1r (~ i))) ⟩ f ^ l · (g ^ l · transp (λ i → R) i0 r' · transp (λ i → R) i0 (g ^ n)) · (1r · transp (λ i → R) i0 (f ^ n) · transp (λ i → R) i0 1r) ∎ curriedϕcoh : (r s r' s' u : R) → (p : u · r · s' ≡ u · r' · s) → (α : ∃[ n ∈ ℕ ] s ≡ (f · g) ^ n) → (β : ∃[ m ∈ ℕ ] s' ≡ (f · g) ^ m) → (γ : ∃[ l ∈ ℕ ] u ≡ (f · g) ^ l) → ϕ (r , s , α) ≡ ϕ (r' , s' , β) curriedϕcoh r s r' s' u p = PT.elim (λ _ → isPropΠ2 (λ _ _ → squash/ _ _)) λ α → PT.elim (λ _ → isPropΠ (λ _ → squash/ _ _)) λ β → PT.rec (squash/ _ _) λ γ → curriedϕcohΣ r s r' s' u p α β γ ϕcoh : (a b : R × S[fg]) → Loc._≈_ R' ([_ⁿ|n≥0] R' (f · g)) (powersFormMultClosedSubset R' (f · g)) a b → ϕ a ≡ ϕ b ϕcoh (r , s , α) (r' , s' , β) ((u , γ) , p) = curriedϕcoh r s r' s' u p α β γ -- the map induced by the universal property open S⁻¹RUniversalProp R' ([_ⁿ|n≥0] R' (f · g)) (powersFormMultClosedSubset R' (f · g)) χ : R[1/fg] → R[1/f][1/g] χ = S⁻¹RHasUniversalProp R[1/f][1/g]AsCommRing /1/1AsCommRingHom fⁿgⁿ/1/1∈R[1/f][1/g]ˣ .fst .fst .fst -- the sanity check: -- both maps send a fraction r/(fg)ⁿ to a double fraction, -- where numerator and denominator are almost the same fraction respectively. -- unfortunately the proofs that the denominators are powers are quite different for -- the two maps, but of course we can ignore them. -- The definition of χ introduces a lot of (1r ·_). Perhaps most surprisingly, -- we have to give the path eq1 for the equality of the numerator of the numerator. φ≡χ : ∀ r → φ r ≡ χ r φ≡χ = invElPropElim _ (λ _ → squash/ _ _) ℕcase where ℕcase : (r : R) (n : ℕ) → φ [ r , (f · g) ^ n , PT.∣ n , refl ∣₁ ] ≡ χ [ r , (f · g) ^ n , PT.∣ n , refl ∣₁ ] ℕcase r n = cong [_] (ΣPathP --look into the components of the double-fractions ( cong [_] (ΣPathP (eq1 , Σ≡Prop (λ x → S'[f] x .snd) (sym (·Lid _)))) , Σ≡Prop (λ x → S'[f][g] x .snd) --ignore proof that denominator is power of g/1 ( cong [_] (ΣPathP (sym (·Lid _) , Σ≡Prop (λ x → S'[f] x .snd) (sym (·Lid _))))))) where S'[f] = ([_ⁿ|n≥0] R' f) S'[f][g] = ([_ⁿ|n≥0] R[1/f]AsCommRing [ g , 1r , powersFormMultClosedSubset R' f .containsOne ]) eq1 : transp (λ i → fst R') i0 r ≡ r · transp (λ i → fst R') i0 1r eq1 = transportRefl r ∙∙ sym (·Rid r) ∙∙ cong (r ·_) (sym (transportRefl 1r)) ",12145,True,2781.3016234696,median "------------------------------------------------------------------------ -- A variant of Paolo Capriotti's variant of higher lenses ------------------------------------------------------------------------ {-# OPTIONS --cubical #-} import Equality.Path as P module Lens.Non-dependent.Higher.Capriotti.Variant {e⁺} (eq : ∀ {a p} → P.Equality-with-paths a p e⁺) where open P.Derived-definitions-and-properties eq open import Logical-equivalence using (_⇔_) open import Prelude as P hiding (id) open import Bijection equality-with-J as B using (_↔_) open import Equality.Path.Isomorphisms eq open import Equivalence equality-with-J as Eq using (_≃_) open import Function-universe equality-with-J as F hiding (id; _∘_) open import H-level equality-with-J open import H-level.Closure equality-with-J open import H-level.Truncation.Propositional eq as T using (∥_∥; ∣_∣) open import Preimage equality-with-J as Preimage open import Univalence-axiom equality-with-J open import Lens.Non-dependent eq import Lens.Non-dependent.Higher eq as Higher private variable a b p : Level A B : Type a P Q : A → Type p ------------------------------------------------------------------------ -- Coherently-constant -- Coherently constant type-valued functions. -- -- This definition is based on Paolo Capriotti's definition of higher -- lenses, but uses a family of equivalences instead of an equality. Coherently-constant : {A : Type a} → (A → Type p) → Type (a ⊔ lsuc p) Coherently-constant {p = p} {A = A} P = ∃ λ (Q : ∥ A ∥ → Type p) → ∀ x → P x ≃ Q ∣ x ∣ -- A preservation lemma for Coherently-constant. -- -- Note that P and Q must target the same universe. Coherently-constant-map : {P : A → Type p} {Q : B → Type p} (f : B → A) → (∀ x → P (f x) ≃ Q x) → Coherently-constant P → Coherently-constant Q Coherently-constant-map {P = P} {Q = Q} f P≃Q (R , P≃R) = R ∘ T.∥∥-map f , λ x → Q x ↝⟨ inverse $ P≃Q x ⟩ P (f x) ↝⟨ P≃R (f x) ⟩□ R ∣ f x ∣ □ -- Coherently-constant is, in a certain sense, closed under Σ. -- -- This lemma is due to Paolo Capriotti. Coherently-constant-Σ : Coherently-constant P → Coherently-constant Q → Coherently-constant (λ x → ∃ λ (y : P x) → Q (x , y)) Coherently-constant-Σ {P = P} {Q = Q} (P′ , p) (Q′ , q) = (λ x → ∃ λ (y : P′ x) → Q′ (T.elim (λ x → P′ x → ∥ ∃ P ∥) (λ _ → Π-closure ext 1 λ _ → T.truncation-is-proposition) (λ x y → ∣ x , _≃_.from (p x) y ∣) x y)) , (λ x → (∃ λ (y : P x) → Q (x , y)) ↝⟨ (Σ-cong (p x) λ y → Q (x , y) ↝⟨ q (x , y) ⟩ Q′ ∣ x , y ∣ ↝⟨ ≡⇒≃ $ cong Q′ $ T.truncation-is-proposition _ _ ⟩□ Q′ ∣ x , _≃_.from (p x) (_≃_.to (p x) y) ∣ □) ⟩□ (∃ λ (y : P′ ∣ x ∣) → Q′ ∣ x , _≃_.from (p x) y ∣) □) ------------------------------------------------------------------------ -- The lens type family -- Paolo Capriotti's variant of higher lenses, but with a family of -- equivalences instead of an equality. Lens : Type a → Type b → Type (lsuc (a ⊔ b)) Lens A B = ∃ λ (get : A → B) → Coherently-constant (get ⁻¹_) -- Some derived definitions (based on Capriotti's). module Lens {A : Type a} {B : Type b} (l : Lens A B) where -- A getter. get : A → B get = proj₁ l -- A predicate. H : Pow a ∥ B ∥ H = proj₁ (proj₂ l) -- An equivalence. get⁻¹-≃ : ∀ b → get ⁻¹ b ≃ H ∣ b ∣ get⁻¹-≃ = proj₂ (proj₂ l) -- All the getter's ""preimages"" are equivalent. get⁻¹-constant : (b₁ b₂ : B) → get ⁻¹ b₁ ≃ get ⁻¹ b₂ get⁻¹-constant b₁ b₂ = get ⁻¹ b₁ ↝⟨ get⁻¹-≃ b₁ ⟩ H ∣ b₁ ∣ ↝⟨ ≡⇒≃ $ cong H $ T.truncation-is-proposition _ _ ⟩ H ∣ b₂ ∣ ↝⟨ inverse $ get⁻¹-≃ b₂ ⟩□ get ⁻¹ b₂ □ -- The two directions of get⁻¹-constant. get⁻¹-const : (b₁ b₂ : B) → get ⁻¹ b₁ → get ⁻¹ b₂ get⁻¹-const b₁ b₂ = _≃_.to (get⁻¹-constant b₁ b₂) get⁻¹-const⁻¹ : (b₁ b₂ : B) → get ⁻¹ b₂ → get ⁻¹ b₁ get⁻¹-const⁻¹ b₁ b₂ = _≃_.from (get⁻¹-constant b₁ b₂) -- Some coherence properties. get⁻¹-const-∘ : (b₁ b₂ b₃ : B) (p : get ⁻¹ b₁) → get⁻¹-const b₂ b₃ (get⁻¹-const b₁ b₂ p) ≡ get⁻¹-const b₁ b₃ p get⁻¹-const-∘ b₁ b₂ b₃ p = _≃_.from (get⁻¹-≃ b₃) (≡⇒→ (cong H $ T.truncation-is-proposition _ _) (_≃_.to (get⁻¹-≃ b₂) (_≃_.from (get⁻¹-≃ b₂) (≡⇒→ (cong H $ T.truncation-is-proposition _ _) (_≃_.to (get⁻¹-≃ b₁) p))))) ≡⟨ cong (_≃_.from (get⁻¹-≃ _) ∘ ≡⇒→ _) $ _≃_.right-inverse-of (get⁻¹-≃ _) _ ⟩ _≃_.from (get⁻¹-≃ b₃) (≡⇒→ (cong H $ T.truncation-is-proposition _ _) (≡⇒→ (cong H $ T.truncation-is-proposition _ _) (_≃_.to (get⁻¹-≃ b₁) p))) ≡⟨ cong (λ eq → _≃_.from (get⁻¹-≃ _) (_≃_.to eq (_≃_.to (get⁻¹-≃ _) _))) $ sym $ ≡⇒≃-trans ext _ _ ⟩ _≃_.from (get⁻¹-≃ b₃) (≡⇒→ (trans (cong H $ T.truncation-is-proposition _ _) (cong H $ T.truncation-is-proposition _ _)) (_≃_.to (get⁻¹-≃ b₁) p)) ≡⟨ cong (λ eq → _≃_.from (get⁻¹-≃ b₃) (≡⇒→ eq _)) $ trans (sym $ cong-trans _ _ _) $ cong (cong H) $ mono₁ 1 T.truncation-is-proposition _ _ ⟩∎ _≃_.from (get⁻¹-≃ b₃) (≡⇒→ (cong H $ T.truncation-is-proposition _ _) (_≃_.to (get⁻¹-≃ b₁) p)) ∎ get⁻¹-const-id : (b : B) (p : get ⁻¹ b) → get⁻¹-const b b p ≡ p get⁻¹-const-id b p = get⁻¹-const b b p ≡⟨ sym $ _≃_.left-inverse-of (get⁻¹-constant _ _) _ ⟩ get⁻¹-const⁻¹ b b (get⁻¹-const b b (get⁻¹-const b b p)) ≡⟨ cong (get⁻¹-const⁻¹ b b) $ get⁻¹-const-∘ _ _ _ _ ⟩ get⁻¹-const⁻¹ b b (get⁻¹-const b b p) ≡⟨ _≃_.left-inverse-of (get⁻¹-constant _ _) _ ⟩∎ p ∎ get⁻¹-const-inverse : (b₁ b₂ : B) (p : get ⁻¹ b₁) → get⁻¹-const b₁ b₂ p ≡ get⁻¹-const⁻¹ b₂ b₁ p get⁻¹-const-inverse b₁ b₂ p = sym $ _≃_.to-from (get⁻¹-constant _ _) ( get⁻¹-const b₂ b₁ (get⁻¹-const b₁ b₂ p) ≡⟨ get⁻¹-const-∘ _ _ _ _ ⟩ get⁻¹-const b₁ b₁ p ≡⟨ get⁻¹-const-id _ _ ⟩∎ p ∎) -- A setter. set : A → B → A set a b = $⟨ get⁻¹-const _ _ ⟩ (get ⁻¹ get a → get ⁻¹ b) ↝⟨ _$ (a , refl _) ⟩ get ⁻¹ b ↝⟨ proj₁ ⟩□ A □ -- Lens laws. get-set : ∀ a b → get (set a b) ≡ b get-set a b = get (proj₁ (get⁻¹-const (get a) b (a , refl _))) ≡⟨ proj₂ (get⁻¹-const (get a) b (a , refl _)) ⟩∎ b ∎ set-get : ∀ a → set a (get a) ≡ a set-get a = proj₁ (get⁻¹-const (get a) (get a) (a , refl _)) ≡⟨ cong proj₁ $ get⁻¹-const-id _ _ ⟩∎ a ∎ set-set : ∀ a b₁ b₂ → set (set a b₁) b₂ ≡ set a b₂ set-set a b₁ b₂ = proj₁ (get⁻¹-const (get (set a b₁)) b₂ (set a b₁ , refl _)) ≡⟨ elim¹ (λ {b} eq → proj₁ (get⁻¹-const (get (set a b₁)) b₂ (set a b₁ , refl _)) ≡ proj₁ (get⁻¹-const b b₂ (set a b₁ , eq))) (refl _) (get-set a b₁) ⟩ proj₁ (get⁻¹-const b₁ b₂ (set a b₁ , get-set a b₁)) ≡⟨⟩ proj₁ (get⁻¹-const b₁ b₂ (get⁻¹-const (get a) b₁ (a , refl _))) ≡⟨ cong proj₁ $ get⁻¹-const-∘ _ _ _ _ ⟩∎ proj₁ (get⁻¹-const (get a) b₂ (a , refl _)) ∎ -- TODO: Can get-set-get and get-set-set be proved for the lens laws -- given above? instance -- The lenses defined above have getters and setters. has-getter-and-setter : Has-getter-and-setter (Lens {a = a} {b = b}) has-getter-and-setter = record { get = Lens.get ; set = Lens.set } ------------------------------------------------------------------------ -- Equality characterisation lemmas -- An equality characterisation lemma. equality-characterisation₁ : {A : Type a} {B : Type b} {l₁ l₂ : Lens A B} → Block ""equality-characterisation"" → let open Lens in (l₁ ≡ l₂) ≃ (∃ λ (g : get l₁ ≡ get l₂) → ∃ λ (h : H l₁ ≡ H l₂) → ∀ b p → subst (_$ ∣ b ∣) h (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym g) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) equality-characterisation₁ {a = a} {l₁ = l₁} {l₂ = l₂} ⊠ = l₁ ≡ l₂ ↝⟨ inverse $ Eq.≃-≡ $ Eq.↔⇒≃ Σ-assoc ⟩ ((get l₁ , H l₁) , get⁻¹-≃ l₁) ≡ ((get l₂ , H l₂) , get⁻¹-≃ l₂) ↔⟨ inverse B.Σ-≡,≡↔≡ ⟩ (∃ λ (eq : (get l₁ , H l₁) ≡ (get l₂ , H l₂)) → subst (λ (g , H) → ∀ b → g ⁻¹ b ≃ H ∣ b ∣) eq (get⁻¹-≃ l₁) ≡ get⁻¹-≃ l₂) ↝⟨ (Σ-cong-contra ≡×≡↔≡ λ _ → F.id) ⟩ (∃ λ ((g , h) : get l₁ ≡ get l₂ × H l₁ ≡ H l₂) → subst (λ (g , H) → ∀ b → g ⁻¹ b ≃ H ∣ b ∣) (cong₂ _,_ g h) (get⁻¹-≃ l₁) ≡ get⁻¹-≃ l₂) ↔⟨ inverse Σ-assoc ⟩ (∃ λ (g : get l₁ ≡ get l₂) → ∃ λ (h : H l₁ ≡ H l₂) → subst (λ (g , H) → ∀ b → g ⁻¹ b ≃ H ∣ b ∣) (cong₂ _,_ g h) (get⁻¹-≃ l₁) ≡ get⁻¹-≃ l₂) ↝⟨ (∃-cong λ _ → ∃-cong λ _ → inverse $ Eq.extensionality-isomorphism ext) ⟩ (∃ λ (g : get l₁ ≡ get l₂) → ∃ λ (h : H l₁ ≡ H l₂) → ∀ b → subst (λ (g , H) → ∀ b → g ⁻¹ b ≃ H ∣ b ∣) (cong₂ _,_ g h) (get⁻¹-≃ l₁) b ≡ get⁻¹-≃ l₂ b) ↝⟨ (∃-cong λ _ → ∃-cong λ _ → ∀-cong ext λ _ → ≡⇒↝ _ $ cong (_≡ _) $ sym $ push-subst-application _ _) ⟩ (∃ λ (g : get l₁ ≡ get l₂) → ∃ λ (h : H l₁ ≡ H l₂) → ∀ b → subst (λ (g , H) → g ⁻¹ b ≃ H ∣ b ∣) (cong₂ _,_ g h) (get⁻¹-≃ l₁ b) ≡ get⁻¹-≃ l₂ b) ↔⟨ (∃-cong λ _ → ∃-cong λ _ → ∀-cong ext λ _ → inverse $ ≃-to-≡↔≡ ext) ⟩ (∃ λ (g : get l₁ ≡ get l₂) → ∃ λ (h : H l₁ ≡ H l₂) → ∀ b p → _≃_.to (subst (λ (g , H) → g ⁻¹ b ≃ H ∣ b ∣) (cong₂ _,_ g h) (get⁻¹-≃ l₁ b)) p ≡ _≃_.to (get⁻¹-≃ l₂ b) p) ↝⟨ (∃-cong λ _ → ∃-cong λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → ≡⇒↝ _ $ cong (_≡ _) $ lemma _ _ _ _) ⟩□ (∃ λ (g : get l₁ ≡ get l₂) → ∃ λ (h : H l₁ ≡ H l₂) → ∀ b p → subst (_$ ∣ b ∣) h (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym g) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) □ where open Lens lemma : ∀ _ _ _ _ → _ ≡ _ lemma g h b p = _≃_.to (subst (λ (g , H) → g ⁻¹ b ≃ H ∣ b ∣) (cong₂ _,_ g h) (get⁻¹-≃ l₁ b)) p ≡⟨ cong (_$ p) Eq.to-subst ⟩ subst (λ (g , H) → g ⁻¹ b → H ∣ b ∣) (cong₂ _,_ g h) (_≃_.to (get⁻¹-≃ l₁ b)) p ≡⟨ subst-→ ⟩ subst (λ (g , H) → H ∣ b ∣) (cong₂ _,_ g h) (_≃_.to (get⁻¹-≃ l₁ b) (subst (λ (g , H) → g ⁻¹ b) (sym $ cong₂ _,_ g h) p)) ≡⟨ subst-∘ _ _ _ ⟩ subst (_$ ∣ b ∣) (cong proj₂ $ cong₂ _,_ g h) (_≃_.to (get⁻¹-≃ l₁ b) (subst (λ (g , H) → g ⁻¹ b) (sym $ cong₂ _,_ g h) p)) ≡⟨ cong₂ (λ p q → subst (λ (H : Pow a _) → H ∣ b ∣) p (_≃_.to (get⁻¹-≃ l₁ b) q)) (cong-proj₂-cong₂-, _ _) (subst-∘ _ _ _) ⟩ subst (_$ ∣ b ∣) h (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (cong proj₁ $ sym $ cong₂ _,_ g h) p)) ≡⟨ cong (λ eq → subst (_$ ∣ b ∣) h (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) eq p))) $ trans (cong-sym _ _) $ cong sym $ cong-proj₁-cong₂-, _ _ ⟩∎ subst (_$ ∣ b ∣) h (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym g) p)) ∎ -- Another equality characterisation lemma. equality-characterisation₂ : {l₁ l₂ : Lens A B} → Block ""equality-characterisation"" → let open Lens in (l₁ ≡ l₂) ≃ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (h : ∀ b → H l₁ b ≡ H l₂ b) → ∀ b p → subst P.id (h ∣ b ∣) (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym (⟨ext⟩ g)) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) equality-characterisation₂ {l₁ = l₁} {l₂ = l₂} ⊠ = l₁ ≡ l₂ ↝⟨ equality-characterisation₁ ⊠ ⟩ (∃ λ (g : get l₁ ≡ get l₂) → ∃ λ (h : H l₁ ≡ H l₂) → ∀ b p → subst (_$ ∣ b ∣) h (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym g) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) ↝⟨ (Σ-cong-contra (Eq.extensionality-isomorphism bad-ext) λ _ → Σ-cong-contra (Eq.extensionality-isomorphism bad-ext) λ _ → F.id) ⟩ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (h : ∀ b → H l₁ b ≡ H l₂ b) → ∀ b p → subst (_$ ∣ b ∣) (⟨ext⟩ h) (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym (⟨ext⟩ g)) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) ↝⟨ (∃-cong λ _ → ∃-cong λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → ≡⇒↝ _ $ cong (_≡ _) $ subst-ext _ _) ⟩□ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (h : ∀ b → H l₁ b ≡ H l₂ b) → ∀ b p → subst P.id (h ∣ b ∣) (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym (⟨ext⟩ g)) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) □ where open Lens -- Yet another equality characterisation lemma. equality-characterisation₃ : {A : Type a} {B : Type b} {l₁ l₂ : Lens A B} → Block ""equality-characterisation"" → Univalence (a ⊔ b) → let open Lens in (l₁ ≡ l₂) ≃ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (h : ∀ b → H l₁ b ≃ H l₂ b) → ∀ b p → _≃_.to (h ∣ b ∣) (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym (⟨ext⟩ g)) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) equality-characterisation₃ {l₁ = l₁} {l₂ = l₂} ⊠ univ = l₁ ≡ l₂ ↝⟨ equality-characterisation₂ ⊠ ⟩ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (h : ∀ b → H l₁ b ≡ H l₂ b) → ∀ b p → subst P.id (h ∣ b ∣) (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym (⟨ext⟩ g)) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) ↝⟨ (∃-cong λ _ → Σ-cong-contra (∀-cong ext λ _ → inverse $ ≡≃≃ univ) λ _ → F.id) ⟩ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (h : ∀ b → H l₁ b ≃ H l₂ b) → ∀ b p → subst P.id (≃⇒≡ univ (h ∣ b ∣)) (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym (⟨ext⟩ g)) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) ↝⟨ (∃-cong λ _ → ∃-cong λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → ≡⇒↝ _ $ cong (_≡ _) $ trans (subst-id-in-terms-of-≡⇒↝ equivalence) $ cong (λ eq → _≃_.to eq _) $ _≃_.right-inverse-of (≡≃≃ univ) _) ⟩□ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (h : ∀ b → H l₁ b ≃ H l₂ b) → ∀ b p → _≃_.to (h ∣ b ∣) (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym (⟨ext⟩ g)) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) □ where open Lens ------------------------------------------------------------------------ -- Conversion functions -- The lenses defined above can be converted to and from the lenses -- defined in Higher. Lens⇔Higher-lens : Lens A B ⇔ Higher.Lens A B Lens⇔Higher-lens {A = A} {B = B} = record { to = λ (g , H , eq) → record { R = Σ ∥ B ∥ H ; equiv = A ↔⟨ (inverse $ drop-⊤-right λ _ → _⇔_.to contractible⇔↔⊤ $ other-singleton-contractible _) ⟩ (∃ λ (a : A) → ∃ λ (b : B) → g a ≡ b) ↔⟨ ∃-comm ⟩ (∃ λ (b : B) → g ⁻¹ b) ↝⟨ ∃-cong eq ⟩ (∃ λ (b : B) → H ∣ b ∣) ↝⟨ (Σ-cong (inverse T.∥∥×≃) λ _ → ≡⇒↝ _ $ cong H $ T.truncation-is-proposition _ _) ⟩ (∃ λ ((b , _) : ∥ B ∥ × B) → H b) ↔⟨ Σ-assoc F.∘ (∃-cong λ _ → ×-comm) F.∘ inverse Σ-assoc ⟩□ Σ ∥ B ∥ H × B □ ; inhabited = proj₁ } ; from = λ l → Higher.Lens.get l , (λ _ → Higher.Lens.R l) , (λ b → inverse (Higher.remainder≃get⁻¹ l b)) } -- The conversion preserves getters and setters. Lens⇔Higher-lens-preserves-getters-and-setters : Preserves-getters-and-setters-⇔ A B Lens⇔Higher-lens Lens⇔Higher-lens-preserves-getters-and-setters = (λ l@(g , H , eq) → refl _ , ⟨ext⟩ λ a → ⟨ext⟩ λ b → let h₁ = _≃_.to (eq (g a)) (a , refl _) h₂ = _≃_.from (≡⇒≃ (cong H _)) (subst (H ∘ proj₁) (sym (_≃_.left-inverse-of T.∥∥×≃ _)) (≡⇒→ (cong H _) h₁)) h₃ = ≡⇒→ (cong H _) h₁ lemma = h₂ ≡⟨ sym $ subst-in-terms-of-inverse∘≡⇒↝ equivalence _ _ _ ⟩ subst H _ (subst (H ∘ proj₁) (sym (_≃_.left-inverse-of T.∥∥×≃ _)) (≡⇒→ (cong H _) h₁)) ≡⟨ cong (λ x → subst H (sym $ T.truncation-is-proposition _ _) (subst (H ∘ proj₁) (sym (_≃_.left-inverse-of T.∥∥×≃ (∣ g a ∣ , b))) x)) $ sym $ subst-in-terms-of-≡⇒↝ equivalence _ _ _ ⟩ subst H _ (subst (H ∘ proj₁) (sym (_≃_.left-inverse-of T.∥∥×≃ _)) (subst H _ h₁)) ≡⟨ cong (λ x → subst H (sym $ T.truncation-is-proposition _ _) x) $ subst-∘ _ _ _ ⟩ subst H _ (subst H _ (subst H _ h₁)) ≡⟨ cong (λ x → subst H (sym $ T.truncation-is-proposition _ _) x) $ subst-subst _ _ _ _ ⟩ subst H _ (subst H _ h₁) ≡⟨ subst-subst _ _ _ _ ⟩ subst H _ h₁ ≡⟨ cong (λ eq → subst H eq h₁) $ mono₁ 1 T.truncation-is-proposition _ _ ⟩ subst H _ h₁ ≡⟨ subst-in-terms-of-≡⇒↝ equivalence _ _ _ ⟩∎ ≡⇒→ (cong H _) h₁ ∎ in Higher.Lens.set (_⇔_.to Lens⇔Higher-lens l) a b ≡⟨⟩ proj₁ (_≃_.from (eq b) h₂) ≡⟨ cong (λ h → proj₁ (_≃_.from (eq b) h)) lemma ⟩ proj₁ (_≃_.from (eq b) h₃) ≡⟨⟩ Lens.set l a b ∎) , (λ l → refl _ , ⟨ext⟩ λ a → ⟨ext⟩ λ b → Lens.set (_⇔_.from Lens⇔Higher-lens l) a b ≡⟨⟩ _≃_.from (Higher.Lens.equiv l) ( ≡⇒→ (cong (λ _ → Higher.Lens.R l) _) (Higher.Lens.remainder l a) , b ) ≡⟨ cong (λ eq → _≃_.from (Higher.Lens.equiv l) (≡⇒→ eq _ , b)) $ cong-const _ ⟩ _≃_.from (Higher.Lens.equiv l) (≡⇒→ (refl _) (Higher.Lens.remainder l a) , b) ≡⟨ cong (λ f → _≃_.from (Higher.Lens.equiv l) (f _ , b)) $ ≡⇒→-refl ⟩ _≃_.from (Higher.Lens.equiv l) (Higher.Lens.remainder l a , b) ≡⟨⟩ Higher.Lens.set l a b ∎) -- Lens A B is equivalent to Higher.Lens A B (assuming univalence). Lens≃Higher-lens : {A : Type a} {B : Type b} → Block ""conversion"" → Univalence (a ⊔ b) → Lens A B ≃ Higher.Lens A B Lens≃Higher-lens {A = A} {B = B} ⊠ univ = Eq.↔→≃ to from to∘from from∘to where to = _⇔_.to Lens⇔Higher-lens from = _⇔_.from Lens⇔Higher-lens to∘from : ∀ l → to (from l) ≡ l to∘from l = _↔_.from (Higher.equality-characterisation₂ ⊠ univ) ( (∥ B ∥ × R ↔⟨ (drop-⊤-left-× λ r → _⇔_.to contractible⇔↔⊤ $ propositional⇒inhabited⇒contractible T.truncation-is-proposition (inhabited r)) ⟩□ R □) , (λ a → ≡⇒→ (cong (λ _ → R) (T.truncation-is-proposition _ _)) (remainder a) ≡⟨ cong (λ eq → ≡⇒→ eq _) $ cong-const _ ⟩ ≡⇒→ (refl _) (remainder a) ≡⟨ cong (_$ _) ≡⇒→-refl ⟩∎ remainder a ∎) , (λ _ → refl _) ) where open Higher.Lens l from∘to : ∀ l → from (to l) ≡ l from∘to l = _≃_.from (equality-characterisation₃ ⊠ univ) ( (λ _ → refl _) , Σ∥B∥H≃H , (λ b p@(a , get-a≡b) → _≃_.to (Σ∥B∥H≃H ∣ b ∣) (_≃_.from (Higher.remainder≃get⁻¹ (to l) b) (subst (_⁻¹ b) (sym (⟨ext⟩ λ _ → refl _)) p)) ≡⟨ cong (_≃_.to (Σ∥B∥H≃H ∣ b ∣) ∘ _≃_.from (Higher.remainder≃get⁻¹ (to l) b)) $ trans (cong (flip (subst (_⁻¹ b)) p) $ trans (cong sym ext-refl) $ sym-refl) $ subst-refl _ _ ⟩ _≃_.to (Σ∥B∥H≃H ∣ b ∣) (_≃_.from (Higher.remainder≃get⁻¹ (to l) b) p) ≡⟨⟩ _≃_.to (Σ∥B∥H≃H ∣ b ∣) (Higher.Lens.remainder (to l) a) ≡⟨⟩ subst H _ (≡⇒→ (cong H _) (_≃_.to (get⁻¹-≃ (get a)) (a , refl _))) ≡⟨ cong (subst H _) $ sym $ subst-in-terms-of-≡⇒↝ equivalence _ _ _ ⟩ subst H _ (subst H _ (_≃_.to (get⁻¹-≃ (get a)) (a , refl _))) ≡⟨ subst-subst _ _ _ _ ⟩ subst H _ (_≃_.to (get⁻¹-≃ (get a)) (a , refl _)) ≡⟨ cong (λ eq → subst H eq (_≃_.to (get⁻¹-≃ (get a)) (a , refl _))) $ mono₁ 1 T.truncation-is-proposition _ _ ⟩ subst H (cong ∣_∣ get-a≡b) (_≃_.to (get⁻¹-≃ (get a)) (a , refl _)) ≡⟨ elim¹ (λ {b} eq → subst H (cong ∣_∣ eq) (_≃_.to (get⁻¹-≃ (get a)) (a , refl _)) ≡ _≃_.to (get⁻¹-≃ b) (a , eq)) ( subst H (cong ∣_∣ (refl _)) (_≃_.to (get⁻¹-≃ (get a)) (a , refl _)) ≡⟨ trans (cong (flip (subst H) _) $ cong-refl _) $ subst-refl _ _ ⟩ _≃_.to (get⁻¹-≃ (get a)) (a , refl _) ∎) _ ⟩∎ _≃_.to (get⁻¹-≃ b) p ∎) ) where open Lens l Σ∥B∥H≃H = λ b → Σ ∥ B ∥ H ↔⟨ (drop-⊤-left-Σ $ _⇔_.to contractible⇔↔⊤ $ propositional⇒inhabited⇒contractible T.truncation-is-proposition b) ⟩□ H b □ -- The equivalence preserves getters and setters. Lens≃Higher-lens-preserves-getters-and-setters : {A : Type a} {B : Type b} (bl : Block ""conversion"") (univ : Univalence (a ⊔ b)) → Preserves-getters-and-setters-⇔ A B (_≃_.logical-equivalence (Lens≃Higher-lens bl univ)) Lens≃Higher-lens-preserves-getters-and-setters ⊠ _ = Lens⇔Higher-lens-preserves-getters-and-setters ------------------------------------------------------------------------ -- Identity -- An identity lens. id : {A : Type a} → Lens A A id = P.id , (λ _ → ↑ _ ⊤) , (λ a → P.id ⁻¹ a ↔⟨ _⇔_.to contractible⇔↔⊤ $ Preimage.id⁻¹-contractible _ ⟩ ⊤ ↔⟨ inverse B.↑↔ ⟩□ ↑ _ ⊤ □) ------------------------------------------------------------------------ -- Some results related to fibres of Lens.set -- When proving that Lens.set ⁻¹ s is a proposition, for -- s : A → B → A, one can assume that B is inhabited. -- -- This result is due to Andrea Vezzosi. [codomain-inhabited→proposition]→proposition : {s : A → B → A} → (B → Is-proposition (Lens.set ⁻¹ s)) ≃ Is-proposition (Lens.set ⁻¹ s) [codomain-inhabited→proposition]→proposition {B = B} {s = s} = block λ b → (B → Is-proposition (Lens.set ⁻¹ s)) ↝⟨ inverse $ T.universal-property (H-level-propositional ext 1) ⟩ (∥ B ∥ → Is-proposition (Lens.set ⁻¹ s)) ↔⟨⟩ (∥ B ∥ → (p q : Lens.set ⁻¹ s) → p ≡ q) ↔⟨ (∀-cong ext λ _ → Π-comm) F.∘ Π-comm ⟩ ((p q : Lens.set ⁻¹ s) → ∥ B ∥ → p ≡ q) ↝⟨ (∀-cong ext λ _ → ∀-cong ext λ _ → lemma b _ _) ⟩ ((p q : Lens.set ⁻¹ s) → p ≡ q) ↔⟨⟩ Is-proposition (Lens.set ⁻¹ s) □ where open Lens lemma : (b : Block ""equality-characterisation"") → (p₁ p₂ : Lens.set ⁻¹ s) → (∥ B ∥ → p₁ ≡ p₂) ≃ (p₁ ≡ p₂) lemma b p₁@(l₁ , eq₁) p₂@(l₂ , eq₂) = (∥ B ∥ → p₁ ≡ p₂) ↝⟨ (∀-cong ext λ _ → ec) ⟩ (∥ B ∥ → ∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (h : ∀ b → H l₁ b ≡ H l₂ b) → ∃ λ (f : ∀ b p → subst P.id (h ∣ b ∣) (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym (⟨ext⟩ g)) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) → ∀ a → ext⁻¹ (subst (λ l → Lens.set l ≡ s) (_≃_.from (equality-characterisation₂ b) (g , h , f)) eq₁) a ≡ ext⁻¹ eq₂ a) ↝⟨ T.push-∥∥ (∣_∣ ∘ get l₁) ⟩ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∥ B ∥ → ∃ λ (h : ∀ b → H l₁ b ≡ H l₂ b) → ∃ λ (f : ∀ b p → subst P.id (h ∣ b ∣) (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym (⟨ext⟩ g)) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) → ∀ a → ext⁻¹ (subst (λ l → Lens.set l ≡ s) (_≃_.from (equality-characterisation₂ b) (g , h , f)) eq₁) a ≡ ext⁻¹ eq₂ a) ↝⟨ (∃-cong λ _ → T.push-∥∥ P.id) ⟩ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (h : ∀ b → H l₁ b ≡ H l₂ b) → ∥ B ∥ → ∃ λ (f : ∀ b p → subst P.id (h ∣ b ∣) (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym (⟨ext⟩ g)) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) → ∀ a → ext⁻¹ (subst (λ l → Lens.set l ≡ s) (_≃_.from (equality-characterisation₂ b) (g , h , f)) eq₁) a ≡ ext⁻¹ eq₂ a) ↝⟨ (∃-cong λ _ → ∃-cong λ _ → T.push-∥∥ ∣_∣) ⟩ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (h : ∀ b → H l₁ b ≡ H l₂ b) → ∃ λ (f : ∀ b p → subst P.id (h ∣ b ∣) (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym (⟨ext⟩ g)) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) → ∥ B ∥ → ∀ a → ext⁻¹ (subst (λ l → Lens.set l ≡ s) (_≃_.from (equality-characterisation₂ b) (g , h , f)) eq₁) a ≡ ext⁻¹ eq₂ a) ↝⟨ (∃-cong λ _ → ∃-cong λ _ → ∃-cong λ _ → T.drop-∥∥ (∣_∣ ∘ get l₁)) ⟩ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (h : ∀ b → H l₁ b ≡ H l₂ b) → ∃ λ (f : ∀ b p → subst P.id (h ∣ b ∣) (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym (⟨ext⟩ g)) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) → ∀ a → ext⁻¹ (subst (λ l → Lens.set l ≡ s) (_≃_.from (equality-characterisation₂ b) (g , h , f)) eq₁) a ≡ ext⁻¹ eq₂ a) ↝⟨ inverse ec ⟩□ p₁ ≡ p₂ □ where ec = p₁ ≡ p₂ ↔⟨ inverse B.Σ-≡,≡↔≡ ⟩ (∃ λ (l : l₁ ≡ l₂) → subst (λ l → Lens.set l ≡ s) l eq₁ ≡ eq₂) ↝⟨ (∃-cong λ _ → inverse $ Eq.≃-≡ $ inverse $ Eq.extensionality-isomorphism ext) ⟩ (∃ λ (l : l₁ ≡ l₂) → ext⁻¹ (subst (λ l → Lens.set l ≡ s) l eq₁) ≡ ext⁻¹ eq₂) ↝⟨ (∃-cong λ _ → inverse $ Eq.extensionality-isomorphism ext) ⟩ (∃ λ (l : l₁ ≡ l₂) → ∀ a → ext⁻¹ (subst (λ l → Lens.set l ≡ s) l eq₁) a ≡ ext⁻¹ eq₂ a) ↝⟨ (Σ-cong-contra (inverse $ equality-characterisation₂ b) λ _ → F.id) ⟩ (∃ λ (l : ∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (h : ∀ b → H l₁ b ≡ H l₂ b) → ∀ b p → subst P.id (h ∣ b ∣) (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym (⟨ext⟩ g)) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) → ∀ a → ext⁻¹ (subst (λ l → Lens.set l ≡ s) (_≃_.from (equality-characterisation₂ b) l) eq₁) a ≡ ext⁻¹ eq₂ a) ↔⟨ (∃-cong λ _ → inverse Σ-assoc) F.∘ inverse Σ-assoc ⟩□ (∃ λ (g : ∀ a → get l₁ a ≡ get l₂ a) → ∃ λ (h : ∀ b → H l₁ b ≡ H l₂ b) → ∃ λ (f : ∀ b p → subst P.id (h ∣ b ∣) (_≃_.to (get⁻¹-≃ l₁ b) (subst (_⁻¹ b) (sym (⟨ext⟩ g)) p)) ≡ _≃_.to (get⁻¹-≃ l₂ b) p) → ∀ a → ext⁻¹ (subst (λ l → Lens.set l ≡ s) (_≃_.from (equality-characterisation₂ b) (g , h , f)) eq₁) a ≡ ext⁻¹ eq₂ a) □ -- The previous result holds also for the lenses in Higher (assuming -- univalence). [codomain-inhabited→proposition]→proposition-for-higher : {A : Type a} {B : Type b} {s : A → B → A} → Univalence (a ⊔ b) → (B → Is-proposition (Higher.Lens.set ⁻¹ s)) ≃ Is-proposition (Higher.Lens.set ⁻¹ s) [codomain-inhabited→proposition]→proposition-for-higher {A = A} {B = B} {s = s} univ = (B → Is-proposition (Higher.Lens.set ⁻¹ s)) ↝⟨ (∀-cong ext λ _ → H-level-cong ext 1 lemma) ⟩ (B → Is-proposition (Lens.set ⁻¹ s)) ↝⟨ [codomain-inhabited→proposition]→proposition ⟩ Is-proposition (Lens.set ⁻¹ s) ↝⟨ inverse $ H-level-cong ext 1 lemma ⟩□ Is-proposition (Higher.Lens.set ⁻¹ s) □ where lemma : Higher.Lens.set ⁻¹ s ≃ Lens.set ⁻¹ s lemma = block λ b → (∃ λ (l : Higher.Lens A B) → Higher.Lens.set l ≡ s) ↝⟨ (Σ-cong (inverse $ Lens≃Higher-lens b univ) λ l → ≡⇒↝ _ $ cong (_≡ s) $ sym $ proj₂ $ proj₂ (Lens≃Higher-lens-preserves-getters-and-setters b univ) l) ⟩□ (∃ λ (l : Lens A B) → Lens.set l ≡ s) □ -- If a certain variant of Higher.lenses-equal-if-setters-equal can be -- proved, then Higher.Lens.set ⁻¹ s is a proposition (assuming -- univalence). lenses-equal-if-setters-equal→set⁻¹-proposition : {A : Type a} {B : Type b} (univ : Univalence (a ⊔ b)) → ((l₁ l₂ : Higher.Lens A B) → B → (s : Higher.Lens.set l₁ ≡ Higher.Lens.set l₂) → ∃ λ (l : l₁ ≡ l₂) → cong Higher.Lens.set l ≡ s) → (s : A → B → A) → Is-proposition (Higher.Lens.set ⁻¹ s) lenses-equal-if-setters-equal→set⁻¹-proposition {B = B} univ lenses-equal-if-setters-equal s = $⟨ lemma ⟩ (B → Is-proposition (Higher.Lens.set ⁻¹ s)) ↝⟨ [codomain-inhabited→proposition]→proposition-for-higher univ ⟩□ Is-proposition (Higher.Lens.set ⁻¹ s) □ where lemma : B → Is-proposition (Higher.Lens.set ⁻¹ s) lemma b (l₁ , set-l₁≡s) (l₂ , set-l₂≡s) = Σ-≡,≡→≡ lemma₁ (subst (λ l → set l ≡ s) lemma₁ set-l₁≡s ≡⟨ subst-∘ _ _ _ ⟩ subst (_≡ s) (cong set lemma₁) set-l₁≡s ≡⟨ subst-trans-sym ⟩ trans (sym (cong set lemma₁)) set-l₁≡s ≡⟨ cong (λ eq → trans (sym eq) set-l₁≡s) lemma₂ ⟩ trans (sym (trans set-l₁≡s (sym set-l₂≡s))) set-l₁≡s ≡⟨ cong (λ eq → trans eq set-l₁≡s) $ sym-trans _ _ ⟩ trans (trans (sym (sym set-l₂≡s)) (sym set-l₁≡s)) set-l₁≡s ≡⟨ trans-[trans-sym]- _ _ ⟩ sym (sym set-l₂≡s) ≡⟨ sym-sym _ ⟩∎ set-l₂≡s ∎) where open Higher.Lens lemma′ = lenses-equal-if-setters-equal l₁ l₂ b (set l₁ ≡⟨ set-l₁≡s ⟩ s ≡⟨ sym set-l₂≡s ⟩∎ set l₂ ∎) lemma₁ = proj₁ lemma′ lemma₂ = proj₂ lemma′ -- If a certain variant of Higher.lenses-equal-if-setters-equal can be -- proved, then lenses with equal setters are equal (assuming -- univalence). lenses-equal-if-setters-equal→lenses-equal-if-setters-equal : {A : Type a} {B : Type b} → Univalence (a ⊔ b) → ((l₁ l₂ : Higher.Lens A B) → B → (s : Higher.Lens.set l₁ ≡ Higher.Lens.set l₂) → ∃ λ (l : l₁ ≡ l₂) → cong Higher.Lens.set l ≡ s) → (l₁ l₂ : Higher.Lens A B) → Higher.Lens.set l₁ ≡ Higher.Lens.set l₂ → l₁ ≡ l₂ lenses-equal-if-setters-equal→lenses-equal-if-setters-equal univ lenses-equal-if-setters-equal l₁ l₂ s = cong proj₁ ( (l₁ , s) ≡⟨ lenses-equal-if-setters-equal→set⁻¹-proposition univ lenses-equal-if-setters-equal (Higher.Lens.set l₂) _ _ ⟩∎ (l₂ , refl _) ∎) ",12279,True,2738.941394403368,median "{- A Cubical proof of Blakers-Massey Theorem (KANG Rongji, Oct. 2021) Based on the previous type-theoretic proof described in Kuen-Bang Hou (Favonia), Eric Finster, Dan Licata, Peter LeFanu Lumsdaine, ""A Mechanization of the Blakers–Massey Connectivity Theorem in Homotopy Type Theory"" (https://arxiv.org/abs/1605.03227) Also the HoTT-Agda formalization by Favonia: (https://github.com/HoTT/HoTT-Agda/blob/master/theorems/homotopy/BlakersMassey.agda) Using cubes explicitly as much as possible. -} {-# OPTIONS --safe #-} module Cubical.Homotopy.BlakersMassey where open import Cubical.Foundations.Prelude open import Cubical.Foundations.GroupoidLaws open import Cubical.Foundations.Transport open import Cubical.Foundations.HLevels open import Cubical.Foundations.Equiv open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Univalence open import Cubical.Data.Nat hiding (elim) open import Cubical.Data.Sigma open import Cubical.HITs.Truncation renaming (hLevelTrunc to Trunc) open import Cubical.Homotopy.Connected open import Cubical.Homotopy.WedgeConnectivity module BlakersMassey {ℓ₁ ℓ₂ ℓ₃ : Level} (X : Type ℓ₁)(Y : Type ℓ₂)(Q : X → Y → Type ℓ₃) {m : HLevel} (leftConn : (x : X) → isConnected (1 + m) (Σ[ y ∈ Y ] Q x y)) {n : HLevel} (rightConn : (y : Y) → isConnected (1 + n) (Σ[ x ∈ X ] Q x y)) where ℓ : Level ℓ = ℓ-max (ℓ-max ℓ₁ ℓ₂) ℓ₃ leftFiber : X → Type (ℓ-max ℓ₂ ℓ₃) leftFiber x = Σ[ y ∈ Y ] Q x y rightFiber : Y → Type (ℓ-max ℓ₁ ℓ₃) rightFiber y = Σ[ x ∈ X ] Q x y {- An alternative formulation of pushout with fewer parameters -} data Pushout : Type ℓ where inl : X → Pushout inr : Y → Pushout push : {x : X}{y : Y} → Q x y → inl x ≡ inr y {- Some preliminary definitions for convenience -} fiberSquare : {x₀ x₁ : X}{y₀ : Y}{p : Pushout}(q₀₀ : Q x₀ y₀)(q₁₀ : Q x₁ y₀) → inl x₁ ≡ p → inl x₀ ≡ p → Type ℓ fiberSquare q₀₀ q₁₀ r' r = PathP (λ i → push q₀₀ (~ i) ≡ r' i) (sym (push q₁₀)) r fiberSquarePush : {x₀ x₁ : X}{y₀ y₁ : Y}(q₀₀ : Q x₀ y₀)(q₁₀ : Q x₁ y₀)(q₁₁ : Q x₁ y₁) → inl x₀ ≡ inr y₁ → Type ℓ fiberSquarePush q₀₀ q₁₀ q₁₁ = fiberSquare q₀₀ q₁₀ (push q₁₁) fiber' : {x₀ : X}{y₀ : Y}(q₀₀ : Q x₀ y₀){x₁ : X}{p : Pushout} → inl x₁ ≡ p → inl x₀ ≡ p → Type ℓ fiber' {y₀ = y₀} q₀₀ {x₁ = x₁} r' r = Σ[ q₁₀ ∈ Q x₁ y₀ ] fiberSquare q₀₀ q₁₀ r' r fiber'Push : {x₀ x₁ : X}{y₀ y₁ : Y}(q₀₀ : Q x₀ y₀)(q₁₁ : Q x₁ y₁) → inl x₀ ≡ inr y₁ → Type ℓ fiber'Push q₀₀ q₁₁ = fiber' q₀₀ (push q₁₁) leftCodeExtended : {x₀ : X}{y₀ : Y}(q₀₀ : Q x₀ y₀) → (x₁ : X){p : Pushout} → inl x₁ ≡ p → inl x₀ ≡ p → Type ℓ leftCodeExtended {y₀ = y₀} q₀₀ x₁ r' r = Trunc (m + n) (fiber' q₀₀ r' r) rightCode : {x₀ : X}(y : Y) → inl x₀ ≡ inr y → Type ℓ rightCode y r = Trunc (m + n) (fiber push r) {- Bunch of coherence data that will be used to construct Code -} {- Definitions of fiber→ -} module _ {x₁ : X}{y₀ : Y}(q₁₀ : Q x₁ y₀) where {- (x₀ , q₀₀) = (x₁ , q₁₀) -} module _ {y₁ : Y}(q₁₁ : Q x₁ y₁) (r : inl x₁ ≡ inr y₁) (p : fiberSquarePush q₁₀ q₁₀ q₁₁ r) where fiber→[q₀₀=q₁₀]-filler : (i j k : I) → Pushout fiber→[q₀₀=q₁₀]-filler i j k' = hfill (λ k → λ { (i = i0) → push q₁₁ (j ∧ k) ; (i = i1) → p k j ; (j = i0) → push q₁₀ (i ∧ ~ k) ; (j = i1) → push q₁₁ k }) (inS (push q₁₀ (i ∧ ~ j))) k' fiber→[q₀₀=q₁₀] : fiber push r fiber→[q₀₀=q₁₀] .fst = q₁₁ fiber→[q₀₀=q₁₀] .snd i j = fiber→[q₀₀=q₁₀]-filler i j i1 ∣fiber→[q₀₀=q₁₀]∣ : rightCode _ r ∣fiber→[q₀₀=q₁₀]∣ = ∣ fiber→[q₀₀=q₁₀] ∣ₕ {- (y₁ , q₁₁) = (y₀ , q₁₀) -} module _ {x₀ : X}(q₀₀ : Q x₀ y₀) (r : inl x₀ ≡ inr y₀) (p : fiberSquarePush q₀₀ q₁₀ q₁₀ r) where fiber→[q₁₁=q₁₀]-filler : (i j k : I) → Pushout fiber→[q₁₁=q₁₀]-filler i j k' = hfill (λ k → λ { (i = i0) → push q₀₀ (j ∨ ~ k) ; (i = i1) → p k j ; (j = i0) → push q₀₀ (~ k) ; (j = i1) → push q₁₀ (~ i ∨ k) }) (inS (push q₁₀ (~ i ∨ ~ j))) k' fiber→[q₁₁=q₁₀] : fiber push r fiber→[q₁₁=q₁₀] .fst = q₀₀ fiber→[q₁₁=q₁₀] .snd i j = fiber→[q₁₁=q₁₀]-filler i j i1 ∣fiber→[q₁₁=q₁₀]∣ : rightCode _ r ∣fiber→[q₁₁=q₁₀]∣ = ∣ fiber→[q₁₁=q₁₀] ∣ₕ {- q₀₀ = q₁₁ = q₁₀ -} fiber→[q₀₀=q₁₀=q₁₁]-filler : (r : inl x₁ ≡ inr y₀) → (p : fiberSquarePush q₁₀ q₁₀ q₁₀ r) → (i j k l : I) → Pushout fiber→[q₀₀=q₁₀=q₁₁]-filler r p i j k l' = hfill (λ l → λ { (i = i0) → fiber→[q₀₀=q₁₀]-filler q₁₀ r p j k l ; (i = i1) → fiber→[q₁₁=q₁₀]-filler q₁₀ r p j k l ; (j = i0) → push q₁₀ ((i ∨ (k ∧ l)) ∧ (k ∨ (i ∧ ~ l))) ; (j = i1) → p l k ; (k = i0) → push q₁₀ ((i ∨ j) ∧ ~ l) ; (k = i1) → push q₁₀ ((i ∧ ~ j) ∨ l) }) (inS (push q₁₀ ((i ∨ (~ k ∧ j)) ∧ (~ k ∨ (i ∧ ~ j))))) l' fiber→[q₀₀=q₁₀=q₁₁] : fiber→[q₀₀=q₁₀] q₁₀ ≡ fiber→[q₁₁=q₁₀] q₁₀ fiber→[q₀₀=q₁₀=q₁₁] i r p .fst = q₁₀ fiber→[q₀₀=q₁₀=q₁₁] i r p .snd j k = fiber→[q₀₀=q₁₀=q₁₁]-filler r p i j k i1 ∣fiber→[q₀₀=q₁₀=q₁₁]∣ : ∣fiber→[q₀₀=q₁₀]∣ q₁₀ ≡ ∣fiber→[q₁₁=q₁₀]∣ q₁₀ ∣fiber→[q₀₀=q₁₀=q₁₁]∣ i r p = ∣ fiber→[q₀₀=q₁₀=q₁₁] i r p ∣ₕ {- Definitions of fiber← -} module _ {x₀ : X}{y₁ : Y}(q₀₁ : Q x₀ y₁) where {- (x₁ , q₁₁) = (x₀ , q₀₁) -} module _ {y₀ : Y}(q₀₀ : Q x₀ y₀) (r : inl x₀ ≡ inr y₁) (p : push q₀₁ ≡ r) where fiber←[q₁₁=q₀₁]-filler : (i j k : I) → Pushout fiber←[q₁₁=q₀₁]-filler i j k' = hfill (λ k → λ { (i = i0) → push q₀₀ (~ j ∧ k) ; (i = i1) → p k j ; (j = i0) → push q₀₀ (~ i ∧ k) ; (j = i1) → push q₀₁ i }) (inS (push q₀₁ (i ∧ j))) k' fiber←[q₁₁=q₀₁] : fiber'Push q₀₀ q₀₁ r fiber←[q₁₁=q₀₁] .fst = q₀₀ fiber←[q₁₁=q₀₁] .snd i j = fiber←[q₁₁=q₀₁]-filler i j i1 ∣fiber←[q₁₁=q₀₁]∣ : leftCodeExtended q₀₀ _ (push q₀₁) r ∣fiber←[q₁₁=q₀₁]∣ = ∣ fiber←[q₁₁=q₀₁] ∣ₕ {- (y₀ , q₀₀) = (y₁ , q₀₁) -} module _ {x₁ : X}(q₁₁ : Q x₁ y₁) (r : inl x₀ ≡ inr y₁) (p : push q₀₁ ≡ r) where fiber←[q₀₀=q₀₁]-filler : (i j k : I) → Pushout fiber←[q₀₀=q₀₁]-filler i j k' = hfill (λ k → λ { (i = i0) → push q₁₁ (~ j ∨ ~ k) ; (i = i1) → p k j ; (j = i0) → push q₀₁ (~ i) ; (j = i1) → push q₁₁ (i ∨ ~ k) }) (inS (push q₀₁ (~ i ∨ j))) k' fiber←[q₀₀=q₀₁] : fiber'Push q₀₁ q₁₁ r fiber←[q₀₀=q₀₁] .fst = q₁₁ fiber←[q₀₀=q₀₁] .snd i j = fiber←[q₀₀=q₀₁]-filler i j i1 ∣fiber←[q₀₀=q₀₁]∣ : leftCodeExtended q₀₁ _ (push q₁₁) r ∣fiber←[q₀₀=q₀₁]∣ = ∣ fiber←[q₀₀=q₀₁] ∣ₕ {- q₀₀ = q₀₁ = q₁₁ -} fiber←[q₀₀=q₀₁=q₁₁]-filler : (r : inl x₀ ≡ inr y₁) → (p : push q₀₁ ≡ r) → (i j k l : I) → Pushout fiber←[q₀₀=q₀₁=q₁₁]-filler r p i j k l' = hfill (λ l → λ { (i = i0) → fiber←[q₁₁=q₀₁]-filler q₀₁ r p j k l ; (i = i1) → fiber←[q₀₀=q₀₁]-filler q₀₁ r p j k l ; (j = i0) → push q₀₁ ((i ∨ (~ k ∧ l)) ∧ (~ k ∨ (i ∧ ~ l))) ; (j = i1) → p l k ; (k = i0) → push q₀₁ ((i ∨ l) ∧ ~ j) ; (k = i1) → push q₀₁ ((i ∧ ~ l) ∨ j) }) (inS (push q₀₁ ((i ∨ (k ∧ j)) ∧ (k ∨ (i ∧ ~ j))))) l' fiber←[q₀₀=q₀₁=q₁₁] : fiber←[q₁₁=q₀₁] q₀₁ ≡ fiber←[q₀₀=q₀₁] q₀₁ fiber←[q₀₀=q₀₁=q₁₁] i r p .fst = q₀₁ fiber←[q₀₀=q₀₁=q₁₁] i r p .snd j k = fiber←[q₀₀=q₀₁=q₁₁]-filler r p i j k i1 ∣fiber←[q₀₀=q₀₁=q₁₁]∣ : ∣fiber←[q₁₁=q₀₁]∣ q₀₁ ≡ ∣fiber←[q₀₀=q₀₁]∣ q₀₁ ∣fiber←[q₀₀=q₀₁=q₁₁]∣ i r p = ∣ fiber←[q₀₀=q₀₁=q₁₁] i r p ∣ₕ {- Definitions of fiber→← -} module _ {x₁ : X}{y₀ : Y}(q₁₀ : Q x₁ y₀) where {- (x₀ , q₀₀) = (x₁ , q₁₀) -} module _ {y₁ : Y}(q₁₁ : Q x₁ y₁) (r : inl x₁ ≡ inr y₁) (p : fiberSquarePush q₁₀ q₁₀ q₁₁ r) where fiber→←[q₀₀=q₁₀]-filler : (i j k l : I) → Pushout fiber→←[q₀₀=q₁₀]-filler i j k l' = let p' = fiber→[q₀₀=q₁₀] q₁₀ q₁₁ r p .snd in hfill (λ l → λ { (i = i0) → fiber←[q₁₁=q₀₁]-filler q₁₁ q₁₀ r p' j k l ; (i = i1) → fiber→[q₀₀=q₁₀]-filler q₁₀ q₁₁ r p l k j ; (j = i0) → push q₁₀ (~ k ∧ l) ; (j = i1) → p' l k ; (k = i0) → push q₁₀ (~ j ∧ l) ; (k = i1) → push q₁₁ j }) (inS (push q₁₁ (j ∧ k))) l' fiber→←[q₀₀=q₁₀] : fiber←[q₁₁=q₀₁] q₁₁ q₁₀ r (fiber→[q₀₀=q₁₀] q₁₀ q₁₁ r p .snd) .snd ≡ p fiber→←[q₀₀=q₁₀] i j k = fiber→←[q₀₀=q₁₀]-filler i j k i1 {- (y₁ , q₁₁) = (y₀ , q₁₀) -} module _ {x₀ : X}(q₀₀ : Q x₀ y₀) (r : inl x₀ ≡ inr y₀) (p : fiberSquarePush q₀₀ q₁₀ q₁₀ r) where fiber→←[q₁₁=q₁₀]-filler : (i j k l : I) → Pushout fiber→←[q₁₁=q₁₀]-filler i j k l' = let p' = fiber→[q₁₁=q₁₀] q₁₀ q₀₀ r p .snd in hfill (λ l → λ { (i = i0) → fiber←[q₀₀=q₀₁]-filler q₀₀ q₁₀ r p' j k l ; (i = i1) → fiber→[q₁₁=q₁₀]-filler q₁₀ q₀₀ r p l k j ; (j = i0) → push q₁₀ (~ k ∨ ~ l) ; (j = i1) → p' l k ; (k = i0) → push q₀₀ (~ j) ; (k = i1) → push q₁₀ (j ∨ ~ l) }) (inS (push q₀₀ (~ j ∨ k))) l' fiber→←[q₁₁=q₁₀] : fiber←[q₀₀=q₀₁] q₀₀ q₁₀ r (fiber→[q₁₁=q₁₀] q₁₀ q₀₀ r p .snd) .snd ≡ p fiber→←[q₁₁=q₁₀] i j k = fiber→←[q₁₁=q₁₀]-filler i j k i1 {- q₀₀ = q₁₀ = q₁₁ -} fiber→←hypercube : (r : inl x₁ ≡ inr y₀) → (p : fiberSquarePush q₁₀ q₁₀ q₁₀ r) → PathP (λ i → fiber←[q₀₀=q₀₁=q₁₁] q₁₀ i r (fiber→[q₀₀=q₁₀=q₁₁] q₁₀ i r p .snd) .snd ≡ p) (fiber→←[q₀₀=q₁₀] q₁₀ r p) (fiber→←[q₁₁=q₁₀] q₁₀ r p) fiber→←hypercube r p i j u v = hcomp (λ l → λ { (i = i0) → fiber→←[q₀₀=q₁₀]-filler q₁₀ r p j u v l ; (i = i1) → fiber→←[q₁₁=q₁₀]-filler q₁₀ r p j u v l ; (j = i0) → fiber←[q₀₀=q₀₁=q₁₁]-filler q₁₀ r (fiber→[q₀₀=q₁₀=q₁₁] q₁₀ i r p .snd) i u v l ; (j = i1) → fiber→[q₀₀=q₁₀=q₁₁]-filler q₁₀ r p i l v u ; (u = i0) → push q₁₀ ((i ∨ (~ v ∧ l)) ∧ (~ v ∨ (i ∧ ~ l))) ; (u = i1) → fiber→[q₀₀=q₁₀=q₁₁] q₁₀ i r p .snd l v ; (v = i0) → push q₁₀ ((i ∨ l) ∧ ~ u) ; (v = i1) → push q₁₀ ((i ∧ ~ l) ∨ u) }) (push q₁₀ ((i ∨ (v ∧ u)) ∧ (v ∨ (i ∧ ~ u)))) {- Definitions of fiber←→ -} module _ {x₀ : X}{y₁ : Y}(q₀₁ : Q x₀ y₁) where {- (x₁ , q₁₁) = (x₀ , q₀₁) -} module _ {y₀ : Y}(q₀₀ : Q x₀ y₀) (r : inl x₀ ≡ inr y₁) (p : push q₀₁ ≡ r) where fiber←→[q₁₁=q₀₁]-filler : (i j k l : I) → Pushout fiber←→[q₁₁=q₀₁]-filler i j k l' = let p' = fiber←[q₁₁=q₀₁] q₀₁ q₀₀ r p .snd in hfill (λ l → λ { (i = i0) → fiber→[q₀₀=q₁₀]-filler q₀₀ q₀₁ r p' j k l ; (i = i1) → fiber←[q₁₁=q₀₁]-filler q₀₁ q₀₀ r p l k j ; (j = i0) → push q₀₁ (k ∧ l) ; (j = i1) → p' l k ; (k = i0) → push q₀₀ (j ∧ ~ l) ; (k = i1) → push q₀₁ l }) (inS (push q₀₀ (j ∧ ~ k))) l' fiber←→[q₁₁=q₀₁] : fiber→[q₀₀=q₁₀] q₀₀ q₀₁ r (fiber←[q₁₁=q₀₁] q₀₁ q₀₀ r p .snd) .snd ≡ p fiber←→[q₁₁=q₀₁] i j k = fiber←→[q₁₁=q₀₁]-filler i j k i1 {- (y₀ , q₀₀) = (y₁ , q₀₁) -} module _ {x₁ : X}(q₁₁ : Q x₁ y₁) (r : inl x₀ ≡ inr y₁) (p : push q₀₁ ≡ r) where fiber←→[q₀₀=q₀₁]-filler : (i j k l : I) → Pushout fiber←→[q₀₀=q₀₁]-filler i j k l' = let p' = fiber←[q₀₀=q₀₁] q₀₁ q₁₁ r p .snd in hfill (λ l → λ { (i = i0) → fiber→[q₁₁=q₁₀]-filler q₁₁ q₀₁ r p' j k l ; (i = i1) → fiber←[q₀₀=q₀₁]-filler q₀₁ q₁₁ r p l k j ; (j = i0) → push q₀₁ (k ∨ ~ l) ; (j = i1) → p' l k ; (k = i0) → push q₀₁ (~ l) ; (k = i1) → push q₁₁ (~ j ∨ l) }) (inS (push q₁₁ (~ j ∨ ~ k))) l' fiber←→[q₀₀=q₀₁] : fiber→[q₁₁=q₁₀] q₁₁ q₀₁ r (fiber←[q₀₀=q₀₁] q₀₁ q₁₁ r p .snd) .snd ≡ p fiber←→[q₀₀=q₀₁] i j k = fiber←→[q₀₀=q₀₁]-filler i j k i1 {- q₀₀ = q₀₁ = q₁₁ -} fiber←→hypercube : (r : inl x₀ ≡ inr y₁) → (p : push q₀₁ ≡ r) → PathP (λ i → fiber→[q₀₀=q₁₀=q₁₁] q₀₁ i r (fiber←[q₀₀=q₀₁=q₁₁] q₀₁ i r p .snd) .snd ≡ p) (fiber←→[q₁₁=q₀₁] q₀₁ r p) (fiber←→[q₀₀=q₀₁] q₀₁ r p) fiber←→hypercube r p i j u v = hcomp (λ l → λ { (i = i0) → fiber←→[q₁₁=q₀₁]-filler q₀₁ r p j u v l ; (i = i1) → fiber←→[q₀₀=q₀₁]-filler q₀₁ r p j u v l ; (j = i0) → fiber→[q₀₀=q₁₀=q₁₁]-filler q₀₁ r (fiber←[q₀₀=q₀₁=q₁₁] q₀₁ i r p .snd) i u v l ; (j = i1) → fiber←[q₀₀=q₀₁=q₁₁]-filler q₀₁ r p i l v u ; (u = i0) → push q₀₁ ((i ∨ (v ∧ l)) ∧ (v ∨ (i ∧ ~ l))) ; (u = i1) → fiber←[q₀₀=q₀₁=q₁₁] q₀₁ i r p .snd l v ; (v = i0) → push q₀₁ ((i ∨ u) ∧ ~ l) ; (v = i1) → push q₀₁ ((i ∧ ~ u) ∨ l) }) (push q₀₁ ((i ∨ (~ v ∧ u)) ∧ (~ v ∨ (i ∧ ~ u)))) module Fiber→ {x₁ : X}{y₀ : Y}(q₁₀ : Q x₁ y₀) = WedgeConnectivity m n (leftFiber x₁ , (y₀ , q₁₀)) (leftConn x₁) (rightFiber y₀ , (x₁ , q₁₀)) (rightConn y₀) (λ (y₁ , q₁₁) (x₀ , q₀₀) → (((r : inl x₀ ≡ inr y₁) → fiberSquarePush q₀₀ q₁₀ q₁₁ r → rightCode _ r) , isOfHLevelΠ2 _ (λ x y → isOfHLevelTrunc _))) (λ (y₁ , q₁₁) → ∣fiber→[q₀₀=q₁₀]∣ q₁₀ q₁₁) (λ (x₀ , q₀₀) → ∣fiber→[q₁₁=q₁₀]∣ q₁₀ q₀₀) (∣fiber→[q₀₀=q₁₀=q₁₁]∣ q₁₀) fiber→ : {x₁ : X}{y₀ : Y}(q₁₀ : Q x₁ y₀) → {x₀ : X}(q₀₀ : Q x₀ y₀) → {y₁ : Y}(q₁₁ : Q x₁ y₁) → (r : inl x₀ ≡ inr y₁) → fiberSquarePush q₀₀ q₁₀ q₁₁ r → rightCode _ r fiber→ q₁₀ q₀₀ q₁₁ = Fiber→.extension q₁₀ (_ , q₁₁) (_ , q₀₀) module Fiber← {x₀ : X}{y₁ : Y}(q₀₁ : Q x₀ y₁) = WedgeConnectivity m n (leftFiber x₀ , (y₁ , q₀₁)) (leftConn x₀) (rightFiber y₁ , (x₀ , q₀₁)) (rightConn y₁) (λ (y₀ , q₀₀) (x₁ , q₁₁) → (((r : inl x₀ ≡ inr y₁) → push q₀₁ ≡ r → leftCodeExtended q₀₀ _ (push q₁₁) r) , isOfHLevelΠ2 _ (λ x y → isOfHLevelTrunc _))) (λ (y₀ , q₀₀) → ∣fiber←[q₁₁=q₀₁]∣ q₀₁ q₀₀) (λ (x₁ , q₁₁) → ∣fiber←[q₀₀=q₀₁]∣ q₀₁ q₁₁) (∣fiber←[q₀₀=q₀₁=q₁₁]∣ q₀₁) fiber← : {x₀ : X}{y₁ : Y}(q₀₁ : Q x₀ y₁) → {y₀ : Y}(q₀₀ : Q x₀ y₀) → {x₁ : X}(q₁₁ : Q x₁ y₁) → (r : inl x₀ ≡ inr y₁) → push q₀₁ ≡ r → leftCodeExtended q₀₀ _ (push q₁₁) r fiber← q₀₁ q₀₀ q₁₁ = Fiber←.extension q₀₁ (_ , q₀₀) (_ , q₁₁) module _ {x₀ x₁ : X}{y₀ y₁ : Y} (q₀₀ : Q x₀ y₀)(q₁₁ : Q x₁ y₁) (r : inl x₀ ≡ inr y₁) where left→rightCodeExtended : leftCodeExtended q₀₀ _ (push q₁₁) r → rightCode _ r left→rightCodeExtended = rec (isOfHLevelTrunc _) (λ (q₁₀ , p) → fiber→ q₁₀ q₀₀ q₁₁ r p) right→leftCodeExtended : rightCode _ r → leftCodeExtended q₀₀ _ (push q₁₁) r right→leftCodeExtended = rec (isOfHLevelTrunc _) (λ (q₀₁ , p) → fiber← q₀₁ q₀₀ q₁₁ r p) {- Definition of one-side homotopy -} module _ {x₁ : X}{y₀ : Y}(q₁₀ : Q x₁ y₀) where {- (x₀ , q₀₀) = (x₁ , q₁₀) -} module _ {y₁ : Y}(q₁₁ : Q x₁ y₁) (r : inl x₁ ≡ inr y₁) (p : fiberSquarePush q₁₀ q₁₀ q₁₁ r) where ∣fiber→←[q₀₀=q₁₀]∣ : right→leftCodeExtended q₁₀ q₁₁ r (fiber→ q₁₀ q₁₀ q₁₁ r p) ≡ ∣ q₁₀ , p ∣ₕ ∣fiber→←[q₀₀=q₁₀]∣ = (λ i → right→leftCodeExtended q₁₀ q₁₁ r (Fiber→.left q₁₀ (_ , q₁₁) i r p)) ∙ recUniq {n = m + n} _ _ _ ∙ (λ i → Fiber←.left q₁₁ (_ , q₁₀) i r (fiber→[q₀₀=q₁₀] q₁₀ q₁₁ r p .snd)) ∙ (λ i → ∣ q₁₀ , fiber→←[q₀₀=q₁₀] q₁₀ q₁₁ r p i ∣ₕ) {- (y₁ , q₁₁) = (y₀ , q₁₀) -} module _ {x₀ : X}(q₀₀ : Q x₀ y₀) (r : inl x₀ ≡ inr y₀) (p : fiberSquarePush q₀₀ q₁₀ q₁₀ r) where ∣fiber→←[q₁₁=q₁₀]∣ : right→leftCodeExtended q₀₀ q₁₀ r (fiber→ q₁₀ q₀₀ q₁₀ r p) ≡ ∣ q₁₀ , p ∣ₕ ∣fiber→←[q₁₁=q₁₀]∣ = (λ i → right→leftCodeExtended q₀₀ q₁₀ r (Fiber→.right q₁₀ (_ , q₀₀) i r p)) ∙ recUniq {n = m + n} _ _ _ ∙ (λ i → Fiber←.right q₀₀ (_ , q₁₀) i r (fiber→[q₁₁=q₁₀] q₁₀ q₀₀ r p .snd)) ∙ (λ i → ∣ q₁₀ , fiber→←[q₁₁=q₁₀] q₁₀ q₀₀ r p i ∣ₕ) {- q₀₀ = q₁₁ = q₁₀ -} module _ (r : inl x₁ ≡ inr y₀) (p : fiberSquarePush q₁₀ q₁₀ q₁₀ r) where path→←Square = (λ i j → right→leftCodeExtended q₁₀ q₁₀ r (Fiber→.homSquare q₁₀ i j r p)) ∙₂ (λ i → recUniq {n = m + n} _ _ _) ∙₂ (λ i j → Fiber←.homSquare q₁₀ i j r (fiber→[q₀₀=q₁₀=q₁₁] q₁₀ i r p .snd)) ∙₂ (λ i j → ∣ (q₁₀ , fiber→←hypercube q₁₀ r p i j) ∣ₕ) ∣fiber→←[q₀₀=q₁₀=q₁₁]∣ : ∣fiber→←[q₀₀=q₁₀]∣ q₁₀ ≡ ∣fiber→←[q₁₁=q₁₀]∣ q₁₀ ∣fiber→←[q₀₀=q₁₀=q₁₁]∣ i r p = path→←Square r p i fiber→← : {x₁ : X}{y₀ : Y}(q₁₀ : Q x₁ y₀) → {x₀ : X}(q₀₀ : Q x₀ y₀) → {y₁ : Y}(q₁₁ : Q x₁ y₁) → (r : inl x₀ ≡ inr y₁) → (p : fiberSquarePush q₀₀ q₁₀ q₁₁ r) → right→leftCodeExtended q₀₀ q₁₁ r (fiber→ q₁₀ q₀₀ q₁₁ r p) ≡ ∣ q₁₀ , p ∣ₕ fiber→← {x₁ = x₁} {y₀ = y₀} q₁₀ q₀₀' q₁₁' = WedgeConnectivity.extension m n (leftFiber x₁ , (y₀ , q₁₀)) (leftConn x₁) (rightFiber y₀ , (x₁ , q₁₀)) (rightConn y₀) (λ (y₁ , q₁₁) (x₀ , q₀₀) → (( (r : inl x₀ ≡ inr y₁) → (p : fiberSquarePush q₀₀ q₁₀ q₁₁ r) → right→leftCodeExtended q₀₀ q₁₁ r (fiber→ q₁₀ q₀₀ q₁₁ r p) ≡ ∣ q₁₀ , p ∣ₕ ) , isOfHLevelΠ2 _ (λ x y → isOfHLevelTruncPath))) (λ (y₁ , q₁₁) → ∣fiber→←[q₀₀=q₁₀]∣ q₁₀ q₁₁) (λ (x₀ , q₀₀) → ∣fiber→←[q₁₁=q₁₀]∣ q₁₀ q₀₀) (∣fiber→←[q₀₀=q₁₀=q₁₁]∣ q₁₀) (_ , q₁₁') (_ , q₀₀') {- Definition of the other side homotopy -} module _ {x₀ : X}{y₁ : Y}(q₀₁ : Q x₀ y₁) where {- (x₁ , q₁₁) = (x₀ , q₀₁) -} module _ {y₀ : Y}(q₀₀ : Q x₀ y₀) (r : inl x₀ ≡ inr y₁) (p : push q₀₁ ≡ r) where ∣fiber←→[q₁₁=q₀₁]∣ : left→rightCodeExtended q₀₀ q₀₁ r (fiber← q₀₁ q₀₀ q₀₁ r p) ≡ ∣ q₀₁ , p ∣ₕ ∣fiber←→[q₁₁=q₀₁]∣ = (λ i → left→rightCodeExtended q₀₀ q₀₁ r (Fiber←.left q₀₁ (_ , q₀₀) i r p)) ∙ recUniq {n = m + n} _ _ _ ∙ (λ i → Fiber→.left q₀₀ (_ , q₀₁) i r (fiber←[q₁₁=q₀₁] q₀₁ q₀₀ r p .snd)) ∙ (λ i → ∣ q₀₁ , fiber←→[q₁₁=q₀₁] q₀₁ q₀₀ r p i ∣ₕ) {- (y₀ , q₀₀) = (y₁ , q₀₁) -} module _ {x₁ : X}(q₁₁ : Q x₁ y₁) (r : inl x₀ ≡ inr y₁) (p : push q₀₁ ≡ r) where ∣fiber←→[q₀₀=q₀₁]∣ : left→rightCodeExtended q₀₁ q₁₁ r (fiber← q₀₁ q₀₁ q₁₁ r p) ≡ ∣ q₀₁ , p ∣ₕ ∣fiber←→[q₀₀=q₀₁]∣ = (λ i → left→rightCodeExtended q₀₁ q₁₁ r (Fiber←.right q₀₁ (_ , q₁₁) i r p)) ∙ recUniq {n = m + n} _ _ _ ∙ (λ i → Fiber→.right q₁₁ (_ , q₀₁) i r (fiber←[q₀₀=q₀₁] q₀₁ q₁₁ r p .snd)) ∙ (λ i → ∣ q₀₁ , fiber←→[q₀₀=q₀₁] q₀₁ q₁₁ r p i ∣ₕ) {- q₀₀ = q₀₁ = q₁₁ -} module _ (r : inl x₀ ≡ inr y₁) (p : push q₀₁ ≡ r) where path←→Square = (λ i j → left→rightCodeExtended q₀₁ q₀₁ r (Fiber←.homSquare q₀₁ i j r p)) ∙₂ (λ i → recUniq {n = m + n} _ _ _) ∙₂ (λ i j → Fiber→.homSquare q₀₁ i j r (fiber←[q₀₀=q₀₁=q₁₁] q₀₁ i r p .snd)) ∙₂ (λ i j → ∣ q₀₁ , fiber←→hypercube q₀₁ r p i j ∣ₕ) ∣fiber←→[q₀₀=q₀₁=q₁₁]∣ : ∣fiber←→[q₁₁=q₀₁]∣ q₀₁ ≡ ∣fiber←→[q₀₀=q₀₁]∣ q₀₁ ∣fiber←→[q₀₀=q₀₁=q₁₁]∣ i r p = path←→Square r p i fiber←→ : {x₀ : X}{y₁ : Y}(q₀₁ : Q x₀ y₁) → {y₀ : Y}(q₀₀ : Q x₀ y₀) → {x₁ : X}(q₁₁ : Q x₁ y₁) → (r : inl x₀ ≡ inr y₁) → (p : push q₀₁ ≡ r) → left→rightCodeExtended q₀₀ q₁₁ r (fiber← q₀₁ q₀₀ q₁₁ r p) ≡ ∣ q₀₁ , p ∣ₕ fiber←→ {x₀ = x₀} {y₁ = y₁} q₀₁ q₀₀' q₁₁' = WedgeConnectivity.extension m n (leftFiber x₀ , (y₁ , q₀₁)) (leftConn x₀) (rightFiber y₁ , (x₀ , q₀₁)) (rightConn y₁) (λ (y₀ , q₀₀) (x₁ , q₁₁) → (( (r : inl x₀ ≡ inr y₁) → (p : push q₀₁ ≡ r) → left→rightCodeExtended q₀₀ q₁₁ r (fiber← q₀₁ q₀₀ q₁₁ r p) ≡ ∣ q₀₁ , p ∣ₕ ) , isOfHLevelΠ2 _ (λ x y → isOfHLevelTruncPath))) (λ (y₀ , q₀₀) → ∣fiber←→[q₁₁=q₀₁]∣ q₀₁ q₀₀) (λ (x₁ , q₁₁) → ∣fiber←→[q₀₀=q₀₁]∣ q₀₁ q₁₁) (∣fiber←→[q₀₀=q₀₁=q₁₁]∣ q₀₁) (_ , q₀₀') (_ , q₁₁') module _ {x₀ x₁ : X}{y₀ y₁ : Y} (q₀₀ : Q x₀ y₀)(q₁₁ : Q x₁ y₁) (r : inl x₀ ≡ inr y₁) where left→right→leftCodeExtended : (a : leftCodeExtended q₀₀ _ (push q₁₁) r) → right→leftCodeExtended q₀₀ q₁₁ r (left→rightCodeExtended q₀₀ q₁₁ r a) ≡ a left→right→leftCodeExtended a = sym (∘rec _ _ _ (right→leftCodeExtended q₀₀ q₁₁ r) a) ∙ (λ i → recId _ (λ (q₁₀ , p) → fiber→← q₁₀ q₀₀ q₁₁ r p) i a) right→left→rightCodeExtended : (a : rightCode _ r) → left→rightCodeExtended q₀₀ q₁₁ r (right→leftCodeExtended q₀₀ q₁₁ r a) ≡ a right→left→rightCodeExtended a = sym (∘rec _ _ _ (left→rightCodeExtended q₀₀ q₁₁ r) a) ∙ (λ i → recId _ (λ (q₀₁ , p) → fiber←→ q₀₁ q₀₀ q₁₁ r p) i a) left≃rightCodeExtended : leftCodeExtended q₀₀ _ (push q₁₁) r ≃ rightCode y₁ r left≃rightCodeExtended = isoToEquiv (iso (left→rightCodeExtended _ _ _) (right→leftCodeExtended _ _ _) right→left→rightCodeExtended left→right→leftCodeExtended) {- Definition and properties of Code -} module _ (x₀ : X)(y₀ : Y)(q₀₀ : Q x₀ y₀) where leftCode' : (x : X){p : Pushout} → inl x ≡ p → inl x₀ ≡ p → Type ℓ leftCode' x r' = leftCodeExtended q₀₀ x r' leftCode : (x : X) → inl x₀ ≡ inl x → Type ℓ leftCode x = leftCode' x refl fiberPath : {x : X}{y : Y} → (q : Q x y) → leftCode' x (push q) ≡ rightCode y fiberPath q i r = ua (left≃rightCodeExtended q₀₀ q r) i pushCode : {x : X}{y : Y} → (q : Q x y) → PathP (λ i → inl x₀ ≡ push q i → Type ℓ) (leftCode x) (rightCode y) pushCode q i = hcomp (λ j → λ { (i = i0) → leftCode _ ; (i = i1) → fiberPath q j }) (leftCode' _ (λ j → push q (i ∧ j))) Code : (p : Pushout) → inl x₀ ≡ p → Type ℓ Code (inl x) = leftCode x Code (inr y) = rightCode y Code (push q i) = pushCode q i {- Transportation rule of pushCode -} transpLeftCode : (y : Y) → (q : Q x₀ y) → (q' : leftCodeExtended q₀₀ _ refl refl) → leftCode' _ (push q) (push q) transpLeftCode y q q' = transport (λ i → leftCode' _ (λ j → push q (i ∧ j)) (λ j → push q (i ∧ j))) q' transpPushCodeβ' : (y : Y) → (q : Q x₀ y) → (q' : leftCodeExtended q₀₀ _ refl refl) → transport (λ i → pushCode q i (λ j → push q (i ∧ j))) q' ≡ left→rightCodeExtended _ _ _ (transpLeftCode y q q') transpPushCodeβ' y q q' i = transportRefl (left→rightCodeExtended _ _ _ (transpLeftCode y q (transportRefl q' i))) i module _ {p : Pushout}(r : inl x₀ ≡ p) where fiber-filler : I → Type ℓ fiber-filler i = fiber' q₀₀ (λ j → r (i ∧ j)) (λ j → r (i ∧ j)) module _ (q : fiberSquare q₀₀ q₀₀ refl refl) where transpLeftCode-filler : (i j k : I) → Pushout transpLeftCode-filler i j k' = hfill (λ k → λ { (i = i0) → push q₀₀ (~ j) ; (i = i1) → r (j ∧ k) ; (j = i0) → push q₀₀ (~ i) ; (j = i1) → r (i ∧ k) }) (inS (q i j)) k' transpLeftCodeβ' : {p : Pushout} → (r : inl x₀ ≡ p) → (q : fiberSquare q₀₀ q₀₀ refl refl) → transport (λ i → fiber-filler r i) (q₀₀ , q) ≡ (q₀₀ , λ i j → transpLeftCode-filler r q i j i1) transpLeftCodeβ' r q = J (λ p r → transport (λ i → fiber-filler r i) (q₀₀ , q) ≡ (q₀₀ , λ i j → transpLeftCode-filler r q i j i1)) (transportRefl _ ∙ (λ k → (q₀₀ , λ i j → transpLeftCode-filler refl q i j k))) r transpLeftCodeβ : (y : Y) → (q : Q x₀ y) → (q' : fiberSquare q₀₀ q₀₀ refl refl) → transpLeftCode y q ∣ q₀₀ , q' ∣ₕ ≡ ∣ q₀₀ , (λ i j → transpLeftCode-filler (push q) q' i j i1) ∣ₕ transpLeftCodeβ y q q' = transportTrunc _ ∙ (λ i → ∣ transpLeftCodeβ' _ q' i ∣ₕ) transpPushCodeβ : (y : Y) → (q : Q x₀ y) → (q' : fiberSquare q₀₀ q₀₀ refl refl) → transport (λ i → pushCode q i (λ j → push q (i ∧ j))) ∣ q₀₀ , q' ∣ₕ ≡ ∣fiber→[q₀₀=q₁₀]∣ q₀₀ q (push q) (λ i j → transpLeftCode-filler (push q) q' i j i1) transpPushCodeβ y q q' = transpPushCodeβ' _ _ _ ∙ (λ i → left→rightCodeExtended _ _ _ (transpLeftCodeβ _ _ q' i)) ∙ recUniq {n = m + n} _ _ _ ∙ (λ i' → Fiber→.left q₀₀ (_ , q) i' (push q) (λ i j → transpLeftCode-filler (push q) q' i j i1)) {- The contractibility of Code -} centerCode : {p : Pushout} → (r : inl x₀ ≡ p) → Code p r centerCode r = transport (λ i → Code _ (λ j → r (i ∧ j))) ∣ q₀₀ , (λ i j → push q₀₀ (~ i ∧ ~ j)) ∣ₕ module _ (y : Y)(q : Q x₀ y) where transp-filler : (i j k : I) → Pushout transp-filler = transpLeftCode-filler (push q) (λ i' j' → push q₀₀ (~ i' ∧ ~ j')) transp-square : fiberSquare q₀₀ q₀₀ (push q) (push q) transp-square i j = transp-filler i j i1 contractionCodeRefl' : fiber→[q₀₀=q₁₀] q₀₀ q (push q) transp-square .snd ≡ refl contractionCodeRefl' i j k = hcomp (λ l → λ { (i = i0) → fiber→[q₀₀=q₁₀]-filler q₀₀ q (push q) transp-square j k l ; (i = i1) → transp-square (~ j ∨ l) k ; (j = i0) → push q (k ∧ (i ∨ l)) ; (j = i1) → transp-square l k ; (k = i0) → push q₀₀ (j ∧ ~ l) ; (k = i1) → push q ((i ∧ ~ j) ∨ l) }) (transp-filler (~ j) k i) contractionCodeRefl : centerCode (push q) ≡ ∣ q , refl ∣ₕ contractionCodeRefl = transpPushCodeβ _ _ _ ∙ (λ i → ∣ q , contractionCodeRefl' i ∣ₕ) module _ (y : Y)(r : inl x₀ ≡ inr y) where contractionCode' : (a : fiber push r) → centerCode r ≡ ∣ a ∣ₕ contractionCode' (q , p') = J (λ r' p → centerCode r' ≡ ∣ q , p ∣ₕ) (contractionCodeRefl _ q) p' contractionCode : (a : Code _ r) → centerCode r ≡ a contractionCode = elim (λ _ → isOfHLevelTruncPath) contractionCode' isContrCode : isContr (Code _ r) isContrCode = centerCode r , contractionCode excision-helper : (x : X) → Trunc (1 + m) (Σ[ y₀ ∈ Y ] Q x y₀) → (y : Y) → (r : inl x ≡ inr y) → isContr (Trunc (m + n) (fiber push r)) excision-helper x y' y r = rec (isProp→isOfHLevelSuc m isPropIsContr) (λ (y₀ , q₀₀) → isContrCode x y₀ q₀₀ y r ) y' {- The Main Result : Blakers-Massey Homotopy Excision Theorem -} Excision : (x : X)(y : Y) → isConnectedFun (m + n) (push {x = x} {y = y}) Excision x y = excision-helper x (leftConn x .fst) y ",12242,True,2892.1512609816755,median "-- In this file we consider the special of localising at a single -- element f : R (or rather the set of powers of f). This is also -- known as inverting f. -- We then prove that localising first at an element f and at an element -- g (or rather the image g/1) is the same as localising at the product f·g -- This fact has an important application in algebraic geometry where it's -- used to define the structure sheaf of a commutative ring. {-# OPTIONS --safe --experimental-lossy-unification #-} module Cubical.Algebra.CommRing.Localisation.InvertingElements where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Function open import Cubical.Foundations.Equiv open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Univalence open import Cubical.Foundations.HLevels open import Cubical.Foundations.Powerset open import Cubical.Foundations.Transport open import Cubical.Functions.FunExtEquiv import Cubical.Data.Empty as ⊥ open import Cubical.Data.Bool open import Cubical.Data.Nat renaming ( _+_ to _+ℕ_ ; _·_ to _·ℕ_ ; _^_ to _^ℕ_ ; +-comm to +ℕ-comm ; +-assoc to +ℕ-assoc ; ·-assoc to ·ℕ-assoc ; ·-comm to ·ℕ-comm) open import Cubical.Data.Nat.Order open import Cubical.Data.Vec open import Cubical.Data.Sigma.Base open import Cubical.Data.Sigma.Properties open import Cubical.Data.FinData open import Cubical.Relation.Nullary open import Cubical.Relation.Binary open import Cubical.Algebra.Group open import Cubical.Algebra.AbGroup open import Cubical.Algebra.Monoid open import Cubical.Algebra.Ring open import Cubical.Algebra.CommRing open import Cubical.Algebra.CommRing.Localisation.Base open import Cubical.Algebra.CommRing.Localisation.UniversalProperty open import Cubical.Algebra.CommRing.Ideal open import Cubical.Algebra.CommRing.FGIdeal open import Cubical.Algebra.CommRing.RadicalIdeal open import Cubical.Algebra.CommRingSolver.Reflection open import Cubical.HITs.SetQuotients as SQ open import Cubical.HITs.PropositionalTruncation as PT open Iso private variable ℓ ℓ' : Level A : Type ℓ module InvertingElementsBase (R' : CommRing ℓ) where open isMultClosedSubset private R = fst R' open CommRingStr (snd R') open Exponentiation R' open RingTheory (CommRing→Ring R') [_ⁿ|n≥0] : R → ℙ R [ f ⁿ|n≥0] g = (∃[ n ∈ ℕ ] g ≡ f ^ n) , isPropPropTrunc -- Σ[ n ∈ ℕ ] (s ≡ f ^ n) × (∀ m → s ≡ f ^ m → n ≤ m) maybe better, this isProp: -- (n,s≡fⁿ,p) (m,s≡fᵐ,q) then n≤m by p and m≤n by q => n≡m powersFormMultClosedSubset : (f : R) → isMultClosedSubset R' [ f ⁿ|n≥0] powersFormMultClosedSubset f .containsOne = PT.∣ zero , refl ∣₁ powersFormMultClosedSubset f .multClosed = PT.map2 λ (m , p) (n , q) → (m +ℕ n) , (λ i → (p i) · (q i)) ∙ ·-of-^-is-^-of-+ f m n R[1/_] : R → Type ℓ R[1/ f ] = Loc.S⁻¹R R' [ f ⁿ|n≥0] (powersFormMultClosedSubset f) -- a quick fact isContrR[1/0] : isContr R[1/ 0r ] fst isContrR[1/0] = [ 1r , 0r , ∣ 1 , sym (·IdR 0r) ∣₁ ] -- everything is equal to 1/0 snd isContrR[1/0] = elimProp (λ _ → squash/ _ _) λ _ → eq/ _ _ ((0r , ∣ 1 , sym (·IdR 0r) ∣₁) , useSolver _ _) where useSolver : ∀ s r → 0r · 1r · s ≡ 0r · r · 0r useSolver = solve R' R[1/_]AsCommRing : R → CommRing ℓ R[1/ f ]AsCommRing = Loc.S⁻¹RAsCommRing R' [ f ⁿ|n≥0] (powersFormMultClosedSubset f) -- A useful lemma: (gⁿ/1)≡(g/1)ⁿ in R[1/f] ^-respects-/1 : {f g : R} (n : ℕ) → [ (g ^ n) , 1r , PT.∣ 0 , (λ _ → 1r) ∣₁ ] ≡ Exponentiation._^_ R[1/ f ]AsCommRing [ g , 1r , powersFormMultClosedSubset _ .containsOne ] n ^-respects-/1 zero = refl ^-respects-/1 {f} {g} (suc n) = eq/ _ _ ( (1r , powersFormMultClosedSubset f .containsOne) , cong (1r · (g · (g ^ n)) ·_) (·IdL 1r)) ∙ cong (CommRingStr._·_ (R[1/ f ]AsCommRing .snd) [ g , 1r , powersFormMultClosedSubset f .containsOne ]) (^-respects-/1 n) -- A slight improvement for eliminating into propositions invElPropElim : {f : R} {P : R[1/ f ] → Type ℓ'} → (∀ x → isProp (P x)) → (∀ (r : R) (n : ℕ) → P [ r , (f ^ n) , PT.∣ n , refl ∣₁ ]) -- ∀ r n → P (r/fⁿ) ---------------------------------------------------------- → ∀ x → P x invElPropElim {f = f} {P = P} PisProp base = elimProp (λ _ → PisProp _) []-case where S[f] = Loc.S R' [ f ⁿ|n≥0] (powersFormMultClosedSubset f) []-case : (a : R × S[f]) → P [ a ] []-case (r , s , s∈S[f]) = PT.rec (PisProp _) Σhelper s∈S[f] where Σhelper : Σ[ n ∈ ℕ ] s ≡ f ^ n → P [ r , s , s∈S[f] ] Σhelper (n , p) = subst P (cong [_] (≡-× refl (Σ≡Prop (λ _ → isPropPropTrunc) (sym p)))) (base r n) invElPropElim2 : {f g : R} {P : R[1/ f ] → R[1/ g ] → Type ℓ'} → (∀ x y → isProp (P x y)) → (∀ (r s : R) (n : ℕ) → P [ r , (f ^ n) , PT.∣ n , refl ∣₁ ] [ s , (g ^ n) , PT.∣ n , refl ∣₁ ]) ---------------------------------------------------------- → ∀ x y → P x y invElPropElim2 {f = f} {g = g} {P = P} PisProp base = invElPropElim (λ _ → isPropΠ (λ _ → PisProp _ _)) reduce1 where reduce1 : ∀ (r : R) (n : ℕ) (y : R[1/ g ]) → P [ r , f ^ n , ∣ n , refl ∣₁ ] y reduce1 r n = invElPropElim (λ _ → PisProp _ _) reduce2 where reduce2 : (s : R) (m : ℕ) → P [ r , f ^ n , ∣ n , refl ∣₁ ] [ s , g ^ m , ∣ m , refl ∣₁ ] reduce2 s m = subst2 P p q (base _ _ l) where l = max m n x : R[1/ f ] x = [ r , f ^ n , ∣ n , refl ∣₁ ] y : R[1/ g ] y = [ s , g ^ m , ∣ m , refl ∣₁ ] x' : R[1/ f ] x' = [ r · f ^ (l ∸ n) , f ^ l , ∣ l , refl ∣₁ ] y' : R[1/ g ] y' = [ s · g ^ (l ∸ m) , g ^ l , ∣ l , refl ∣₁ ] p : x' ≡ x p = eq/ _ _ ((1r , ∣ 0 , refl ∣₁) , path) where useSolver1 : ∀ a b c → 1r · (a · b) · c ≡ a · (b · c) useSolver1 = solve R' useSolver2 : ∀ a b → a · b ≡ 1r · a · b useSolver2 = solve R' path : 1r · (r · f ^ (l ∸ n)) · f ^ n ≡ 1r · r · f ^ l path = 1r · (r · f ^ (l ∸ n)) · f ^ n ≡⟨ useSolver1 _ _ _ ⟩ r · (f ^ (l ∸ n) · f ^ n) ≡⟨ cong (r ·_) (·-of-^-is-^-of-+ _ _ _) ⟩ r · f ^ (l ∸ n +ℕ n) ≡⟨ cong (λ k → r · f ^ k) (≤-∸-+-cancel right-≤-max) ⟩ r · f ^ l ≡⟨ useSolver2 _ _ ⟩ 1r · r · f ^ l ∎ q : y' ≡ y q = eq/ _ _ ((1r , ∣ 0 , refl ∣₁) , path) where useSolver1 : ∀ a b c → 1r · (a · b) · c ≡ a · (b · c) useSolver1 = solve R' useSolver2 : ∀ a b → a · b ≡ 1r · a · b useSolver2 = solve R' path : 1r · (s · g ^ (l ∸ m)) · g ^ m ≡ 1r · s · g ^ l path = 1r · (s · g ^ (l ∸ m)) · g ^ m ≡⟨ useSolver1 _ _ _ ⟩ s · (g ^ (l ∸ m) · g ^ m) ≡⟨ cong (s ·_) (·-of-^-is-^-of-+ _ _ _) ⟩ s · g ^ (l ∸ m +ℕ m) ≡⟨ cong (λ k → s · g ^ k) (≤-∸-+-cancel left-≤-max) ⟩ s · g ^ l ≡⟨ useSolver2 _ _ ⟩ 1r · s · g ^ l ∎ -- For predicates over the set of powers powersPropElim : {f : R} {P : R → Type ℓ'} → (∀ x → isProp (P x)) → (∀ n → P (f ^ n)) ------------------------------ → ∀ s → s ∈ [ f ⁿ|n≥0] → P s powersPropElim {f = f} {P = P} PisProp base s = PT.rec (PisProp s) λ (n , p) → subst P (sym p) (base n) module RadicalLemma (R' : CommRing ℓ) (f g : (fst R')) where open IsRingHom open isMultClosedSubset open CommRingTheory R' open RingTheory (CommRing→Ring R') open CommIdeal R' hiding (subst-∈) renaming (_∈_ to _∈ᵢ_) open RadicalIdeal R' open Exponentiation R' open InvertingElementsBase R' open S⁻¹RUniversalProp R' [ f ⁿ|n≥0] (powersFormMultClosedSubset f) hiding (S⁻¹RHasUniversalProp) open S⁻¹RUniversalProp R' [ g ⁿ|n≥0] (powersFormMultClosedSubset g) hiding (_/1 ; /1AsCommRingHom) open CommRingStr (R' .snd) private R = R' .fst ⟨_⟩ : R → CommIdeal ⟨ f ⟩ = ⟨ replicateFinVec 1 f ⟩[ R' ] unitHelper : f ∈ᵢ √ ⟨ g ⟩ → (g /1) ∈ R[1/ f ]AsCommRing ˣ unitHelper = PT.rec isPropGoal (uncurry ℕhelper) where isPropGoal = Units.inverseUniqueness _ (g /1) ℕhelper : (n : ℕ) → f ^ n ∈ᵢ ⟨ g ⟩ → (g /1) ∈ R[1/ f ]AsCommRing ˣ ℕhelper n = PT.rec isPropGoal -- fⁿ≡αg → g⁻¹≡α/fⁿ λ (α , p) → [ (α zero) , (f ^ n) , ∣ n , refl ∣₁ ] , eq/ _ _ ((1r , powersFormMultClosedSubset f .containsOne) , useSolver1 _ _ ∙ sym p ∙ useSolver2 _) where useSolver1 : ∀ x y → 1r · (x · y) · 1r ≡ y · x + 0r useSolver1 = solve R' useSolver2 : ∀ x → x ≡ 1r · 1r · (1r · x) useSolver2 = solve R' toUnit : f ∈ᵢ √ ⟨ g ⟩ → ∀ s → s ∈ [ g ⁿ|n≥0] → (s /1) ∈ R[1/ f ]AsCommRing ˣ toUnit f∈√⟨g⟩ = powersPropElim (λ x → Units.inverseUniqueness _ (x /1)) λ n → subst-∈ (R[1/ f ]AsCommRing ˣ) (sym (^-respects-/1 n)) (Exponentiation.^-presUnit _ _ n (unitHelper f∈√⟨g⟩)) module DoubleLoc (R' : CommRing ℓ) (f g : (fst R')) where open isMultClosedSubset open CommRingStr (snd R') open CommRingTheory R' open Exponentiation R' open InvertingElementsBase open RingTheory (CommRing→Ring R') open CommRingStr (snd (R[1/_]AsCommRing R' f)) renaming ( _·_ to _·ᶠ_ ; 1r to 1ᶠ ; _+_ to _+ᶠ_ ; 0r to 0ᶠ ; ·IdL to ·ᶠ-lid ; ·IdR to ·ᶠ-rid ; ·Assoc to ·ᶠ-assoc ; ·Comm to ·ᶠ-comm) open IsRingHom private R = fst R' R[1/f] = R[1/_] R' f R[1/f]AsCommRing = R[1/_]AsCommRing R' f R[1/fg] = R[1/_] R' (f · g) R[1/fg]AsCommRing = R[1/_]AsCommRing R' (f · g) R[1/f][1/g] = R[1/_] (R[1/_]AsCommRing R' f) [ g , 1r , powersFormMultClosedSubset R' f .containsOne ] R[1/f][1/g]AsCommRing = R[1/_]AsCommRing (R[1/_]AsCommRing R' f) [ g , 1r , powersFormMultClosedSubset R' f .containsOne ] R[1/f][1/g]ˣ = R[1/f][1/g]AsCommRing ˣ _/1/1 : R → R[1/f][1/g] r /1/1 = [ [ r , 1r , PT.∣ 0 , refl ∣₁ ] , 1ᶠ , PT.∣ 0 , refl ∣₁ ] /1/1AsCommRingHom : CommRingHom R' R[1/f][1/g]AsCommRing fst /1/1AsCommRingHom = _/1/1 snd /1/1AsCommRingHom = makeIsRingHom refl lem+ lem· where lem+ : _ lem+ r r' = cong [_] (≡-× (cong [_] (≡-× (cong₂ _+_ (sym (·IdR _) ∙ (λ i → (·IdR r (~ i)) · (·IdR 1r (~ i)))) (sym (·IdR _) ∙ (λ i → (·IdR r' (~ i)) · (·IdR 1r (~ i))))) (Σ≡Prop (λ _ → isPropPropTrunc) (sym (·IdL _) ∙ (λ i → (·IdL 1r (~ i)) · (·IdL 1r (~ i))))))) (Σ≡Prop (λ _ → isPropPropTrunc) (sym (·ᶠ-lid 1ᶠ)))) lem· : _ lem· r r' = cong [_] (≡-× (cong [_] (≡-× refl (Σ≡Prop (λ _ → isPropPropTrunc) (sym (·IdL _))))) (Σ≡Prop (λ _ → isPropPropTrunc) (sym (·ᶠ-lid 1ᶠ)))) -- this will give us a map R[1/fg] → R[1/f][1/g] by the universal property of localisation fⁿgⁿ/1/1∈R[1/f][1/g]ˣ : (s : R) → s ∈ ([_ⁿ|n≥0] R' (f · g)) → s /1/1 ∈ R[1/f][1/g]ˣ fⁿgⁿ/1/1∈R[1/f][1/g]ˣ = powersPropElim R' (λ s → R[1/f][1/g]ˣ (s /1/1) .snd) ℕcase where ℕcase : (n : ℕ) → ((f · g) ^ n) /1/1 ∈ R[1/f][1/g]ˣ ℕcase n = [ [ 1r , (f ^ n) , PT.∣ n , refl ∣₁ ] , [ (g ^ n) , 1r , PT.∣ 0 , refl ∣₁ ] --denominator , PT.∣ n , ^-respects-/1 _ n ∣₁ ] , eq/ _ _ ((1ᶠ , powersFormMultClosedSubset _ _ .containsOne) , eq/ _ _ ((1r , powersFormMultClosedSubset _ _ .containsOne) , path)) where eq1 : ∀ x → 1r · (1r · (x · 1r) · 1r) · (1r · 1r · (1r · 1r)) ≡ x eq1 = solve R' eq2 : ∀ x y → x · y ≡ 1r · (1r · 1r · (1r · y)) · (1r · (1r · x) · 1r) eq2 = solve R' path : 1r · (1r · ((f · g) ^ n · 1r) · 1r) · (1r · 1r · (1r · 1r)) ≡ 1r · (1r · 1r · (1r · g ^ n)) · (1r · (1r · f ^ n) · 1r) path = 1r · (1r · ((f · g) ^ n · 1r) · 1r) · (1r · 1r · (1r · 1r)) ≡⟨ eq1 ((f · g) ^ n) ⟩ (f · g) ^ n ≡⟨ ^-ldist-· _ _ _ ⟩ f ^ n · g ^ n ≡⟨ eq2 (f ^ n) (g ^ n) ⟩ 1r · (1r · 1r · (1r · g ^ n)) · (1r · (1r · f ^ n) · 1r) ∎ open PathToS⁻¹R pathtoR[1/fg] : PathToS⁻¹R R' ([_ⁿ|n≥0] R' (f · g)) (powersFormMultClosedSubset R' (f · g)) R[1/f][1/g]AsCommRing /1/1AsCommRingHom φS⊆Aˣ pathtoR[1/fg] = fⁿgⁿ/1/1∈R[1/f][1/g]ˣ kerφ⊆annS pathtoR[1/fg] r p = toGoal helperR[1/f] where open RingTheory (CommRing→Ring R[1/f]AsCommRing) renaming ( 0RightAnnihilates to 0ᶠRightAnnihilates ; 0LeftAnnihilates to 0ᶠ-leftNullifies) open Exponentiation R[1/f]AsCommRing renaming (_^_ to _^ᶠ_) hiding (·-of-^-is-^-of-+ ; ^-ldist-·) S[f] = Loc.S R' ([_ⁿ|n≥0] R' f) (powersFormMultClosedSubset R' f) S[fg] = Loc.S R' ([_ⁿ|n≥0] R' (f · g)) (powersFormMultClosedSubset R' (f · g)) g/1 : R[1/_] R' f g/1 = [ g , 1r , powersFormMultClosedSubset R' f .containsOne ] S[g/1] = Loc.S R[1/f]AsCommRing ([_ⁿ|n≥0] R[1/f]AsCommRing g/1) (powersFormMultClosedSubset R[1/f]AsCommRing g/1) r/1 : R[1/_] R' f r/1 = [ r , 1r , powersFormMultClosedSubset R' f .containsOne ] -- this is the crucial step, modulo truncation we can take p to be generated -- by the quotienting relation of localisation. Note that we wouldn't be able -- to prove our goal if kerφ⊆annS was formulated with a Σ instead of a ∃ ∥r/1,1/1≈0/1,1/1∥ : ∃[ u ∈ S[g/1] ] fst u ·ᶠ r/1 ·ᶠ 1ᶠ ≡ fst u ·ᶠ 0ᶠ ·ᶠ 1ᶠ ∥r/1,1/1≈0/1,1/1∥ = Iso.fun (SQ.isEquivRel→TruncIso (Loc.locIsEquivRel _ _ _) _ _) p helperR[1/f] : ∃[ n ∈ ℕ ] [ g ^ n · r , 1r , PT.∣ 0 , refl ∣₁ ] ≡ 0ᶠ helperR[1/f] = PT.rec isPropPropTrunc (uncurry (uncurry (powersPropElim R[1/f]AsCommRing (λ _ → isPropΠ (λ _ → isPropPropTrunc)) baseCase))) ∥r/1,1/1≈0/1,1/1∥ where baseCase : ∀ n → g/1 ^ᶠ n ·ᶠ r/1 ·ᶠ 1ᶠ ≡ g/1 ^ᶠ n ·ᶠ 0ᶠ ·ᶠ 1ᶠ → ∃[ n ∈ ℕ ] [ g ^ n · r , 1r , PT.∣ 0 , refl ∣₁ ] ≡ 0ᶠ baseCase n q = PT.∣ n , path ∣₁ where path : [ g ^ n · r , 1r , PT.∣ 0 , refl ∣₁ ] ≡ 0ᶠ path = [ g ^ n · r , 1r , PT.∣ 0 , refl ∣₁ ] ≡⟨ cong [_] (≡-× refl (Σ≡Prop (λ _ → isPropPropTrunc) (sym (·IdR _)))) ⟩ [ g ^ n , 1r , PT.∣ 0 , refl ∣₁ ] ·ᶠ r/1 ≡⟨ cong (_·ᶠ r/1) (^-respects-/1 _ n) ⟩ g/1 ^ᶠ n ·ᶠ r/1 ≡⟨ sym (·ᶠ-rid _) ⟩ g/1 ^ᶠ n ·ᶠ r/1 ·ᶠ 1ᶠ ≡⟨ q ⟩ g/1 ^ᶠ n ·ᶠ 0ᶠ ·ᶠ 1ᶠ ≡⟨ cong (_·ᶠ 1ᶠ) (0ᶠRightAnnihilates _) ∙ 0ᶠ-leftNullifies 1ᶠ ⟩ 0ᶠ ∎ toGoal : ∃[ n ∈ ℕ ] [ g ^ n · r , 1r , PT.∣ 0 , refl ∣₁ ] ≡ 0ᶠ → ∃[ u ∈ S[fg] ] fst u · r ≡ 0r toGoal = PT.rec isPropPropTrunc Σhelper where Σhelper : Σ[ n ∈ ℕ ] [ g ^ n · r , 1r , PT.∣ 0 , refl ∣₁ ] ≡ 0ᶠ → ∃[ u ∈ S[fg] ] fst u · r ≡ 0r Σhelper (n , q) = PT.map Σhelper2 helperR where -- now, repeat the above strategy with q ∥gⁿr≈0∥ : ∃[ u ∈ S[f] ] fst u · (g ^ n · r) · 1r ≡ fst u · 0r · 1r ∥gⁿr≈0∥ = Iso.fun (SQ.isEquivRel→TruncIso (Loc.locIsEquivRel _ _ _) _ _) q helperR : ∃[ m ∈ ℕ ] f ^ m · g ^ n · r ≡ 0r helperR = PT.rec isPropPropTrunc (uncurry (uncurry (powersPropElim R' (λ _ → isPropΠ (λ _ → isPropPropTrunc)) baseCase))) ∥gⁿr≈0∥ where baseCase : (m : ℕ) → f ^ m · (g ^ n · r) · 1r ≡ f ^ m · 0r · 1r → ∃[ m ∈ ℕ ] f ^ m · g ^ n · r ≡ 0r baseCase m q' = PT.∣ m , path ∣₁ where path : f ^ m · g ^ n · r ≡ 0r path = (λ i → ·IdR (·Assoc (f ^ m) (g ^ n) r (~ i)) (~ i)) ∙∙ q' ∙∙ (λ i → ·IdR (0RightAnnihilates (f ^ m) i) i) Σhelper2 : Σ[ m ∈ ℕ ] f ^ m · g ^ n · r ≡ 0r → Σ[ u ∈ S[fg] ] fst u · r ≡ 0r Σhelper2 (m , q') = (((f · g) ^ l) , PT.∣ l , refl ∣₁) , path where l = max m n path : (f · g) ^ l · r ≡ 0r path = (f · g) ^ l · r ≡⟨ cong (_· r) (^-ldist-· _ _ _) ⟩ f ^ l · g ^ l · r ≡⟨ cong₂ (λ x y → f ^ x · g ^ y · r) (sym (≤-∸-+-cancel {m = m} left-≤-max)) (sym (≤-∸-+-cancel {m = n} right-≤-max)) ⟩ f ^ (l ∸ m +ℕ m) · g ^ (l ∸ n +ℕ n) · r ≡⟨ cong₂ (λ x y → x · y · r) (sym (·-of-^-is-^-of-+ _ _ _)) (sym (·-of-^-is-^-of-+ _ _ _)) ⟩ f ^ (l ∸ m) · f ^ m · (g ^ (l ∸ n) · g ^ n) · r ≡⟨ cong (_· r) (·CommAssocSwap _ _ _ _) ⟩ f ^ (l ∸ m) · g ^ (l ∸ n) · (f ^ m · g ^ n) · r ≡⟨ sym (·Assoc _ _ _) ⟩ f ^ (l ∸ m) · g ^ (l ∸ n) · (f ^ m · g ^ n · r) ≡⟨ cong (f ^ (l ∸ m) · g ^ (l ∸ n) ·_) q' ⟩ f ^ (l ∸ m) · g ^ (l ∸ n) · 0r ≡⟨ 0RightAnnihilates _ ⟩ 0r ∎ surχ pathtoR[1/fg] = invElPropElim _ (λ _ → isPropPropTrunc) toGoal where open Exponentiation R[1/f]AsCommRing renaming (_^_ to _^ᶠ_) hiding (·-of-^-is-^-of-+ ; ^-ldist-·) open CommRingStr (snd R[1/f][1/g]AsCommRing) renaming (_·_ to _·R[1/f][1/g]_) hiding (1r ; ·IdL ; ·IdR ; ·Assoc) open Units R[1/f][1/g]AsCommRing g/1 : R[1/_] R' f g/1 = [ g , 1r , powersFormMultClosedSubset R' f .containsOne ] S[fg] = Loc.S R' ([_ⁿ|n≥0] R' (f · g)) (powersFormMultClosedSubset R' (f · g)) baseCase : (r : R) (m n : ℕ) → ∃[ x ∈ R × S[fg] ] (x .fst /1/1) ≡ [ [ r , f ^ m , PT.∣ m , refl ∣₁ ] , [ g ^ n , 1r , PT.∣ 0 , refl ∣₁ ] , PT.∣ n , ^-respects-/1 _ n ∣₁ ] ·R[1/f][1/g] (x .snd .fst /1/1) baseCase r m n = PT.∣ ((r · f ^ (l ∸ m) · g ^ (l ∸ n)) -- x .fst , (f · g) ^ l , PT.∣ l , refl ∣₁) -- x .snd , eq/ _ _ ((1ᶠ , PT.∣ 0 , refl ∣₁) , eq/ _ _ ((1r , PT.∣ 0 , refl ∣₁) , path)) ∣₁ -- reduce equality of double fractions into equality in R where eq1 : ∀ r flm gln gn fm → 1r · (1r · (r · flm · gln) · (gn · 1r)) · (1r · (fm · 1r) · 1r) ≡ r · flm · (gln · gn) · fm eq1 = solve R' eq2 : ∀ r flm gl fm → r · flm · gl · fm ≡ r · (flm · fm ) · gl eq2 = solve R' eq3 : ∀ r fgl → r · fgl ≡ 1r · (1r · (r · fgl) · 1r) · (1r · 1r · (1r · 1r)) eq3 = solve R' l = max m n path : 1r · (1r · (r · f ^ (l ∸ m) · g ^ (l ∸ n)) · (g ^ n · 1r)) · (1r · (f ^ m · 1r) · 1r) ≡ 1r · (1r · (r · (f · g) ^ l) · 1r) · (1r · 1r · (1r · 1r)) path = 1r · (1r · (r · f ^ (l ∸ m) · g ^ (l ∸ n)) · (g ^ n · 1r)) · (1r · (f ^ m · 1r) · 1r) ≡⟨ eq1 r (f ^ (l ∸ m)) (g ^ (l ∸ n)) (g ^ n) (f ^ m) ⟩ r · f ^ (l ∸ m) · (g ^ (l ∸ n) · g ^ n) · f ^ m ≡⟨ cong (λ x → r · f ^ (l ∸ m) · x · f ^ m) (·-of-^-is-^-of-+ _ _ _) ⟩ r · f ^ (l ∸ m) · g ^ (l ∸ n +ℕ n) · f ^ m ≡⟨ cong (λ x → r · f ^ (l ∸ m) · g ^ x · f ^ m) (≤-∸-+-cancel right-≤-max) ⟩ r · f ^ (l ∸ m) · g ^ l · f ^ m ≡⟨ eq2 r (f ^ (l ∸ m)) (g ^ l) (f ^ m) ⟩ r · (f ^ (l ∸ m) · f ^ m) · g ^ l ≡⟨ cong (λ x → r · x · g ^ l) (·-of-^-is-^-of-+ _ _ _) ⟩ r · f ^ (l ∸ m +ℕ m) · g ^ l ≡⟨ cong (λ x → r · f ^ x · g ^ l) (≤-∸-+-cancel left-≤-max) ⟩ r · f ^ l · g ^ l ≡⟨ sym (·Assoc _ _ _) ⟩ r · (f ^ l · g ^ l) ≡⟨ cong (r ·_) (sym (^-ldist-· _ _ _)) ⟩ r · (f · g) ^ l ≡⟨ eq3 r ((f · g) ^ l) ⟩ 1r · (1r · (r · (f · g) ^ l) · 1r) · (1r · 1r · (1r · 1r)) ∎ base-^ᶠ-helper : (r : R) (m n : ℕ) → ∃[ x ∈ R × S[fg] ] (x .fst /1/1) ≡ [ [ r , f ^ m , PT.∣ m , refl ∣₁ ] , g/1 ^ᶠ n , PT.∣ n , refl ∣₁ ] ·R[1/f][1/g] (x .snd .fst /1/1) base-^ᶠ-helper r m n = subst (λ y → ∃[ x ∈ R × S[fg] ] (x .fst /1/1) ≡ [ [ r , f ^ m , PT.∣ m , refl ∣₁ ] , y ] ·R[1/f][1/g] (x .snd .fst /1/1)) (Σ≡Prop (λ _ → isPropPropTrunc) (^-respects-/1 _ n)) (baseCase r m n) indStep : (r : R[1/_] R' f) (n : ℕ) → ∃[ x ∈ R × S[fg] ] (x .fst /1/1) ≡ [ r , g/1 ^ᶠ n , PT.∣ n , refl ∣₁ ] ·R[1/f][1/g] (x .snd .fst /1/1) indStep = invElPropElim _ (λ _ → isPropΠ λ _ → isPropPropTrunc) base-^ᶠ-helper toGoal : (r : R[1/_] R' f) (n : ℕ) → ∃[ x ∈ R × S[fg] ] (x .fst /1/1) ·R[1/f][1/g] ((x .snd .fst /1/1) ⁻¹) ⦃ φS⊆Aˣ pathtoR[1/fg] (x .snd .fst) (x .snd .snd) ⦄ ≡ [ r , g/1 ^ᶠ n , PT.∣ n , refl ∣₁ ] toGoal r n = PT.map Σhelper (indStep r n) where Σhelper : Σ[ x ∈ R × S[fg] ] (x .fst /1/1) ≡ [ r , g/1 ^ᶠ n , PT.∣ n , refl ∣₁ ] ·R[1/f][1/g] (x .snd .fst /1/1) → Σ[ x ∈ R × S[fg] ] (x .fst /1/1) ·R[1/f][1/g] ((x .snd .fst /1/1) ⁻¹) ⦃ φS⊆Aˣ pathtoR[1/fg] (x .snd .fst) (x .snd .snd) ⦄ ≡ [ r , g/1 ^ᶠ n , PT.∣ n , refl ∣₁ ] Σhelper ((r' , s , s∈S[fg]) , p) = (r' , s , s∈S[fg]) , ⁻¹-eq-elim ⦃ φS⊆Aˣ pathtoR[1/fg] s s∈S[fg] ⦄ p -- the main result: localising at one element and then at another is -- the same as localising at the product. -- takes forever to compute without experimental lossy unification R[1/fg]≡R[1/f][1/g] : R[1/fg]AsCommRing ≡ R[1/f][1/g]AsCommRing R[1/fg]≡R[1/f][1/g] = S⁻¹RChar R' ([_ⁿ|n≥0] R' (f · g)) (powersFormMultClosedSubset R' (f · g)) _ /1/1AsCommRingHom pathtoR[1/fg] -- In this module we construct the map R[1/fg]→R[1/f][1/g] directly -- and show that it is equal (although not judgementally) to the map induced -- by the universal property of localisation, i.e. transporting along the path -- constructed above. Given that this is the easier direction, we can see that -- it is pretty cumbersome to prove R[1/fg]≡R[1/f][1/g] directly, -- which illustrates the usefulness of S⁻¹RChar quite well. private module check where φ : R[1/fg] → R[1/f][1/g] φ = SQ.rec squash/ ϕ ϕcoh where S[fg] = Loc.S R' ([_ⁿ|n≥0] R' (f · g)) (powersFormMultClosedSubset R' (f · g)) curriedϕΣ : (r s : R) → Σ[ n ∈ ℕ ] s ≡ (f · g) ^ n → R[1/f][1/g] curriedϕΣ r s (n , s≡fg^n) = [ [ r , (f ^ n) , PT.∣ n , refl ∣₁ ] , [ (g ^ n) , 1r , PT.∣ 0 , refl ∣₁ ] --denominator , PT.∣ n , ^-respects-/1 R' n ∣₁ ] curriedϕ : (r s : R) → ∃[ n ∈ ℕ ] s ≡ (f · g) ^ n → R[1/f][1/g] curriedϕ r s = elim→Set (λ _ → squash/) (curriedϕΣ r s) coh where coh : (x y : Σ[ n ∈ ℕ ] s ≡ (f · g) ^ n) → curriedϕΣ r s x ≡ curriedϕΣ r s y coh (n , s≡fg^n) (m , s≡fg^m) = eq/ _ _ ((1ᶠ , PT.∣ 0 , refl ∣₁) , eq/ _ _ ( (1r , powersFormMultClosedSubset R' f .containsOne) , path)) where eq1 : ∀ r gm fm → 1r · (1r · r · gm) · (1r · fm · 1r) ≡ r · (gm · fm) eq1 = solve R' path : 1r · (1r · r · (g ^ m)) · (1r · (f ^ m) · 1r) ≡ 1r · (1r · r · (g ^ n)) · (1r · (f ^ n) · 1r) path = 1r · (1r · r · (g ^ m)) · (1r · (f ^ m) · 1r) ≡⟨ eq1 r (g ^ m) (f ^ m) ⟩ r · (g ^ m · f ^ m) ≡⟨ cong (r ·_) (sym (^-ldist-· g f m)) ⟩ r · ((g · f) ^ m) ≡⟨ cong (λ x → r · (x ^ m)) (·Comm _ _) ⟩ r · ((f · g) ^ m) ≡⟨ cong (r ·_) ((sym s≡fg^m) ∙ s≡fg^n) ⟩ r · ((f · g) ^ n) ≡⟨ cong (λ x → r · (x ^ n)) (·Comm _ _) ⟩ r · ((g · f) ^ n) ≡⟨ cong (r ·_) (^-ldist-· g f n) ⟩ r · (g ^ n · f ^ n) ≡⟨ sym (eq1 r (g ^ n) (f ^ n)) ⟩ 1r · (1r · r · (g ^ n)) · (1r · (f ^ n) · 1r) ∎ ϕ : R × S[fg] → R[1/f][1/g] ϕ = uncurry2 curriedϕ -- λ (r / (fg)ⁿ) → ((r / fⁿ) / gⁿ) curriedϕcohΣ : (r s r' s' u : R) → (p : u · r · s' ≡ u · r' · s) → (α : Σ[ n ∈ ℕ ] s ≡ (f · g) ^ n) → (β : Σ[ m ∈ ℕ ] s' ≡ (f · g) ^ m) → (γ : Σ[ l ∈ ℕ ] u ≡ (f · g) ^ l) → ϕ (r , s , PT.∣ α ∣₁) ≡ ϕ (r' , s' , PT.∣ β ∣₁) curriedϕcohΣ r s r' s' u p (n , s≡fgⁿ) (m , s'≡fgᵐ) (l , u≡fgˡ) = eq/ _ _ ( ( [ (g ^ l) , 1r , powersFormMultClosedSubset R' f .containsOne ] , PT.∣ l , ^-respects-/1 R' l ∣₁) , eq/ _ _ ((f ^ l , PT.∣ l , refl ∣₁) , path)) where eq1 : ∀ fl gl r gm fm → fl · (gl · r · gm) · (1r · fm · 1r) ≡ fl · gl · r · (gm · fm) eq1 = solve R' path : f ^ l · (g ^ l · transp (λ i → R) i0 r · transp (λ i → R) i0 (g ^ m)) · (1r · transp (λ i → R) i0 (f ^ m) · transp (λ i → R) i0 1r) ≡ f ^ l · (g ^ l · transp (λ i → R) i0 r' · transp (λ i → R) i0 (g ^ n)) · (1r · transp (λ i → R) i0 (f ^ n) · transp (λ i → R) i0 1r) path = f ^ l · (g ^ l · transp (λ i → R) i0 r · transp (λ i → R) i0 (g ^ m)) · (1r · transp (λ i → R) i0 (f ^ m) · transp (λ i → R) i0 1r) ≡⟨ (λ i → f ^ l · (g ^ l · transportRefl r i · transportRefl (g ^ m) i) · (1r · transportRefl (f ^ m) i · transportRefl 1r i)) ⟩ f ^ l · (g ^ l · r · g ^ m) · (1r · f ^ m · 1r) ≡⟨ eq1 (f ^ l) (g ^ l) r (g ^ m) (f ^ m) ⟩ f ^ l · g ^ l · r · (g ^ m · f ^ m) ≡⟨ (λ i → ^-ldist-· f g l (~ i) · r · ^-ldist-· g f m (~ i)) ⟩ (f · g) ^ l · r · (g · f) ^ m ≡⟨ cong (λ x → (f · g) ^ l · r · x ^ m) (·Comm _ _) ⟩ (f · g) ^ l · r · (f · g) ^ m ≡⟨ (λ i → u≡fgˡ (~ i) · r · s'≡fgᵐ (~ i)) ⟩ u · r · s' ≡⟨ p ⟩ u · r' · s ≡⟨ (λ i → u≡fgˡ i · r' · s≡fgⁿ i) ⟩ (f · g) ^ l · r' · (f · g) ^ n ≡⟨ cong (λ x → (f · g) ^ l · r' · x ^ n) (·Comm _ _) ⟩ (f · g) ^ l · r' · (g · f) ^ n ≡⟨ (λ i → ^-ldist-· f g l i · r' · ^-ldist-· g f n i) ⟩ f ^ l · g ^ l · r' · (g ^ n · f ^ n) ≡⟨ sym (eq1 (f ^ l) (g ^ l) r' (g ^ n) (f ^ n)) ⟩ f ^ l · (g ^ l · r' · g ^ n) · (1r · f ^ n · 1r) ≡⟨ (λ i → f ^ l · (g ^ l · transportRefl r' (~ i) · transportRefl (g ^ n) (~ i)) · (1r · transportRefl (f ^ n) (~ i) · transportRefl 1r (~ i))) ⟩ f ^ l · (g ^ l · transp (λ i → R) i0 r' · transp (λ i → R) i0 (g ^ n)) · (1r · transp (λ i → R) i0 (f ^ n) · transp (λ i → R) i0 1r) ∎ curriedϕcoh : (r s r' s' u : R) → (p : u · r · s' ≡ u · r' · s) → (α : ∃[ n ∈ ℕ ] s ≡ (f · g) ^ n) → (β : ∃[ m ∈ ℕ ] s' ≡ (f · g) ^ m) → (γ : ∃[ l ∈ ℕ ] u ≡ (f · g) ^ l) → ϕ (r , s , α) ≡ ϕ (r' , s' , β) curriedϕcoh r s r' s' u p = PT.elim (λ _ → isPropΠ2 (λ _ _ → squash/ _ _)) λ α → PT.elim (λ _ → isPropΠ (λ _ → squash/ _ _)) λ β → PT.rec (squash/ _ _) λ γ → curriedϕcohΣ r s r' s' u p α β γ ϕcoh : (a b : R × S[fg]) → Loc._≈_ R' ([_ⁿ|n≥0] R' (f · g)) (powersFormMultClosedSubset R' (f · g)) a b → ϕ a ≡ ϕ b ϕcoh (r , s , α) (r' , s' , β) ((u , γ) , p) = curriedϕcoh r s r' s' u p α β γ -- the map induced by the universal property open S⁻¹RUniversalProp R' ([_ⁿ|n≥0] R' (f · g)) (powersFormMultClosedSubset R' (f · g)) χ : R[1/fg] → R[1/f][1/g] χ = S⁻¹RHasUniversalProp R[1/f][1/g]AsCommRing /1/1AsCommRingHom fⁿgⁿ/1/1∈R[1/f][1/g]ˣ .fst .fst .fst -- the sanity check: -- both maps send a fraction r/(fg)ⁿ to a double fraction, -- where numerator and denominator are almost the same fraction respectively. -- unfortunately the proofs that the denominators are powers are quite different for -- the two maps, but of course we can ignore them. -- The definition of χ introduces a lot of (1r ·_). Perhaps most surprisingly, -- we have to give the path eq1 for the equality of the numerator of the numerator. φ≡χ : ∀ r → φ r ≡ χ r φ≡χ = invElPropElim _ (λ _ → squash/ _ _) ℕcase where ℕcase : (r : R) (n : ℕ) → φ [ r , (f · g) ^ n , PT.∣ n , refl ∣₁ ] ≡ χ [ r , (f · g) ^ n , PT.∣ n , refl ∣₁ ] ℕcase r n = cong [_] (ΣPathP --look into the components of the double-fractions ( cong [_] (ΣPathP (eq1 , Σ≡Prop (λ x → S'[f] x .snd) (sym (·IdL _)))) , Σ≡Prop (λ x → S'[f][g] x .snd) --ignore proof that denominator is power of g/1 ( cong [_] (ΣPathP (sym (·IdL _) , Σ≡Prop (λ x → S'[f] x .snd) (sym (·IdL _))))))) where S'[f] = ([_ⁿ|n≥0] R' f) S'[f][g] = ([_ⁿ|n≥0] R[1/f]AsCommRing [ g , 1r , powersFormMultClosedSubset R' f .containsOne ]) eq1 : transp (λ i → fst R') i0 r ≡ r · transp (λ i → fst R') i0 1r eq1 = transportRefl r ∙∙ sym (·IdR r) ∙∙ cong (r ·_) (sym (transportRefl 1r)) ",12145,True,2779.944960931273,median "{- Formal verification of authenticated append-only skiplists in Agda, version 1.0. Copyright (c) 2020 Oracle and/or its affiliates. Licensed under the Universal Permissive License v 1.0 as shown at https://opensource.oracle.com/licenses/upl -} open import Data.Unit.NonEta open import Data.Empty open import Data.Sum open import Data.Product open import Data.Product.Properties open import Data.Fin hiding (_<_; _≤_) open import Data.Fin.Properties using () renaming (_≟_ to _≟Fin_) open import Data.Nat renaming (_≟_ to _≟ℕ_; _≤?_ to _≤?ℕ_) open import Data.Nat.Properties open import Data.List renaming (map to List-map) open import Data.List.Properties using (∷-injective; length-map) open import Data.List.Relation.Unary.Any renaming (map to Any-map) open import Data.List.Relation.Unary.All renaming (lookup to All-lookup; map to All-map) open import Data.List.Relation.Unary.All.Properties hiding (All-map) open import Data.List.Relation.Unary.Any.Properties renaming (map⁺ to Any-map⁺) open import Data.List.Relation.Binary.Pointwise using (decidable-≡) open import Data.Bool hiding (_<_; _≤_) open import Data.Maybe renaming (map to Maybe-map) open import Function open import Relation.Binary.PropositionalEquality open import Relation.Binary.Core open import Relation.Nullary open import AAOSL.Lemmas open import AAOSL.Abstract.Hash open import AAOSL.Abstract.DepRel -- This module defines the DepRel type, which represents the class of AAOSLs we -- consider, and proves properties about any DepRel. module AAOSL.Abstract.Advancement -- A Hash function maps a bytestring into a hash. (hash : ByteString → Hash) -- And is collision resistant (hash-cr : ∀{x y} → hash x ≡ hash y → Collision hash x y ⊎ x ≡ y) -- Indexes can be encoded in an injective way (encodeI : ℕ → ByteString) (encodeI-inj : (m n : ℕ) → encodeI m ≡ encodeI n → m ≡ n) (dep : DepRel) where -- Brings the DepRel names into scope instantiated -- for the module parameters in question. open DepRel dep hop-prog : ∀{m}(h : HopFrom m) → hop-tgt h ≢ m hop-prog = <⇒≢ ∘ hop-< hop-≤ : ∀{m}(h : HopFrom m) → hop-tgt h ≤ m hop-≤ = <⇒≤ ∘ hop-< depsof : ℕ → List ℕ depsof 0 = [] depsof (suc i) = List-map hop-tgt (nats (lvlof (suc i))) depsof-ne : ∀ m → depsof m ≡ [] → m ≡ 0 depsof-ne 0 hyp = refl depsof-ne (suc m) hyp = let le0 = trans (sym (length-map hop-tgt (nats (lvlof (suc m)))) ) (cong length hyp) le-nz = nats-length (lvlof-s m) in ⊥-elim (1≤0-⊥ (subst (1 ≤_) le0 le-nz)) hopFromZ-⊥ : (h : HopFrom 0) → ⊥ hopFromZ-⊥ h = fin0-⊥ (subst Fin lvlof-z h) where fin0-⊥ : Fin 0 → ⊥ fin0-⊥ () hop-tgt-is-dep : {m : ℕ}(h : HopFrom m) → hop-tgt h ∈ depsof m hop-tgt-is-dep {0} h = ⊥-elim (hopFromZ-⊥ h) hop-tgt-is-dep {suc m} h = Any-map⁺ (Any-map (cong hop-tgt) (nats-correct h)) -- Two simple but useful lemmas made to work over our abstract -- index type. ≤-≢-mon : ∀{i j tgt} → tgt ≢ j → tgt ≤ j → i ≤ tgt → i ≢ j ≤-≢-mon tgt≢j tgt≤j i≤tgt i≡j = tgt≢j (sym (≤-antisym (subst (_≤ _) i≡j i≤tgt) tgt≤j)) ≟ℕ-refl : (s : ℕ) → (s ≟ℕ s) ≡ yes refl ≟ℕ-refl s with s ≟ℕ s ...| no abs = ⊥-elim (abs refl) ...| yes refl = refl ⊥-prop : (a b : ⊥) → a ≡ b ⊥-prop () () ≟ℕ-neg : (m n : ℕ) → (p : m ≢ n) → (m ≟ℕ n) ≡ no p ≟ℕ-neg m n p with m ≟ℕ n ...| yes imp = ⊥-elim (p imp) ...| no r = cong no (fun-ext (λ x → ⊥-prop (r x) (p x))) HopFrom≢0 : ∀{j}(h : HopFrom j) → j ≢ 0 HopFrom≢0 {j} h refl = hopFromZ-⊥ h open WithCryptoHash hash hash-cr -- This function is total, even though we won't always know a hash for every -- index. That's ok, we only use the hashes of the relevant indexes. View : Set View = ℕ → Hash -- An inhabitant of 'Agree s t ixs' is a proof that the views s and t -- agree on the hash of every index i ∈ ixs. Agree : View → View → List ℕ → Set Agree v u = All (λ s → v s ≡ u s) -- Returns the list of hashes that the authenticator -- at the given index depends on. deps-hash : ℕ → View → List Hash deps-hash s tbl = List-map tbl (depsof s) -------------------------- -- Defining authenticators -- -- We need a function for computing the authenticator for a -- log position given its index, a hash of its datum, and a -- View that provides the authenticators for each of the -- indexes' dependencies. We also need to prove two -- injectivity lemmas for this function, showing that, unless -- there is a hash collision, the function is injective in -- both the datum hashes and also the dependencies. -- -- Below we define the function (called auth') as presented by -- Maniatis and Baker, and prove two injectivity lemmas for -- it: auth-inj-1' and auth-inj-2'. -- -- Our development made clear that any such function that -- satisfies these two injectivity properties suffices, and we -- found a much simpler definition, which is presented below -- (auth, auth-inj-1 and auth-inj-2), which are the ones -- actually used by the rest of the proof. -- TODO-2: Make auth, auth-inj-1 and auth-inj-2 module -- parameters that can be instantiated with either version, or -- any other function satisfying these properties -- Partial authenticators comes first. p-auth : (i : ℕ) → Hash → Hash → Hash p-auth i h hᵢ = hash (encodeI i ++ (encodeH h ++ encodeH hᵢ)) -- Together with their injectivity modulo hash collisions p-auth-inj : ∀{i h}(m n : Hash) → p-auth i h m ≡ p-auth i h n → HashBroke ⊎ m ≡ n p-auth-inj {i} {h} m n pm≡pn with hash-cr pm≡pn ...| inj₁ col = inj₁ (( encodeI i ++ encodeH h ++ encodeH m , encodeI i ++ encodeH h ++ encodeH n ), col) ...| inj₂ prf with ++-inj {m = encodeI i} {n = encodeI i} refl prf ...| (_ , hm≡hn) with ++-inj {m = encodeH h} {n = encodeH h} refl hm≡hn ...| (_ , m≡n) = inj₂ ( encodeH-inj m n m≡n) auth' : (s : ℕ) → Hash → View → Hash auth' s h tbl = hash-concat (List-map (p-auth s h) (deps-hash s tbl)) auth-inj-1' : {j : ℕ}{h₁ h₂ : Hash}{t₁ t₂ : View} → j ≢ 0 → auth' j h₁ t₁ ≡ auth' j h₂ t₂ → HashBroke ⊎ h₁ ≡ h₂ auth-inj-1' {j} {h₁} {h₂} {t₁} {t₂} j≢s₀ hip with depsof j | inspect depsof j ...| [] | [ R ] = ⊥-elim (j≢s₀ (depsof-ne j R)) ...| dj ∷ djs | _ with hash-concat-inj {List-map (p-auth j h₁) (List-map t₁ (dj ∷ djs))} {List-map (p-auth j h₂) (List-map t₂ (dj ∷ djs))} hip ...| inj₁ hb = inj₁ hb ...| inj₂ res with ∷-injective res ...| aux , auxs with hash-cr aux ...| inj₁ col = inj₁ (( encodeI j ++ encodeH h₁ ++ encodeH (t₁ dj) , encodeI j ++ encodeH h₂ ++ encodeH (t₂ dj)) , col) ...| inj₂ res' with ++-injₕ {m = encodeI j} res' ...| res'' with ++-inj {m = encodeH h₁} {encodeH h₂} (encodeH-len-lemma h₁ h₂) res'' ...| hh , ll = inj₂ (encodeH-inj h₁ h₂ hh) auth-inj-2' : {i : ℕ}{h : Hash}(t₁ t₂ : View) → auth' i h t₁ ≡ auth' i h t₂ → HashBroke ⊎ Agree t₁ t₂ (depsof i) auth-inj-2' {i} {h} t₁ t₂ hip with hash-concat-inj {List-map (p-auth i h) (List-map t₁ (depsof i))} {List-map (p-auth i h) (List-map t₂ (depsof i))} hip ...| inj₁ hb = inj₁ hb ...| inj₂ res = auth-inj-2-aux {i} {h} t₁ t₂ (depsof i) res where auth-inj-2-aux : {i : ℕ}{h : Hash}(t₁ t₂ : View)(l : List ℕ) → List-map (p-auth i h) (List-map t₁ l) ≡ List-map (p-auth i h) (List-map t₂ l) → HashBroke ⊎ Agree t₁ t₂ l auth-inj-2-aux {i} {h} t₁ t₂ [] pl₁≡pl₂ = inj₂ [] auth-inj-2-aux {i} {h} t₁ t₂ (x ∷ xs) pl₁≡pl₂ with ∷-injective pl₁≡pl₂ ...| (hprf , tprf) with p-auth-inj {i} {h} (t₁ x) (t₂ x) hprf ...| inj₁ hb = inj₁ hb ...| inj₂ t₁x≡t₂x with auth-inj-2-aux {i} {h} t₁ t₂ xs tprf ...| inj₁ hb = inj₁ hb ...| inj₂ agreeTail = inj₂ (t₁x≡t₂x All.∷ agreeTail) -- Next we define a much simpler variant of the auth function, -- and prove that it too satisfies the required injectivity -- properties. -- Authenticators will depend on all p-auths of the -- dependencies of a node. auth : (s : ℕ) → Hash → View → Hash auth s h tbl = hash-concat (hash (encodeI s) ∷ h ∷ deps-hash s tbl) -- We will be using two separate injectivity functions. One is -- for the hash of the data in a node, which can't be the -- initial node! auth-inj-1 : {j : ℕ}{h₁ h₂ : Hash}{t₁ t₂ : View} → j ≢ 0 → auth j h₁ t₁ ≡ auth j h₂ t₂ → HashBroke ⊎ h₁ ≡ h₂ auth-inj-1 {j} {h₁} {h₂} {t₁} {t₂} j≢s₀ hip with hash-concat-inj { hash (encodeI j) ∷ h₁ ∷ deps-hash j t₁ } { hash (encodeI j) ∷ h₂ ∷ deps-hash j t₂ } hip ...| inj₁ hb = inj₁ hb ...| inj₂ r = inj₂ (proj₁ (∷-injective (proj₂ (∷-injective r)))) -- The second one does induction on the list of dependencies. auth-inj-2 : {i : ℕ}{h : Hash}(t₁ t₂ : View) → auth i h t₁ ≡ auth i h t₂ → HashBroke ⊎ Agree t₁ t₂ (depsof i) auth-inj-2 {i} {h} t₁ t₂ hip with hash-concat-inj { hash (encodeI i) ∷ h ∷ deps-hash i t₁ } { hash (encodeI i) ∷ h ∷ deps-hash i t₂ } hip ...| inj₁ hb = inj₁ hb ...| inj₂ r = inj₂ (auth-inj-2-aux t₁ t₂ (depsof i) (proj₂ (∷-injective (proj₂ (∷-injective r))))) where auth-inj-2-aux : (t₁ t₂ : View)(l : List ℕ) → List-map t₁ l ≡ List-map t₂ l → Agree t₁ t₂ l auth-inj-2-aux t1 t2 [] hyp = [] auth-inj-2-aux t1 t2 (x ∷ l) hyp = proj₁ (∷-injective hyp) ∷ auth-inj-2-aux t1 t2 l (proj₂ (∷-injective hyp)) ------------------------ ------------------------ -- Advancement Proofs -- ------------------------ ------------------------ -- Finally, advancement proofs in their simple variant data AdvPath : ℕ → ℕ → Set where AdvDone : ∀{i} → AdvPath i i AdvThere : ∀{j i} → Hash -- datum digest → (h : HopFrom j) → AdvPath (hop-tgt h) i → AdvPath j i -- Override a view with a hash for a specific index. _∪₁_ : View → ℕ × Hash → View _∪₁_ tbl (s , h) s' with s ≟ℕ s' ...| yes _ = h ...| no _ = tbl s' -- The rebuild function is, essentially, a transformer over -- the current view of the skiplog. It is PARAMOUNT to return -- a new 'view' of the world, as we can see in rebuild-⊕ lemma. -- Otherwise, it becomes seriously intricate to express -- that rebuilding the hash of index j ""depends on"" the rebuilt -- hashes of j's dependencies. rebuild : ∀{i j} → AdvPath j i → View → View rebuild {i} AdvDone tbl = tbl rebuild (AdvThere {j = j} x h prf) tbl = let tbl' = rebuild prf tbl in tbl' ∪₁ (j , auth j x tbl') lemma1 : ∀{j i} → AdvPath j i → i ≤ j lemma1 AdvDone = ≤-refl lemma1 {j} (AdvThere x h a) = ≤-trans (lemma1 a) (hop-≤ h) rebuild-tgt-lemma : ∀{j i}(a : AdvPath j i){t : View} → rebuild a t i ≡ t i rebuild-tgt-lemma AdvDone = refl rebuild-tgt-lemma {j} {i} (AdvThere x h a) rewrite ≟ℕ-neg j i (<⇒≢ (≤-<-trans (lemma1 a) (hop-< h)) ∘ sym) = rebuild-tgt-lemma a lemma2 : ∀{i}(a : AdvPath i i) → a ≡ AdvDone lemma2 AdvDone = refl lemma2 (AdvThere x h a) = ⊥-elim (hop-prog h (sym (≤-antisym (lemma1 a) (hop-≤ h)))) -- Lemma3 states that if a hop exists, then it is not from -- s₀. This is necessary to eliminate some nasty cases. lemma3 : ∀{j i} → (h : HopFrom j) → AdvPath (hop-tgt h) i → j ≢ 0 lemma3 h a = HopFrom≢0 h ---------------------- -- Proof Splitting -- ---------------------- _⊕_ : ∀{j k i} → AdvPath j k → AdvPath k i → AdvPath j i AdvDone ⊕ rest = rest (AdvThere d h a) ⊕ rest = AdvThere d h (a ⊕ rest) ⊕-id-r : ∀{j i}(a : AdvPath j i) → a ⊕ AdvDone ≡ a ⊕-id-r AdvDone = refl ⊕-id-r (AdvThere x h a) = cong (AdvThere x h) (⊕-id-r a) -- A value of type 'i ∈AP a' illustrates index i as a dependency -- of 'a'. data _∈AP_ (i₀ : ℕ) : {j i : ℕ} → AdvPath j i → Set where hereTgtDone : i₀ ∈AP (AdvDone {i₀}) hereTgtThere : ∀{i}{d : Hash}{hop : HopFrom i₀}{a : AdvPath (hop-tgt hop) i} → i₀ ∈AP (AdvThere d hop a) step : ∀{i j}{d : Hash}{hop : HopFrom j}{a : AdvPath (hop-tgt hop) i} → i₀ ≢ j → i₀ ∈AP a → i₀ ∈AP (AdvThere d hop a) ∈AP-src : ∀{j i}{a : AdvPath j i} → j ∈AP a ∈AP-src {a = AdvDone} = hereTgtDone ∈AP-src {a = AdvThere x h a} = hereTgtThere ∈AP-tgt : ∀{j i}{a : AdvPath j i} → i ∈AP a ∈AP-tgt {a = AdvDone} = hereTgtDone ∈AP-tgt {a = AdvThere x h a} = step (<⇒≢ (≤-<-trans (lemma1 a) (hop-< h))) ∈AP-tgt ∈AP-≤ : ∀{j i}{a : AdvPath j i} → {i0 : ℕ} → i0 ∈AP a → i0 ≤ j ∈AP-≤ hereTgtDone = ≤-refl ∈AP-≤ hereTgtThere = ≤-refl ∈AP-≤ (step _ hyp) = ≤-trans (∈AP-≤ hyp) (hop-≤ _) ∈AP-≥ : ∀{j i}{a : AdvPath j i} → {i0 : ℕ} → i0 ∈AP a → i ≤ i0 ∈AP-≥ hereTgtDone = ≤-refl ∈AP-≥ {a = a} hereTgtThere = lemma1 a ∈AP-≥ (step _ hyp) = ∈AP-≥ hyp rebuild-⊕ : ∀{j k i} → {t : View} → (a₁ : AdvPath j k) → (a₂ : AdvPath k i) → ∀{l} → l ∈AP a₂ → rebuild (a₁ ⊕ a₂) t l ≡ rebuild a₂ t l rebuild-⊕ AdvDone a₂ hyp = refl rebuild-⊕ {j} (AdvThere x h a₁) a₂ {l} hyp with j ≟ℕ l ...| yes nope = ⊥-elim (≤-≢-mon (hop-prog h) (hop-≤ h) (≤-trans (∈AP-≤ hyp) (lemma1 a₁)) (sym nope)) ...| no ok = rebuild-⊕ a₁ a₂ hyp ∈AP-cut : ∀{j k i} → (a : AdvPath j i) → k ∈AP a → Σ (AdvPath j k × AdvPath k i) (λ { (x , y) → a ≡ x ⊕ y }) ∈AP-cut AdvDone hereTgtDone = (AdvDone , AdvDone) , refl ∈AP-cut (AdvThere d h a) hereTgtThere = (AdvDone , AdvThere d h a) , refl ∈AP-cut (AdvThere d h a) (step x prf) with ∈AP-cut a prf ...| xy , ind = (AdvThere d h (proj₁ xy) , proj₂ xy) , cong (AdvThere d h) ind ∈AP-cut₁ : ∀{j k i} → (a : AdvPath j i) → k ∈AP a → AdvPath k i ∈AP-cut₁ a prf = proj₂ (proj₁ (∈AP-cut a prf)) ∈AP-∈-cut : ∀{j k i} → (a : AdvPath j i) → (prf : k ∈AP a) → ∀{m} → m ∈AP a → m ≤ k → m ∈AP (∈AP-cut₁ a prf) ∈AP-∈-cut AdvDone hereTgtDone m∈ap hyp = m∈ap ∈AP-∈-cut (AdvThere _ _ _) hereTgtThere m∈ap hyp = m∈ap ∈AP-∈-cut (AdvThere d h a) (step x prf) hereTgtThere hyp = ⊥-elim (<⇒≱ (hop-< h) (≤-trans hyp (∈AP-≤ prf))) ∈AP-∈-cut (AdvThere d h a) (step x prf) (step x₁ m∈ap) hyp = ∈AP-∈-cut a prf m∈ap hyp ∈AP-cut₁-rebuild : ∀{j k i} → (a : AdvPath j i) → (prf : k ∈AP a) → {s : ℕ} → (s ∈AP (∈AP-cut₁ a prf)) → ∀{t} → rebuild a t s ≡ rebuild (∈AP-cut₁ a prf) t s ∈AP-cut₁-rebuild a prf s∈cut {t} with ∈AP-cut a prf ...| (x , y) , refl = rebuild-⊕ x y s∈cut ∈AP-⊕ : ∀{j i₁ k i₂ i} → {e : AdvPath j k}{a₁ : AdvPath k i₁} → {a₂ : AdvPath k i₂} → i ∈AP (e ⊕ a₁) → i ∈AP a₂ → i ∈AP a₁ ∈AP-⊕ {e = AdvDone} hyp1 hyp2 = hyp1 ∈AP-⊕ {e = AdvThere x h e} hereTgtThere hyp2 with ≤-antisym (∈AP-≤ hyp2) (lemma1 (AdvThere x h e)) ...| refl = ⊥-elim (hop-prog h (≤-antisym (hop-≤ h) (lemma1 e))) ∈AP-⊕ {e = AdvThere x h e} (step x₁ hyp1) hyp2 = ∈AP-⊕ hyp1 hyp2 ∈AP-point' : ∀{j k i} → {a₁ : AdvPath j k} → {a₂ : AdvPath k i} → {m : ℕ} → m ∈AP a₁ → m ∈AP a₂ → m ≡ k ∈AP-point' hereTgtDone h2 = refl ∈AP-point' {a₁ = AdvThere d h a₁} {a₂} hereTgtThere h2 = ⊥-elim (≤-≢-mon (≤-≢-mon (hop-prog h) (hop-≤ h) (lemma1 a₁) ∘ sym) (∈AP-≤ h2) (lemma1 (AdvThere d h a₁)) refl) ∈AP-point' (step x h1) h2 = ∈AP-point' h1 h2 ∈AP-point'' : ∀{j₁ j₂ i₁ i₂} → {a₁ : AdvPath j₁ i₁} → {a₂ : AdvPath j₂ i₂} → j₂ < i₁ → {i : ℕ} → i ∈AP a₁ → i ∈AP a₂ → ⊥ ∈AP-point'' j β : (α *) (toFam (f P ⊗ id)) ⇒ toFam p β ._ ((b , ._) , refl) = (b , refl) K : ⟦ P ⋊ I ⟧ (M (P ⋊ I)) → ⟦ P ⋊ I ⟧ (M (P ⋊ I) × E) K (a , v) = (a , abs'' a (v' a v)) where v' : (a : Sym (P ⋊ I)) (v : Π' (f (P ⋊ I)) (λ e → M (P ⋊ I)) a) (bi : Arit (P ⋊ I)) → f (P ⋊ I) bi ≡ a → M (P ⋊ I) × E v' ._ v₁ bi refl = (v₁ (bi , refl) , proj₁ bi) φ : M (P ⋊ I) × Arit P → M (P ⋊ I) φ = corec-M c where h : ⟦ P ⋊ I ⟧ (M (P ⋊ I)) × Arit P → ⟦ P ⋊ I ⟧ (M (P ⋊ I) × Arit P) h (((a , i) , v) , b) = ((a , t b) , abs'' (a , t b) (v' (a , t b) b v)) where v' : (ai' : Sym (P ⋊ I)) (b : Arit P) (v : Π' (f (P ⋊ I)) (λ _ → M (P ⋊ I)) (proj₁ ai' , i)) (i : Arit (P ⋊ I)) → f (P ⋊ I) i ≡ ai' → M (P ⋊ I) × Arit P v' ._ b v₁ (b₁ , _) refl = (app (b₁ , i) v₁ , b) c : M (P ⋊ I) × Arit P → ⟦ P ⋊ I ⟧ (M (P ⋊ I) × Arit P) c = h ∘ (ξ' ⊗ id) ψ : M (P ⋊ I) → M (P ⋊ I) ψ = corec-M c where c : M (P ⋊ I) → ⟦ P ⋊ I ⟧ (M (P ⋊ I)) c = ⟦ φ ⟧₁ ∘ K ∘ ξ' u₂ : M P → M (P ⋊ I) u₂ = ψ ∘ u₁ {- {- -- | Same as u₂??? u₂' : ∀ {I} (C : DPoly {I}) → M (↓ C) → M (↓ C ⋊ I) u₂' {I} C x = M₁ (polyHom α β) x where α : Sym (↓ C) → Sym ((↓ C) ⋊ I) α a = (a , t C {!!}) -- (root x)) -- (s C (root x))) β : (α *) (toFam (f (↓ C) ⊗ id)) ⇒ toFam (p C tt) β ._ ((a , ._) , refl) = (a , refl) φ : {I : Set} (C : DPoly {I}) {i : Size} → M {i} (↓ C ⋊ I) × Arit (↓ C) → M {i} (↓ C ⋊ I) ξ (φ {I} C (x , b)) {j} = q (ξ x) where m : ⟦ ↓ C ⋊ I ⟧ (M {j} (↓ C ⋊ I)) → Sym (↓ C ⋊ I) m ((a , i) , v) = (a , (t C b)) q : ⟦ ↓ C ⋊ I ⟧ (M {j} (↓ C ⋊ I)) → ⟦ ↓ C ⋊ I ⟧ (M {j} (↓ C ⋊ I)) q u = (m u , abs'' (m u) (v' u)) where v' : (u : ⟦ ↓ C ⋊ I ⟧ (M {j} (↓ C ⋊ I))) (b : Arit (↓ C ⋊ I)) → f (↓ C ⋊ I) b ≡ m u → M {j} (↓ C ⋊ I) v' ((._ , i) , v) (b , ._) refl = φ C ((app (b , i) v) , b) ψ : {I : Set} (C : DPoly {I}) {i : Size} → M {i} (↓ C ⋊ I) → M {i} (↓ C ⋊ I) ξ (ψ {I} C x) {j} = q (ξ x) where q : ⟦ ↓ C ⋊ I ⟧ (M {j} (↓ C ⋊ I)) → ⟦ ↓ C ⋊ I ⟧ (M {j} (↓ C ⋊ I)) q (a , v) = (a , abs'' a (v' (a , v))) where v' : (u' : ⟦ ↓ C ⋊ I ⟧ (M {j} (↓ C ⋊ I))) (a' : Arit (↓ C ⋊ I)) → f (↓ C ⋊ I) a' ≡ proj₁ u' → M {j} (↓ C ⋊ I) v' (._ , v) a' refl = φ C (app a' v , proj₁ a') u₂ : ∀ {i} {I} (C : DPoly {I}) → M (↓ C) → M {i} (↓ C ⋊ I) u₂ C = ψ C ∘ u₁ C -} Vφ : (i : I) → (M P → Set) Vφ i x = (s (root x) ≡ i) × (u₁ x ≡ u₂ x) --V' : {I : Set} (C : DPoly {I} {I}) → Fam I --V' C = ⟪ Vφ C ⟫² {- lem₂ : {I : Set} {C : DPoly {I} {I}} → (x : M (↓ C)) (b : E C) (v : Π' (p C) (λ e → M (↓ C)) (p C b)) → ξ' x ≡ (_ , v) → u₁ C x ≡ u₂ C x → u₁ C (app b v) ≡ u₂ C (app b v) lem₂ {I} {C} x b v pr≡ u₁≡u₂ = {!!} where w : (x : ⟦ ↓ C ⟧ (M (↓ C))) (b : E C) (v : Π' (p C) (λ e → M (↓ C)) (p C b)) → x ≡ (_ , v) → u₁ C (app b v) ≡ u₂ C (app b v) w ._ b v refl = {!!} -- bar : ξ' (u₁ C x) ≡ ⟦ ↓ C ⟧₁ u₁ (M₁ lem₁ : {I : Set} {C : DPoly {I} {I}} → (x : M (↓ C)) (b : E C) (v : Π' (p C) (λ e → M (↓ C)) (p C b)) → ξ' x ≡ (_ , v) → u₁ C x ≡ u₂ C x → s C (root (app b v)) ≡ t C b lem₁ x b v pr≡ u₁≡u₂ = {!!} {- ξV : ∀ {I} {C : DPoly {I} {I}} → V' C ⇒ T C (V' C) ξV {C = dpoly A s E p t} .(s (proj₁ (ξ x))) (x , refl , u₁≡u₂) = ins (root x) (abs'' (root x) (v' (root x) (proj₂ (ξ' x)) refl)) where C = dpoly A s E p t v' : (a : A) (v : Π' p (λ e → M (↓ C)) a) (q : ξ' x ≡ (a , v)) (b : E) → p b ≡ a → Σ (M (↓ C)) (Vφ C (t b)) v' .(p b) v q b refl = (app b v , lem₁ x b v q u₁≡u₂ , (lem₂ x b v q u₁≡u₂)) -} -} V' : M P → Set V' x = u₁ x ≡ u₂ x Φ : (M P → Set) → (M P → Set) Φ U x = let (a , v) = ξ' x in Π'' (f P) a (λ {(b , pr) → Σ[ y ∈ M P ] ( U y and idx y ≡ t b and q b (a , v) pr y ) }) where q : (b : E) (u : ⟦ P ⟧ (M P)) → f P b ≡ proj₁ u → M P → Set q b (._ , v) refl y = app b v ≡ y {- q : (b : E) (u : ⟦ P ⟧ (M P)) → f P b ≡ proj₁ u → (j : I) → U' j → Set q b (._ , v) refl .(idx y) (ins y z) = app b v ≡ y -} {- V'-postFP : V' ⊆ Φ V' V'-postFP x x∈V' (b , fb≡ξx₁) = (r b (ξ' x) fb≡ξx₁ , {!!}) where r : (b₁ : E) (u : ⟦ P ⟧ (M P)) → f P b₁ ≡ proj₁ u → predToFam idx V' (t b₁) r b₁ (._ , v) refl = r' b₁ (app b₁ v) where r' : (b₂ : E) (x' : M P) → predToFam idx V' (t b₂) r' b₂ x' = ins ? {!!} -} V'-final : (U : M P → Set) → U ⊆ Φ U → U ⊆ V' V'-final = {!!} -- | This predicate on M (↓ C) ensures that we can define a map -- V → s a ≡ ⟦ ↓ C ⟧ (i × (t *) V. record V-pred (i : I) (x : M P) : Set where coinductive field -- | For ξ x = (a , v), we require s a = i sigma-idx : s (proj₁ (ξ x)) ≡ i -- | For ξ x = (a , v), we require ∀ b with p b = a that -- idx (v b) = s a and v b ∈ V (t b) reidx : Π'' (f P) (proj₁ (ξ x)) (λ {(e , eq) → idx ((proj₂ (ξ x)) (e , eq)) ≡ t e × V-pred (t e) ((proj₂ (ξ x)) (e , eq)) }) open V-pred {- V : {I : Set} (C : DPoly {I} {I}) → Fam I V C i = Σ (M (↓ C)) (V-pred C i) Σ≡₁ : {I : Set} {A : Fam I} → {x y : Σ I A} → x ≡ y → proj₁ x ≡ proj₁ y Σ≡₁ {x = i , a} {.i , .a} refl = refl foofoo : {I : Set} {A : Fam I} → (x y : Σ I A) → (p : x ≡ y) → A (proj₁ y) foofoo x .x refl = proj₂ x Σ≡₂ : {I : Set} {A : Fam I} → {x y : Σ I A} → (p : x ≡ y) → foofoo x y p ≡ proj₂ y Σ≡₂ {x = i , a} {.i , .a} refl = refl out-V : {I : Set} {C : DPoly {I} {I}} → V C ⇒ T C (V C) out-V {I} {C = dpoly A s E p t} i (x , v-proof) = foo i v-proof (sigma-idx v-proof) where P : DPoly P = dpoly A s E p t u : ⟦ ↓ P ⟧ (M (↓ P)) u = ξ x -- uaie : (u' : ⟦ ↓ P ⟧ (M (↓ P))) → f (↓ P) e ≡ proj₁ u' → A → Set -- uaie u' pr = Π' (p tt) (λ e → V-pred P (t e) ((proj₂ u') (e , {!!}))) foo : (i' : I) → V-pred P i' x → s (proj₁ u) ≡ i' → T P (V P) i' foo .(s (proj₁ u)) pr refl = ins (proj₁ u) (v'' u refl) where v'' : (u' : ⟦ ↓ P ⟧ (M (↓ P))) → u' ≡ ξ x → Π' p (λ e → V P (t e)) (proj₁ u') v'' (.(p e) , v) u'=ξx (e , refl) = (x' , {!!}) -- bar x {!v!} {!!} {!!} pr) where x' : M (↓ P) x' = v (e , refl) aiu = proj₂ (reidx pr (e , {!!})) bar : (x' : M (↓ P)) (v₁ : Π' (f (↓ P)) (λ e₁ → M (↓ P)) (proj₁ (ξ x'))) → v₁ ≡ proj₂ (ξ x') → (q : f (↓ P) e ≡ proj₁ (ξ x')) → V-pred P (s (proj₁ (ξ x'))) x' → V-pred P (t e) (v₁ (e , q)) bar x'' .(proj₂ (ξ x'')) refl q pr' = proj₂ (reidx pr' (e , q)) tu : s (root (proj₂ (ξ x) (e , Σ≡₁ u'=ξx))) ≡ t e tu = proj₁ (reidx pr (e , Σ≡₁ u'=ξx)) {- bar : (v₁ : Π' (f (↓ P)) (λ e₁ → M (↓ P)) (proj₁ (ξ x))) → v₁ ≡ proj₂ (ξ x) → V-pred P (t e) x' bar ._ refl = proj₂ (reidx pr ?) -} tiu : V-pred P (t e) (proj₂ (ξ x) (e , Σ≡₁ u'=ξx)) tiu = proj₂ (reidx pr (e , Σ≡₁ u'=ξx)) -- Want out-s : M (↓ C ⋊ I) → T C (M {i} (↓ C ⋊ I)) T' : {I : Set} → DPoly {I} {I} → (X : I → Set) → -- ^ Parameter (I → Set) T' C X = T C {!!} {- out-s' : ∀ {i} {I} {C : DPoly {I}} → M (↓ C ⋊ I) → T' C (M {i} (↓ C ⋊ I)) out-s' = ? -} -- | Candidate for R C out-s : ∀ {i} {I} {C : DPoly {I}} → M (↓ C ⋊ I) → ⟦ ↓ C ⟧ (M {i} (↓ C ⋊ I)) out-s {i} {I} {C} x = (q (ξ x) , abs'' (q (ξ x)) (h (ξ x))) where q : ⟦ ↓ C ⋊ I ⟧ (M {i} (↓ C ⋊ I)) → Sym (↓ C) q (a , _) = proj₁ a h : (u : ⟦ ↓ C ⋊ I ⟧ (M {i} (↓ C ⋊ I))) (a : Arit (↓ C)) → f (↓ C) a ≡ q u → M {i} (↓ C ⋊ I) h ((._ , b) , v') a refl = app (a , b) v' -} -} ",12223,False,2265.9631747562557,median "------------------------------------------------------------------------ -- The ""circle"" ------------------------------------------------------------------------ {-# OPTIONS --erased-cubical --safe #-} -- Partly following the HoTT book. -- The module is parametrised by a notion of equality. The higher -- constructor of the HIT defining the circle uses path equality, but -- the supplied notion of equality is used for many other things. import Equality.Path as P module Circle {e⁺} (eq : ∀ {a p} → P.Equality-with-paths a p e⁺) where open P.Derived-definitions-and-properties eq hiding (elim) open import Logical-equivalence using (_⇔_) open import Prelude open import Bijection equality-with-J as Bijection using (_↔_) import Bijection P.equality-with-J as PB open import Equality.Groupoid equality-with-J open import Equality.Path.Isomorphisms eq open import Equality.Path.Isomorphisms.Univalence eq import Equality.Path.Isomorphisms P.equality-with-paths as PI open import Equality.Tactic equality-with-J hiding (module Eq) open import Equivalence equality-with-J as Eq using (_≃_) import Equivalence P.equality-with-J as PE import Erased.Cubical eq as E open import Function-universe equality-with-J as F hiding (id; _∘_) open import Group equality-with-J as G using (_≃ᴳ_) import Group.Cyclic eq as C open import Groupoid equality-with-J open import H-level equality-with-J as H-level open import H-level.Closure equality-with-J open import H-level.Truncation eq as T using (∥_∥[1+_]) open import H-level.Truncation.Propositional eq as Trunc using (∥_∥; ∣_∣) open import H-level.Truncation.Propositional.One-step eq as O using (∥_∥¹) open import Integer equality-with-J as Int using (ℤ; +_; -[1+_]; ℤ-group) open import Nat equality-with-J open import Pointed-type equality-with-J as PT using (_≃ᴮ_) open import Pointed-type.Homotopy-group eq open import Sphere eq as Sphere using (𝕊) open import Suspension eq as Suspension using (Susp; north; south; meridian) open import Univalence-axiom equality-with-J as Univ using (Univalence) private variable a p : Level A : Type p P : A → Type p f : (x : A) → P x b ℓ x : A ------------------------------------------------------------------------ -- The type and some eliminators -- The circle. data 𝕊¹ : Type where base : 𝕊¹ loopᴾ : base P.≡ base loop : base ≡ base loop = _↔_.from ≡↔≡ loopᴾ -- A dependent eliminator, expressed using paths. elimᴾ : (P : 𝕊¹ → Type p) (b : P base) → P.[ (λ i → P (loopᴾ i)) ] b ≡ b → (x : 𝕊¹) → P x elimᴾ P b ℓ base = b elimᴾ P b ℓ (loopᴾ i) = ℓ i -- A non-dependent eliminator, expressed using paths. recᴾ : (b : A) → b P.≡ b → 𝕊¹ → A recᴾ = elimᴾ _ -- A dependent eliminator. elim : (P : 𝕊¹ → Type p) (b : P base) → subst P loop b ≡ b → (x : 𝕊¹) → P x elim P b ℓ = elimᴾ P b (subst≡→[]≡ ℓ) -- A ""computation"" rule. elim-loop : dcong (elim P b ℓ) loop ≡ ℓ elim-loop = dcong-subst≡→[]≡ (refl _) -- Every dependent function of type (x : 𝕊¹) → P x can be expressed -- using elim. η-elim : {f : (x : 𝕊¹) → P x} → f ≡ elim P (f base) (dcong f loop) η-elim {P = P} {f = f} = ⟨ext⟩ $ elim _ (refl _) (subst (λ x → f x ≡ elim P (f base) (dcong f loop) x) loop (refl _) ≡⟨ subst-in-terms-of-trans-and-dcong ⟩ trans (sym (dcong f loop)) (trans (cong (subst P loop) (refl _)) (dcong (elim P (f base) (dcong f loop)) loop)) ≡⟨ cong (trans (sym (dcong f loop))) $ trans (cong (flip trans _) $ cong-refl _) $ trans-reflˡ _ ⟩ trans (sym (dcong f loop)) (dcong (elim P (f base) (dcong f loop)) loop) ≡⟨ cong (trans (sym (dcong f loop))) elim-loop ⟩ trans (sym (dcong f loop)) (dcong f loop) ≡⟨ trans-symˡ _ ⟩∎ refl _ ∎) -- A non-dependent eliminator. rec : (b : A) → b ≡ b → 𝕊¹ → A rec b ℓ = recᴾ b (_↔_.to ≡↔≡ ℓ) -- A ""computation"" rule. rec-loop : cong (rec b ℓ) loop ≡ ℓ rec-loop = cong-≡↔≡ (refl _) -- Every function from 𝕊¹ to A can be expressed using rec. η-rec : {f : 𝕊¹ → A} → f ≡ rec (f base) (cong f loop) η-rec {f = f} = ⟨ext⟩ $ elim _ (refl _) (subst (λ x → f x ≡ rec (f base) (cong f loop) x) loop (refl _) ≡⟨ subst-in-terms-of-trans-and-cong ⟩ trans (sym (cong f loop)) (trans (refl _) (cong (rec (f base) (cong f loop)) loop)) ≡⟨ cong (trans (sym (cong f loop))) $ trans-reflˡ _ ⟩ trans (sym (cong f loop)) (cong (rec (f base) (cong f loop)) loop) ≡⟨ cong (trans (sym (cong f loop))) rec-loop ⟩ trans (sym (cong f loop)) (cong f loop) ≡⟨ trans-symˡ _ ⟩∎ refl _ ∎) -- An alternative non-dependent eliminator. rec′ : (b : A) → b ≡ b → 𝕊¹ → A rec′ {A = A} b ℓ = elim (const A) b (subst (const A) loop b ≡⟨ subst-const _ ⟩ b ≡⟨ ℓ ⟩∎ b ∎) -- A ""computation"" rule. rec′-loop : cong (rec′ b ℓ) loop ≡ ℓ rec′-loop = dcong≡→cong≡ elim-loop ------------------------------------------------------------------------ -- Some equivalences -- The circle can be expressed as a suspension. 𝕊¹≃Susp-Bool : 𝕊¹ ≃ Susp Bool 𝕊¹≃Susp-Bool = Eq.↔→≃ to from to∘from from∘to where north≡north = north ≡⟨ meridian false ⟩ south ≡⟨ sym $ meridian true ⟩∎ north ∎ to : 𝕊¹ → Susp Bool to = rec north north≡north module From = Suspension.Rec base base (if_then refl base else loop) from : Susp Bool → 𝕊¹ from = From.rec to∘from : ∀ x → to (from x) ≡ x to∘from = Suspension.elim _ (to (from north) ≡⟨⟩ north ∎) (to (from south) ≡⟨⟩ north ≡⟨ meridian true ⟩∎ south ∎) (λ b → subst (λ x → to (from x) ≡ x) (meridian b) (refl north) ≡⟨ subst-in-terms-of-trans-and-cong ⟩ trans (sym (cong (to ∘ from) (meridian b))) (trans (refl _) (cong id (meridian b))) ≡⟨ cong₂ (trans ∘ sym) (trans (sym $ cong-∘ _ _ _) $ cong (cong to) From.rec-meridian) (trans (trans-reflˡ _) $ sym $ cong-id _) ⟩ trans (sym (cong to (if b then refl base else loop))) (meridian b) ≡⟨ lemma b ⟩∎ meridian true ∎) where lemma : (b : Bool) → _ ≡ _ lemma true = trans (sym (cong to (if true ⦂ Bool then refl base else loop))) (meridian true) ≡⟨⟩ trans (sym (cong to (refl base))) (meridian true) ≡⟨ prove (Trans (Sym (Cong _ Refl)) (Lift _)) (Lift _) (refl _) ⟩∎ meridian true ∎ lemma false = trans (sym (cong to (if false ⦂ Bool then refl base else loop))) (meridian false) ≡⟨⟩ trans (sym (cong to loop)) (meridian false) ≡⟨ cong (λ p → trans (sym p) (meridian false)) rec-loop ⟩ trans (sym north≡north) (meridian false) ≡⟨ prove (Trans (Sym (Trans (Lift _) (Sym (Lift _)))) (Lift _)) (Trans (Trans (Lift _) (Sym (Lift _))) (Lift _)) (refl _) ⟩ trans (trans (meridian true) (sym $ meridian false)) (meridian false) ≡⟨ trans-[trans-sym]- _ _ ⟩∎ meridian true ∎ from∘to : ∀ x → from (to x) ≡ x from∘to = elim _ (from (to base) ≡⟨⟩ base ∎) (subst (λ x → from (to x) ≡ x) loop (refl base) ≡⟨ subst-in-terms-of-trans-and-cong ⟩ trans (sym (cong (from ∘ to) loop)) (trans (refl base) (cong id loop)) ≡⟨ cong₂ (trans ∘ sym) (trans (sym $ cong-∘ _ to _) $ cong (cong from) rec-loop) (trans (trans-reflˡ _) $ sym $ cong-id _) ⟩ trans (sym (cong from north≡north)) loop ≡⟨ prove (Trans (Sym (Cong _ (Trans (Lift _) (Sym (Lift _))))) (Lift _)) (Trans (Trans (Cong from (Lift (meridian true))) (Sym (Cong from (Lift (meridian false))))) (Lift _)) (refl _) ⟩ trans (trans (cong from (meridian true)) (sym $ cong from (meridian false))) loop ≡⟨ cong₂ (λ p q → trans (trans p (sym q)) loop) From.rec-meridian From.rec-meridian ⟩ trans (trans (if true ⦂ Bool then refl base else loop) (sym $ if false ⦂ Bool then refl base else loop)) loop ≡⟨⟩ trans (trans (refl base) (sym loop)) loop ≡⟨ trans-[trans-sym]- _ _ ⟩∎ refl base ∎) -- The circle is equivalent to the 1-dimensional sphere. 𝕊¹≃𝕊¹ : 𝕊¹ ≃ 𝕊 1 𝕊¹≃𝕊¹ = 𝕊¹ ↝⟨ 𝕊¹≃Susp-Bool ⟩ Susp Bool ↔⟨ Suspension.cong-↔ Sphere.Bool↔𝕊⁰ ⟩ Susp (𝕊 0) ↔⟨⟩ 𝕊 1 □ ------------------------------------------------------------------------ -- The loop space of the circle -- The function trans is commutative for the loop space of the circle. trans-commutative : (p q : base ≡ base) → trans p q ≡ trans q p trans-commutative = flip $ Transitivity-commutative.commutative base _∙_ ∙-base base-∙ where _∙_ : 𝕊¹ → 𝕊¹ → 𝕊¹ x ∙ y = rec x (elim (λ x → x ≡ x) loop lemma x) y where lemma : subst (λ x → x ≡ x) loop loop ≡ loop lemma = ≡⇒↝ _ (sym [subst≡]≡[trans≡trans]) (refl _) base-∙ : ∀ x → x ∙ base ≡ x base-∙ _ = refl _ ∙-base : ∀ y → base ∙ y ≡ y ∙-base = elim _ (refl _) (subst (λ x → rec base loop x ≡ x) loop (refl _) ≡⟨ subst-in-terms-of-trans-and-cong ⟩ trans (sym (cong (rec base loop) loop)) (trans (refl _) (cong id loop)) ≡⟨ cong (trans _) $ trans-reflˡ _ ⟩ trans (sym (cong (rec base loop) loop)) (cong id loop) ≡⟨ cong₂ (trans ∘ sym) rec-loop (sym $ cong-id _) ⟩ trans (sym loop) loop ≡⟨ trans-symˡ _ ⟩∎ refl _ ∎) -- The loop space is equivalent to x ≡ x, for any x : 𝕊¹. base≡base≃≡ : {x : 𝕊¹} → (base ≡ base) ≃ (x ≡ x) base≡base≃≡ = elim (λ x → (base ≡ base) ≃ (x ≡ x)) Eq.id (Eq.lift-equality ext $ ⟨ext⟩ λ eq → _≃_.to (subst (λ x → (base ≡ base) ≃ (x ≡ x)) loop Eq.id) eq ≡⟨ cong (_$ eq) Eq.to-subst ⟩ subst (λ x → base ≡ base → x ≡ x) loop id eq ≡⟨ subst-→ ⟩ subst (λ x → x ≡ x) loop (subst (λ _ → base ≡ base) (sym loop) eq) ≡⟨ cong (subst (λ x → x ≡ x) loop) $ subst-const _ ⟩ subst (λ x → x ≡ x) loop eq ≡⟨ ≡⇒↝ _ (sym [subst≡]≡[trans≡trans]) ( trans eq loop ≡⟨ trans-commutative _ _ ⟩∎ trans loop eq ∎) ⟩∎ eq ∎) _ private -- Definitions used to define base≡base≃ℤ and Fundamental-group≃ℤ. module base≡base≃ℤ (univ : Univalence lzero) where -- The universal cover of the circle. Cover : 𝕊¹ → Type Cover = rec ℤ (Univ.≃⇒≡ univ Int.successor) to : base ≡ x → Cover x to = flip (subst Cover) (+ 0) ≡⇒≃-cong-Cover-loop : Univ.≡⇒≃ (cong Cover loop) ≡ Int.successor ≡⇒≃-cong-Cover-loop = Univ.≡⇒≃ (cong Cover loop) ≡⟨ cong Univ.≡⇒≃ rec-loop ⟩ Univ.≡⇒≃ (Univ.≃⇒≡ univ Int.successor) ≡⟨ _≃_.right-inverse-of (Univ.≡≃≃ univ) _ ⟩∎ Int.successor ∎ subst-Cover-loop : ∀ i → subst Cover loop i ≡ Int.suc i subst-Cover-loop i = subst Cover loop i ≡⟨ subst-in-terms-of-≡⇒↝ equivalence _ _ _ ⟩ Univ.≡⇒→ (cong Cover loop) i ≡⟨ cong (λ eq → _≃_.to eq _) ≡⇒≃-cong-Cover-loop ⟩∎ _≃_.to Int.successor i ∎ subst-Cover-sym-loop : ∀ i → subst Cover (sym loop) i ≡ Int.pred i subst-Cover-sym-loop i = subst Cover (sym loop) i ≡⟨ subst-in-terms-of-inverse∘≡⇒↝ equivalence _ _ _ ⟩ _≃_.from (Univ.≡⇒≃ (cong Cover loop)) i ≡⟨ cong (λ eq → _≃_.from eq _) ≡⇒≃-cong-Cover-loop ⟩∎ _≃_.from Int.successor i ∎ module 𝕊¹-G = Groupoid (groupoid 𝕊¹) loops : ℤ → base ≡ base loops = loop 𝕊¹-G.^_ to-loops : ∀ i → to (loops i) ≡ i to-loops (+ zero) = subst Cover (refl _) (+ 0) ≡⟨ subst-refl _ _ ⟩∎ + zero ∎ to-loops (+ suc n) = subst Cover (trans (loops (+ n)) loop) (+ 0) ≡⟨ sym $ subst-subst _ _ _ _ ⟩ subst Cover loop (subst Cover (loops (+ n)) (+ 0)) ≡⟨⟩ subst Cover loop (to (loops (+ n))) ≡⟨ cong (subst Cover loop) $ to-loops (+ n) ⟩ subst Cover loop (+ n) ≡⟨ subst-Cover-loop _ ⟩∎ + suc n ∎ to-loops -[1+ zero ] = subst Cover (trans (refl _) (sym loop)) (+ 0) ≡⟨ cong (flip (subst Cover) _) $ trans-reflˡ _ ⟩ subst Cover (sym loop) (+ 0) ≡⟨ subst-Cover-sym-loop _ ⟩∎ -[1+ zero ] ∎ to-loops -[1+ suc n ] = subst Cover (trans (loops -[1+ n ]) (sym loop)) (+ 0) ≡⟨ sym $ subst-subst _ _ _ _ ⟩ subst Cover (sym loop) (subst Cover (loops -[1+ n ]) (+ 0)) ≡⟨⟩ subst Cover (sym loop) (to (loops -[1+ n ])) ≡⟨ cong (subst Cover (sym loop)) $ to-loops -[1+ n ] ⟩ subst Cover (sym loop) -[1+ n ] ≡⟨ subst-Cover-sym-loop _ ⟩∎ -[1+ suc n ] ∎ loops-pred-loop : ∀ i → trans (loops (Int.pred i)) loop ≡ loops i loops-pred-loop i = trans (loops (Int.pred i)) loop ≡⟨ cong (flip trans _ ∘ loops) $ Int.pred≡-1+ i ⟩ trans (loops (Int.-[ 1 ] Int.+ i)) loop ≡⟨ cong (flip trans _) $ sym $ 𝕊¹-G.^∘^ {j = i} Int.-[ 1 ] ⟩ trans (trans (loops i) (loops (Int.-[ 1 ]))) loop ≡⟨⟩ trans (trans (loops i) (trans (refl _) (sym loop))) loop ≡⟨ cong (flip trans _) $ cong (trans _) $ trans-reflˡ _ ⟩ trans (trans (loops i) (sym loop)) loop ≡⟨ trans-[trans-sym]- _ _ ⟩∎ loops i ∎ from : ∀ x → Cover x → base ≡ x from = elim _ loops (⟨ext⟩ λ i → subst (λ x → Cover x → base ≡ x) loop loops i ≡⟨ subst-→ ⟩ subst (base ≡_) loop (loops (subst Cover (sym loop) i)) ≡⟨ sym trans-subst ⟩ trans (loops (subst Cover (sym loop) i)) loop ≡⟨ cong (flip trans _ ∘ loops) $ subst-Cover-sym-loop _ ⟩ trans (loops (Int.pred i)) loop ≡⟨ loops-pred-loop i ⟩∎ loops i ∎) from-to : (eq : base ≡ x) → from x (to eq) ≡ eq from-to = elim¹ (λ {x} eq → from x (to eq) ≡ eq) (from base (to (refl base)) ≡⟨⟩ loops (subst Cover (refl base) (+ 0)) ≡⟨ cong loops $ subst-refl _ _ ⟩ loops (+ 0) ≡⟨⟩ refl base ∎) loops-+ : ∀ i j → loops (i Int.+ j) ≡ trans (loops i) (loops j) loops-+ i j = loops (i Int.+ j) ≡⟨ cong loops $ Int.+-comm i ⟩ loops (j Int.+ i) ≡⟨ sym $ 𝕊¹-G.^∘^ j ⟩∎ trans (loops i) (loops j) ∎ -- The loop space of the circle is equivalent to the type of integers -- (assuming univalence). -- -- The proof is based on the one presented by Licata and Shulman in -- ""Calculating the Fundamental Group of the Circle in Homotopy Type -- Theory"". base≡base≃ℤ : Univalence lzero → (base ≡ base) ≃ ℤ base≡base≃ℤ univ = Eq.↔→≃ to loops to-loops from-to where open base≡base≃ℤ univ -- The circle's fundamental group is equivalent to the group of -- integers (assuming univalence). Fundamental-group≃ℤ : Univalence lzero → Fundamental-group (𝕊¹ , base) ≃ᴳ ℤ-group Fundamental-group≃ℤ univ = G.≃ᴳ-sym λ where .G.Homomorphic.related → inverse (∥ base ≡ base ∥[1+ 1 ] ↝⟨ T.∥∥-cong $ base≡base≃ℤ univ ⟩ ∥ ℤ ∥[1+ 1 ] ↔⟨ _⇔_.to (T.+⇔∥∥↔ {n = 1}) Int.ℤ-set ⟩□ ℤ □) .G.Homomorphic.homomorphic i j → cong T.∣_∣ (loops-+ i j) where open base≡base≃ℤ univ -- The circle is a groupoid (assuming univalence). 𝕊¹-groupoid : Univalence lzero → H-level 3 𝕊¹ 𝕊¹-groupoid univ {x = x} {y = y} = $⟨ (λ {_ _} → Int.ℤ-set) ⟩ Is-set ℤ ↝⟨ H-level-cong _ 2 (inverse $ base≡base≃ℤ univ) ⦂ (_ → _) ⟩ Is-set (base ≡ base) ↝⟨ (λ s → elim (λ x → ∀ y → Is-set (x ≡ y)) (elim _ s (H-level-propositional ext 2 _ _)) ((Π-closure ext 1 λ _ → H-level-propositional ext 2) _ _) x y) ⟩□ Is-set (x ≡ y) □ -- The type of endofunctions on 𝕊¹ is equivalent to -- ∃ λ (x : 𝕊¹) → x ≡ x. 𝕊¹→𝕊¹≃Σ𝕊¹≡ : (𝕊¹ → 𝕊¹) ≃ ∃ λ (x : 𝕊¹) → x ≡ x 𝕊¹→𝕊¹≃Σ𝕊¹≡ = Eq.↔→≃ to from to-from from-to where to : (𝕊¹ → 𝕊¹) → ∃ λ (x : 𝕊¹) → x ≡ x to f = f base , cong f loop from : (∃ λ (x : 𝕊¹) → x ≡ x) → (𝕊¹ → 𝕊¹) from = uncurry rec to-from : ∀ p → to (from p) ≡ p to-from (x , eq) = cong (x ,_) (cong (rec x eq) loop ≡⟨ rec-loop ⟩∎ eq ∎) from-to : ∀ f → from (to f) ≡ f from-to f = rec (f base) (cong f loop) ≡⟨ sym η-rec ⟩∎ f ∎ -- The type of endofunctions on 𝕊¹ is equivalent to 𝕊¹ × ℤ (assuming -- univalence). -- -- This result was pointed out to me by Paolo Capriotti. 𝕊¹→𝕊¹≃𝕊¹×ℤ : Univalence lzero → (𝕊¹ → 𝕊¹) ≃ (𝕊¹ × ℤ) 𝕊¹→𝕊¹≃𝕊¹×ℤ univ = (𝕊¹ → 𝕊¹) ↝⟨ 𝕊¹→𝕊¹≃Σ𝕊¹≡ ⟩ (∃ λ (x : 𝕊¹) → x ≡ x) ↝⟨ (∃-cong λ _ → inverse base≡base≃≡) ⟩ 𝕊¹ × base ≡ base ↝⟨ (∃-cong λ _ → base≡base≃ℤ univ) ⟩□ 𝕊¹ × ℤ □ -- The forward direction of 𝕊¹→𝕊¹≃𝕊¹×ℤ maps the identity function to -- base , + 1. 𝕊¹→𝕊¹≃𝕊¹×ℤ-id : (univ : Univalence lzero) → _≃_.to (𝕊¹→𝕊¹≃𝕊¹×ℤ univ) id ≡ (base , + 1) 𝕊¹→𝕊¹≃𝕊¹×ℤ-id univ = _≃_.from-to (𝕊¹→𝕊¹≃𝕊¹×ℤ univ) (rec base (trans (refl base) loop) ≡⟨ cong (rec base) $ trans-reflˡ _ ⟩ rec base loop ≡⟨ cong (rec base) $ cong-id _ ⟩ rec base (cong id loop) ≡⟨ sym η-rec ⟩∎ id ∎) -- The forward direction of 𝕊¹→𝕊¹≃𝕊¹×ℤ maps the constant function -- returning base to base , + 0. 𝕊¹→𝕊¹≃𝕊¹×ℤ-const : (univ : Univalence lzero) → _≃_.to (𝕊¹→𝕊¹≃𝕊¹×ℤ univ) (const base) ≡ (base , + 0) 𝕊¹→𝕊¹≃𝕊¹×ℤ-const univ = _≃_.from-to (𝕊¹→𝕊¹≃𝕊¹×ℤ univ) (rec base (refl base) ≡⟨ cong (rec base) $ sym $ cong-const _ ⟩ rec base (cong (const base) loop) ≡⟨ sym η-rec ⟩∎ const base ∎) ------------------------------------------------------------------------ -- A conversion function -- The one-step truncation of the unit type is equivalent to the -- circle. -- -- Paolo Capriotti informed me about this result. ∥⊤∥¹≃𝕊¹ : ∥ ⊤ ∥¹ ≃ 𝕊¹ ∥⊤∥¹≃𝕊¹ = _↔_.from ≃↔≃ $ PE.↔→≃ (O.recᴾ λ where .O.∣∣ʳ _ → base .O.∣∣-constantʳ _ _ → loopᴾ) (recᴾ O.∣ _ ∣ (O.∣∣-constantᴾ _ _)) (elimᴾ _ P.refl (λ _ → P.refl)) (O.elimᴾ λ where .O.∣∣ʳ _ → P.refl .O.∣∣-constantʳ _ _ _ → P.refl) ------------------------------------------------------------------------ -- Some negative results -- The equality loop is not equal to refl base. loop≢refl : loop ≢ refl base loop≢refl = E.Stable-¬ E.[ loop ≡ refl base →⟨ Type-set ⟩ Is-set Type →⟨ Univ.¬-Type-set univ ⟩□ ⊥ □ ] where module _ (loop≡refl : loop ≡ refl base) where refl≡ : (A : Type) (A≡A : A ≡ A) → refl A ≡ A≡A refl≡ A A≡A = refl A ≡⟨⟩ refl (rec A A≡A base) ≡⟨ sym $ cong-refl _ ⟩ cong (rec A A≡A) (refl base) ≡⟨ cong (cong (rec A A≡A)) $ sym loop≡refl ⟩ cong (rec A A≡A) loop ≡⟨ rec-loop ⟩∎ A≡A ∎ Type-set : Is-set Type Type-set {x = A} {y = B} = elim¹ (λ p → ∀ q → p ≡ q) (refl≡ A) -- Thus the circle is not a set. ¬-𝕊¹-set : ¬ Is-set 𝕊¹ ¬-𝕊¹-set = Is-set 𝕊¹ ↝⟨ (λ h → h) ⟩ Is-proposition (base ≡ base) ↝⟨ (λ h → h _ _) ⟩ loop ≡ refl base ↝⟨ loop≢refl ⟩□ ⊥ □ -- It is not necessarily the case that the one-step truncation of a -- proposition is a proposition. ¬-Is-proposition-∥∥¹ : ¬ ({A : Type a} → Is-proposition A → Is-proposition ∥ A ∥¹) ¬-Is-proposition-∥∥¹ {a = a} = ({A : Type a} → Is-proposition A → Is-proposition ∥ A ∥¹) ↝⟨ _$ H-level.mono₁ 0 (↑-closure 0 ⊤-contractible) ⟩ Is-proposition ∥ ↑ a ⊤ ∥¹ ↝⟨ H-level-cong _ 1 (O.∥∥¹-cong-↔ Bijection.↑↔) ⟩ Is-proposition ∥ ⊤ ∥¹ ↝⟨ H-level-cong _ 1 ∥⊤∥¹≃𝕊¹ ⟩ Is-proposition 𝕊¹ ↝⟨ ¬-𝕊¹-set ∘ H-level.mono₁ 1 ⟩□ ⊥ □ -- A function with the type of refl (for 𝕊¹) that is not equal to -- refl. not-refl : (x : 𝕊¹) → x ≡ x not-refl = elim _ loop (subst (λ z → z ≡ z) loop loop ≡⟨ ≡⇒↝ _ (sym [subst≡]≡[trans≡trans]) (refl _) ⟩∎ loop ∎) -- The function not-refl is not equal to refl. not-refl≢refl : not-refl ≢ refl not-refl≢refl = not-refl ≡ refl ↝⟨ cong (_$ _) ⟩ loop ≡ refl base ↝⟨ loop≢refl ⟩□ ⊥ □ -- There is a value with the type of refl that is not equal to refl. ∃≢refl : ∃ λ (f : (x : 𝕊¹) → x ≡ x) → f ≢ refl ∃≢refl = not-refl , not-refl≢refl -- For every universe level there is a type A such that -- (x : A) → x ≡ x is not a proposition. ¬-type-of-refl-propositional : ∃ λ (A : Type a) → ¬ Is-proposition ((x : A) → x ≡ x) ¬-type-of-refl-propositional {a = a} = ↑ _ 𝕊¹ , (Is-proposition (∀ x → x ≡ x) ↝⟨ (λ prop → prop _ _) ⟩ cong lift ∘ proj₁ ∃≢refl ∘ lower ≡ cong lift ∘ refl ∘ lower ↝⟨ cong (_∘ lift) ⟩ cong lift ∘ proj₁ ∃≢refl ≡ cong lift ∘ refl ↝⟨ cong (cong lower ∘_) ⟩ cong lower ∘ cong lift ∘ proj₁ ∃≢refl ≡ cong lower ∘ cong lift ∘ refl ↝⟨ ≡⇒↝ _ (cong₂ _≡_ (⟨ext⟩ λ _ → cong-∘ _ _ _) (⟨ext⟩ λ _ → cong-∘ _ _ _)) ⟩ cong id ∘ proj₁ ∃≢refl ≡ cong id ∘ refl ↝⟨ ≡⇒↝ _ (sym $ cong₂ _≡_ (⟨ext⟩ λ _ → cong-id _) (⟨ext⟩ λ _ → cong-id _)) ⟩ proj₁ ∃≢refl ≡ refl ↝⟨ proj₂ ∃≢refl ⟩□ ⊥ □) -- Every element of the circle is /merely/ equal to the base point. -- -- This lemma was mentioned by Mike Shulman in a blog post -- (http://homotopytypetheory.org/2013/07/24/cohomology/). all-points-on-the-circle-are-merely-equal : (x : 𝕊¹) → ∥ x ≡ base ∥ all-points-on-the-circle-are-merely-equal = elim _ ∣ refl base ∣ (Trunc.truncation-is-proposition _ _) -- Thus every element of the circle is not not equal to the base -- point. all-points-on-the-circle-are-¬¬-equal : (x : 𝕊¹) → ¬ ¬ x ≡ base all-points-on-the-circle-are-¬¬-equal x = x ≢ base ↝⟨ Trunc.rec ⊥-propositional ⟩ ¬ ∥ x ≡ base ∥ ↝⟨ _$ all-points-on-the-circle-are-merely-equal x ⟩□ ⊥ □ -- It is not the case that every point on the circle is equal to the -- base point. ¬-all-points-on-the-circle-are-equal : ¬ ((x : 𝕊¹) → x ≡ base) ¬-all-points-on-the-circle-are-equal = ((x : 𝕊¹) → x ≡ base) ↝⟨ (λ hyp x y → x ≡⟨ hyp x ⟩ base ≡⟨ sym (hyp y) ⟩∎ y ∎) ⟩ Is-proposition 𝕊¹ ↝⟨ mono₁ 1 ⟩ Is-set 𝕊¹ ↝⟨ ¬-𝕊¹-set ⟩□ ⊥ □ -- Thus double-negation shift for Type-valued predicates over 𝕊¹ does -- not hold in general. ¬-double-negation-shift : ¬ ({P : 𝕊¹ → Type} → ((x : 𝕊¹) → ¬ ¬ P x) → ¬ ¬ ((x : 𝕊¹) → P x)) ¬-double-negation-shift = ({P : 𝕊¹ → Type} → ((x : 𝕊¹) → ¬ ¬ P x) → ¬ ¬ ((x : 𝕊¹) → P x)) ↝⟨ _$ all-points-on-the-circle-are-¬¬-equal ⟩ ¬ ¬ ((x : 𝕊¹) → x ≡ base) ↝⟨ _$ ¬-all-points-on-the-circle-are-equal ⟩□ ⊥ □ -- Furthermore excluded middle for arbitrary types (in Type) does not -- hold. ¬-excluded-middle : ¬ ({A : Type} → Dec A) ¬-excluded-middle = ({A : Type} → Dec A) ↝⟨ (λ em ¬¬a → [ id , ⊥-elim ∘ ¬¬a ] em) ⟩ ({A : Type} → ¬ ¬ A → A) ↝⟨ (λ dne → flip _$_ ∘ (dne ∘_)) ⟩ ({P : 𝕊¹ → Type} → ((x : 𝕊¹) → ¬ ¬ P x) → ¬ ¬ ((x : 𝕊¹) → P x)) ↝⟨ ¬-double-negation-shift ⟩□ ⊥ □ -- H-level.Closure.proj₁-closure cannot be generalised by replacing -- the assumption ∀ a → B a with ∀ a → ∥ B a ∥. -- -- This observation is due to Andrea Vezzosi. ¬-generalised-proj₁-closure : ¬ ({A : Type} {B : A → Type} → (∀ a → ∥ B a ∥) → ∀ n → H-level n (Σ A B) → H-level n A) ¬-generalised-proj₁-closure generalised-proj₁-closure = $⟨ singleton-contractible _ ⟩ Contractible (Σ 𝕊¹ (_≡ base)) ↝⟨ generalised-proj₁-closure all-points-on-the-circle-are-merely-equal 0 ⟩ Contractible 𝕊¹ ↝⟨ mono (zero≤ 2) ⟩ Is-set 𝕊¹ ↝⟨ ¬-𝕊¹-set ⟩□ ⊥ □ -- There is no based equivalence between the circle and the product of -- the circle with itself. -- -- This result was pointed out to me by Paolo Capriotti. 𝕊¹≄ᴮ𝕊¹×𝕊¹ : ¬ (𝕊¹ , base) ≃ᴮ ((𝕊¹ , base) PT.× (𝕊¹ , base)) 𝕊¹≄ᴮ𝕊¹×𝕊¹ = E.Stable-¬ E.[ (𝕊¹ , base) ≃ᴮ ((𝕊¹ , base) PT.× (𝕊¹ , base)) ↝⟨ ≃ᴮ→≃ᴳ (𝕊¹ , base) ((𝕊¹ , base) PT.× (𝕊¹ , base)) 0 ⟩ Fundamental-group (𝕊¹ , base) ≃ᴳ Fundamental-group ((𝕊¹ , base) PT.× (𝕊¹ , base)) ↝⟨ flip G.↝ᴳ-trans (Homotopy-group-[1+ 0 ]-× (𝕊¹ , base) (𝕊¹ , base)) ⟩ Fundamental-group (𝕊¹ , base) ≃ᴳ (Fundamental-group (𝕊¹ , base) G.× Fundamental-group (𝕊¹ , base)) ↝⟨ flip G.↝ᴳ-trans (G.↝-× (Fundamental-group≃ℤ univ) (Fundamental-group≃ℤ univ)) ∘ G.↝ᴳ-trans (G.≃ᴳ-sym (Fundamental-group≃ℤ univ)) ⟩ ℤ-group ≃ᴳ (ℤ-group G.× ℤ-group) ↝⟨ C.ℤ≄ᴳℤ×ℤ ⟩□ ⊥ □ ] -- 𝕊¹ is not equivalent to 𝕊¹ × 𝕊¹. -- -- This result was pointed out to me by Paolo Capriotti. 𝕊¹≄𝕊¹×𝕊¹ : ¬ 𝕊¹ ≃ (𝕊¹ × 𝕊¹) 𝕊¹≄𝕊¹×𝕊¹ hyp = let x , y = _≃_.to hyp base in all-points-on-the-circle-are-¬¬-equal x λ x≡base → all-points-on-the-circle-are-¬¬-equal y λ y≡base → 𝕊¹≄ᴮ𝕊¹×𝕊¹ (hyp , cong₂ _,_ x≡base y≡base) ------------------------------------------------------------------------ -- An alternative approach to defining eliminators and proving -- computation rules for arbitrary notions of equality, based on an -- anonymous reviewer's suggestion -- Circle eq p is an axiomatisation of the circle, for the given -- notion of equality eq, eliminating into Type p. -- -- Note that the statement of the computation rule for ""loop"" is more -- complicated than above (elim-loop). The reason is that the -- computation rule for ""base"" does not hold definitionally. Circle : ∀ {e⁺} → (∀ {a p} → P.Equality-with-paths a p e⁺) → (p : Level) → Type (lsuc p) Circle eq p = ∃ λ (𝕊¹ : Type) → ∃ λ (base : 𝕊¹) → ∃ λ (loop : base ≡.≡ base) → (P : 𝕊¹ → Type p) (b : P base) (ℓ : ≡.subst P loop b ≡.≡ b) → ∃ λ (elim : (x : 𝕊¹) → P x) → ∃ λ (elim-base : elim base ≡.≡ b) → ≡.subst (λ b → ≡.subst P loop b ≡.≡ b) elim-base (≡.dcong elim loop) ≡.≡ ℓ where module ≡ = P.Derived-definitions-and-properties eq -- A circle defined for paths (P.equality-with-J) is equivalent to one -- defined for eq. Circle≃Circle : Circle P.equality-with-paths p ≃ Circle eq p Circle≃Circle = ∃-cong λ _ → ∃-cong λ _ → Σ-cong (inverse ≡↔≡) λ loop → ∀-cong ext λ P → ∀-cong ext λ b → Π-cong-contra ext subst≡↔subst≡ λ ℓ → ∃-cong λ f → Σ-cong (inverse ≡↔≡) λ f-base → let lemma = P.elim¹ (λ eq → _↔_.from subst≡↔subst≡ (P.subst (λ b → P.subst P loop b P.≡ b) eq (P.dcong f loop)) ≡ P.subst (λ b → subst P (_↔_.from ≡↔≡ loop) b ≡ b) eq (_↔_.from subst≡↔subst≡ (P.dcong f loop))) (_↔_.from subst≡↔subst≡ (P.subst (λ b → P.subst P loop b P.≡ b) P.refl (P.dcong f loop)) ≡⟨ cong (_↔_.from subst≡↔subst≡) $ _↔_.from ≡↔≡ $ P.subst-refl (λ b → P.subst P loop b P.≡ b) _ ⟩ _↔_.from subst≡↔subst≡ (P.dcong f loop) ≡⟨ sym $ _↔_.from ≡↔≡ $ P.subst-refl (λ b → subst P (_↔_.from ≡↔≡ loop) b ≡ b) _ ⟩∎ P.subst (λ b → subst P (_↔_.from ≡↔≡ loop) b ≡ b) P.refl (_↔_.from subst≡↔subst≡ (P.dcong f loop)) ∎) _ in P.subst (λ b → P.subst P loop b P.≡ b) f-base (P.dcong f loop) P.≡ _↔_.to subst≡↔subst≡ ℓ ↔⟨ ≡↔≡ F.∘ inverse (from≡↔≡to (Eq.↔⇒≃ subst≡↔subst≡)) F.∘ inverse ≡↔≡ ⟩ _↔_.from subst≡↔subst≡ (P.subst (λ b → P.subst P loop b P.≡ b) f-base (P.dcong f loop)) P.≡ ℓ ↝⟨ ≡⇒↝ _ (cong (P._≡ _) lemma) ⟩ P.subst (λ b → subst P (_↔_.from ≡↔≡ loop) b ≡ b) f-base (_↔_.from subst≡↔subst≡ (P.dcong f loop)) P.≡ ℓ ↝⟨ ≡⇒↝ _ $ cong (λ eq → P.subst (λ b → subst P (_↔_.from ≡↔≡ loop) b ≡ b) f-base eq P.≡ ℓ) $ _↔_.from-to (inverse subst≡↔subst≡) dcong≡dcong ⟩ P.subst (λ b → subst P (_↔_.from ≡↔≡ loop) b ≡ b) f-base (dcong f (_↔_.from ≡↔≡ loop)) P.≡ ℓ ↔⟨ inverse subst≡↔subst≡ ⟩□ subst (λ b → subst P (_↔_.from ≡↔≡ loop) b ≡ b) (_↔_.from ≡↔≡ f-base) (dcong f (_↔_.from ≡↔≡ loop)) ≡ ℓ □ -- An implemention of the circle for paths (P.equality-with-paths). circleᴾ : Circle P.equality-with-paths p circleᴾ = 𝕊¹ , base , loopᴾ , λ P b ℓ → let elim = elimᴾ P b (PI.subst≡→[]≡ {B = P} ℓ) in elim , P.refl , (P.subst (λ b → P.subst P loopᴾ b P.≡ b) P.refl (P.dcong elim loopᴾ) P.≡⟨ P.subst-refl (λ b → P.subst P loopᴾ b P.≡ b) _ ⟩ P.dcong elim loopᴾ P.≡⟨ PI.dcong-subst≡→[]≡ {f = elim} {eq₂ = ℓ} P.refl ⟩∎ ℓ ∎) -- An implementation of the circle for eq. circle : Circle eq p circle = _≃_.to Circle≃Circle circleᴾ -- The latter implementation computes in the right way for ""base"". _ : let _ , base′ , _ , elim′ = circle {p = p} in ∀ {P b ℓ} → proj₁ (elim′ P b ℓ) base′ ≡ b _ = refl _ -- The usual computation rule for ""loop"" can be derived. elim-loop-circle : let _ , _ , loop′ , elim′ = circle {p = p} in ∀ {P b ℓ} → dcong (proj₁ (elim′ P b ℓ)) loop′ ≡ ℓ elim-loop-circle {P = P} {b = b} {ℓ = ℓ} = let _ , _ , loop′ , elim′ = circle elim″ , elim″-base , elim″-loop = elim′ P b ℓ lemma = refl _ ≡⟨ sym from-≡↔≡-refl ⟩ _↔_.from ≡↔≡ P.refl ≡⟨⟩ elim″-base ∎ in dcong elim″ loop′ ≡⟨ sym $ subst-refl _ _ ⟩ subst (λ b → subst P loop′ b ≡ b) (refl _) (dcong elim″ loop′) ≡⟨ cong (λ eq → subst (λ b → subst P loop′ b ≡ b) eq (dcong elim″ loop′)) lemma ⟩ subst (λ b → subst P loop′ b ≡ b) elim″-base (dcong elim″ loop′) ≡⟨ elim″-loop ⟩∎ ℓ ∎ -- An alternative to Circle≃Circle that does not give the ""right"" -- computational behaviour for circle′ below. Circle≃Circle′ : Circle P.equality-with-paths p ≃ Circle eq p Circle≃Circle′ = ∃-cong λ _ → ∃-cong λ _ → Σ-cong (inverse ≡↔≡) λ loop → ∀-cong ext λ P → ∀-cong ext λ b → Π-cong ext (inverse subst≡↔subst≡) λ ℓ → ∃-cong λ f → Σ-cong (inverse ≡↔≡) λ f-base → let lemma = P.elim¹ (λ eq → _↔_.from subst≡↔subst≡ (P.subst (λ b → P.subst P loop b P.≡ b) eq (P.dcong f loop)) ≡ P.subst (λ b → subst P (_↔_.from ≡↔≡ loop) b ≡ b) eq (_↔_.from subst≡↔subst≡ (P.dcong f loop))) (_↔_.from subst≡↔subst≡ (P.subst (λ b → P.subst P loop b P.≡ b) P.refl (P.dcong f loop)) ≡⟨ cong (_↔_.from subst≡↔subst≡) $ _↔_.from ≡↔≡ $ P.subst-refl (λ b → P.subst P loop b P.≡ b) _ ⟩ _↔_.from subst≡↔subst≡ (P.dcong f loop) ≡⟨ sym $ _↔_.from ≡↔≡ $ P.subst-refl (λ b → subst P (_↔_.from ≡↔≡ loop) b ≡ b) _ ⟩∎ P.subst (λ b → subst P (_↔_.from ≡↔≡ loop) b ≡ b) P.refl (_↔_.from subst≡↔subst≡ (P.dcong f loop)) ∎) _ in P.subst (λ b → P.subst P loop b P.≡ b) f-base (P.dcong f loop) P.≡ ℓ ↔⟨ ≡↔≡ F.∘ from-isomorphism (inverse $ Eq.≃-≡ $ Eq.↔⇒≃ $ inverse subst≡↔subst≡) F.∘ inverse ≡↔≡ ⟩ _↔_.from subst≡↔subst≡ (P.subst (λ b → P.subst P loop b P.≡ b) f-base (P.dcong f loop)) P.≡ _↔_.from subst≡↔subst≡ ℓ ↝⟨ ≡⇒↝ _ (cong (P._≡ _↔_.from subst≡↔subst≡ ℓ) lemma) ⟩ P.subst (λ b → subst P (_↔_.from ≡↔≡ loop) b ≡ b) f-base (_↔_.from subst≡↔subst≡ (P.dcong f loop)) P.≡ _↔_.from subst≡↔subst≡ ℓ ↝⟨ ≡⇒↝ _ $ cong (λ eq → P.subst (λ b → subst P (_↔_.from ≡↔≡ loop) b ≡ b) f-base eq P.≡ _↔_.from subst≡↔subst≡ ℓ) $ _↔_.from-to (inverse subst≡↔subst≡) dcong≡dcong ⟩ P.subst (λ b → subst P (_↔_.from ≡↔≡ loop) b ≡ b) f-base (dcong f (_↔_.from ≡↔≡ loop)) P.≡ _↔_.from subst≡↔subst≡ ℓ ↔⟨ inverse subst≡↔subst≡ ⟩□ subst (λ b → subst P (_↔_.from ≡↔≡ loop) b ≡ b) (_↔_.from ≡↔≡ f-base) (dcong f (_↔_.from ≡↔≡ loop)) ≡ _↔_.from subst≡↔subst≡ ℓ □ -- An alternative implementation of the circle for eq. circle′ : Circle eq p circle′ = _≃_.to Circle≃Circle′ circleᴾ -- This implementation does not compute in the right way for ""base"". -- The following code is (at the time of writing) rejected by Agda. -- _ : -- let _ , base′ , _ , elim′ = circle′ {p = p} in -- ∀ {P b ℓ} → -- proj₁ (elim′ P b ℓ) base′ ≡ b -- _ = refl _ ",12337,False,2489.201687628768,median "{-# OPTIONS --safe #-} module Definition.Typed where open import Definition.Untyped open import Tools.Nat using (Nat) open import Tools.Product import Tools.PropositionalEquality as PE infixl 30 _∙_ infix 30 Πⱼ_▹_▹_▹_ -- Well-typed variables data _∷_^_∈_ : (x : Nat) (A : Term) (r : TypeInfo) (Γ : Con Term) → Set where here : ∀ {Γ A r} → 0 ∷ wk1 A ^ r ∈ (Γ ∙ A ^ r ) there : ∀ {Γ A rA B rB x} (h : x ∷ A ^ rA ∈ Γ) → Nat.suc x ∷ wk1 A ^ rA ∈ (Γ ∙ B ^ rB) mutual -- Well-formed context data ⊢_ : Con Term → Set where ε : ⊢ ε _∙_ : ∀ {Γ A r} → ⊢ Γ → Γ ⊢ A ^ r → ⊢ Γ ∙ A ^ r -- Well-formed type data _⊢_^_ (Γ : Con Term) : Term → TypeInfo → Set where Uⱼ : ∀ {r} → ⊢ Γ → Γ ⊢ Univ r ¹ ^ [ ! , ∞ ] univ : ∀ {A r l} → Γ ⊢ A ∷ Univ r l ^ [ ! , next l ] → Γ ⊢ A ^ [ r , ι l ] -- Well-formed term of a type data _⊢_∷_^_ (Γ : Con Term) : Term → Term → TypeInfo → Set where univ : ∀ {r l l'} → l < l' → ⊢ Γ → Γ ⊢ (Univ r l) ∷ (Univ ! l') ^ [ ! , next l' ] ℕⱼ : ⊢ Γ → Γ ⊢ ℕ ∷ U ⁰ ^ [ ! , ι ¹ ] Emptyⱼ : ∀ {l} → ⊢ Γ → Γ ⊢ Empty l ∷ SProp l ^ [ ! , next l ] Πⱼ_▹_▹_▹_ : ∀ {F rF lF G lG r l} → lF ≤ l → lG ≤ l → Γ ⊢ F ∷ (Univ rF lF) ^ [ ! , next lF ] → Γ ∙ F ^ [ rF , ι lF ] ⊢ G ∷ (Univ r lG) ^ [ ! , next lG ] → Γ ⊢ Π F ^ rF ° lF ▹ G ° lG ° l ∷ (Univ r l) ^ [ ! , next l ] ∃ⱼ_▹_ : ∀ {F G l} → Γ ⊢ F ∷ SProp l ^ [ ! , next l ] → Γ ∙ F ^ [ % , ι l ] ⊢ G ∷ SProp l ^ [ ! , next l ] → Γ ⊢ ∃ F ▹ G ∷ SProp l ^ [ ! , next l ] var : ∀ {A rl x} → ⊢ Γ → x ∷ A ^ rl ∈ Γ → Γ ⊢ var x ∷ A ^ rl lamⱼ : ∀ {F r l rF lF G lG t} → lF ≤ l → lG ≤ l → Γ ⊢ F ^ [ rF , ι lF ] → Γ ∙ F ^ [ rF , ι lF ] ⊢ t ∷ G ^ [ r , ι lG ] → Γ ⊢ lam F ▹ t ^ l ∷ Π F ^ rF ° lF ▹ G ° lG ° l ^ [ r , ι l ] _∘ⱼ_ : ∀ {g a F rF lF G lG r lΠ} → Γ ⊢ g ∷ Π F ^ rF ° lF ▹ G ° lG ° lΠ ^ [ r , ι lΠ ] → Γ ⊢ a ∷ F ^ [ rF , ι lF ] → Γ ⊢ g ∘ a ^ lΠ ∷ G [ a ] ^ [ r , ι lG ] ⦅_,_,_,_⦆ⱼ : ∀ {l F G t u} → Γ ⊢ F ^ [ % , ι l ] → Γ ∙ F ^ [ % , ι l ] ⊢ G ^ [ % , ι l ] → Γ ⊢ t ∷ F ^ [ % , ι l ] → Γ ⊢ u ∷ G [ t ] ^ [ % , ι l ] → Γ ⊢ ⦅ G , t , u ⦆ ∷ ∃ F ▹ G ^ [ % , ι l ] fstⱼ : ∀ {F G t l} → Γ ⊢ F ∷ SProp l ^ [ ! , next l ] → Γ ∙ F ^ [ % , ι l ] ⊢ G ∷ SProp l ^ [ ! , next l ] → Γ ⊢ t ∷ ∃ F ▹ G ^ [ % , ι l ] → Γ ⊢ fst t ∷ F ^ [ % , ι l ] sndⱼ : ∀ {F G t l} → Γ ⊢ F ∷ SProp l ^ [ ! , next l ] → Γ ∙ F ^ [ % , ι l ] ⊢ G ∷ SProp l ^ [ ! , next l ] → Γ ⊢ t ∷ ∃ F ▹ G ^ [ % , ι l ] → Γ ⊢ snd t ∷ G [ fst t ] ^ [ % , ι l ] zeroⱼ : ⊢ Γ → Γ ⊢ zero ∷ ℕ ^ [ ! , ι ⁰ ] sucⱼ : ∀ {n} → Γ ⊢ n ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ suc n ∷ ℕ ^ [ ! , ι ⁰ ] natrecⱼ : ∀ {G rG lG s z n} → Γ ∙ ℕ ^ [ ! , ι ⁰ ] ⊢ G ^ [ rG , ι lG ] → Γ ⊢ z ∷ G [ zero ] ^ [ rG , ι lG ] → Γ ⊢ s ∷ Π ℕ ^ ! ° ⁰ ▹ (G ^ rG ° lG ▹▹ G [ suc (var Nat.zero) ]↑ ° lG ° lG) ° lG ° lG ^ [ rG , ι lG ] → Γ ⊢ n ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ natrec lG G z s n ∷ G [ n ] ^ [ rG , ι lG ] Emptyrecⱼ : ∀ {A l lA rA e} → Γ ⊢ A ^ [ rA , ι lA ] → Γ ⊢ e ∷ Empty l ^ [ % , ι l ] -> Γ ⊢ Emptyrec lA l A e ∷ A ^ [ rA , ι lA ] Idⱼ : ∀ {A l t u} → Γ ⊢ A ∷ U l ^ [ ! , next l ] → Γ ⊢ t ∷ A ^ [ ! , ι l ] → Γ ⊢ u ∷ A ^ [ ! , ι l ] → Γ ⊢ Id A t u ∷ SProp l ^ [ ! , next l ] Idreflⱼ : ∀ {A l t} → Γ ⊢ t ∷ A ^ [ ! , ι l ] → Γ ⊢ Idrefl A t ∷ (Id A t t) ^ [ % , ι l ] transpⱼ : ∀ {A l P t s u e} → Γ ⊢ A ^ [ ! , l ] → Γ ∙ A ^ [ ! , l ] ⊢ P ^ [ % , l ] → Γ ⊢ t ∷ A ^ [ ! , l ] → Γ ⊢ s ∷ P [ t ] ^ [ % , l ] → Γ ⊢ u ∷ A ^ [ ! , l ] → Γ ⊢ e ∷ (Id A t u) ^ [ % , l ] → Γ ⊢ transp A P t s u e ∷ P [ u ] ^ [ % , l ] castⱼ : ∀ {A B r e t} → Γ ⊢ A ∷ Univ r ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ B ∷ Univ r ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ e ∷ (Id (Univ r ⁰) A B) ^ [ % , next ⁰ ] → Γ ⊢ t ∷ A ^ [ r , ι ⁰ ] → Γ ⊢ cast ⁰ A B e t ∷ B ^ [ r , ι ⁰ ] castreflⱼ : ∀ {A t} → Γ ⊢ A ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ t ∷ A ^ [ ! , ι ⁰ ] → Γ ⊢ castrefl A t ∷ (Id A t (cast ⁰ A A (Idrefl (U ⁰) A) t)) ^ [ % , ι ⁰ ] conv : ∀ {t A B r} → Γ ⊢ t ∷ A ^ r → Γ ⊢ A ≡ B ^ r → Γ ⊢ t ∷ B ^ r -- Type equality data _⊢_≡_^_ (Γ : Con Term) : Term → Term → TypeInfo → Set where univ : ∀ {A B r l} → Γ ⊢ A ≡ B ∷ (Univ r l) ^ [ ! , next l ] → Γ ⊢ A ≡ B ^ [ r , ι l ] refl : ∀ {A r} → Γ ⊢ A ^ r → Γ ⊢ A ≡ A ^ r sym : ∀ {A B r} → Γ ⊢ A ≡ B ^ r → Γ ⊢ B ≡ A ^ r trans : ∀ {A B C r} → Γ ⊢ A ≡ B ^ r → Γ ⊢ B ≡ C ^ r → Γ ⊢ A ≡ C ^ r -- Term equality data _⊢_≡_∷_^_ (Γ : Con Term) : Term → Term → Term → TypeInfo → Set where refl : ∀ {t A l} → Γ ⊢ t ∷ A ^ [ ! , l ] → Γ ⊢ t ≡ t ∷ A ^ [ ! , l ] sym : ∀ {t u A l} → Γ ⊢ t ≡ u ∷ A ^ [ ! , l ] → Γ ⊢ u ≡ t ∷ A ^ [ ! , l ] trans : ∀ {t u v A l} → Γ ⊢ t ≡ u ∷ A ^ [ ! , l ] → Γ ⊢ u ≡ v ∷ A ^ [ ! , l ] → Γ ⊢ t ≡ v ∷ A ^ [ ! , l ] conv : ∀ {A B r t u} → Γ ⊢ t ≡ u ∷ A ^ r → Γ ⊢ A ≡ B ^ r → Γ ⊢ t ≡ u ∷ B ^ r Π-cong : ∀ {E F G H rF lF rG lG l} → lF ≤ l → lG ≤ l → Γ ⊢ F ^ [ rF , ι lF ] → Γ ⊢ F ≡ H ∷ (Univ rF lF) ^ [ ! , next lF ] → Γ ∙ F ^ [ rF , ι lF ] ⊢ G ≡ E ∷ (Univ rG lG) ^ [ ! , next lG ] → Γ ⊢ Π F ^ rF ° lF ▹ G ° lG ° l ≡ Π H ^ rF ° lF ▹ E ° lG ° l ∷ (Univ rG l) ^ [ ! , next l ] ∃-cong : ∀ {E F G H l} → Γ ⊢ F ^ [ % , ι l ] → Γ ⊢ F ≡ H ∷ SProp l ^ [ ! , next l ] → Γ ∙ F ^ [ % , ι l ] ⊢ G ≡ E ∷ SProp l ^ [ ! , next l ] → Γ ⊢ ∃ F ▹ G ≡ ∃ H ▹ E ∷ SProp l ^ [ ! , next l ] app-cong : ∀ {a b f g F G rF lF lG l} → Γ ⊢ f ≡ g ∷ Π F ^ rF ° lF ▹ G ° lG ° l ^ [ ! , ι l ] → Γ ⊢ a ≡ b ∷ F ^ [ rF , ι lF ] → Γ ⊢ f ∘ a ^ l ≡ g ∘ b ^ l ∷ G [ a ] ^ [ ! , ι lG ] β-red : ∀ {a t F rF lF G lG l} → lF ≤ l → lG ≤ l → Γ ⊢ F ^ [ rF , ι lF ] → Γ ∙ F ^ [ rF , ι lF ] ⊢ t ∷ G ^ [ ! , ι lG ] → Γ ⊢ a ∷ F ^ [ rF , ι lF ] → Γ ⊢ (lam F ▹ t ^ l) ∘ a ^ l ≡ t [ a ] ∷ G [ a ] ^ [ ! , ι lG ] η-eq : ∀ {f g F rF lF lG l G} → lF ≤ l → lG ≤ l → Γ ⊢ F ^ [ rF , ι lF ] → Γ ⊢ f ∷ Π F ^ rF ° lF ▹ G ° lG ° l ^ [ ! , ι l ] → Γ ⊢ g ∷ Π F ^ rF ° lF ▹ G ° lG ° l ^ [ ! , ι l ] → Γ ∙ F ^ [ rF , ι lF ] ⊢ wk1 f ∘ var Nat.zero ^ l ≡ wk1 g ∘ var Nat.zero ^ l ∷ G ^ [ ! , ι lG ] → Γ ⊢ f ≡ g ∷ Π F ^ rF ° lF ▹ G ° lG ° l ^ [ ! , ι l ] suc-cong : ∀ {m n} → Γ ⊢ m ≡ n ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ suc m ≡ suc n ∷ ℕ ^ [ ! , ι ⁰ ] natrec-cong : ∀ {z z′ s s′ n n′ F F′ l} → Γ ∙ ℕ ^ [ ! , ι ⁰ ] ⊢ F ≡ F′ ^ [ ! , ι l ] → Γ ⊢ z ≡ z′ ∷ F [ zero ] ^ [ ! , ι l ] → Γ ⊢ s ≡ s′ ∷ Π ℕ ^ ! ° ⁰ ▹ (F ^ ! ° l ▹▹ F [ suc (var Nat.zero) ]↑ ° l ° l) ° l ° l ^ [ ! , ι l ] → Γ ⊢ n ≡ n′ ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ natrec l F z s n ≡ natrec l F′ z′ s′ n′ ∷ F [ n ] ^ [ ! , ι l ] natrec-zero : ∀ {z s F l} → Γ ∙ ℕ ^ [ ! , ι ⁰ ] ⊢ F ^ [ ! , ι l ] → Γ ⊢ z ∷ F [ zero ] ^ [ ! , ι l ] → Γ ⊢ s ∷ Π ℕ ^ ! ° ⁰ ▹ (F ^ ! ° l ▹▹ F [ suc (var Nat.zero) ]↑ ° l ° l) ° l ° l ^ [ ! , ι l ] → Γ ⊢ natrec l F z s zero ≡ z ∷ F [ zero ] ^ [ ! , ι l ] natrec-suc : ∀ {n z s F l} → Γ ⊢ n ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ∙ ℕ ^ [ ! , ι ⁰ ] ⊢ F ^ [ ! , ι l ] → Γ ⊢ z ∷ F [ zero ] ^ [ ! , ι l ] → Γ ⊢ s ∷ Π ℕ ^ ! ° ⁰ ▹ (F ^ ! ° l ▹▹ F [ suc (var Nat.zero) ]↑ ° l ° l) ° l ° l ^ [ ! , ι l ] → Γ ⊢ natrec l F z s (suc n) ≡ (s ∘ n ^ l) ∘ (natrec l F z s n) ^ l ∷ F [ suc n ] ^ [ ! , ι l ] Emptyrec-cong : ∀ {A A' l lEmpty e e'} → Γ ⊢ A ≡ A' ^ [ ! , ι l ] → Γ ⊢ e ∷ Empty lEmpty ^ [ % , ι lEmpty ] → Γ ⊢ e' ∷ Empty lEmpty ^ [ % , ι lEmpty ] → Γ ⊢ Emptyrec l lEmpty A e ≡ Emptyrec l lEmpty A' e' ∷ A ^ [ ! , ι l ] proof-irrelevance : ∀ {t u A l} → Γ ⊢ t ∷ A ^ [ % , l ] → Γ ⊢ u ∷ A ^ [ % , l ] → Γ ⊢ t ≡ u ∷ A ^ [ % , l ] Id-cong : ∀ {A A' l t t' u u'} → Γ ⊢ A ≡ A' ∷ Univ ! l ^ [ ! , next l ] → Γ ⊢ t ≡ t' ∷ A ^ [ ! , ι l ] → Γ ⊢ u ≡ u' ∷ A ^ [ ! , ι l ] → Γ ⊢ Id A t u ≡ Id A' t' u' ∷ SProp l ^ [ ! , next l ] Id-Π : ∀ {A rA lA lB l B t u} → lA ≤ l → lB ≤ l → Γ ⊢ A ∷ Univ rA lA ^ [ ! , next lA ] → Γ ∙ A ^ [ rA , ι lA ] ⊢ B ∷ Univ ! lB ^ [ ! , next lB ] → Γ ⊢ t ∷ (Π A ^ rA ° lA ▹ B ° lB ° l) ^ [ ! , ι l ] → Γ ⊢ u ∷ (Π A ^ rA ° lA ▹ B ° lB ° l) ^ [ ! , ι l ] → Γ ⊢ (Id (Π A ^ rA ° lA ▹ B ° lB ° l) t u) ≡ Π A ^ rA ° lA ▹ (Id B ((wk1 t) ∘ (var 0) ^ l) ((wk1 u) ∘ (var 0) ^ l)) ° lB ° l ∷ SProp l ^ [ ! , next l ] Id-ℕ-00 : ⊢ Γ → Γ ⊢ (Id ℕ zero zero) ≡ Unit {⁰} ∷ SProp ⁰ ^ [ ! , next ⁰ ] Id-ℕ-SS : ∀ {m n} → Γ ⊢ m ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ n ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ (Id ℕ (suc m) (suc n)) ≡ (Id ℕ m n) ∷ SProp ⁰ ^ [ ! , next ⁰ ] Id-U-ΠΠ : ∀ {A A' rA B B'} → Γ ⊢ A ∷ (Univ rA ⁰) ^ [ ! , next ⁰ ] → Γ ∙ A ^ [ rA , ι ⁰ ] ⊢ B ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ A' ∷ (Univ rA ⁰) ^ [ ! , next ⁰ ] → Γ ∙ A' ^ [ rA , ι ⁰ ] ⊢ B' ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ (Id (U ⁰) (Π A ^ rA ° ⁰ ▹ B ° ⁰ ° ⁰) (Π A' ^ rA ° ⁰ ▹ B' ° ⁰ ° ⁰)) ≡ ∃ (Id (Univ rA ⁰) A A') ▹ (Π (wk1 A') ^ rA ° ⁰ ▹ Id (U ⁰) ((wk (lift (step id)) B) [ cast ⁰ (wk1 (wk1 A')) (wk1 (wk1 A)) (Idsym (Univ rA ⁰) (wk1 (wk1 A)) (wk1 (wk1 A')) (var 1)) (var 0) ]↑) (wk (lift (step id)) B') ° ¹ ° ¹) ∷ SProp ¹ ^ [ ! , next ¹ ] Id-U-ℕℕ : ⊢ Γ → Γ ⊢ Id (U ⁰) ℕ ℕ ≡ Unit {¹} ∷ (SProp ¹) ^ [ ! , next ¹ ] Id-SProp : ∀ {A B} → Γ ⊢ A ∷ SProp ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ B ∷ SProp ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ Id (SProp ⁰) A B ≡ (A ^ % ° ⁰ ▹▹ B ° ⁰ ° ¹) ×× (B ^ % ° ⁰ ▹▹ A ° ⁰ ° ¹) ∷ SProp ¹ ^ [ ! , next ¹ ] Id-ℕ-0S : ∀ {t} → Γ ⊢ t ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ Id ℕ zero (suc t) ≡ Empty ⁰ ∷ (SProp ⁰) ^ [ ! , next ⁰ ] Id-ℕ-S0 : ∀ {t} → Γ ⊢ t ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ Id ℕ (suc t) zero ≡ Empty ⁰ ∷ (SProp ⁰) ^ [ ! , next ⁰ ] Id-U-ℕΠ : ∀ {A rA B} → Γ ⊢ A ∷ Univ rA ⁰ ^ [ ! , next ⁰ ] → Γ ∙ A ^ [ rA , ι ⁰ ] ⊢ B ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ Id (U ⁰) ℕ (Π A ^ rA ° ⁰ ▹ B ° ⁰ ° ⁰) ≡ Empty ¹ ∷ SProp ¹ ^ [ ! , next ¹ ] Id-U-Πℕ : ∀ {A rA B} → Γ ⊢ A ∷ Univ rA ⁰ ^ [ ! , next ⁰ ] → Γ ∙ A ^ [ rA , ι ⁰ ] ⊢ B ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ Id (U ⁰) (Π A ^ rA ° ⁰ ▹ B ° ⁰ ° ⁰) ℕ ≡ Empty ¹ ∷ SProp ¹ ^ [ ! , next ¹ ] Id-U-ΠΠ!% : ∀ {A rA B A' rA' B' } → rA PE.≢ rA' → Γ ⊢ A ∷ Univ rA ⁰ ^ [ ! , next ⁰ ] → Γ ∙ A ^ [ rA , ι ⁰ ] ⊢ B ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ A' ∷ Univ rA' ⁰ ^ [ ! , next ⁰ ] → Γ ∙ A' ^ [ rA' , ι ⁰ ] ⊢ B' ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ Id (U ⁰) (Π A ^ rA ° ⁰ ▹ B ° ⁰ ° ⁰) (Π A' ^ rA' ° ⁰ ▹ B' ° ⁰ ° ⁰) ≡ Empty ¹ ∷ SProp ¹ ^ [ ! , next ¹ ] cast-cong : ∀ {A A' B B' e e' t t'} → let l = ⁰ in Γ ⊢ A ≡ A' ∷ U l ^ [ ! , next l ] → Γ ⊢ B ≡ B' ∷ U l ^ [ ! , next l ] → Γ ⊢ t ≡ t' ∷ A ^ [ ! , ι l ] → Γ ⊢ e ∷ (Id (U ⁰) A B) ^ [ % , next ⁰ ] → Γ ⊢ e' ∷ (Id (U ⁰) A' B') ^ [ % , next ⁰ ] → Γ ⊢ cast l A B e t ≡ cast l A' B' e' t' ∷ B ^ [ ! , ι l ] cast-Π : ∀ {A A' rA B B' e f} → let l = ⁰ in let lA = ⁰ in let lB = ⁰ in Γ ⊢ A ∷ (Univ rA lA) ^ [ ! , next lA ] → Γ ∙ A ^ [ rA , ι lA ] ⊢ B ∷ U lB ^ [ ! , next lB ] → Γ ⊢ A' ∷ (Univ rA lA) ^ [ ! , next lA ] → Γ ∙ A' ^ [ rA , ι lA ] ⊢ B' ∷ U lB ^ [ ! , next lB ] → Γ ⊢ e ∷ Id (U l) (Π A ^ rA ° lA ▹ B ° lB ° l) (Π A' ^ rA ° lA ▹ B' ° lB ° l) ^ [ % , next l ] → Γ ⊢ f ∷ (Π A ^ rA ° lA ▹ B ° lB ° l) ^ [ ! , ι l ] → Γ ⊢ (cast l (Π A ^ rA ° lA ▹ B ° lB ° l) (Π A' ^ rA ° lA ▹ B' ° lB ° l) e f) ≡ (lam A' ▹ (let a = cast l (wk1 A') (wk1 A) (Idsym (Univ rA l) (wk1 A) (wk1 A') (fst (wk1 e))) (var 0) in cast l (B [ a ]↑) B' ((snd (wk1 e)) ∘ (var 0) ^ ¹) ((wk1 f) ∘ a ^ l)) ^ l) ∷ Π A' ^ rA ° lA ▹ B' ° lB ° l ^ [ ! , ι l ] cast-ℕ-0 : ∀ {e} → Γ ⊢ e ∷ Id (U ⁰) ℕ ℕ ^ [ % , next ⁰ ] → Γ ⊢ cast ⁰ ℕ ℕ e zero ≡ zero ∷ ℕ ^ [ ! , ι ⁰ ] cast-ℕ-S : ∀ {e n} → Γ ⊢ e ∷ Id (U ⁰) ℕ ℕ ^ [ % , next ⁰ ] → Γ ⊢ n ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ cast ⁰ ℕ ℕ e (suc n) ≡ suc (cast ⁰ ℕ ℕ e n) ∷ ℕ ^ [ ! , ι ⁰ ] mutual data _⊢_⇒_∷_^_ (Γ : Con Term) : Term → Term → Term → TypeLevel → Set where conv : ∀ {A B l t u} → Γ ⊢ t ⇒ u ∷ A ^ l → Γ ⊢ A ≡ B ^ [ ! , l ] → Γ ⊢ t ⇒ u ∷ B ^ l app-subst : ∀ {A B t u a rA lA lB l} → Γ ⊢ t ⇒ u ∷ Π A ^ rA ° lA ▹ B ° lB ° l ^ ι l → Γ ⊢ a ∷ A ^ [ rA , ι lA ] → Γ ⊢ t ∘ a ^ l ⇒ u ∘ a ^ l ∷ B [ a ] ^ ι lB β-red : ∀ {A B lA lB a t rA l} → lA ≤ l → lB ≤ l → Γ ⊢ A ^ [ rA , ι lA ] → Γ ∙ A ^ [ rA , ι lA ] ⊢ t ∷ B ^ [ ! , ι lB ] → Γ ⊢ a ∷ A ^ [ rA , ι lA ] → Γ ⊢ (lam A ▹ t ^ l) ∘ a ^ l ⇒ t [ a ] ∷ B [ a ] ^ ι lB natrec-subst : ∀ {z s n n′ F l} → Γ ∙ ℕ ^ [ ! , ι ⁰ ] ⊢ F ^ [ ! , ι l ] → Γ ⊢ z ∷ F [ zero ] ^ [ ! , ι l ] → Γ ⊢ s ∷ Π ℕ ^ ! ° ⁰ ▹ (F ^ ! ° l ▹▹ F [ suc (var Nat.zero) ]↑ ° l ° l) ° l ° l ^ [ ! , ι l ] → Γ ⊢ n ⇒ n′ ∷ ℕ ^ ι ⁰ → Γ ⊢ natrec l F z s n ⇒ natrec l F z s n′ ∷ F [ n ] ^ ι l natrec-zero : ∀ {z s F l } → Γ ∙ ℕ ^ [ ! , ι ⁰ ] ⊢ F ^ [ ! , ι l ] → Γ ⊢ z ∷ F [ zero ] ^ [ ! , ι l ] → Γ ⊢ s ∷ Π ℕ ^ ! ° ⁰ ▹ (F ^ ! ° l ▹▹ F [ suc (var Nat.zero) ]↑ ° l ° l ) ° l ° l ^ [ ! , ι l ] → Γ ⊢ natrec l F z s zero ⇒ z ∷ F [ zero ] ^ ι l natrec-suc : ∀ {n z s F l} → Γ ⊢ n ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ∙ ℕ ^ [ ! , ι ⁰ ] ⊢ F ^ [ ! , ι l ] → Γ ⊢ z ∷ F [ zero ] ^ [ ! , ι l ] → Γ ⊢ s ∷ Π ℕ ^ ! ° ⁰ ▹ (F ^ ! ° l ▹▹ F [ suc (var Nat.zero) ]↑ ° l ° l) ° l ° l ^ [ ! , ι l ] → Γ ⊢ natrec l F z s (suc n) ⇒ (s ∘ n ^ l) ∘ (natrec l F z s n) ^ l ∷ F [ suc n ] ^ ι l Id-subst : ∀ {A A' l t u} → Γ ⊢ A ⇒ A' ∷ Univ ! l ^ next l → Γ ⊢ t ∷ A ^ [ ! , ι l ] → Γ ⊢ u ∷ A ^ [ ! , ι l ] → Γ ⊢ Id A t u ⇒ Id A' t u ∷ SProp l ^ next l Id-ℕ-subst : ∀ {m m' n} → Γ ⊢ m ⇒ m' ∷ ℕ ^ ι ⁰ → Γ ⊢ n ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ Id ℕ m n ⇒ Id ℕ m' n ∷ SProp ⁰ ^ next ⁰ Id-ℕ-0-subst : ∀ {n n'} → Γ ⊢ n ⇒ n' ∷ ℕ ^ ι ⁰ → Γ ⊢ Id ℕ zero n ⇒ Id ℕ zero n' ∷ SProp ⁰ ^ next ⁰ Id-ℕ-S-subst : ∀ {m n n'} → Γ ⊢ m ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ n ⇒ n' ∷ ℕ ^ ι ⁰ → Γ ⊢ Id ℕ (suc m) n ⇒ Id ℕ (suc m) n' ∷ SProp ⁰ ^ next ⁰ Id-U-subst : ∀ {A A' B} → Γ ⊢ A ⇒ A' ∷ U ⁰ ^ next ⁰ → Γ ⊢ B ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ Id (U ⁰ ) A B ⇒ Id (U ⁰) A' B ∷ SProp ¹ ^ next ¹ Id-U-ℕ-subst : ∀ {B B'} → Γ ⊢ B ⇒ B' ∷ U ⁰ ^ next ⁰ → Γ ⊢ Id (U ⁰) ℕ B ⇒ Id (U ⁰) ℕ B' ∷ SProp ¹ ^ next ¹ Id-U-Π-subst : ∀ {A rA P B B'} → Γ ⊢ A ∷ (Univ rA ⁰) ^ [ ! , next ⁰ ] → Γ ∙ A ^ [ rA , ι ⁰ ] ⊢ P ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ B ⇒ B' ∷ U ⁰ ^ next ⁰ → Γ ⊢ Id (U ⁰) (Π A ^ rA ° ⁰ ▹ P ° ⁰ ° ⁰) B ⇒ Id (U ⁰) (Π A ^ rA ° ⁰ ▹ P ° ⁰ ° ⁰) B' ∷ SProp ¹ ^ next ¹ Id-Π : ∀ {A rA lA lB l B t u} → lA ≤ l → lB ≤ l → Γ ⊢ A ∷ Univ rA lA ^ [ ! , next lA ] → Γ ∙ A ^ [ rA , ι lA ] ⊢ B ∷ Univ ! lB ^ [ ! , next lB ] → Γ ⊢ t ∷ (Π A ^ rA ° lA ▹ B ° lB ° l) ^ [ ! , ι l ] → Γ ⊢ u ∷ (Π A ^ rA ° lA ▹ B ° lB ° l) ^ [ ! , ι l ] → Γ ⊢ (Id (Π A ^ rA ° lA ▹ B ° lB ° l) t u) ⇒ Π A ^ rA ° lA ▹ (Id B ((wk1 t) ∘ (var 0) ^ l) ((wk1 u) ∘ (var 0) ^ l)) ° lB ° l ∷ SProp l ^ next l Id-ℕ-00 : ⊢ Γ → Γ ⊢ (Id ℕ zero zero) ⇒ Unit {⁰} ∷ SProp ⁰ ^ next ⁰ Id-ℕ-SS : ∀ {m n} → Γ ⊢ m ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ n ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ (Id ℕ (suc m) (suc n)) ⇒ (Id ℕ m n) ∷ SProp ⁰ ^ next ⁰ Id-U-ΠΠ : ∀ {A A' rA B B'} → Γ ⊢ A ∷ (Univ rA ⁰) ^ [ ! , next ⁰ ] → Γ ∙ A ^ [ rA , ι ⁰ ] ⊢ B ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ A' ∷ (Univ rA ⁰) ^ [ ! , next ⁰ ] → Γ ∙ A' ^ [ rA , ι ⁰ ] ⊢ B' ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ (Id (U ⁰) (Π A ^ rA ° ⁰ ▹ B ° ⁰ ° ⁰) (Π A' ^ rA ° ⁰ ▹ B' ° ⁰ ° ⁰)) ⇒ ∃ (Id (Univ rA ⁰) A A') ▹ (Π (wk1 A') ^ rA ° ⁰ ▹ Id (U ⁰) ((wk1d B) [ cast ⁰ (wk1 (wk1 A')) (wk1 (wk1 A)) (Idsym (Univ rA ⁰) (wk1 (wk1 A)) (wk1 (wk1 A')) (var 1)) (var 0) ]↑) (wk1d B') ° ¹ ° ¹) ∷ SProp ¹ ^ next ¹ Id-U-ℕℕ : ⊢ Γ → Γ ⊢ (Id (U ⁰) ℕ ℕ) ⇒ Unit {¹} ∷ SProp ¹ ^ next ¹ Id-SProp : ∀ {A B} → Γ ⊢ A ∷ SProp ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ B ∷ SProp ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ Id (SProp ⁰) A B ⇒ (A ^ % ° ⁰ ▹▹ B ° ⁰ ° ¹) ×× (B ^ % ° ⁰ ▹▹ A ° ⁰ ° ¹) ∷ SProp ¹ ^ next ¹ Id-ℕ-0S : ∀ {t} → Γ ⊢ t ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ Id ℕ zero (suc t) ⇒ Empty ⁰ ∷ SProp ⁰ ^ next ⁰ Id-ℕ-S0 : ∀ {t} → Γ ⊢ t ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ Id ℕ (suc t) zero ⇒ Empty ⁰ ∷ SProp ⁰ ^ next ⁰ Id-U-ℕΠ : ∀ {A rA B} → Γ ⊢ A ∷ Univ rA ⁰ ^ [ ! , next ⁰ ] → Γ ∙ A ^ [ rA , ι ⁰ ] ⊢ B ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ Id (U ⁰) ℕ (Π A ^ rA ° ⁰ ▹ B ° ⁰ ° ⁰) ⇒ Empty ¹ ∷ SProp ¹ ^ next ¹ Id-U-Πℕ : ∀ {A rA B} → Γ ⊢ A ∷ Univ rA ⁰ ^ [ ! , next ⁰ ] → Γ ∙ A ^ [ rA , ι ⁰ ] ⊢ B ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ Id (U ⁰) (Π A ^ rA ° ⁰ ▹ B ° ⁰ ° ⁰) ℕ ⇒ Empty ¹ ∷ SProp ¹ ^ next ¹ Id-U-ΠΠ!% : ∀ {A rA B A' rA' B' } → rA PE.≢ rA' → Γ ⊢ A ∷ Univ rA ⁰ ^ [ ! , next ⁰ ] → Γ ∙ A ^ [ rA , ι ⁰ ] ⊢ B ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ A' ∷ Univ rA' ⁰ ^ [ ! , next ⁰ ] → Γ ∙ A' ^ [ rA' , ι ⁰ ] ⊢ B' ∷ U ⁰ ^ [ ! , next ⁰ ] → Γ ⊢ Id (U ⁰) (Π A ^ rA ° ⁰ ▹ B ° ⁰ ° ⁰) (Π A' ^ rA' ° ⁰ ▹ B' ° ⁰ ° ⁰) ⇒ Empty ¹ ∷ SProp ¹ ^ next ¹ cast-subst : ∀ {A A' B e t} → let l = ⁰ in Γ ⊢ A ⇒ A' ∷ U l ^ next l → Γ ⊢ B ∷ U l ^ [ ! , next l ] → Γ ⊢ e ∷ Id (U l) A B ^ [ % , next l ] → Γ ⊢ t ∷ A ^ [ ! , ι l ] → Γ ⊢ cast l A B e t ⇒ cast l A' B e t ∷ B ^ ι l cast-ℕ-subst : ∀ {B B' e t} → Γ ⊢ B ⇒ B' ∷ U ⁰ ^ next ⁰ → Γ ⊢ e ∷ Id (U ⁰) ℕ B ^ [ % , next ⁰ ] → Γ ⊢ t ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ cast ⁰ ℕ B e t ⇒ cast ⁰ ℕ B' e t ∷ B ^ ι ⁰ cast-Π-subst : ∀ {A rA P B B' e t} → let l = ⁰ in let lA = ⁰ in let lP = ⁰ in Γ ⊢ A ∷ (Univ rA lA) ^ [ ! , next lA ] → Γ ∙ A ^ [ rA , ι lA ] ⊢ P ∷ U lP ^ [ ! , next lA ] → Γ ⊢ B ⇒ B' ∷ U l ^ next l → Γ ⊢ e ∷ Id (U l) (Π A ^ rA ° lA ▹ P ° lP ° l) B ^ [ % , next l ] → Γ ⊢ t ∷ (Π A ^ rA ° lA ▹ P ° lP ° l) ^ [ ! , ι l ] → Γ ⊢ cast l (Π A ^ rA ° lA ▹ P ° lP ° l) B e t ⇒ cast l (Π A ^ rA ° lA ▹ P ° lP ° l) B' e t ∷ B ^ ι l cast-Π : ∀ {A A' rA B B' e f} → let l = ⁰ in Γ ⊢ A ∷ (Univ rA l) ^ [ ! , next l ] → Γ ∙ A ^ [ rA , ι l ] ⊢ B ∷ U l ^ [ ! , next l ] → Γ ⊢ A' ∷ (Univ rA l) ^ [ ! , next l ] → Γ ∙ A' ^ [ rA , ι l ] ⊢ B' ∷ U l ^ [ ! , next l ] → Γ ⊢ e ∷ Id (U l) (Π A ^ rA ° l ▹ B ° l ° l) (Π A' ^ rA ° l ▹ B' ° l ° l) ^ [ % , next l ] → Γ ⊢ f ∷ (Π A ^ rA ° l ▹ B ° l ° l) ^ [ ! , ι l ] → Γ ⊢ (cast l (Π A ^ rA ° l ▹ B ° l ° l) (Π A' ^ rA ° l ▹ B' ° l ° l) e f) ⇒ (lam A' ▹ (let a = cast l (wk1 A') (wk1 A) (Idsym (Univ rA l) (wk1 A) (wk1 A') (fst (wk1 e))) (var 0) in cast l (B [ a ]↑) B' ((snd (wk1 e)) ∘ (var 0) ^ ¹) ((wk1 f) ∘ a ^ l)) ^ l ) ∷ Π A' ^ rA ° l ▹ B' ° l ° l ^ ι l cast-ℕ-0 : ∀ {e} → Γ ⊢ e ∷ Id (U ⁰) ℕ ℕ ^ [ % , next ⁰ ] → Γ ⊢ cast ⁰ ℕ ℕ e zero ⇒ zero ∷ ℕ ^ ι ⁰ cast-ℕ-S : ∀ {e n} → Γ ⊢ e ∷ Id (U ⁰) ℕ ℕ ^ [ % , next ⁰ ] → Γ ⊢ n ∷ ℕ ^ [ ! , ι ⁰ ] → Γ ⊢ cast ⁰ ℕ ℕ e (suc n) ⇒ suc (cast ⁰ ℕ ℕ e n) ∷ ℕ ^ ι ⁰ cast-ℕ-cong : ∀ {e t u} → Γ ⊢ e ∷ Id (U ⁰) ℕ ℕ ^ [ % , next ⁰ ] → Γ ⊢ t ⇒ u ∷ ℕ ^ ι ⁰ → Γ ⊢ cast ⁰ ℕ ℕ e t ⇒ cast ⁰ ℕ ℕ e u ∷ ℕ ^ ι ⁰ -- Type reduction data _⊢_⇒_^_ (Γ : Con Term) : Term → Term → TypeInfo → Set where univ : ∀ {A B r l} → Γ ⊢ A ⇒ B ∷ (Univ r l) ^ next l → Γ ⊢ A ⇒ B ^ [ r , ι l ] -- Term reduction closure data _⊢_⇒*_∷_^_ (Γ : Con Term) : Term → Term → Term → TypeLevel → Set where id : ∀ {A l t} → Γ ⊢ t ∷ A ^ [ ! , l ] → Γ ⊢ t ⇒* t ∷ A ^ l _⇨_ : ∀ {A l t t′ u} → Γ ⊢ t ⇒ t′ ∷ A ^ l → Γ ⊢ t′ ⇒* u ∷ A ^ l → Γ ⊢ t ⇒* u ∷ A ^ l -- Type reduction closure data _⊢_⇒*_^_ (Γ : Con Term) : Term → Term → TypeInfo → Set where id : ∀ {A r} → Γ ⊢ A ^ r → Γ ⊢ A ⇒* A ^ r _⇨_ : ∀ {A A′ B r} → Γ ⊢ A ⇒ A′ ^ r → Γ ⊢ A′ ⇒* B ^ r → Γ ⊢ A ⇒* B ^ r -- Type reduction to whnf _⊢_↘_^_ : (Γ : Con Term) → Term → Term → TypeInfo → Set Γ ⊢ A ↘ B ^ r = Γ ⊢ A ⇒* B ^ r × Whnf B -- Term reduction to whnf _⊢_↘_∷_^_ : (Γ : Con Term) → Term → Term → Term → TypeLevel → Set Γ ⊢ t ↘ u ∷ A ^ l = Γ ⊢ t ⇒* u ∷ A ^ l × Whnf u -- Type equality with well-formed types _⊢_:≡:_^_ : (Γ : Con Term) → Term → Term → TypeInfo → Set Γ ⊢ A :≡: B ^ r = Γ ⊢ A ^ r × Γ ⊢ B ^ r × (Γ ⊢ A ≡ B ^ r) -- Term equality with well-formed terms _⊢_:≡:_∷_^_ : (Γ : Con Term) → Term → Term → Term → TypeInfo → Set Γ ⊢ t :≡: u ∷ A ^ r = Γ ⊢ t ∷ A ^ r × Γ ⊢ u ∷ A ^ r × (Γ ⊢ t ≡ u ∷ A ^ r) -- Type reduction closure with well-formed types record _⊢_:⇒*:_^_ (Γ : Con Term) (A B : Term) (r : TypeInfo) : Set where constructor [[_,_,_]] field ⊢A : Γ ⊢ A ^ r ⊢B : Γ ⊢ B ^ r D : Γ ⊢ A ⇒* B ^ r open _⊢_:⇒*:_^_ using () renaming (D to red) public -- Term reduction closure with well-formed terms record _⊢_:⇒*:_∷_^_ (Γ : Con Term) (t u A : Term) (l : TypeLevel) : Set where constructor [[_,_,_]] field ⊢t : Γ ⊢ t ∷ A ^ [ ! , l ] ⊢u : Γ ⊢ u ∷ A ^ [ ! , l ] d : Γ ⊢ t ⇒* u ∷ A ^ l open _⊢_:⇒*:_∷_^_ using () renaming (d to redₜ) public -- Well-formed substitutions. data _⊢ˢ_∷_ (Δ : Con Term) (σ : Subst) : (Γ : Con Term) → Set where id : Δ ⊢ˢ σ ∷ ε _,_ : ∀ {Γ A rA} → Δ ⊢ˢ tail σ ∷ Γ → Δ ⊢ head σ ∷ subst (tail σ) A ^ rA → Δ ⊢ˢ σ ∷ Γ ∙ A ^ rA -- Conversion of well-formed substitutions. data _⊢ˢ_≡_∷_ (Δ : Con Term) (σ σ′ : Subst) : (Γ : Con Term) → Set where id : Δ ⊢ˢ σ ≡ σ′ ∷ ε _,_ : ∀ {Γ A rA} → Δ ⊢ˢ tail σ ≡ tail σ′ ∷ Γ → Δ ⊢ head σ ≡ head σ′ ∷ subst (tail σ) A ^ rA → Δ ⊢ˢ σ ≡ σ′ ∷ Γ ∙ A ^ rA -- Note that we cannot use the well-formed substitutions. -- For that, we need to prove the fundamental theorem for substitutions. -- Some derivable rules Unitⱼ : ∀ {Γ l} (⊢Γ : ⊢ Γ) → Γ ⊢ Unit ∷ SProp l ^ [ ! , next l ] Unitⱼ ⊢Γ = Πⱼ ≡is≤ PE.refl ▹ ≡is≤ PE.refl ▹ Emptyⱼ ⊢Γ ▹ Emptyⱼ (⊢Γ ∙ univ (Emptyⱼ ⊢Γ)) typeUnit : ∀ {l} → Type (Unit {l}) typeUnit = Πₙ Ugenⱼ : ∀ {r Γ l} → ⊢ Γ → Γ ⊢ Univ r l ^ [ ! , next l ] Ugenⱼ {l = ⁰} ⊢Γ = univ (univ 0<1 ⊢Γ) Ugenⱼ {l = ¹} ⊢Γ = Uⱼ ⊢Γ ",12047,True,2893.4322035126215,median "script ""auto_mr2016.ash"" # This is meant for items that have a date of 2016. # Handling: Witchess Set, Snojo, Source Terminal, Protonic Accelerator Pack # Time-Spinner boolean snojoFightAvailable(); boolean auto_advWitchess(string target); boolean auto_advWitchess(string target, string option); boolean auto_haveWitchess(); boolean auto_haveSourceTerminal(); boolean auto_sourceTerminalRequest(string request); boolean auto_sourceTerminalEnhance(string request); int auto_sourceTerminalEnhanceLeft(); boolean auto_sourceTerminalExtrude(string request); int auto_sourceTerminalExtrudeLeft(); int[string] auto_sourceTerminalStatus(); boolean auto_doPrecinct(); item auto_bestBadge(); boolean auto_sourceTerminalEducate(skill first); boolean auto_sourceTerminalEducate(skill first, skill second); boolean LX_ghostBusting(); boolean expectGhostReport(); boolean haveGhostReport(); boolean timeSpinnerGet(string goal); boolean timeSpinnerConsume(item goal); boolean timeSpinnerCombat(monster goal); boolean timeSpinnerCombat(monster goal, string option); boolean timeSpinnerAdventure(string option); boolean timeSpinnerAdventure(); boolean rethinkingCandy(effect acquire); boolean rethinkingCandy(effect acquire, boolean simulate); boolean rethinkingCandyList(); //Supplemental int auto_advWitchessTargets(string target); boolean snojoFightAvailable() { if(!is_unrestricted($item[X-32-F Snowman Crate])) { return false; } if(!get_property(""snojoAvailable"").to_boolean()) { return false; } if(my_inebriety() > inebriety_limit()) { return false; } if(!get_property(""kingLiberated"").to_boolean()) { int[string] controls; controls[""MUSCLE""] = 1; controls[""MYSTICALITY""] = 2; controls[""MOXIE""] = 3; controls[""Muscle""] = 1; controls[""Mysticality""] = 2; controls[""Moxie""] = 3; //List the three desired goals and then a ""final"" state that we stay in string[int] standard; standard[0] = ""Moxie""; standard[1] = ""Mysticality""; standard[2] = ""Muscle""; standard[3] = ""Moxie""; if((my_path() == ""Avatar of Boris"") && (possessEquipment($item[Boris\\'s Helm]) || possessEquipment($item[Boris\\'s Helm (Askew)]))) { standard[0] = ""Muscle""; standard[1] = ""Mysticality""; standard[2] = ""Moxie""; standard[3] = ""Mysticality""; } if(my_path() == ""Community Service"") { standard[0] = ""Mysticality""; standard[1] = ""Moxie""; standard[2] = ""Muscle""; standard[3] = ""Mysticality""; } if(my_path() == ""License to Adventure"") { standard[0] = ""Mysticality""; standard[1] = ""Moxie""; standard[2] = ""Muscle""; standard[3] = ""Mysticality""; } if((get_property(""snojo"" + standard[0] + ""Wins"").to_int() < 14) && (get_property(""snojoSetting"") != to_upper_case(standard[0]))) { string temp = visit_url(""place.php?whichplace=snojo&action=snojo_controller""); temp = run_choice(controls[standard[0]]); } if((get_property(""snojoSetting"") == to_upper_case(standard[0])) && (get_property(""snojo"" + standard[0] + ""Wins"").to_int() >= 14) && (get_property(""snojoSetting"") != to_upper_case(standard[1])) && (get_property(""snojo"" + standard[1] + ""Wins"").to_int() < 14)) { string temp = visit_url(""place.php?whichplace=snojo&action=snojo_controller""); temp = run_choice(controls[standard[1]]); } if((get_property(""snojoSetting"") == to_upper_case(standard[1])) && (get_property(""snojo"" + standard[1] + ""Wins"").to_int() >= 14) && (get_property(""snojoSetting"") != to_upper_case(standard[2])) && (get_property(""snojo"" + standard[2] + ""Wins"").to_int() < 14)) { string temp = visit_url(""place.php?whichplace=snojo&action=snojo_controller""); temp = run_choice(controls[standard[2]]); } if((get_property(""snojoSetting"") == to_upper_case(standard[2])) && (get_property(""snojo"" + standard[2] + ""Wins"").to_int() >= 11) && (get_property(""snojoSetting"") != to_upper_case(standard[3]))) { string temp = visit_url(""place.php?whichplace=snojo&action=snojo_controller""); temp = run_choice(controls[standard[3]]); } } if(get_property(""snojoSetting"") == ""NONE"") { auto_log_info(""Snojo not set, attempting to set to "" + my_primestat(), ""blue""); visit_url(""place.php?whichplace=snojo&action=snojo_controller""); } return (get_property(""_snojoFreeFights"").to_int() < 10); } boolean auto_haveSourceTerminal() { if(!is_unrestricted($item[Source Terminal])) { return false; } static boolean didCheck = false; if((auto_my_path() == ""Nuclear Autumn"") && !didCheck) { didCheck = true; string temp = visit_url(""place.php?whichplace=falloutshelter&action=vault_term""); if(contains_text(temp, ""Source Terminal"")) { set_property(""auto_haveSourceTerminal"", true); } } return (auto_get_campground() contains $item[Source Terminal]); } boolean auto_sourceTerminalRequest(string request) { //enhance .enh [meat|items|init|critical] //enquiry .enq [familiar|monsters] //educate .edu [digitize|extract] //extrude .ext [food|booze|goggles] auto_log_info(""Source Terminal request: "" + request, ""green""); //""campground.php?action=terminal&hack=enhance items.enh"" if(auto_haveSourceTerminal()) { if(auto_my_path() == ""Nuclear Autumn"") { string temp = visit_url(""place.php?whichplace=falloutshelter&action=vault_term""); } else { string temp = visit_url(""campground.php?action=terminal""); } # temp = visit_url(""choice.php?pwd=&whichchoice=1191&option=1&input=reset""); string temp = visit_url(""choice.php?pwd=&whichchoice=1191&option=1&input="" + request); # temp = visit_url(""choice.php?pwd=&whichchoice=1191&option=1&input=reset""); return true; } return false; } boolean auto_sourceTerminalExtrude(string request) { if(!auto_haveSourceTerminal()) { return false; } if(auto_sourceTerminalExtrudeLeft() == 0) { return false; } string actual = """"; request = to_lower_case(request); switch(request) { case ""food"": case ""food.ext"": case ""browser cookie"": actual = ""food""; break; case ""booze"": case ""booze.ext"": case ""hacked gibson"": actual = ""booze""; break; case ""goggles"": case ""goggles.ext"": case ""source shades"": actual = ""goggles""; break; default: return false; } return auto_sourceTerminalRequest(""extrude -f "" + actual + "".ext""); } int auto_sourceTerminalExtrudeLeft() { if(auto_haveSourceTerminal()) { return 3 - get_property(""_sourceTerminalExtrudes"").to_int(); } return 0; } boolean auto_sourceTerminalEnhance(string request) { if(!auto_haveSourceTerminal()) { return false; } if(auto_sourceTerminalEnhanceLeft() == 0) { return false; } string actual = """"; switch(request) { case ""meat"": case ""meat.enh"": actual = ""meat""; break; case ""item"": case ""items"": case ""item.enh"": case ""items.enh"": actual = ""items""; break; case ""substats"": case ""substats.enh"": case ""stats"": actual = ""substats""; break; case ""damage"": case ""damage.enh"": actual = ""damage""; break; case ""init"": case ""initiative"": actual = ""init""; break; case ""critical"": actual = ""critical""; break; default: return false; } if(contains_text(get_property(""sourceTerminalEnhanceKnown""), actual + "".enh"")) { return auto_sourceTerminalRequest(""enhance "" + actual + "".enh""); } return false; } int auto_sourceTerminalEnhanceLeft() { if(auto_haveSourceTerminal()) { int used = get_property(""_sourceTerminalEnhanceUses"").to_int(); int total = 1; if(get_property(""sourceTerminalChips"") != """") { string[int] chips = split_string(get_property(""sourceTerminalChips""), "",""); foreach index in chips { string chip = trim(chips[index]); if((chip == ""CRAM"") || (chip == ""SCRAM"")) { total += 1; } } } return total - used; } return 0; } int[string] auto_sourceTerminalMissing() { int[string] status; status[""ASHRAM""] = 1; status[""CRAM""] = 1; status[""DIAGRAM""] = 1; status[""DRAM""] = 1; status[""GRAM""] = 10; status[""INGRAM""] = 1; status[""PRAM""] = 10; status[""SCRAM""] = 1; status[""SPAM""] = 10; status[""TRAM""] = 1; status[""TRIGRAM""] = 1; status[""booze.ext""] = 1; status[""compress.edu""] = 1; status[""cram.ext""] = 1; status[""critical.enh""] = 1; status[""damage.enh""] = 1; status[""digitize""] = 3; status[""digitize.edu""] = 1; status[""dram.ext""] = 1; status[""duplicate.edu""] = 1; status[""educate""] = 2; status[""enhance""] = 103; status[""enhanceBuff""] = 100; status[""enhanceUses""] = 3; status[""enquiry""] = 250; status[""extract.edu""] = 1; status[""familiar.enq""] = 1; status[""familiar.ext""] = 1; status[""food.ext""] = 1; status[""goggles.ext""] = 1; status[""gram.ext""] = 1; status[""init.enh""] = 1; status[""items.enh""] = 1; status[""meat.enh""] = 1; status[""monsters.enq""] = 1; status[""mpReduce""] = 15; status[""portscan.edu""] = 1; status[""pram.ext""] = 1; status[""protect.enq""] = 1; status[""spam.ext""] = 1; status[""stats.enq""] = 1; status[""substats.enh""] = 1; status[""tram.ext""] = 1; status[""turbo.edu""] = 1; int[string] have = auto_sourceTerminalStatus(); foreach thing in have { status[thing] -= have[thing]; } return status; } int[string] auto_sourceTerminalStatus() { int[string] status; if(auto_haveSourceTerminal()) { string temp = visit_url(""campground.php?action=terminal""); temp = visit_url(""choice.php?pwd=&whichchoice=1191&option=1&input=reset""); temp = visit_url(""choice.php?pwd=&whichchoice=1191&option=1&input=status""); temp = visit_url(""choice.php?pwd=&whichchoice=1191&option=1&input=ls""); matcher ramMatcher = create_matcher(""
((?:[A-Z]*?)?[RP]AM) (chip(?:s?)) installed([:,]) ((?:\\\\d+)|(?:\\\\w))"", temp); while(ramMatcher.find()) { if(ramMatcher.group(3) == "","") { status[ramMatcher.group(1)] = 1; } else { status[ramMatcher.group(1)] = ramMatcher.group(4).to_int(); } } matcher extrude = create_matcher(""\\\\b((?:\\\\w+?)[.](?:ext|enh|edu|enq))"", temp); while(extrude.find()) { status[extrude.group(1)] = 1; } # temp = visit_url(""choice.php?pwd=&whichchoice=1191&option=1&input=reset""); status[""enhanceBuff""] = 25 + (25 * status[""INGRAM""]) + (5 * status[""PRAM""]); status[""enhanceUses""] = 1 + status[""CRAM""] + status[""SCRAM""]; status[""enhance""] = status[""enhanceBuff""] + status[""enhanceUses""]; status[""enquiry""] = 50 + ((status[""DIAGRAM""] + 1) * status[""GRAM""] * 10); status[""educate""] = 1 + status[""DRAM""]; status[""digitize""] = 1 + status[""TRIGRAM""] + status[""TRAM""]; status[""mpReduce""] = (5 * status[""ASHRAM""]) + status[""SPAM""]; } return status; } boolean auto_sourceTerminalEducate(skill first, skill second) { if(!auto_haveSourceTerminal()) { return false; } if(auto_my_path() == ""Pocket Familiars"") { return false; } if(first == $skill[none]) { first = second; second = $skill[none]; } if(!contains_text(get_property(""sourceTerminalChips""), ""DRAM"")) { second = $skill[none]; set_property(""sourceTerminalEducate2"", """"); } if(first == $skill[none]) { return false; } string firstSkill = to_lower_case(to_string(first)) + "".edu""; string secondSkill = to_lower_case(to_string(second)) + "".edu""; if((get_property(""sourceTerminalEducate1"") == firstSkill) || (get_property(""sourceTerminalEducate2"") == firstSkill)) { if((get_property(""sourceTerminalEducate1"") == secondSkill) || (get_property(""sourceTerminalEducate2"") == secondSkill) || (secondSkill == ""none.edu"")) { return true; } } auto_sourceTerminalRequest(""educate "" + firstSkill); if(secondSkill != ""none.edu"") { auto_sourceTerminalRequest(""educate "" + secondSkill); } return true; } boolean auto_sourceTerminalEducate(skill first) { return auto_sourceTerminalEducate(first, $skill[none]); } boolean auto_haveWitchess() { if(!is_unrestricted($item[Witchess Set])) { return false; } return (auto_get_campground() contains $item[Witchess Set]); } boolean auto_advWitchess(string target) { return auto_advWitchess(target, """"); } boolean auto_advWitchess(string target, string option) { if(!auto_haveWitchess()) { return false; } if(my_adventures() == 0) { return false; } int goal = auto_advWitchessTargets(target); if(goal == 0) { return false; } if(get_property(""_auto_witchessBattles"").to_int() >= 5) { return false; } set_property(""_auto_witchessBattles"", get_property(""_auto_witchessBattles"").to_int() + 1); string temp = visit_url(""campground.php?action=witchess""); if(!contains_text(temp, ""Examine the shrink ray"")) { set_property(""_auto_witchessBattles"", 5); return false; } temp = visit_url(""choice.php?whichchoice=1181&pwd=&option=1""); matcher witchessMatcher = create_matcher(""You can fight (\\\\d) more piece(s?) today"", temp); if(witchessMatcher.find()) { int consider = (5 - witchessMatcher.group(1).to_int()) + 1; if(consider > get_property(""_auto_witchessBattles"").to_int()) { set_property(""_auto_witchessBattles"", consider); } } else { set_property(""_auto_witchessBattles"", 5); return false; } temp = visit_url(""choice.php?pwd=&option=2&whichchoice=1182""); string[int] pages; pages[0] = ""campground.php?action=witchess""; pages[1] = ""choice.php?whichchoice=1181&pwd=&option=1""; pages[2] = ""choice.php?pwd="" + my_hash() + ""&whichchoice=1182&option=1&piece="" + goal; // We use 4 to cause pages[2] to use GET. return autoAdvBypass(4, pages, $location[Noob Cave], option); } int auto_advWitchessTargets(string target) { target = to_lower_case(target); if((target == ""knight"") || (target == ""meat"") || (target == ""food"")) { return 1936; } if((target == ""pawn"") || (target == ""spleen"") || (target == ""init"")) { return 1935; } if((target == ""bishop"") || (target == ""item"") || (target == ""booze"")) { return 1942; } if((target == ""rook"") || (target == ""ml"") || (target == ""stats"")) { return 1938; } if((target == 1942) && (auto_my_path() == ""Teetotaler"")) { return 1936; } if((target == ""ox"") || (target == ""ox-head shield"") || (target == ""shield"") || (target == ""pvp"") || (target == ""hp"") || (target == ""resist"") || (target == ""resistance"")) { return 1937; } if((target == ""king"") || (target == ""dented scepter"") || (target == ""scepter"") || (target == ""club"") || (target == ""muscle"") || (target == ""hpregen"")) { return 1940; } if((target == ""witch"") || (target == ""battle broom"") || (target == ""broom"") || (target == ""myst"") || (target == ""mpregen"") || (target == ""spell"")) { return 1941; } if((target == ""queen"") || (target == ""very pointy crown"") || (target == ""crown"") || (target == ""adv"") || (target == ""moxie"") || (target == ""nc"") || (target == ""noncombat"") || (target == ""non-combat"")) { return 1939; } return 0; } item auto_bestBadge() { item retval = $item[none]; foreach it in $items[Plastic Detective Badge, Bronze Detective Badge, Silver Detective Badge, Gold Detective Badge] { if(possessEquipment(it)) { retval = it; } } return retval; } boolean auto_doPrecinct() { if(!is_unrestricted($item[Detective School Application])) { return false; } if(!get_property(""hasDetectiveSchool"").to_boolean()) { return false; } if(get_property(""_detectiveCasesCompleted"").to_int() >= 3) { return false; } if(svn_info(""Ezandora-Detective-Solver-branches-Release"").last_changed_rev > 0) { //Assume if someone has this installed that they want to use it. cli_execute(""ash import solveAllCases(false);""); return true; } if(get_property(""auto_eggDetective"") != """") { set_property(""auto_eggDetective"", """"); } string page = visit_url(""place.php?whichplace=town_wrong&action=townwrong_precinct""); matcher eggMatcher = create_matcher(""You have been on this case for (\\\\d+) minute(?:s?)"", page); if(!eggMatcher.find()) { if(!contains_text(page, ""The Precinct"")) { return false; } int casesLeft = 0; matcher precinctMatcher = create_matcher(""[(](\\\\d) more case(?:s?) today[)]"", page); if(precinctMatcher.find()) { casesLeft = to_int(precinctMatcher.group(1)); auto_log_info(""We have "" + casesLeft + "" case(s) leftover!"", ""green""); } if(casesLeft == 0) { page = visit_url(""wham.php"", false); if(!contains_text(page, ""You have been on this case for"")) { return false; } auto_log_info(""Trying to resume case...."", ""red""); } page = visit_url(""choice.php?pwd=&whichchoice=1193&option=1""); eggMatcher = create_matcher(""You have been on this case for (\\\\d+) minute(?:s?)"", page); if(!contains_text(page, ""murdered with an egg"")) { if(!eggMatcher.find()) { auto_log_info(""Someone was not murdered with an egg.... that's sad."" + page, ""red""); return false; } } auto_log_info(""Murdered with an egg! I love Egg!!"", ""green""); page = visit_url(""wham.php"", false); } eggMatcher = create_matcher(""You have been on this case for (\\\\d+) minute(?:s?)"", page); if(!eggMatcher.find()) { auto_log_info(""I can not resolve my case situation...."", ""red""); return false; } while(!contains_text(get_property(""auto_eggDetective""), ""solved"")) { string[int] eggData = split_string(get_property(""auto_eggDetective""), "",""); int i=1; while(i<=9) { boolean visited = false; foreach index in eggData { string[int] subEgg = split_string(eggData[index], "":""); if(subEgg[0].to_int() == i) { visited = true; break; } } if(!visited) { auto_log_info(""Going to visit room: "" + i, ""green""); page = visit_url(""wham.php?visit="" + i, false); matcher personMatcher = create_matcher(""(?:\\\\s+)(?:\\\\s+)
(?:\\\\s+)([a-zA-Z ]+?)(?:\\\\s+?)
(?:\\\\s+?)([a-zA-Z -]+)(?:\\\\s+?)

(?:\\\\s+?)[(]([a-zA-Z ']+?)[)]"", page); if(personMatcher.find()) { string person = personMatcher.group(1); string job = personMatcher.group(2); string room = personMatcher.group(3); auto_log_info(""Found "" + personMatcher.group(1), ""green""); auto_log_info(""Found "" + personMatcher.group(2), ""green""); auto_log_info(""Found "" + personMatcher.group(3), ""green""); string generated = """" + i + "":"" + room + "":"" + person + "":"" + job; //Get killer response as well. page = visit_url(""wham.php?ask=killer&visit="" + i, false); matcher killerMatcher = create_matcher(""you (?:ask|say)(?:.*?)

(.*?)(\\\\s*?)"", page); if(killerMatcher.find()) { string killerInfo = killerMatcher.group(1); killerInfo = replace_string(killerInfo, "","", """"); killerInfo = replace_string(killerInfo, "":"", """"); killerInfo = replace_string(killerInfo, ""

"", """"); killerInfo = replace_string(killerInfo, """", """"); killerInfo = replace_string(killerInfo, """", """"); string[int] nameSplit = split_string(person, "" ""); foreach index in nameSplit { killerInfo = replace_string(killerInfo, nameSplit[index], """"); } generated += "":"" + killerInfo; } else { auto_log_info(""Jerkwad '"" + person + ""' won't say anything!"", ""blue""); generated += "":liar""; } set_property(""auto_eggDetective"", generated + "","" + get_property(""auto_eggDetective"")); } } i += 1; } eggData = split_string(get_property(""auto_eggDetective""), "",""); auto_log_info(""Generating goals..."", ""blue""); //At this point we\\'ve visited every place and queried everyone. Now we need to determine who is identifying a killer. //Extract names and jobs boolean[string] personGoals; boolean[string] jobGoals; boolean[string] locationGoals; foreach index in eggData { if(eggData[index] == """") { continue; } string[int] subEgg = split_string(eggData[index], "":""); personGoals[subEgg[2]] = true; jobGoals[subEgg[3]] = true; locationGoals[subEgg[1]] = true; } auto_log_info(""Verifications...."", ""blue""); foreach index in eggData { string[int] subEgg = split_string(eggData[index], "":""); if(count(subEgg) < 4) { continue; } boolean isTruth = true; if(subEgg[4] == ""liar"") { isTruth = false; } if(subEgg[4] != ""liar"") { boolean hasAnyone = false; string oldValue = subEgg[4]; foreach goal in personGoals { matcher goalMatcher = create_matcher(""\\\\b"" + goal + ""\\\\b"",subEgg[4]); if(goalMatcher.find()) { hasAnyone = true; subEgg[4] = goal; } } foreach goal in jobGoals { matcher goalMatcher = create_matcher(""\\\\b"" + goal + ""\\\\b"",subEgg[4]); if(goalMatcher.find()) { hasAnyone = true; subEgg[4] = goal; } } string replaceString = ""liar""; if(hasAnyone) { replaceString = subEgg[4]; } string temp = get_property(""auto_eggDetective""); temp = replace_string(temp, oldValue, replaceString); set_property(""auto_eggDetective"", temp); eggData = split_string(get_property(""auto_eggDetective""), "",""); subEgg[4] = replaceString; } if(subEgg[4] != ""liar"") { auto_log_info(subEgg[2] + "" is accusing: "" + subEgg[4], ""blue""); //Now we need to determine if they are lying or not. int currentLocation = to_int(subEgg[0]); page = visit_url(""wham.php?visit="" + currentLocation, false); int otherPerson = 1; boolean corrupted = false; string locationName = subEgg[1]; while((otherPerson <= 9) && isTruth) { if(currentLocation == otherPerson) { otherPerson += 1; continue; } string[int] currentEgg; foreach index in eggData { string[int] subEgg = split_string(eggData[index], "":""); if(to_int(subEgg[0]) == otherPerson) { currentEgg = subEgg; } } page = visit_url(""wham.php?ask="" + otherPerson + ""&visit="" + currentLocation, false); matcher killerMatcher = create_matcher(""you (?:ask|say)(?:.*?)

(.*?)(\\\\s*?)"", page); if(killerMatcher.find()) { string killerInfo = killerMatcher.group(1); //We are asking to attach a job to the person. They might not know. //We need to look up the particular person. boolean exact = false; int count = 0; foreach goal in jobGoals { matcher goalMatcher = create_matcher(""\\\\b"" + goal + ""\\\\b"",killerInfo); if(goalMatcher.find()) { if(goal != currentEgg[3]) { auto_log_info(""Asked about "" + currentEgg[2] + "","" + currentEgg[3] + "" and was told: "" + goal, ""red""); count += 1; } else { exact = true; } } } if(!exact && (count != 0)) { isTruth = false; } exact = false; count = 0; foreach goal in locationGoals { matcher goalMatcher = create_matcher(""\\\\b"" + goal + ""\\\\b"",killerInfo); if(goalMatcher.find()) { if(goal != currentEgg[1]) { auto_log_info(""Asked about "" + currentEgg[2] + "","" + currentEgg[1] + "" and was told: "" + goal, ""red""); count += 1; } else { exact = true; } } } if(!exact && (count != 0)) { if(killerInfo == locationName) { if(corrupted) { auto_log_info(""Doubly corrupted possible truth teller. This person is probably correct."", ""blue""); return false; } auto_log_info(""Corrupted truth teller? Going to retry...."", ""red""); corrupted = true; continue; } isTruth = false; } } //if still isTruth, we can try the relative questions if so desired. //Really, we should check the list of accused and try to uniquify it. otherPerson += 1; corrupted = false; } } if(subEgg[4] == ""liar"") { isTruth = false; } if(isTruth) { auto_log_info(subEgg[2] + "" is accusing: "" + subEgg[4] + "" and may be telling the truth!"", ""blue""); //Find person they are accusing and do it. string[int] currentEgg; foreach index in eggData { string[int] subsubEgg = split_string(eggData[index], "":""); if((subsubEgg[2] == subEgg[4]) || (subsubEgg[3] == subEgg[4])) { auto_log_info(""Accusation against: "" + subsubEgg[2], ""blue""); page = visit_url(""wham.php?visit="" + subsubEgg[0], false); eggMatcher = create_matcher(""You have been on this case for (\\\\d+) minute(?:s?)"", page); if(eggMatcher.find()) { auto_log_info(""On the case for "" + eggMatcher.group(1) + "" minutes..."", ""green""); } page = visit_url(""wham.php?visit="" + subsubEgg[0] + ""&accuse="" + subsubEgg[0], false); matcher pensionMatcher = create_matcher(""been awarded (\\\\d+) cop dollars"", page); if(pensionMatcher.find()) { auto_log_info(""Received a pension of "" + pensionMatcher.group(1) + "" cop dollars."", ""green""); } set_property(""auto_eggDetective"", """"); return true; } } } } set_property(""auto_eggDetective"", get_property(""auto_eggDetective"") + ""solved""); return false; } return true; } boolean expectGhostReport() { if(total_turns_played() >= get_property(""nextParanormalActivity"").to_int()) { if(total_turns_played() > get_property(""nextParanormalActivity"").to_int()) { string page = visit_url(""charpane.php""); matcher myGhost = create_matcher(""(?:.*?)(.*?)"", page); if(myGhost.find()) { location goal = to_location(myGhost.group(1)); set_property(""ghostLocation"", goal); set_property(""questPAGhost"", ""started""); } } #

Investigate the paranormal activity reported at The Haunted Conservatory.
if(get_property(""questPAGhost"") == ""unstarted"") { return true; } } return false; } boolean haveGhostReport() { if(get_property(""questPAGhost"") == ""unstarted"") { return false; } if((get_property(""questPAGhost"") == ""started"") && (get_property(""ghostLocation"") != """")) { return true; } return false; } boolean LX_ghostBusting() { if(!possessEquipment($item[Protonic Accelerator Pack])) { return false; } if(get_property(""questPAGhost"") == ""unstarted"") { if(!expectGhostReport()) { return false; } if(get_property(""questPAGhost"") == ""unstarted"") { return false; } } location goal = get_property(""ghostLocation"").to_location(); boolean canAttempt = have_equipped($item[Protonic Accelerator Pack]); if(possessEquipment($item[Protonic Accelerator Pack]) && can_equip($item[Protonic Accelerator Pack])) { canAttempt = true; } if((goal != $location[none]) && canAttempt) { if((auto_my_path() == ""Community Service"") && (my_daycount() == 1) && (goal == $location[The Spooky Forest])) { return false; } useCocoon(); auto_log_info(""Ghost busting time! At: "" + get_property(""ghostLocation""), ""blue""); boolean newbieFail = false; if(goal == $location[The Skeleton Store]) { startMeatsmithSubQuest(); if(internalQuestStatus(""questM23Meatsmith"") == -1) { newbieFail = true; } else if(internalQuestStatus(""questM23Meatsmith"") == 0) { if(item_amount($item[Skeleton Store Office Key]) > 0) { set_property(""choiceAdventure1060"", 4); } else { set_property(""choiceAdventure1060"", 1); } } else { set_property(""choiceAdventure1060"", 2); } } if(item_amount($item[Check to the Meatsmith]) > 0) { string temp = visit_url(""shop.php?whichshop=meatsmith""); temp = visit_url(""choice.php?pwd=&whichchoice=1059&option=2""); return true; } if(goal == $location[Madness Bakery]) { startArmorySubQuest(); if(internalQuestStatus(""questM25Armorer"") == -1) { newbieFail = true; } else if(internalQuestStatus(""questM25Armorer"") <= 1) { set_property(""choiceAdventure1061"", 1); } else { set_property(""choiceAdventure1061"", 5); } } if(item_amount($item[no-handed pie]) > 0) { string temp = visit_url(""shop.php?whichshop=armory""); temp = visit_url(""choice.php?pwd=&whichchoice=1065&option=2""); return true; } if(goal == $location[The Overgrown Lot]) { //Meh. startGalaktikSubQuest(); if(internalQuestStatus(""questM24Doc"") == -1) { newbieFail = true; } else if(get_property(""questM24Doc"") != ""finished"") { set_property(""choiceAdventure1062"", 1); } else { set_property(""choiceAdventure1062"", 4); } } if((item_amount($item[Swindleblossom]) >= 3) && (item_amount($item[Fraudwort]) >= 3) && (item_amount($item[Shysterweed]) >= 3)) { string temp = visit_url(""shop.php?whichshop=doc""); temp = visit_url(""shop.php?whichshop=doc&action=talk""); temp = visit_url(""choice.php?pwd=&whichchoice=1064&option=2""); return true; } if((goal == $location[The Batrat and Ratbat Burrow]) && (internalQuestStatus(""questL04Bat"") < 1)) { return false; } if((goal == $location[Cobb\\'s Knob Laboratory]) && (item_amount($item[Cobb\\'s Knob Lab Key]) == 0)) { return false; } if((goal == $location[Lair of the Ninja Snowmen]) && ((get_property(""auto_trapper"") != ""yeti"") && (get_property(""auto_trapper"") != ""finished""))) { return false; } if((goal == $location[The VERY Unquiet Garves]) && (get_property(""auto_crypt"") != ""finished"")) { return false; } if(goal == $location[The Castle in the Clouds in the Sky (Top Floor)]) { if(get_property(""auto_castleground"") != ""finished"") { return false; } if(L10_topFloor() || L10_holeInTheSkyUnlock()) { return true; } } if(goal == $location[Lair of the Ninja Snowmen]) { if((item_amount($item[Ninja Rope]) == 0) || (item_amount($item[Ninja Carabiner]) == 0) || (item_amount($item[Ninja Crampons]) == 0)) { if(L8_trapperYeti()) { return true; } } } if((goal == $location[The Red Zeppelin]) && (internalQuestStatus(""questL11Ron"") < 3)) { return false; } if((goal == $location[The Hidden Park]) && (get_property(""auto_hiddenunlock"") == ""finished"")) { return false; } item replaceAcc3 = $item[none]; if(goal == $location[Inside The Palindome]) { if(!possessEquipment($item[Talisman O\\' Namsilat])) { return false; } if(equipped_item($slot[acc3]) != $item[Talisman O\\' Namsilat]) { replaceAcc3 = equipped_item($slot[acc3]); autoEquip($slot[acc3], $item[Talisman O\\' Namsilat]); } } if(newbieFail) { auto_log_critical(""Can't bust that ghost, we don't feel good!!"", ""blue""); abort(""Ghost busting failure, this should not happen""); set_property(""questPAGhost"", ""unstarted""); set_property(""ghostLocation"", """"); return false; } if((equipped_item($slot[Back]) != $item[Protonic Accelerator Pack]) && can_equip($item[Protonic Accelerator Pack])) { autoEquip($slot[Back], $item[Protonic Accelerator Pack]); } auto_log_info(""Time to bust some ghosts!!!"", ""green""); boolean advVal = autoAdv(goal); if(replaceAcc3 != $item[none]) { autoEquip($slot[acc3], replaceAcc3); } if(have_effect($effect[Beaten Up]) == 0) { set_property(""questPAGhost"", ""unstarted""); set_property(""ghostLocation"", """"); } return advVal; } return false; } boolean timeSpinnerGet(string goal) { goal = to_lower_case(goal); if(!($strings[booze, drink, food, memory, history, ears, mall, none] contains goal)) { return false; } if($strings[booze, drink, food, memory, history, ears, mall] contains goal) { if(get_property(""_timeSpinnerReplicatorUsed"").to_boolean()) { return false; } } if((goal == ""booze"") && (get_property(""timeSpinnerMedals"").to_int() < 5)) { return false; } if((goal == ""drink"") && (get_property(""timeSpinnerMedals"").to_int() < 5)) { return false; } if((goal == ""food"") && (get_property(""timeSpinnerMedals"").to_int() < 15)) { return false; } if((goal == ""history"") && (get_property(""timeSpinnerMedals"").to_int() < 10)) { return false; } if((goal == ""memory"") && (get_property(""timeSpinnerMedals"").to_int() < 20)) { return false; } if(is_unrestricted($item[Time-Spinner]) && (item_amount($item[Time-Spinner]) > 0) && (get_property(""_timeSpinnerMinutesUsed"").to_int() <= 8)) { if(svn_info(""Ezandora-Far-Future-branches-Release"").last_changed_rev > 0) { //Required by dependencies cli_execute(""FarFuture "" + goal); return true; } return false; } return false; } boolean timeSpinnerConsume(item goal) { if(is_unrestricted($item[Time-Spinner]) && (item_amount($item[Time-Spinner]) > 0) && (get_property(""_timeSpinnerMinutesUsed"").to_int() <= 7)) { string temp = visit_url(""inv_use.php?pwd=&which=3&whichitem=9104""); if(get_property(""_timeSpinnerMinutesUsed"").to_int() <= 7) { temp = visit_url(""choice.php?pwd=&whichchoice=1195&option=2""); temp = visit_url(""choice.php?pwd=&whichchoice=1197&option=1&foodid="" + to_int(goal)); } } return false; } boolean timeSpinnerAdventure() { return timeSpinnerAdventure(""""); } boolean timeSpinnerAdventure(string option) { if(is_unrestricted($item[Time-Spinner]) && (item_amount($item[Time-Spinner]) > 0) && (get_property(""_timeSpinnerMinutesUsed"").to_int() <= 9)) { string temp = visit_url(""inv_use.php?pwd=&which=3&whichitem=9104""); if(get_property(""_timeSpinnerMinutesUsed"").to_int() <= 9) { string[int] pages; pages[0] = ""inv_use.php?pwd=&which=3&whichitem=9104""; pages[1] = ""choice.php?pwd=&whichchoice=1195&option=3""; if(autoAdvBypass(0, pages, $location[Noob Cave], option)) {} return true; } } return false; } boolean timeSpinnerCombat(monster goal) { return timeSpinnerCombat(goal, """"); } boolean timeSpinnerCombat(monster goal, string option) { if(is_unrestricted($item[Time-Spinner]) && (item_amount($item[Time-Spinner]) > 0) && (get_property(""_timeSpinnerMinutesUsed"").to_int() <= 7)) { string temp = visit_url(""inv_use.php?pwd=&which=3&whichitem=9104""); if(get_property(""_timeSpinnerMinutesUsed"").to_int() <= 7) { string[int] pages; pages[0] = ""inv_use.php?pwd=&which=3&whichitem=9104""; pages[1] = ""choice.php?pwd=&whichchoice=1195&option=1""; pages[2] = ""choice.php?pwd=&whichchoice=1196&option=1&monid="" + goal.id; if(autoAdvBypass(0, pages, $location[Noob Cave], option)) { handleTracker(goal, $item[Time-Spinner], ""auto_copies""); } else { if(get_property(""lastEncounter"") == ""Travel to a Recent Fight"") { string temp = visit_url(""choice.php?pwd&whichchoice=1196&option=2""); } else { abort(""Time-Spinner combat failed and we were unable to leave the Time-Spinner""); } return false; } return true; } } return false; } boolean rethinkingCandyList() { boolean[effect] synthesis = $effects[Synthesis: Hot, Synthesis: Cold, Synthesis: Pungent, Synthesis: Scary, Synthesis: Greasy, Synthesis: Strong, Synthesis: Smart, Synthesis: Cool, Synthesis: Hardy, Synthesis: Energy, Synthesis: Greed, Synthesis: Collection, Synthesis: Movement, Synthesis: Learning, Synthesis: Style]; foreach eff in synthesis { auto_log_info(""Trying effect: "" + eff + "": "" + string_modifier(eff, ""Modifiers"") , ""orange""); rethinkingCandy(eff, true); } return true; } boolean rethinkingCandy(effect acquire) { return rethinkingCandy(acquire, false); } boolean rethinkingCandy(effect acquire, boolean simulate) { if(!have_skill($skill[Sweet Synthesis]) && !simulate) { return false; } if((spleen_left() == 0) && !simulate) { return false; } boolean[effect] synthesisList = $effects[Synthesis: Hot, Synthesis: Cold, Synthesis: Pungent, Synthesis: Scary, Synthesis: Greasy, Synthesis: Strong, Synthesis: Smart, Synthesis: Cool, Synthesis: Hardy, Synthesis: Energy, Synthesis: Greed, Synthesis: Collection, Synthesis: Movement, Synthesis: Learning, Synthesis: Style]; effect[int] synthesis = List(synthesisList); if(!(synthesisList contains acquire)) { return false; } int maxprice = 2500; if(get_property(""auto_maxCandyPrice"").to_int() != 0) { maxprice = get_property(""auto_maxCandyPrice"").to_int(); } item[int] simpleList; item[int] complexList; foreach it in $items[] { if(it.candy && (item_amount(it) > 0) && (auto_mall_price(it) <= maxprice) && it.tradeable) { if(it.candy_type == ""simple"") { simpleList[count(simpleList)] = it; } else if(it.candy_type == ""complex"") { complexList[count(complexList)] = it; } } } sort simpleList by auto_mall_price(value); sort complexList by auto_mall_price(value); item[int] simple = List(simpleList); item[int] complex = List(complexList); int bestCost = 2 * maxprice; item bestFirst = $item[none]; item bestSecond = $item[none]; if($effects[Synthesis: Hot, Synthesis: Cold, Synthesis: Pungent, Synthesis: Scary, Synthesis: Greasy] contains acquire) { int goal = ListFind(synthesis, acquire) % 5; for(int i=0; i 1) { startNextIndex = i; } for(int j=startNextIndex; j 1) { startNextIndex = i; } for(int j=startNextIndex; j""); } last_was_indention = contains_text(line, ""class=\\""r_indention\\""""); building_line.append(line); first = false; } subentry.entries[i] = to_string(building_line); } } Record ChecklistGeneratedEntryHTML { buffer out; boolean small_enough_for_showhide_to_ignore; string abridged_header_text; }; ChecklistGeneratedEntryHTML ChecklistGenerateEntryHTMLFull(ChecklistEntry entry, ChecklistSubentry [int] subentries, string anchor_url, boolean setting_use_holding_containers_per_subentry) { Vec2i max_image_dimensions_large = Vec2iMake(__setting_image_width_large, 75); Vec2i max_image_dimensions_medium = Vec2iMake(__setting_image_width_medium, 50); Vec2i max_image_dimensions_small = Vec2iMake(__setting_image_width_small, 50); if (__setting_small_size_uses_full_width) max_image_dimensions_small = Vec2iMake(__setting_image_width_small,__setting_image_width_small); boolean outputting_anchor = anchor_url != """"; boolean outputting_as_anchor = anchor_url != """"; string [string] main_containers_base_map; if (outputting_as_anchor) main_containers_base_map = mapMake(""target"", ""mainpane"", ""href"", entry.url, ""class"", ""r_a_undecorated""); string anchor_prefix_html = """"; //HTMLGenerateTagPrefix(""a"", main_containers_base_map); string main_container_tag = ""div""; if (outputting_as_anchor) main_container_tag = ""a""; ChecklistGeneratedEntryHTML final_result; buffer result; if (true) { buffer image_container; if (outputting_anchor && !__setting_entire_area_clickable) image_container.append(anchor_prefix_html); image_container.append(KOLImageGenerateImageHTML(entry.image_lookup_name, true, max_image_dimensions_large, ""r_cl_image_container_large"")); image_container.append(KOLImageGenerateImageHTML(entry.image_lookup_name, true, max_image_dimensions_medium, ""r_cl_image_container_medium"")); if (!__setting_small_size_uses_full_width) image_container.append(KOLImageGenerateImageHTML(entry.image_lookup_name, true, max_image_dimensions_small, ""r_cl_image_container_small"")); if (outputting_anchor && !__setting_entire_area_clickable) image_container.append(""""); //result.HTMLAppendDivOfClass(image_container, ""r_cl_l_left""); string [string] cl_l_left_map = main_containers_base_map.mapCopy(); cl_l_left_map[""class""] += "" r_cl_l_left""; result.HTMLAppendTagPrefix(main_container_tag, cl_l_left_map); result.append(image_container); result.HTMLAppendTagSuffix(main_container_tag); } //else //result.HTMLAppendDivOfClass(KOLImageGenerateImageHTML(entry.image_lookup_name, true, max_image_dimensions_large), ""r_cl_l_left""); //result.HTMLAppendTagPrefix(""div"", ""class"", ""r_cl_l_right_container""); string [string] r_cl_l_right_container = main_containers_base_map.mapCopy(); r_cl_l_right_container[""class""] += "" r_cl_l_right_container""; result.HTMLAppendTagPrefix(main_container_tag, r_cl_l_right_container); if (outputting_anchor && !__setting_entire_area_clickable) result.append(anchor_prefix_html); //internal_processing_data //if (entry.internal_processing_data contains ""content_id"") //r_cl_l_right_content_map[""data-content-ids""] = entry.internal_processing_data[""content_id""]; result.HTMLAppendTagPrefix(""div"", ""class"", ""r_cl_l_right_content""); if (__setting_small_size_uses_full_width) { result.append(KOLImageGenerateImageHTML(entry.image_lookup_name, true, max_image_dimensions_small, ""r_cl_image_container_small"")); result.HTMLAppendTagWrap(""div"", """", mapMake(""class"", ""r_small_float_indention"", ""style"", ""height: "" + __kol_image_generate_image_html_return_final_size.y + ""px;"")); //result.HTMLAppendDivOfClass("""", ""r_small_float_indention""); //  to have it display. hack } string [string] hardcoded_combination_tag_descriptions = { ""free instakill"":""Free instant kills"", ""daily free fight"":""Daily free fights"", ""free banish"":""Free banishes"", ""emotion chip combat"":""Emotion chip"", ""banish"":""Turn-costing banishes"", ""zutara"":""Fortune Teller"", ""telegraph skill"":"""", ""consumption junction, what's your function?"":""Consumption space"", }; buffer abridged_buffer; //int approximate_subtext_height = 0; boolean first = true; int approximate_lines = subentries.count(); foreach j in subentries { ChecklistSubentry subentry = subentries[j]; if (subentry.header == """") continue; string subheader = subentry.header; boolean indent_this_entry = false; if (!first && entry.should_indent_after_first_subentry) { indent_this_entry = true; } if (indent_this_entry) result.HTMLAppendTagPrefix(""div"", ""class"", ""r_indention""); //internal_processing_data_subentry_content_id if (true) { //result.append(HTMLGenerateSpanOfClass(subheader, ""r_cl_subheader"")); string [string] subheader_map = mapMake(""class"", ""r_cl_subheader""); if (entry.internal_processing_data_subentry_content_id.count() > 0) subheader_map[""data-content-id""] = entry.internal_processing_data_subentry_content_id[j]; result.HTMLAppendTagPrefix(""span"", subheader_map); result.append(subheader); result.HTMLAppendTagSuffix(""span""); if (first) { abridged_buffer.HTMLAppendTagPrefix(""span"", ""class"", ""r_cl_subheader_abridged""); string core_text = subheader; if (entry.abridged_header != """") { core_text = entry.abridged_header; } else if (entry.combination_tag != """" && subentries.count() > 1) { if (hardcoded_combination_tag_descriptions contains entry.combination_tag) { if (hardcoded_combination_tag_descriptions[entry.combination_tag] != """") { core_text = hardcoded_combination_tag_descriptions[entry.combination_tag]; } } else { core_text = entry.combination_tag.capitaliseFirstLetter(); } } final_result.abridged_header_text = core_text.entity_encode(); abridged_buffer.append(core_text); abridged_buffer.HTMLAppendTagSuffix(""span""); } } string indention_class = ""r_indention""; if (__setting_small_size_uses_full_width) indention_class = ""r_indention_not_small""; if (true) { string [string] indention_map = mapMake(""class"", indention_class); if (entry.internal_processing_data_subentry_content_id.count() > 0) indention_map[""data-content-id""] = entry.internal_processing_data_subentry_content_id[j]; result.HTMLAppendTagPrefix(""div"", indention_map); } approximate_lines += subentry.modifiers.count(); approximate_lines += subentry.entries.count(); if (subentry.modifiers.count() > 0) result.append(ChecklistGenerateModifierSpan(listJoinComponents(subentry.modifiers, "", ""))); if (subentry.entries.count() > 0) { //approximate_subtext_height += subentry.entries.count(); int intra_k = 0; if (setting_use_holding_containers_per_subentry) result.HTMLAppendTagPrefix(""div"", ""class"", ""r_cl_holding_container""); //HRs while (intra_k < subentry.entries.count()) { if (intra_k > 0) { result.append(""
""); } string line = subentry.entries[listKeyForIndex(subentry.entries, intra_k)]; //if (line.contains_text(""
"") || line.contains_text(""
"")) //approximate_subtext_height += 1; //if (line.contains_text(""""); } result.append(""
""); if (indent_this_entry) result.append(""
""); first = false; } result.append(""""); //r_cl_l_right_content result.HTMLAppendTagPrefix(""div"", ""class"", ""r_cl_l_right_content_abridged""); result.append(abridged_buffer); result.append(""""); //r_cl_l_right_content_abridged if (outputting_anchor && !__setting_entire_area_clickable) result.append(""""); result.HTMLAppendTagSuffix(main_container_tag); //r_cl_l_right_container if (!__use_flexbox_on_checklists) result.HTMLAppendDivOfClass("""", ""r_end_floating_elements""); //stop floating final_result.out = result; final_result.small_enough_for_showhide_to_ignore = approximate_lines <= 1; //approximate_subtext_height <= 1; //final_result.small_enough_for_showhide_to_ignore = false; return final_result; } buffer ChecklistGenerateEntryHTML(ChecklistEntry entry, ChecklistSubentry [int] subentries, string anchor_url, boolean setting_use_holding_containers_per_subentry) { return ChecklistGenerateEntryHTMLFull(entry, subentries, anchor_url, setting_use_holding_containers_per_subentry).out; } buffer ChecklistGenerate(Checklist cl, boolean output_borders) { ChecklistEntry [int] entries = cl.entries; //Combine entries with identical combination tags: ChecklistEntry [string] combination_tag_entries; foreach key, entry in entries { if (entry.combination_tag == """") continue; if (entry.only_show_as_extra_important_pop_up) continue; //do not support this feature with this if (entry.subentries_on_mouse_over.count() > 0) continue; if (entry.container_div_attributes.count() > 0) continue; if (!(combination_tag_entries contains entry.combination_tag)) { entry.importance_level -= 1; //combined entries gain a hack; a level above everything else combination_tag_entries[entry.combination_tag] = entry; continue; } ChecklistEntry master_entry = combination_tag_entries[entry.combination_tag]; if (entry.should_highlight) master_entry.should_highlight = true; if (master_entry.url == """" && entry.url != """") master_entry.url = entry.url; master_entry.importance_level = min(master_entry.importance_level, entry.importance_level - 1); foreach key, subentry in entry.subentries { master_entry.subentries.listAppend(subentry); //Bring over internal_processing_data_subentry_content_id: master_entry.internal_processing_data_subentry_content_id[master_entry.subentries.count() - 1] = entry.internal_processing_data_subentry_content_id[key]; } foreach key, value in entry.internal_processing_data { if (!(master_entry.internal_processing_data contains key)) master_entry.internal_processing_data[key] = value; else { master_entry.internal_processing_data[key] += ""|"" + value; } } remove entries[key]; } //Sort by importance: sort entries by value.importance_level; if (true) { //Format subentries: foreach i in entries { ChecklistEntry entry = entries[i]; foreach j in entry.subentries { ChecklistFormatSubentry(entry.subentries[j]); } foreach j in entry.subentries_on_mouse_over { ChecklistFormatSubentry(entry.subentries_on_mouse_over[j]); } } } boolean skip_first_entry = false; string special_subheader = """"; if (entries.count() > 0) { if (entries[0].image_lookup_name == ""special subheader"") { if (entries[0].subentries.count() > 0) { special_subheader = entries[0].subentries[0].header; skip_first_entry = true; } } } buffer result; if (output_borders) result.HTMLAppendDivOfClass("""", ""r_cl_inter_spacing_divider""); //spacing if (!cl.disable_generating_id) result.HTMLAppendTagWrap(""a"", """", mapMake(""id"", HTMLConvertStringToAnchorID(cl.title), ""class"", ""r_cl_internal_anchor"")); string [string] main_container_map; main_container_map[""class""] = ""r_cl_checklist_container""; if (!cl.disable_generating_id) main_container_map[""id""] = HTMLConvertStringToAnchorID(cl.title + "" checklist container""); main_container_map[""data-title""] = cl.title; if (!output_borders) main_container_map[""style""] = ""border:0px;""; result.HTMLAppendTagPrefix(""div"", main_container_map); result.HTMLAppendTagWrap(""div"", cl.title, mapMake(""class"", ""r_cl_header r_clickable"", ""onmousedown"", ""checklistHeaderButtonClicked(window.event)"")); if (special_subheader != """") result.append(ChecklistGenerateModifierSpan(special_subheader)); int starting_intra_i = 0; if (skip_first_entry) starting_intra_i = 1; int intra_i = 0; int entries_output = 0; boolean last_was_highlighted = false; int current_mouse_over_id = 1; foreach i in entries { if (intra_i < starting_intra_i) { intra_i += 1; continue; } ChecklistEntry entry = entries[i]; if (intra_i > starting_intra_i && !__use_flexbox_on_checklists) { boolean next_is_highlighted = false; if (entry.should_highlight) next_is_highlighted = true; string class_name = ""r_cl_hr""; if (last_was_highlighted || next_is_highlighted) class_name = ""r_cl_hr_extended""; result.HTMLAppendTagPrefix(""hr"", ""class"", class_name); } if (__use_table_based_layouts) __setting_entire_area_clickable = true; boolean outputting_anchor = false; buffer anchor_prefix_html; if (entry.url != """") { anchor_prefix_html = HTMLGenerateTagPrefix(""a"", mapMake(""target"", ""mainpane"", ""href"", entry.url, ""class"", ""r_a_undecorated"")); outputting_anchor = true; } if (outputting_anchor && __setting_entire_area_clickable) result.append(anchor_prefix_html); boolean setting_use_holding_containers_per_subentry = true; Vec2i max_image_dimensions_large = Vec2iMake(__setting_image_width_large, 75); Vec2i max_image_dimensions_medium = Vec2iMake(__setting_image_width_medium, 50); Vec2i max_image_dimensions_small = Vec2iMake(__setting_image_width_small, 50); if (__setting_small_size_uses_full_width) max_image_dimensions_small = Vec2iMake(__setting_image_width_small,__setting_image_width_small); string container_class = ""r_cl_l_container""; if (entry.should_highlight) container_class += "" r_cl_l_container_highlighted""; last_was_highlighted = entry.should_highlight; ChecklistGeneratedEntryHTML generated_entry = ChecklistGenerateEntryHTMLFull(entry, entry.subentries, entry.url, setting_use_holding_containers_per_subentry); buffer generated_subentry_html = generated_entry.out; if (generated_entry.small_enough_for_showhide_to_ignore) container_class += "" r_cl_l_container_always_minimised""; if (entry.subentries_on_mouse_over.count() > 0) { buffer generated_mouseover_subentry_html = ChecklistGenerateEntryHTML(entry, entry.subentries_on_mouse_over, entry.url, setting_use_holding_containers_per_subentry); //Can't properly escape, so generate two no-show divs and replace them as needed: //We could just have a div that shows up when we mouse over... //This is currently very buggy. entry.container_div_attributes[""onmouseenter""] = ""event.currentTarget.innerHTML = document.getElementById('r_temp_o"" + current_mouse_over_id + ""').innerHTML""; entry.container_div_attributes[""onmouseleave""] = ""event.currentTarget.innerHTML = document.getElementById('r_temp_l"" + current_mouse_over_id + ""').innerHTML""; result.HTMLAppendTagPrefix(""div"", ""id"", ""r_temp_o"" + current_mouse_over_id, ""style"", ""display:none""); result.append(generated_mouseover_subentry_html); result.HTMLAppendTagSuffix(""div""); result.HTMLAppendTagPrefix(""div"", ""id"", ""r_temp_l"" + current_mouse_over_id, ""style"", ""display:none""); result.append(generated_subentry_html); result.HTMLAppendTagSuffix(""div""); current_mouse_over_id += 1; } entry.container_div_attributes[""class""] += (entry.container_div_attributes contains ""class"" ? "" "" : """") + container_class; //string entry_stable_id = entry.internal_generation_identifier; string entry_stable_id = entry.universal_id; if (entry.combination_tag != """") entry_stable_id = entry.combination_tag; if (entry_stable_id != """") entry.container_div_attributes[""data-stable-id""] = entry_stable_id; else if (my_id() == 1557284) print_html(""warning: no stable id for "" + entry.subentries[0].header); //usually caused by a lack of checklistentrymake //if (generated_entry.abridged_header_text != """") //entry.container_div_attributes[""data-abridged-text""] = generated_entry.abridged_header_text; if (entry.internal_processing_data contains ""content_id"") entry.container_div_attributes[""data-content-ids""] = entry.internal_processing_data[""content_id""]; result.HTMLAppendTagPrefix(""div"", entry.container_div_attributes); /*if (__use_table_based_layouts) { //table-based layout: result.append(""""); result.HTMLAppendTagWrap(""td"", """", mapMake(""style"", ""width:"" + __setting_indention_width + "";"")); result.append(""""); result.HTMLAppendTagPrefix(""td"", ""style"", ""text-align:left; vertical-align:top""); boolean first = true; foreach j in entry.subentries { ChecklistSubentry subentry = entry.subentries[j]; if (subentry.header == """") continue; string subheader = subentry.header; boolean indent_this_entry = false; if (first) { first = false; } else if (entry.should_indent_after_first_subentry) { indent_this_entry = true; } if (indent_this_entry) result.HTMLAppendTagPrefix(""div"", ""class"", ""r_indention""); result.append(""
""); result.HTMLAppendTagPrefix(""td"", ""style"", ""min-width:"" + __setting_image_width_large + ""px; max-width:"" + __setting_image_width_large + ""px; width:"" + __setting_image_width_large + ""px;vertical-align:top; text-align: center;""); result.append(KOLImageGenerateImageHTML(entry.image_lookup_name, true, max_image_dimensions_large)); result.append(""
""); result.append(""""); result.HTMLAppendTagWrap(""td"", """", mapMake(""style"", ""width:"" + __setting_indention_width + "";"")); result.append(""""); result.append(""
""); result.append(HTMLGenerateSpanOfClass(subheader, ""r_cl_subheader"")); result.append(""
""); if (subentry.modifiers.count() > 0) result.append(ChecklistGenerateModifierSpan(listJoinComponents(subentry.modifiers, "", "") + ""
"")); if (subentry.entries.count() > 0) { int intra_k = 0; while (intra_k < subentry.entries.count()) { if (intra_k > 0) result.append(""
""); string line = subentry.entries[listKeyForIndex(subentry.entries, intra_k)]; line = HTMLGenerateDivOfClass(line, ""r_cl_holding_container""); //For nested HRs result.append(line); intra_k += 1; } } result.append(""
""); if (indent_this_entry) result.append(""""); } result.append(""""); result.append(""""); } else*/ if (true) { if (__use_flexbox_on_checklists && __enable_showhide_feature) { //int approximate_height = generated_subentry_html.split_string(""<"").count(); //r_cl_holding_container string [string] showhide_map; showhide_map[""class""] = ""r_cl_l_left_showhide""; if (generated_entry.small_enough_for_showhide_to_ignore)// || !output_borders) { showhide_map[""class""] += "" r_cl_l_left_showhide_blank""; } else { showhide_map[""class""] += "" r_clickable""; showhide_map[""onmousedown""] = ""showhideButtonClicked(window.event)""; } result.append(HTMLGenerateTagWrap(""div"", "" "", showhide_map)); //result.append(""
"" + approximate_height + ""
""); } //div-based layout: //result.append(ChecklistGenerateEntryHTML(entry, entry.subentries, entry.url, setting_use_holding_containers_per_subentry)); result.append(generated_subentry_html); } result.append(""""); if (outputting_anchor && __setting_entire_area_clickable) result.append(""""); intra_i += 1; entries_output += 1; } result.append(""""); if (output_borders) result.HTMLAppendDivOfClass("""", ""r_cl_inter_spacing_divider""); return result; } buffer ChecklistGenerate(Checklist cl) { return ChecklistGenerate(cl, true); } Record ChecklistCollection { Checklist [string] checklists; }; //NOTE: WILL DESTRUCTIVELY EDIT CHECKLISTS GIVEN TO IT //mostly because there's no easy way to copy an object in ASH //without manually writing a copy function and insuring it is synched Checklist [int] ChecklistCollectionMergeWithLinearList(ChecklistCollection collection, Checklist [int] other_checklists) { Checklist [int] result; boolean [string] seen_titles; foreach key, checklist in other_checklists { seen_titles[checklist.title] = true; result.listAppend(checklist); } foreach key, checklist in collection.checklists { if (seen_titles contains checklist.title) { foreach key, checklist2 in result { if (checklist2.title == checklist.title) { checklist2.entries.listAppendList(checklist.entries); break; } } } else { result.listAppend(checklist); } } return result; } Checklist lookup(ChecklistCollection checklists, string name) { if (checklists.checklists contains name) return checklists.checklists[name]; Checklist c = ChecklistMake(); c.title = name; checklists.checklists[c.title] = c; return c; } //Preferred use. Returns entry you just added: //Example usage: //checklists.add(C_RESOURCES, ChecklistEntryMake(etc)); //I suppose we could do... //checklists.add(C_RESOURCES).setURL(""inventory.php"").setImage(""__item disco ball"").addSubentries(subentries).setShouldHighlightIfAdventuringAtLocation($location[noob cave]); //What would be nice if we could do something like this: //checklists.add(C_RESOURCES, {url:""inventory.php"", image:""__item disco ball"", subentry:{title:""Important Title"", description:description}, highlightLocation:$location[noob cave]}); //and location: doing both url: and highlightLocation: //checklists.add(C_RESOURCES, {location:$location[noob cave], item:$item[disco ball], subentry:{title:""Important Title"", description:description}}); //with some prefix to make that work without quotes //or better //checklists.add(C_RESOURCES, {location:$location[noob cave], item:$item[disco ball], title:""Important Title"", description:description}); //which just automatically creates a single subentry //But, I don't think mafia's map system is strong enough for that, and functions don't allow tagging arguments like that. Alas. ChecklistEntry add(ChecklistCollection checklists, string collection_name, ChecklistEntry entry) { Checklist c = checklists.lookup(collection_name); return c.entries.listAppend(entry); } //if resupported, needs unique_id /*ChecklistEntry add(ChecklistCollection checklists, string collection_name) { ChecklistEntry entry = ChecklistEntryMake(); Checklist c = checklists.lookup(collection_name); return c.entries.listAppend(entry); }*/ ",12473,False,2216.3738597942665,median "= The Newsboat RSS Feedreader :toc: left :sectnums: :sectanchors: :sectlinks: :nofooter: == Introduction Newsboat is an RSS/Atom feedreader. RSS and Atom are a number of widely-used XML formats to transmit, publish and syndicate articles, for example news or blog articles. Newsboat is designed to be used on text terminals on Unix or Unix-like systems such as GNU/Linux, FreeBSD or macOS. === Platforms Newsboat has been tested on Linux (with glibc and musl-libc), FreeBSD and macOS. NetBSD is currently not supported, due to technical limitations in the `iconv()` implementation. === Why ""Newsboat""? ""Newsboat"" is a play on the name of its ancestor, ""Newsbeuter"". They're spelled quite differently, but sound similar. (""Newsbeuter"" is a pun on German word ""wildbeuter""; ""newsboat"" is an English word.) Newsboats were the vessels that collected and delivered news shuffling between boats in the port. Newsboat the program will collect the news for you, just like its namesakes did back in the day. == Installation === Pre-built binaries Newsboat binaries are available in a number of repositories: // UPDATE README.md IF YOU CHANGE THIS LIST - various Linux and BSD distributions, Homebrew etc.; https://repology.org/project/newsboat[here's a non-exclusive list]; - distribution-independent https://snapcraft.io/docs/installing-snapd[Snap] store: $ sudo snap install newsboat // UPDATE README.md IF YOU CHANGE THIS LIST === From source ==== Download the source code The most up-to-date source code can always be downloaded from the Git repository: $ git clone git://github.com/newsboat/newsboat.git There are also signed release tarballs available from https://newsboat.org/[our website]. ==== Install dependencies Newsboat depends on a number of libraries, which need to be installed before Newsboat can be compiled. Make sure to install the header files as well (on Debian and derivatives, headers are in `-dev` packages, e.g. `libsqlite3-dev`.) // UPDATE README.md IF YOU CHANGE THIS LIST - GCC 4.9 or newer, or Clang 3.6 or newer - Stable https://www.rust-lang.org/en-US/[Rust] and Cargo (Rust's package manager) (1.42.0 or newer; might work with older versions, but we don't check that) - http://www.clifford.at/stfl/[STFL (version 0.21 or newer)] - https://www.sqlite.org/download.html[SQLite3 (version 3.5 or newer)] - https://curl.haxx.se/download.html[libcurl (version 7.21.6 or newer)] - Header files for the SSL library that libcurl uses. You can find out which library that is from the output of `curl --version`; most often that's OpenSSL, sometimes GnuTLS, or maybe something else. - GNU gettext (on systems that don't provide gettext in the libc): ftp://ftp.gnu.org/gnu/gettext/ - https://pkg-config.freedesktop.org/wiki/[pkg-config] - http://xmlsoft.org/downloads.html[libxml2] - https://github.com/json-c/json-c/wiki[json-c (version 0.11 or newer)] - https://asciidoctor.org/[Asciidoctor] (1.5.3 or newer) Developers will also need: - https://github.com/woboq/tr[`xtr` (version 0.1.4 or newer)] (can be installed with `cargo install xtr`) - http://www.ssw.uni-linz.ac.at/coco/[Coco/R for C++], needed to re-generate filter language parser using `regenerate-parser` target. // UPDATE README.md IF YOU CHANGE THIS LIST ==== Compile and install // UPDATE README.md IF YOU CHANGE THIS LIST There are a few different ways: - build inside Docker. For that, check out _doc/docker.md_ in the source tree. Note that the resulting binary might not run outside of that same Docker container if your system doesn't have all the necessary libraries, or if their versions are too old; - build in a chroot: to avoid polluting your system with developer packages, or to avoid upgrading, you might use a tool like https://wiki.debian.org/Debootstrap[`debootstrap`] to create an isolated environment. Once that's done, just build from source as outlined in the next item; - build from source: $ make # pass -jN to use N CPU cores, e.g. -j8 $ sudo make install # install everything under /usr/local + To install to a different directory, pass `prefix` like so: `sudo make prefix=/opt/newsboat install`. + To uninstall, run `sudo make uninstall`. Cross-compilers need to set `CARGO_BUILD_TARGET`; see https://doc.rust-lang.org/cargo/reference/config.html#environment-variables[cargo documentation]. // UPDATE README.md IF YOU CHANGE THIS LIST == First Steps include::chapter-firststeps.asciidoc[] .Configuration Commands [frame=""all"", grid=""all"", format=""dsv"", separator=""||"", options=""header"", cols=""10,15,15l,40,20l""] |====================================================================================================== Configuration Command||Argument(s)||Default||Description||Example include::configcommands-linked.dsv[] |====================================================================================================== [[available-operations]] .<> [frame=""all"", grid=""all"", format=""dsv"", separator=""||"", options=""header"", cols=""20,20,60""] |========================================================================= Operation||Default key||Description include::keycmds-linked.dsv[] |========================================================================= Keys, as used in the bind-key configuration command, use a special syntax. Lowercase keys, uppercase keys and special characters are written literally. The ""Enter"" key is written as `ENTER`, ""Tab"" key as `TAB`, and the ""Esc"" key is written as `ESC`. The function keys ""F1"" to ""F12"" are written as `F1` to `F12`. The ""Space"" key is written as `SPACE`. Key combinations with the ""Ctrl"" key, such as ""Ctrl-R"", are written as `^R`. Please be aware that all Ctrl-related key combinations need to be written in uppercase. The following identifiers for keys are supported: - `ENTER` (Enter key) - `BACKSPACE` (backspace key) - `LEFT` (left cursor) - `RIGHT` (right cursor) - `UP` (up cursor) - `DOWN` (down cursor) - `PPAGE` (page up cursor) - `NPAGE` (page down cursor) - `HOME` (cursor to beginning of list/article) - `END` (cursor to end of list/article) - `ESC` (Esc key) - `TAB` (Tab key) === Example Configuration ---- # a comment max-items 100 # such comments are possible, too browser links show-read-feeds no unbind-key R bind-key ^R reload-all ---- === Using Double Quotes _**TL;DR**: use double quotes for strings that contain spaces or double quotes. Escape double quotes (use `\\""`) and backslashes (use `\\\\`). Don't escape stuff outside of double quotes, and don't use single quotes for quoting — Newsboat doesn't support that._ Many of Newsboat's options expect strings as arguments, be it commands, passwords, dialog titles, URLs etc. Some options even take _multiple_ strings at once. These strings can contain spaces, which might confuse Newsboat since it already uses spaces to separate option names from option arguments. To help Newsboat understand your intent, put such strings into double quotes: browser ""firefox --new-tab %u"" What if you need a double quote inside a string? Escape it with a backslash: ocnews-password ""UnbalancedQuotes\\""AreSoFun!"" And what about the backslash itself? Escape it, too! Suppose you have a program called `my favourite pager`, and you want to view articles with it. Newsboat ultimately passes commands to the shell, and shell expects spaces to be escaped if you want them preserved. But since Newsboat interprets backslashes, you have to add _another_ layer of escaping. Thus, you end up with a command like this: pager ""/usr/bin/my\\\\ favourite\\\\ pager"" === Configuring Colors It is possible to configure custom color settings in newsboat. The basic configuration syntax is: color [ ...] This means that if you configure colors for a certain element, you need to provide a foreground color and a background color as a minimum. The following colors are supported: - `black` - `red` - `green` - `yellow` - `blue` - `magenta` - `cyan` - `white` - `default` - `color`, e.g. `color123` The `default` color means that the terminal's default color will be used. The `color` color name (where `` is a decimal number *not* starting with zero) can be used if your terminal support 256 colors (e.g. `gnome-terminal`, `xterm` with `$TERM` set to `xterm-256color`). Newsboat contains support for 256 color terminals since version 2.1. For a complete chart of colors and their corresponding numbers, please see https://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html[]. Optionally, you can also add one or more attributes. The following attributes are supported: - `standout` - `underline` - `reverse` - `blink` - `dim` - `bold` - `protect` - `invis` Currently, the following elements are supported: - `listnormal`: a normal list item - `listfocus`: the currently selected list item - `listnormal_unread`: an unread list item - `listfocus_unread`: the currently selected and unread list item - `info`: the info bars on top and bottom - `background`: the application background - `article`: the article text - `end-of-text-marker`: filler lines (~) below blocks of text The default color configuration of newsboat looks like this: color background white black color listnormal white black color listfocus yellow blue bold color listnormal_unread magenta black color listfocus_unread magenta blue bold color info yellow blue bold color article white black === Files include::chapter-files.asciidoc[] === Migrating from other RSS Feed Readers It is very likely that you have used other RSS feed readers before. In this case, it is practical to migrate the previous configuration to newsboat. ==== Newsbeuter (automatic migration) Newsboat is a fork of Newsbeuter, so the migration from the latter is partially automated. Simple enough configurations will be transferred without any user intervention, while more complicated ones might require a little tweaking afterwards. To prevent data loss, please check the results before deleting your old configuration. Pay extra attention to files that you <> in your configuration--you'd probably want to manually copy them over to Newsboat directories, and possibly update the include paths. Migration from Newsbeuter is attempted on startup if the following conditions are met: * none of `-u`, `-c`, `-C` options were specified; and * the urls file doesn't exist (neither _~/.newsboat/urls_ nor _$XDG_CONFIG_HOME/newsboat/urls_). Newsboat first tries to migrate an XDG configuration, and if that fails, it tries the dotdir one. If that fails as well, Newsboat proceeds with the startup as usual. XDG migration checks that: * _$XDG_CONFIG_HOME/newsbeuter/_ is readable and executable; and * neither _$XDG_CONFIG_HOME/newsboat/_ nor _$XDG_DATA_HOME/newsboat/_ exist. If both conditions are met, Newsboat tries to create its XDG dirs (aborting the migration if that fails), then copies the following files: _urls_ and _config_ from config dir; _cache.db_, _queue_, _history.search_, _history.cmdline_ from data dir. Dotdir migration checks that _~/.newsbeuter/_ is readable and executable, and _~/.newsboat/_ doesn't exist. If those conditions are met, it tries to create _~/.newsboat/_ (aborting the migration if that fails), then copies the following files: _urls_, _cache.db_, _config_, _queue_, _history.search_, _history.cmdline_. There's one scenario where the process breaks: if you have an XDG configuration for Newsbeuter, _~/.newsboat/_ exists and _~/.newsboat/urls_ doesn't exist, then Newsboat will migrate XDG files and proceed, ignoring the dotdir. Please don't confuse the poor program like that! ==== Other readers (via OPML) The vast amount of RSS feed readers allows the export of subscriptions via OPML files. OPML is an XML file format that was designed to save outlines, and has found its primary use in the import and export of feed subscriptions between different RSS feed readers. The best thing to start with is to export your subscriptions from the old reader. Usually, RSS feed readers have appropriate menu items available to do so. Snownews provides a script to convert your current subscription file into an OPML file: snow2opml > ~/blogroll.opml This command creates from your Snownews configuration a file _blogroll.opml_ in your home directory. To export the subscription list from raggle, the following command is necessary: raggle --export-opml ~/blogroll.opml When you have exported the subscriptions from your old RSS feed reader, you can import them into newsboat: newsboat -i ~/blogroll.opml Don't worry, newsboat won't destroy your existing configuration, or add subscriptions more than once: every URL that is added to the subscription list is checked before whether it is already in the list, and is only added if not. This makes it possible to merge several OPML files into your subscription list. If your old RSS feed reader was able to structure your subscriptions in hierarchies, and reflected this structure in the exported OPML file, newsboat doesn't throw away this information (although it doesn't support hierarchies), but generates tags from it. Tags are newsboat's way of organizing subscriptions in a non-hierarchical way. More information on the use of tags can be found below. Imagine the following folder hierarchy: |- News | |- Europe | `- International |- IT | |- Linux | |- Windows | `- Programming | |- C++ | |- Ruby | `- Erlang `- Private Subscriptions found in the folder ""Private"" will be tagged with ""Private"", subscriptions in the folder ""International"" will be tagged with ""News"" and ""News/International"", subscriptions in the folder ""Erlang"" will be tagged ith ""IT"", ""IT/Programming"" and ""IT/Programming/Erlang"", and so on. This means that when you select the tag ""Programming"" in newsboat, you will see all subscriptions that were in the ""Programming"" folder or one of its subfolders before. This means that you will lose virtually nothing of your previously configured structure. == Newsboat as a Client for Newsreading Services Newsboat is a perfectly capable feedreader in its own right, but it can’t cover _all_ the use-cases. For example, you might want to synchronize your news between devices, or you don’t have a computer that’s running 24/7 to fetch your feeds. In such cases, you might register with some online feedreader, and use Newsboat as a client. The next few sections provide configuration instructions for each supported service. === The Old Reader https://theoldreader.com/[The Old Reader] is a successor to Google Reader. In order to use it, you first need to configure the proper URL source: urls-source ""oldreader"" In addition, Newsboat needs to know your The Old Reader username and password so that it can authenticate with the service: oldreader-login ""your-oldreader-account"" oldreader-password ""your-password"" Note that double quotes should be escaped, i.e. you should write `\\""` instead of `""`. See also <>, <>, and <<_passwords_for_external_apis>>. After setting these configuration values, you can start Newsboat. It will authenticate with The Old Reader and download your subscription list. When you mark single items or complete feeds as read, Newsboat will synchronize this information directly to The Old Reader. This, of course, includes opening articles. Toggling read articles back to ""unread"" is also communicated to The Old Reader. In addition, The Old Reader provides the ability to ""star"" and to ""share"" articles. Starred articles are basically bookmarks, while shared articles are shown to people that follow your The Old Reader account. Newsboat allows the use of this feature by mapping its powerful ""flags"" to the ""star""/""unstar"" resp. ""share""/""unshare"" operations. In order to use this mapping, all you need to do is to configure the flags that shall be used: oldreader-flag-share ""a"" oldreader-flag-star ""b"" After that, use these flags when you edit flags for an article, and these articles will be starred resp. shared. By default, Newsboat also shows The Old Reader ""special feeds"": - People you follow: articles shared by people that you follow. - Starred items: articles that you starred. - Shared items: articles that you shared. You can disable these feeds by setting the following configuration variable: oldreader-show-special-feeds no The Old Reader's folders are converted into Newsboat tags. You can select and filter feeds by tags; see <<_tagging>> and <<_filter_language>> for details. === NewsBlur https://newsblur.com/[NewsBlur] is a successor to Google Reader. To use it, set your <>: urls-source ""newsblur"" Then, configure your NewsBlur credentials: newsblur-login ""your-newsblur-account"" newsblur-password ""your-password"" Note that double quotes should be escaped, i.e. you should write `\\""` instead of `""`. See also <>, <>, and <<_passwords_for_external_apis>>. Finally, set a path to the file where Newsboat can store the HTTP cookies: cookie-cache ""~/.newsboat/cookies.txt"" When you start Newsboat, it will download the feeds that you configured in NewsBlur. Please take a closer look at the <> for what you can configure in Newsboat regarding NewsBlur. NewsBlur's folders are converted into Newsboat tags. You can select and filter feeds by tags; see <<_tagging>> and <<_filter_language>> for details. === FeedHQ https://feedhq.org/[FeedHQ] is a successor to Google Reader. Configuration basically works the same as with <<_the_old_reader,The Old Reader>>. First, set your <>: urls-source ""feedhq"" Then, configure your FeedHQ credentials: feedhq-login ""your-feedhq-account"" feedhq-password ""your-password"" Note that double quotes should be escaped, i.e. you should write `\\""` instead of `""`. See also <>, <>, and <<_passwords_for_external_apis>>. If you're using a standalone instance, you should add one more setting: feedhq-url ""https://the.url.of/your/feedhq/instance"" When you start Newsboat, it will download the feeds that you configured in FeedHQ. Please take a closer look at the <> for what you can configure in Newsboat regarding FeedHQ. FeedHQ's folders are converted into Newsboat tags. You can select and filter feeds by tags; see <<_tagging>> and <<_filter_language>> for details. === Bazqux https://bazqux.com/[Bazqux] uses ""Google Reader API"", which is also used by other readers like FeedHQ. Thus, one can leverage Newsboat's support for FeedHQ (described above) to synchronize with Bazqux: urls-source ""feedhq"" feedhq-url ""https://bazqux.com/"" feedhq-login ""username"" feedhq-password ""password"" See <<_passwords_for_external_apis>> for other, more secure ways to store your password. === Tiny Tiny RSS Newsboat can be used to synchronize with https://tt-rss.org/[Tiny Tiny RSS] installations. Tiny Tiny RSS is a web-based and (optionally) multi-user feed reader. If you want to use Tiny Tiny RSS support, don't forget to activate the external API support in your preferences. To use Tiny Tiny RSS support, you need to configure a few things. First of all, Newsboat needs to know that you want to use Tiny Tiny RSS and which installation exactly: urls-source ""ttrss"" ttrss-url ""https://example.com/ttrss/"" In addition, it requires username and password for authentication: ttrss-login ""myusername"" ttrss-password ""mypassword"" Note that double quotes should be escaped, i.e. you should write `\\""` instead of `""`. See also <>, <>, and <<_passwords_for_external_apis>>. Tiny Tiny RSS provides two modes of usage: single-user mode and multi-user mode. Newsboat needs to know about this, too: in single-user mode, authentication is done via Basic HTTP authentication, while in multi-user mode, authentication is done against Tiny Tiny RSS itself. ttrss-mode ""single"" # ""multi"" is default If Tiny Tiny RSS is configured in multi-user mode and still deployed behind an additional HTTP-BasicAuth, the required username and password (which may deviate from <> and <>) can be specified in the user-part of the url like this: ttrss-url ""https://htuser:htpasswd@example.com/ttrss/"" With these settings, Newsboat should be able to connect to Tiny Tiny RSS and download your subscribed feeds. Articles or even complete feeds that you marked as read are synchronized directly to Tiny Tiny RSS. Tiny Tiny RSS provides the ability to ""star"" and to ""publish"" articles. Starred articles are basically bookmarks, while published articles can be retrieved via a public RSS feed. Newsboat allows the use of these features by mapping its flags to the ""star"" and ""publish"" operations. In order to use this mapping, you need to configure the flags that shall be used: ttrss-flag-star ""s"" ttrss-flag-publish ""p"" After that, use these flags when you edit flags for an article, and these articles will be starred resp. published. TT-RSS folders are converted into Newsboat tags. You can select and filter feeds by tags; see <<_tagging>> and <<_filter_language>> for details. === ownCloud News and nextCloud News https://github.com/owncloudarchive/news[ownCloud News] and https://github.com/nextcloud/news[nextCloud News] implement the same protocol, so Newsboat treats them as equivalent. Instructions below apply to both. First, set your <> to `ocnews` and tell Newsboat where to find your ownCloud instance: urls-source ""ocnews"" ocnews-url ""https://localhost/owncloud"" Username and password are required: ocnews-login ""user"" ocnews-password ""password"" See also <>, <>, and <<_passwords_for_external_apis>>. ownCloud News API uses HTTP basic auth, therefore running ownCloud with SSL is highly recommended. If for any reason you don't want Newsboat to verify the hostname of your instance against the hostname specified in the SSL certificate you're using, just say so: ocnews-verifyhost ""no"" If you see intermittent ""Authentication failed"" errors, try https://docs.nextcloud.com/server/stable/admin_manual/configuration_server/caching_configuration.html[configuring memory caching]. That should improve the responsiveness of the API and fix the errors. ownCloud News provides the ability to ""star"" articles; starred articles are basically bookmarks. Newsboat allows the use of this feature by mapping user-specified flag to the ""star"" operation. In order to use this mapping, you need to configure the flag that shall be used: ocnews-flag-star ""s"" OwnCloud News' folders are converted into Newsboat tags. You can select and filter feeds by tags; see <<_tagging>> and <<_filter_language>> for details. === Inoreader https://inoreader.com/[Inoreader] is a successor to Google Reader. To use Newsboat with Inoreader, you should first https://www.inoreader.com/developers/register-app[register your own application]. Inoreader's API doesn't provide efficient access to all the data Newsboat needs, so the program has to scrape feeds. That generates a lot of API requests, which are rate-limited per application. Thus we ask users to register their own apps, to avoid interfering with others. Please also be mindful of this when enabling <> or lowering <>. With app ID and key in hand, tell Newsboat you'd like to use Inoreader: urls-source ""inoreader"" inoreader-app-id ""INSERT_ID_HERE"" inoreader-app-key ""INSERT_KEY_HERE"" In addition, Newsboat needs to know your Inoreader username and password so that it can authenticate with Inoreader. Note that this is NOT your login with your Google or Facebook account. If you use one of those to login to Inoreader, you have to create a username and password in Inoreader _Preferences > Profile_ inoreader-login ""your-inoreader-account"" inoreader-password ""your-password"" (Note that double quotes should be escaped, i.e. you should write `{backslash}""` instead of `""`.) See also <>, <>, and <<_passwords_for_external_apis>>. After setting these configuration values, you can start Newsboat. It will authenticate with Inoreader and download your subscription list. If you use ""folders"" in Inoreader to organize your feeds, Newsboat will make them available via its ""tags"" capability: each feed is tagged with the name of the folder in which it resides. You can select and filter feeds by tags; see <<_tagging>> and <<_filter_language>> sections for details. When you mark single items or complete feeds as read, Newsboat will synchronize this information directly to Inoreader. This, of course, includes opening articles. Toggling read articles back to ""unread"" is also communicated to Inoreader. In addition, Inoreader provides the ability to ""star"" and to ""share"" articles. Starred articles are basically bookmarks, while shared articles are shown to people that follow your Inoreader account. Newsboat allows the use of this feature by mapping its powerful ""flags"" to the ""star""/""unstar"" resp. ""share""/""unshare"" operations. In order to use this mapping, all you need to do is to configure the flags that shall be used: inoreader-flag-share ""a"" inoreader-flag-star ""b"" After that, use these flags when you edit flags for an article, and these articles will be starred resp. shared. By default, Newsboat also shows Inoreader ""special feeds"": - Starred items - Shared items - Liked items - Saved web pages You can disable these feeds by setting the following configuration variable: inoreader-show-special-feeds no === OPML Online Subscription Mode This mode provides one-way synchronization of subscriptions from the online service to Newsboat. In other words, Newsboat will know what feeds you've subscribed to, but the online service won't know what feeds you're reading in Newsboat. This mode works with any service that publishes your subscriptions in OPML format. To enable this mode, you need to set an appropriate URLs source and then tell Newsboat where to get the OPML file(s): urls-source ""opml"" opml-url ""https://example.com/feeds.opml"" ""https://example.com/more.opml"" === Passwords for external APIs include::chapter-password.asciidoc[] == Advanced Features === Tagging include::chapter-tagging.asciidoc[] === Scripts and Filters (Snownews Extensions) include::chapter-snownews.asciidoc[] === Bookmarking Newsboat contains a plugin-based bookmarking system. When a user bookmarks a link (possible in the article list, in the article view, and in the URL view), they are asked for the URL to bookmark (already preset with the URL of the current selection), the bookmark title (in most cases preset with the title of the current selection), the bookmark description and (since 2.10) the title of the feed the user is currently in. After the question for the description, an external program, configured via the configuration command <>, is executed with 4 (since 2.10) commandline parameters. The plugin itself implements the actual bookmark saving (e.g. writing the bookmark to an external file, or storing it to a del.icio.us account). If everything went OK, the plugin simply exits. In case something goes wrong while saving the bookmark, it writes out an error message as a single line. This error message is then presented to the user from within newsboat. Newsboat comes with an example plugin, which implements a simple tab-separated bookmark file. This example can be found in the _doc/examples_ subdirectory. === Command Line include::chapter-cmdline.asciidoc[] .Available Commandline Commands [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""20,20,40,20l""] |============================================================================= Command:Syntax:Description:Example [[cmd-quit]]<>:quit:Quit newsboat.:quit [[cmd-q]]<>:q:Alias for quit.:quit [[cmd-save]]<>:save :Save the currently select article to disk. This works in the article list and in the article view.:save ~/important.txt [[cmd-set]]<>:set [=|&|!]:Set configuration variable to . If no value is specified, the current value is printed out. Specifying a _!_ after the name of boolean configuration variables toggles their values, a _&_ directly after the name of a configuration variable of any type resets its value to the documented default value.:set reload-time=15 [[cmd-tag]]<>:tag :Only display feeds with the tag .:tag news [[cmd-goto]]<>:goto :Search for a feed whose name contains the case-insensitive substring.:goto foo [[cmd-source]]<>:source [...]:Load the specified configuration files. This allows it to load alternative configuration files or reload already loaded configuration files on-the-fly from the filesystem.:source ~/.newsboat/colors [[cmd-dumpconfig]]<>:dumpconfig :Save current internal state of configuration to file, so that it can be instantly reused as configuration file.:dumpconfig ~/.newsboat/config.saved [[cmd-dumpform]]<>:dumpform:Dump current dialog to text file. This is meant for debugging purposes only.:dumpform [[cmd-exec]]<>:exec :Run a keybind operation in the current context.:exec open-all-unread-in-browser-and-mark-read [[cmd-number]]<>::Jump to the entry with the index (usually seen at the left side of the list). This currently works for the feed list, article list, tag selection and filter selection forms.:30 |============================================================================= === Filter Language Newsboat provides a powerful filter language that enables the user to filter the content of many dialogs, such as the feed list or the article list. The basic concept is that every feed and every article has a number of attributes which can then be compared with user-supplied values, and these comparisons and be logically AND'ed, OR'ed and grouped. Examples for simple filter expressions are: unread_count > 0 rssurl =~ ""^https:"" age between 0:10 Logically connecting and grouping such expressions looks like in the following examples: ( unread_count > 0 and unread_count < 10 ) or total_count > 100 ( author =~ ""Frank"" or author =~ ""John"" ) and ( title =~ ""Linux"" or title =~ ""FreeBSD"" ) The possibilities for combining such queries is endless, sky (actually: the available memory) is the limit. To filter your feeds, press ""F"" in the feed list, enter your filter expression, and press ""Enter"". To clear the filter, press ""Ctrl-F"". To filter the articles in the article list, press ""F"", enter your expression, and press ""Enter"". Clearing the filter works the same as before. Be aware that only certain attributes work in both dialogs. The table below lists all available attributes and their context, i.e. an attribute that belongs to a feed can only be matched in the feed list, while an attribute that belongs to an article can only be matched in the article list. .[[available-comparison-operators]]<> [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""30,70""] |====================================================================== Operator:Meaning +=+ / +==+:test for equality +!=+:test for inequality; logical negation of the +=+ operator +=~+:test whether https\\://pubs.opengroup.org/onlinepubs/9699919799.2008edition/basedefs/V1_chap09.html[POSIX extended regular expression] matches, case-insensitively +!~+:logical negation of the +=~+ operator +<+:less than +>+:greater than +<=+:less than or equal +>=+:greater than or equal +between+:within a range of integer values, where the two integer values are separated by a colon (see above for an example) +#+:contains; this operator matches if a word is contained in a list of space-separated words (useful for matching tags, see below) +!#+:contains not; the negation of the +#+ operator |====================================================================== .Available Attributes [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""30,30,40""] |========================================================================= Attribute:Context:Meaning [[attr-title]]<>:article:article title [[attr-link]]<>:article:article link [[attr-author]]<>:article:article author [[attr-content]]<>:article:article body [[attr-date]]<>:article:publication date of the article [[attr-guid]]<>:article:a unique identifier of the article [[attr-unread]]<>:article:indicates whether the article has been read [[attr-enclosure_url]]<>:article:the URL of an enclosure (e.g. podcast file), empty if there is no enclosure [[attr-enclosure_type]]<>:article:the MIME type of the enclosure, empty if there is no enclosure [[attr-flags]]<>:article:The set of flags of the article [[attr-age]]<>:article:Age of an article (in days) [[attr-articleindex]]<>:article:Index of an article in an article list [[attr-feedtitle]]<>:feed, article:title of the feed [[attr-description]]<>:feed, article:feed description [[attr-feedlink]]<>:feed, article:link to the feed [[attr-feeddate]]<>:feed, article:publication date of the feed [[attr-rssurl]]<>:feed, article:RSS URL of the feed [[attr-unread_count]]<>:feed, article:number of unread articles in the feed [[attr-total_count]]<>:feed, article:total number of articles in the feed [[attr-tags]]<>:feed, article:all tags that are associated with the feed [[attr-feedindex]]<>:feed, article:Index of a feed in the feed list |========================================================================= Note that it's also possible to filter for feed attributes when you query for article attributes. This is because every article is internally linked to the feed from which it was downloaded. === Killfiles Sometimes, a user is confronted with certain content they don't want to read, e.g. on topics the user is not interested in or articles written by certain people. In Usenet, such functionality within software is traditionally called a ""killfile"", i.e. based on the content of this ""killfile"", articles that match certain conditions do not get displayed and are not presented to the user at all. In newsboat, such a ""killfile"" can be implemented on a per-article basis via the configuration file. The most important configuration command for this is <>: ignore-article ""*"" ""title =~ \\""Gentoo\\"""" ignore-article ""https://synflood.at/blog/index.php?/feeds/index.rss2"" ""title =~ \\""newsboat\\"""" It takes two parameters. The first one is either a URL of a feed, or `""*""` to match any feed (asterisk is _not_ a pattern, glob or regex—we simply reserve it to mean ""all feeds""). The second argument is <<_filter_language,a filter expression>> for an article, probably <<_using_double_quotes,in double quotes to preserve spaces inside>>. If newsboat hits an article in the specified RSS feed that matches the specified filter expression, then this article is ignored and never presented to the user. The configuration itself can contain as many <> commands as desired. You can also specify the way an article is ignored. There are two ways available: - During download: articles are ignored when a feed is downloaded and parsed, and thus won't be written to the local cache. - During display: articles are downloaded and written to the local cache, but are ignored when a feed is displayed. Both modes have their advantages and disadvantages: while the download ignore mode saves some storage, you cannot simply ""undo"" the ignore by removing it from the configuration file: if an ignored article has already vanished from a feed, it won't reappear. On the other hand, the display ignore mode requires some more space, but has the advantage that an ignore can be ""undone"" by removing the ignore-article configuration command from the configuration. The default ignore mode is `""download""`. You can set the <> in the configuration file: ignore-mode ""display"" === Query Feeds Query feeds are a mechanism of newsboat to define custom ""meta feeds"" by using newsboat's built-in filter language. A query feed is a feed that is aggregated from all currently downloaded articles of all feeds. To narrow down the set of articles, the user has to specify a filter. Only articles that match this filter are added to the query feed. A query feed is updated whenever it is entered in the feed list. When you change the unread flag of an article, this is reflected in the feed where the article was originally fetched. If you want query feeds to be updated at startup, set <> to `yes`. To define a query feed, the user has to add a line to the _urls_ file in the following format: query:: [ ...] The `query:` in the beginning tells newsboat that it's a query feed, `` specifies the name under which the query feed shall be displayed in the feed list, and `` is the filter expression that shall be used. Like every other feed, a query feed can be tagged to organize it like a regular feed. This feature is often used to create a feed that contains all unread articles: ""query:Unread Articles:unread = \\""yes\\"""" Note the <<_using_double_quotes,use of double quotes>> to preserve spaces in the filter expression. If you want to combine several feeds to one single feed, a good solution is to tag the feeds that you want to combine with one certain tag, and then create a query feed that only displays articles from feeds with that certain tag: https://domain1.tld/feed.xml fun news tag1 https://domain2.tld/?feed.rss private jokes tag1 https://domain3.tld/feeds.rss news ""query:tag1 Articles:tags # \\""tag1\\"""" In this example, the feeds https://domain1.tld/feed.xml and https://domain2.tld/?feed.rss are aggregated into the query feed named ""tag1 Articles"", but the feed https://domain3.tld/feeds.rss is not. Basically, the possibility of what can be realized with query feeds is only limited by what can be queried from articles and feeds with the filter language and by your creativity. === Flagging Articles To support custom categorization of articles by the user, it is possible to flag an article. A valid flag is any character from _A_ to _Z_ and from _a_ to _z_. Every article can be flagged with up to 52 different flags, i.e. every letter from the Roman alphabet in upper and lower case. Flagging is easy: just select an article in the article list, or enter the article view, and press ""Ctrl-E"". This will start the flag editor. By pressing ""Enter"", the new flags are saved. You can cancel by pressing the ""Esc"" key. The flags of an article can be used in every filter expression. The flags of an article are always ordered, and when new flags are added, ordering is immediately restored. This behaviour can also be relied upon when querying articles via the filter language. If an article contains one or more flags, it is marked with an ""!"" in the article list. In the article view, all flags (if available) are listed. === Macro Support In newsboat, it's possible to define macros to execute more than one command at once. A macro is configured using the <> configuration command. The first parameter to `macro` is the key, all parameters afterwards are operations (as listed in the <> table above), optionally with parameters on their own, separated by the `;` character. Here's a simple example: macro k open ; reload ; quit macro o open-in-browser ; toggle-article-read ""read"" When the user presses the macro prefix ("","" by default) and then the ""k"" key, the three operations <>, <> and <> will be executed subsequently. The macro prefix can be changed from the default "","" to another key, e.g. ""+"" (if you don't unbind the default "","" you're left with two macro prefixes): bind-key + macro-prefix unbind-key , It is also possible to modify configuration variables within macros, which can e.g. be used to temporarily modify the <> configuration variable to do something else, such as running an image viewer from the URLs view: macro i set browser ""feh %u""; open-in-browser ; set browser ""elinks %u"" You can even use this feature to enqueue any of the URLs from the URLs view to podboat's download queue (which might be in _~/.locale/share/newsboat/queue_ if you're using XDG directories): macro E set browser ""echo %u >> ~/.newsboat/queue"" ; open-in-browser ; set browser ""elinks %u"" === Commandline Commands Newsboat comes with a `-x` option that indicates that commands added as arguments to the command line shall be executed. Currently, the following commands are available: - `reload`: this option reloads all feeds, and quits newsboat without printing any output. This is useful if a user wants to periodically reload all feeds without always having a running newsboat instance, e.g. from cron. - `print-unread`: this option prints the number of unread articles and quits newsboat. This is useful for users who want to integrate this number into some kind of monitoring system. === Format Strings Newsboat contains a powerful format string system to make it possible for the user to configure the format of various aspects of the application, such as the format of entries in the feed list or in the article list. Format strings are similar to those that are found in the `printf` function in the C programming language. A format sequence begins with the _%_ character, followed by optional alignment indication: positive numbers indicate that the text that is inserted for the sequence shall be padded on the left to a total width that is specified by the number, while negative number specify padding on the right. Followed by the padding indication comes the actual sequence identifier, which is usually a single letter. In addition, newsboat provides other, more powerful sequences, such as `%>[char]`, which indicates that the text right to the sequence will be aligned right on the screen, and characters between the text on the left and the text on the right will be filled by `[char]`. Another powerful format is the conditional sequence, `%?[char]?[format 1]&[format 2]?`: if the text of the sequence identifier `[char]` contains any non-whitespace characters, then `[format 1]` will be evaluated and inserted, otherwise `[format 2]` will be evaluated and inserted. The `&` and `[format 2]` are optional, i.e. if the identifier's text is empty, then an empty string will be inserted. The following tables show what sequence identifiers are available for which format: .Available Identifiers for feedlist-format [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""30,70""] |====================================================================== Identifier:Meaning [[feedlist-format-d]]<>:Feed description [[feedlist-format-i]]<>:Feed index [[feedlist-format-l]]<>:Feed link [[feedlist-format-L]]<>:Feed RSS URL [[feedlist-format-n]]<>:""unread"" flag field [[feedlist-format-S]]<>:download status [[feedlist-format-t]]<>:Feed title [[feedlist-format-T]]<>:First tag of a feed in the URLs file [[feedlist-format-u]]<>:""unread/total"" field [[feedlist-format-U]]<>:""unread"" field [[feedlist-format-c]]<>:""total"" field |====================================================================== While a <> operation is running, the download status indicates the download status of a feed, which can be ""to be downloaded"" (indicated by ""_""), ""currently downloading"" (indicated by "".""), successfully downloaded (indicated by "" "") and ""download error"" (indicated by ""x""). .Available Identifiers for articlelist-format [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""30,70""] |====================================================================== Identifier:Meaning [[articlelist-format-a]]<>:Article author [[articlelist-format-D]]<>:Publication date. This can be tweaked further with <> [[articlelist-format-f]]<>:Two characters\\: 1) ""N"" if article is unread, ""D"" if article is deleted, a space otherwise; 2) ""!"" if article has flags, a space otherwise. [[articlelist-format-n]]<>:""unread"" field [[articlelist-format-d]]<>:""deleted"" field [[articlelist-format-F]]<>:Article flags [[articlelist-format-i]]<>:Article index [[articlelist-format-t]]<>:Article title [[articlelist-format-T]]<>:If the article list displays articles from different feeds, then this identifier contains the title of the feed to which the article belongs. [[articlelist-format-L]]<>:Article length |====================================================================== .Available Identifiers for selecttag-format [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""30,70""] |====================================================================== Identifier:Meaning [[selecttag-format-i]]<>:Line's index in the list [[selecttag-format-T]]<>:The tag this line corresponds to [[selecttag-format-f]]<>:Number of unread feeds under this tag [[selecttag-format-n]]<>:Number of unread articles in feeds tagged with this tag [[selecttag-format-u]]<>:Number of feeds tagged with this tag |====================================================================== .Available Identifiers for notify-format [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""30,70""] |====================================================================== Identifier:Meaning [[notify-format-n]]<>:Number of unread articles [[notify-format-f]]<>:Number of unread feeds [[notify-format-d]]<>:Number of new unread articles (i.e. that were added through the last reload) [[notify-format-D]]<>:Number of new unread feeds (i.e. that were added through the last reload) |====================================================================== .Available Identifiers for podlist-format [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""30,70""] |====================================================================== Identifier:Meaning [[podlist-format-i]]<>:Dowload index [[podlist-format-d]]<>:Currently downloaded size in megabytes, displays one digit of precision [[podlist-format-t]]<>:Total dowload size in megabytes, displays one digit of precision [[podlist-format-p]]<>:Dowloaded precentage, displays one digit of precision [[podlist-format-k]]<>:Dowload speed, displays two digit of precision, always in KB/s (does not include the ""KB/s"" text) [[podlist-format-K]]<>:Dowload speed, displays two digit of precision, human readable (automatically switches between KB/s, MB/s, and GB/s) [[podlist-format-S]]<>:Status of download, displays one of the folowing; ""queued"", ""downloading"", ""ready"", ""canceled"", ""deleted"", ""incomplete"", ""played"", ""finished"" or ""failed"" [[podlist-format-u]]<>:Url of the download [[podlist-format-F]]<>:Absolute filename of the download from the root directory (e.g. ~/downloads/podcast.mp3 -> /home/name/downloads/podcast.mp3) [[podlist-format-b]]<>:Basename of the download (e.g. /home/name/downloads/podcast.mp3 -> podcast.mp3) |====================================================================== Examples: feedlist-format ""%4i %n %11u %t"" articlelist-format ""%4i %f %D %?T?|%-17T| ?%t"" notify-format ""%d new articles (%n unread articles, %f unread feeds)"" podlist-format ""%4i [%-5p %%] %-12S %F"" .Available Identifiers for download-path and download-filename-format [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""30,70""] |====================================================================== Identifier:Meaning [[download-filename-format-u]]<>:Filename part of the download URL. May be empty. May include https\\://en.wikipedia.org/wiki/Query_string[a query string] [[download-filename-format-n]]<>:Name of the podcast feed [[download-filename-format-N]]<>:Name of the podcast feed. Contains the original feed's name, even when selected through a query feed [[download-filename-format-h]]<>:Name of the podcast feed's hostname [[download-filename-format-t]]<>:Title of the podcast episode [[download-filename-format-e]]<>:Extension of the podcast episode [[download-filename-format-F]]<>:Publication date of the podcast episode formatted as yyyy-mm-dd [[download-filename-format-m]]<>:Month when podcast episode was published [[download-filename-format-b]]<>:Abbreviated month name when podcast episode was published [[download-filename-format-d]]<>:Day when podcast episode was published [[download-filename-format-H]]<>:Hour when podcast episode was published [[download-filename-format-M]]<>:Minute when podcast episode was published [[download-filename-format-S]]<>:Second when podcast episode was published [[download-filename-format-y]]<>:Year when podcast episode was published formatted as yy [[download-filename-format-Y]]<>:Year when podcast episode was published formatted as yyyy |====================================================================== ==== Dialog Titles You can customize the title format of all available dialogs. Here is a list of dialogs with their respective title format configuration variables, and a list of available formats and their meaning. Please note that the title formats are localized, so if you work on a different locale that is supported by newsboat, the actually displayed title text may vary unless you customize it. .Dialog Title Formats [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""20,30,50l""] |========================================================================== Dialog:Configuration Variable:Default Value Feed List:<>:%N %V - %?F?Feeds&Your feeds? (%u unread, %t total)%?F? matching filter `%F'&?%?T? - tag `%T'&? Article List:<>:%N %V - Articles in feed '%T' (%u unread, %t total)%?F? matching filter `%F'&? - %U Search Result:<>:%N %V - Search results (%u unread, %t total)%?F? matching filter `%F'&? File Browser:<>:%N %V - %?O?Open File&Save File? - %f Directory Browser:<>:%N %V - %?O?Open Directory&Save File? - %f Help:<>:%N %V - Help Select Tag Dialog:<>:%N %V - Select Tag Select Filter Dialog:<>:%N %V - Select Filter Article View:<>:%N %V - Article '%T' (%u unread, %t total) URL View:<>:%N %V - URLs Dialog List:<>:%N %V - Dialogs |========================================================================== .Common Title Format Identifiers [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""30,70""] |====================================================================== Identifier:Meaning [[common-title-format-N]]<>:Name of the program, i.e. ""newsboat"" [[common-title-format-V]]<>:Program version [[common-title-format-u]]<>:Number of unread articles (if applicable) [[common-title-format-t]]<>:Number of total articles (if applicable) [[common-title-format-F]]<>:Current filter expression (if applicable, empty if no filter is active) |====================================================================== .Feed List Title Format Identifiers [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""30,70""] |====================================================================== Identifier:Meaning [[feedlist-title-format-T]]<>:Currently selected tag (empty if none selected) |====================================================================== .Article List Title Format Identifiers [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""30,70""] |====================================================================== Identifier:Meaning [[articlelist-title-format-T]]<>:Feed title [[articlelist-title-format-U]]<>:Feed URL |====================================================================== .File Browser Title Format Identifiers [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""30,70""] |====================================================================== Identifier:Meaning [[filebrowser-title-format-f]]<>:Current path [[filebrowser-title-format-O]]<>:Non-empty if file browser is in open mode, empty if in save mode |====================================================================== .Directory Browser Title Format Identifiers [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""30,70""] |====================================================================== Identifier:Meaning [[dirbrowser-title-format-f]]<>:Current path [[dirbrowser-title-format-O]]<>:Non-empty if directory browser is in open mode, empty if in save mode |====================================================================== .Article View Title Format Identifiers [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""30,70""] |====================================================================== Identifier:Meaning [[articleview-title-format-T]]<>:Article title [[articleview-title-format-F]]<>:Feed title |====================================================================== === Highlighting Text Newsboat supports the highlighting of text in the feed list, the article list and the article view, using regular expressions to describe patterns to be highlighted. The command syntax goes like this: highlight [ [ ...]] Valid values for `` are `feedlist`, `articlelist`, `article` and `all`. When specifying `all`, the matching will be done in all three views. The `` must be a https://pubs.opengroup.org/onlinepubs/9699919799.2008edition/basedefs/V1_chap09.html[POSIX extended regular expression], which will be matched case-insensitive against the text. If multiple highlight matches overlap, the style of the later specified highlight rule will be applied. `` and `` specify the foreground color resp. the background color of the matches. You can also specify 0 or more attributes. You can find a list of valid colors and attributes in the <<_configuring_colors>>. Examples for possible highlighting configurations are: highlight all ""newsboat"" red highlight article ""^(Feed|Title|Author|Link|Date):"" default default underline highlight feedlist ""https?://[^ ]+"" yellow red bold Note the <<_using_double_quotes,use of double quotes>> to preserve spaces in the regular expressions. ==== Highlighting Articles in the Article List In addition to generally highlighting text, there is also a specific way to highlight articles in the article list based on whether they match a certain filter expression. This means that you can highlight items in the article list based on their content. This is done using the <> configuration command. The syntax is similar to the <> configuration command, with the difference that there's no need to specify a target (since it only applies in the article list), and instead of a regular expression, a filter expression is used. After the filter expression, the colors and attributes are specified in the same way. Example: highlight-article ""author =~ \\""Andreas Krennmair\\"""" white red bold Note the <<_using_double_quotes,use of double quotes>> to preserve spaces in the filter expression. === Advanced Dialog Management Newsboat supports an advanced concept of dialogs. Previously, all dialogs (feed list, article list, article view) were internally laid out as a pure stack. In 2.0, this changed: all dialogs are managed in a list, and the user can jump to another, previously opened dialog from everywhere. This allows a user to open more than one article list, more than one article view, etc., and switch between them without closing them. The main dialog for this feature can be reached by pressing the ""v"" key. This opens the list of open dialogs. From there, the user can switch to another dialog by selecting the appropriate entry and pressing ""Enter"", or can close open dialogs by selecting them and pressing ""Ctrl-X"". === Podcast Support include::chapter-podcasts.asciidoc[] .Podboat Configuration Commands [frame=""all"", grid=""all"", format=""dsv"", separator=""||"", options=""header"", cols=""10,15,15l,40,20l""] |====================================================================================================== Configuration Command||Argument(s)||Default||Description||Example include::podboat-cmds-linked.dsv[] |====================================================================================================== .Available Operations in Podboat [frame=""all"", grid=""all"", format=""dsv"", options=""header"", cols=""20,20,60""] |========================================================================= Operation:Default key:Description [[pb-quit]]<>:q:Quit the program. [[pb-hard-quit]]<>:Q:Quit the program without confirmation. [[pb-help]]<>:?:Show the help screen. [[pb-download]]<>:d:Download the currently selected URL. [[pb-cancel]]<>:c:Cancel the currently selected download. [[pb-play]]<>:p:Start player with currently selected download. [[pb-mark-as-finished]]<>:m:Mark currently selected entry as finished. [[pb-delete]]<>:D:Delete the currently selected URL from the queue. [[pb-purge]]<>:P:Remove all finished and deleted downloads from the queue and load URLs that were newly added to the queue. [[pb-toggle-download-all]]<>:a:Toggle the ""automatic download"" feature where all queued URLs are downloaded one after the other. The ""max-downloads"" configuration option controls how many downloads are done in parallel. [[pb-increase-max-dls]]<>:+:Increase the ""max-downloads"" option by 1. [[pb-decrease-max-dls]]<>:-:Decrease the ""max-downloads"" option by 1. If the option is already 1, no further decrease is possible. |========================================================================= A usual ""use case"" is to configure newsboat to automatically enqueue newly found podcast download URLs. Then, the user reloads the podcast RSS feeds in newsboat, and after that, uses podboat to view the current queue, and either selectively download certain files or automatically download them all together by pressing ""a"" within podboat. === Running multiple copies of Newsboat simultaneously During development and testing, you might want to run a second copy of Newsboat, operating with different config, URLs list or cache file. This can be achieved by creative use of XDG environment variables. This approach is not beautiful, but it works. First of all, you will need to create a directory to store the data. Let's call it _test_: $ mkdir -p test/newsboat Note that we also create a subdirectory called _newsboat_; this is required to satisfy XDG specification. **ATTENTION**: if this subdirectory is absent, Newsboat will attempt to run on your live data! You can now create _config_ and _urls_ files inside _test/newsboat_; you can also copy _cache.db_ if you don't want to start with a fresh one. When the files are ready, you can invoke Newsboat as follows: $ XDG_CONFIG_HOME=test XDG_DATA_HOME=test newsboat (This will look +newsboat+ binary up in your +PATH+; if you've just built your own, use +./newsboat+ instead, or provide a full path.) By modifying the environment in which Newsboat runs you also modify environments of all the programs that Newsboat starts; that includes filters and external HTML renderers. If they rely on +XDG_*+ variables, they will look for things in +test+ directory and might fail. For filters, you should either copy the files they need to _test_, or invoke them in such a way that they don't look in XDG directories at all. For renderers, you can work around the issue by undoing the modifications to environment, e.g.: html-renderer ""XDG_CONFIG_HOME=$HOME/.config XDG_DATA_HOME=$HOME/.data w3c"" As already said: not beautiful, but gets the job done. === Using SQLite Triggers with newsboat This section was written by mailto:elrond+newsbeuter(at)samba-tng.org[Elrond], originally for Newsbeuter. SQLite, the db used by newsboat, supports triggers. These are small snippets of SQL that get executed inside the database by the database engine. They're stored inside the db and the normal user (including newsboat itself) doesn't see them. Just the db seems to do some magic: Like changing some values when you change another value. So what is this good for when looking at newsboat? Well, first off, it's a hack. The real answer should be to use application logic (do it inside newsboat, not in the db). So: Don't use this, unless you know, what you're doing, and unless you have some sort of backup. ==== Example So after the ""don't use it"" you still want to know, what one can do? So here's an example. Suppose you have a strange feed where the articles become ""new"" by just changing their subject, and nothing else changes. The body is just empty, and the URL keeps the same. This feed really exists. It's the ""updated software rss feed"" of some major company and the title just contains the name of the driver and version number. And the URL points to the download page. newsboat considers articles only as new, when they have a new UniqueID (this is good). So those articles are never marked as new (unread) ever again. So what can we do? We do some magic: We let the db test if newsboat changes the subject and then let itself mark the article again as unread. 1. You need the `sqlite3` command line tool (available via `apt-get install sqlite3` on Debian) or some other tool to do direct sql on the sqlite database. 2. Start `sqlite3` with the newsboat db: Rivendell:~/.newsboat% sqlite3 cache.db SQLite version 3.4.2 Enter "".help"" for instructions sqlite> 3. Create the trigger: sqlite> create trigger update_item_title update of title on rss_item > for each row when old.title != new.title > begin > update rss_item set unread = 1 where rowid == new.rowid; > end; 4. Leave `sqlite3` with ""Ctrl-D"" or `.quit`. That's it. newsboat (well, its db) now marks articles as unread when their title changes. And nicely enough this works all inside newsboat, no need to restart it so that it rereads the cache, that magically modifies itself. It just works. === Environment variables include::chapter-environment-variables.asciidoc[] == Feedback If you want to tell us something related to newsboat, don't hesitate to send an email to our mailing list: newsboat@googlegroups.com Alternatively, you can reach the newsboat developers on IRC: channel #newsboat on irc.freenode.net. If you want to report newsboat bugs, please use this issue tracker: https://github.com/newsboat/newsboat/issues/[] == License MIT License Copyright 2006-2015 Andreas Krennmair + Copyright 2015-2020 Alexander Batischev + Copyright 2006-2017 Newsbeuter contributors + Copyright 2017-2020 Newsboat contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",16238,True,2821.244439270854,median "--- title: Rozdział 5. System okien X part: Część I. Pierwsze kroki prev: books/handbook/ports next: books/handbook/partii --- [[x11]] = System okien X :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 5 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/x11/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[x11-synopsis]] == Streszczenie Środowisko graficzne dostępne we FreeBSD korzysta z zaawansowanego serwera graficznego X11 - implementacji open-source Systemu okien X obejmującej zarówno Xorg jak i XFree86(TM). FreeBSD 5.2.1-RELEASE oraz wcześniejsze wydania wykorzystują XFree86(TM), serwer X11 opracowany przez The XFree86(TM) Project, Inc. Od wersji FreeBSD 5.3-RELEASE podstawową i oficjalną odmianą X11 jest Xorg, serwer przygotowywany przez X.Org Foundation, rozprowadzany na licencji bardzo zbliżonej do wykorzystywanej przez FreeBSD. Dostępne są również komercyjne serwery X dla FreeBSD. Niniejszy rozdział omawia zagadnienia związane z instalacją i konfiguracją X11 kładąc szczególny nacisk na serwer Xorg. Informacje o konfiguracji XFree86(TM) (np. w starszych wersjach FreeBSD gdzie XFree86(TM) był domyślnym serwerem X11) zawsze znaleźć można w archiwalnych wersjach Podręcznika FreeBSD (ang.) na stronie http://docs.FreeBSD.org/doc/[http://docs.FreeBSD.org/doc/]. Informacje odnośnie obsługiwanego przez X11 sprzętu dostępne są na stronie internetowej projektu http://www.x.org/[Xorg]. Po przeczytaniu tego rozdziału będziemy wiedzieć: * Jakie elementy wchodzą w skład Systemu okien X i jakie są ich wzajemne relacje. * Jak zainstalować i skonfigurować X11. * Jak instalować i korzystać z róźnych menadżerów okien. * Jak korzystać z czcionek TrueType(R) w X11. * Jak skonfigurować system do logowania graficznego (XDM). Przed przeczytaniem tego rozdziału powinniśmy wiedzieć: * Jak instalować dodatkowe oprogramowanie (crossref:ports[ports,Instalacja programów: pakiety i porty]). [[x-understanding]] == Zrozumieć X Korzystanie z X pierwszy raz może być niejakim szokiem dla osób, które dotychczas korzystały z innych środowisk graficznych, jak np. Microsoft(R) Windows(R) czy Mac OS(R). O ile nie jest wymagane znać wszystkie detale wielu elementów X i jak one ze sobą współpracują, o tyle podstawowa wiedza w tym zakresie pozwoli nam w pełni wykorzystać możliwości X-ów. === Czemu X? X nie jest pierwszym systemem okienkowym napisanym dla systemów typu UNIX(R), lecz jest on najbardziej popularnym. Grupa projektantów, która przygotowała X, pracowała wcześniej nad innym systemem. System ten nazywał się ""W"" (od ""Window""). X była po prostu kolejną literą w rzymskim alfabecie. System X może być nazywany po prostu ""X"", ""System okien X"", ""X11"" oraz jeszcze na wiele innych sposobów. Może się również okazać, że stosowanie terminu ""X Windows"" w odniesieniu do X11 jest traktowane jako obraźliwe przez niektóre osoby. Więcej informacji dostępnych jest w man:X[7]. === Model klient/serwer Od samego początku System X zorientowany był na pracę w sieci, stąd też wykorzystanie modelu ""klient-serwer"". W modelu systemu X, ""serwer X"" pracuje na komputerze wyposażonym w klawiaturę, monitor i myszkę. Do zadań serwera należy m.in. zarządzanie wyświetlaniem, czy obsługa sygnałów z klawiatury. Każda aplikacja graficzna (jak np. XTerm czy man:getenv[3]) jest ""klientem"". Klient wysyła komunikaty do serwera typu ""Proszę w tym miejscu narysować okienko"". Serwer natomiast: ""Użytkownik właśnie kliknął przycisk OK"". W warunkach domowych czy w małym biurze serwer i klienci pracują z reguły na tym samym komputerze. Tym nie mniej istnieje możliwość uruchomienia serwera X na słabszej maszynie a aplikacje (klienci) na np. potężnej i drogiej maszynie obsługującej całe biuro. W takim wypadku komunikacja pomiędzy klientami a serwerem odbywa się za pomocą sieci. Bywa to mylące, gdyż terminologia stosowana w systemie X jest dokładnie odwrotna do tego czego należałoby się spodziewać w typowym modelu ""klient-serwer"", czyli ""serwera X"" pracującego na mocniejszej maszynie oraz ""klienta X"" na komputerze biurkowym. Stąd też należy pamiętać, że serwer X jest komputerem z monitorem i klawiaturą, podczas gdy klienci X są programami wyświetlającymi okienka. Protokół X11 w żaden sposób nie zmusza ani klientów ani serwera, by obydwa działały na tym samym systemie operacyjnym, czy nawet typie komputera. Możliwe jest zatem uruchomienie serwera X w systemie Microsoft(R) Windows(R) czy Mac OS(R) firmy Apple za pomocą dostępnych darmowych i komercyjnych narzędzi. === Menedżer okien Filozofia systemu X jest bardzo zbliżona do filozofii Uniksa: ""narzędzia, nie reguły"". Oznacza to, że X nie stara się narzucać jak ma zostać wykonane zadanie, dostarcza jedynie narzędzi pozostawiając użytkownikowi decyzję o sposobie ich wykorzystania. Stąd też X nie wymusza jak powinny wyglądać okienka, jak je przesuwać po ekranie za pomocą myszki, jakie skróty klawiaturowe wykorzystać by przełączać pomiędzy okienkami (np. kbd:[Alt+Tab] w w przypadku Microsoft(R) Windows(R)), jak powinny wyglądać nagłówki okienek, itd. Serwer X oddelegowuje tą odpowiedzialność do aplikacji nazywanej ""Menedżerem okien"". Istnieje całe mnóstwo menedżerów okien dla systemu X: AfterStep, Blackbox, ctwm, Enlightenment, fvwm, Sawfish, twm, Window Maker i wiele więcej. Każdy z nich oferuje inny wygląd i sposób obsługi; niektóre obsługują ""wirtualne pulpity""; inne umożliwiają definiować własne skróty klawiszowych do zarządzania pulpitem; jeszcze inne posiadają przycisk ""Start"" bądź podobne rozwiązanie; w niektórych można zmieniać dowolnie motywy graficzne, pozwalając na całkowitą zmianę wyglądu i zachowania przy uruchamianiu nowego motywu. Te menedżery i wiele innych dostępne są w kategorii [.filename]#x11-wm# w Kolekcji portów. Ponadto, również środowiska graficzne KDE oraz GNOME posiadają w pełni zintegrowane, własne menedżery okien. Każdy menedżer okien posiada również odrębny mechanizm konfiguracyjny; niektóre wykorzystują ręcznie modyfikowane pliki konfiguracyjne, inne dysponują narzędziami graficznymi, a przynajmniej jeden (Sawfish) wykorzystuje plik konfiguracyjny napisany w języku Lisp. [NOTE] .Sposób uaktywniania ==== Kolejną funkcją realizowaną przez menedżera okien jest ""sposób uaktywniania"" okien za pomocą myszy. Każdy system okienkowy potrzebuje pewnego sposobu wyboru okna, które będzie aktywnie przyjmować sygnały z klawiatury i powinno wskazywać, które okno jest aktywne. Znanym wszystkim sposobem uaktywniania jest zapewne ""kliknij-by-uaktywnić"". Jest to metoda wykorzystywana w systemie Microsoft(R) Windows(R), w której okno zostaje uaktywnione po otrzymaniu kliknięcia myszką. X nie obsługuje żadnego sposobu uaktywniania sam z siebie. To właśnie menedżer okien kontroluje, które okno jest aktywne w danych czasie. Różne menedżery wspierają różne metody uaktywniania. Wszystkie z nich obsługują kliknij-by-uaktywnić a większość z nich obsługuje również kilka innych. Najczęściej spotykane sposoby uaktywniania: aktywuj-za-myszą:: Aktywne jest okno znajdujące się bezpośrednio pod wskaźnikiem myszki. Przy czym, nie koniecznie jest to te samo okno, które znajduje się nad wszystkimi innymi oknami. Zmiana aktywnego okna dokonywana jest przez wskazanie na inne okno. Nie jest wymagane kliknięcie na nim. leniwe uaktywnianie:: Ta metoda jest drobną wariacją metody aktywuj-za-myszą, w której w sytuacji gdy wskaźnik myszy jest przesunięty nad wolne pole wówczas żadne okno nie jest aktywne, a wszystkie wprowadzane znaki są tracone. W tej metodzie natomiast aktywne okno jest zmieniane tylko gdy wskaźnik zostanie przesunięty nad nowe okno, natomiast nie w momencie gdy opuści bieżące okno. kliknij-by-uaktywnić:: Aktywne okno jest wybierane poprzez kliknięcie na nie myszką. Okno może później być ""podniesione"" i pojawić się nad wszystkimi innymi oknami. Wszystkie wprowadzane znaki są kierowane do tego okna, nawet jeśli wskaźnik myszki zostanie przesunięty nad inne okno. Wiele menedżerów okien wspiera również inne metody, podobnie jak wariacje powyższych. Najlepiej jest sprawdzić dokumentację danego menedżera. ==== === Elementy interfejsu graficznego Podejście Systemu X do dostarczania narzędzi a nie reguł dotyczy również elementów interfejsu graficznego widocznych na ekranie w każdej uruchomionej aplikacji. Pod pojęciem ""elementu interfejsu graficznego"" (ang. widget) kryją się wszystkie elementy, które można kliknąć bądź w inny sposób nimi manipulować; przyciski, pola wyboru, przyciski opcji, ikony, listy, itd. W systemach Microsoft(R) Windows(R) nazywają się one ""formantkami"" (ang. controls). Zarówno Microsoft(R) Windows(R) jak i Apple Mac OS(R) stosują bardzo rygorystyczne podejście do elementów interfejsu graficznego. Od twórców programów wymaga się by ich aplikacje wyglądały jednakowo. Natomiast przy tworzeniu X, nie uznano za rozsądne narzucanie jednego stylu graficznego czy zestawu elementów interfejsu, do którego miałyby być dostosowane wszystkie programy. W rezultacie nie należy się spodziewać, że aplikacje graficzne będą posiadały jednakowy wygląd czy sposób obsługiwania. Istnieje kilka popularnych zestawów elementów interfejsu graficznego i ich wariacji, włączając w to oryginalny zestaw Athena z MIT, Motif(R) (na podstawie którego został przygotowany zestaw elementów interfejsu graficznego Microsoft(R) Windows(R); wszystkie krawędzie fazowane, trzy odcienie szarości), OpenLook i inne. Większość nowszych programów graficznych będzie zapewne wykorzystywać jeden ze współczesnych zestawów elementów interfejsu, jak np. Qt, wykorzystywany w KDE, bądź GTK+, stosowany w projekcie GNOME. Pod tym względem, istnieje pewne podobieństwo w wyglądzie i zachowaniu środowisk graficznych w systemach typu UNIX(R), co z pewnością ułatwi pracę z systemem początkującym użytkownikom. [[x-install]] == Instalacja X11 Domyślną implementacją serwera X11 dla FreeBSD jest Xorg. Jest on serwerem graficznym o otwartym kodzie (open source) Systemu okien X przygotowanym przez X.Org Foundation. Bazuje on na kodzie XFree86(TM) 4.4RC2 i X11R6.6. Wersją Xorg dostępną aktualnie z kolekcji portów FreeBSD jest 7.7. By skompilować i zainstalować Xorg z kolekcji portów wpisujemy: [source,shell] .... # cd /usr/ports/x11/xorg # make install clean .... [NOTE] ==== Nim zaczniemy upewnijmy się, że dysponujemy 4 GB wolnej przestrzeni na dysku na potrzeby kompilacji. ==== Alternatywnie, X11 może zostać zainstalowany z pakietów binarnych za pomocą man:pkg_add[1]. W przypadku wykorzystania opcji zdalnego pobierania pakietów z sieci przez man:pkg_add[1] należy pominąć numer wersji pakietu. Program man:pkg_add[1] automatycznie pobierze najnowszą wersję aplikacji. Zatem, by pobrać i zainstalować pakiet Xorg wystarczy wpisać: [source,shell] .... # pkg_add -r xorg .... [NOTE] ==== Powyższe polecenia zainstalują kompletne środowisko X11 zawierające serwery, klienty, czcionki itd. Dostępne są również osobne pakiety i porty elementów X11. ==== Pozostała część niniejszego rozdziału wyjaśnia jak skonfigurować serwer X11 oraz jak skonfigurować wspomagające efektywność naszej pracy środowisko pulpitowe. [[x-config]] == Konfiguracja X11 === Nim zaczniemy Przed rozpoczęciem konfiguracji X11 potrzebne nam będą następujące informacje o docelowym systemie: * Parametry monitora * Rodzaj chipsetu karty graficznej * Rozmiar pamięci karty graficznej Parametry monitora są wykorzystywane przez X11 do określenia rozdzielczości i częstotliwości odświeżania ekranu, na jakich ma pracować. Parametry te można z reguły odczytać z dokumentacji dostarczonej wraz z monitorem bądź ze strony producenta. Potrzebne są dwa przedziały liczbowe: częstotliwość odchylania poziomego oraz częstotliwość synchronizacji pionowej. Od rodzaju chipsetu karty graficznej zależy który moduł X11 wykorzysta do komunikacji z kartą graficzną. W większości przypadków możliwe jest automatyczne wykrycie rodzaju chipsetu. Tym nie mniej warto jest go znać, na wypadek gdyby autodetekcja nie powiodła się. Rozmiar pamięci karty graficznej wpływa bezpośrednio na rozdzielczość i głębię kolorów, przy których system będzie pracował. Informacja ta jest istotna, by użytkownik znał ograniczenia systemu w tym zakresie. === Konfiguracja X11 Konfiguracja X11 jest procesem składającym się z kilku kroków. Pierwszym z nich jest przygotowanie wstępnego pliku konfiguracyjnego. Wystarczy jako użytkownik `root` wpisać: [source,shell] .... # Xorg -configure .... Wygeneruje to szkielet konfiguracji X11 w katalogu [.filename]#/root#, w pliku o nazwie [.filename]#xorg.conf.new# (niezależnie czy skorzystaliśmy z man:su[1] czy zalogowaliśmy się bezpośrednio na konto, plik zostanie utworzony w katalogu zdefiniowanym w zmiennej `$HOME` dla użytkownika `root`). X11 spróbuje wykryć parametry sprzętu graficznego zainstalowanego w komputerze i zapisać plik konfiguracyjny, by przy starcie serwera X były ładowane właściwe sterowniki dla wykrytego sprzętu. Kolejnym krokiem jest przetestowanie konfiguracji i sprawdzenie czy Xorg jest w stanie współpracować ze sprzętem graficznym w systemie. W tym celu należy wpisać: [source,shell] .... # Xorg -config xorg.conf.new .... Jeśli na ekranie pojawi się siatka złożona z czarnych i szarych elementów, a także kursor myszy w kształcie litery X, oznaczać to będzie, że X11 został skonfigurowany poprawnie. By wyłączyć ekran testowy wystarczy wcisnąć kombinację klawiszy kbd:[Ctrl+Alt+Backspace]. [NOTE] ==== Jeśli okaże się, że kursor nie reaguje na ruchy myszy będziemy musieli wpierw ją skonfigurować. crossref:install[mouse,Ustawienia myszki] rozdziału ""Instalacja FreeBSD"" zawiera szczegółowe informacje na ten temat. ==== Następnym krokiem jest dostrojenie konfiguracji pliku [.filename]#xorg.conf.new# do naszych upodobań. Otwórzmy plik w edytorze tekstu, np. w man:emacs[1] bądź man:ee[1]. Wpierw powinniśmy dodać częstotliwości z jakimi może pracować nasz monitor. Z reguły określane są jako częstotliwości synchronizacji pionowej i poziomej. Wartości te są dodawane do pliku [.filename]#xorg.conf.new# w sekcji `""Monitor""`: [.programlisting] .... Section ""Monitor"" Identifier ""Monitor0"" VendorName ""Monitor Vendor"" ModelName ""Monitor Model"" HorizSync 30-107 VertRefresh 48-120 EndSection .... Słów kluczowych `HorizSync` i `VertRefresh` może brakować w pliku konfiguracyjnym. Jeśli tak jest, można je śmiało dodać wpisując właściwą wartość częstotliwości odchylania poziomego zaraz po `HorizSync` oraz wartość częstotliwości synchronizacji pionowej po `VertRefresh`. W powyższym przykładzie wartości te zostały wpisane. X umożliwia również korzystanie z funkcji DPMS (Energy Star), jeśli dysponujemy monitorem zgodnym z tym standardem. Program man:xset[1] kontroluje limity czasowe i może wymusić tryb oczekiwania, zawieszenia czy tryby wyłączania. Jeśli chcemy włączyć funkcje DPMS dla naszego monitora, musimy dodać poniższy wiersz w sekcji monitora: [.programlisting] .... Option ""DPMS"" .... Mając wciąż otwarty w edytorze plik [.filename]#xorg.conf.new# wybierzmy domyślną rozdzielczość i głębię kolorów. Parametry te definiowane są w sekcji `""Screen""`: [.programlisting] .... Section ""Screen"" Identifier ""Screen0"" Device ""Card0"" Monitor ""Monitor0"" DefaultDepth 24 SubSection ""Display"" Viewport 0 0 Depth 24 Modes ""1024x768"" EndSubSection EndSection .... Słowo kluczowe `DefaultDepth` odnosi się do domyślnej głębi kolorów. Opcja ta może być zmieniona za pomocą parametru `-depth` polecenia man:Xorg[1]. Słowo kluczowe `Modes` odnosi się do rozdzielczości, w której ma pracować serwer X dla danej głębi kolorów. Należy zwrócić uwagę, iż dostępne są jedynie standardowe tryby VESA, zgodne ze sprzętem graficznym instalowanym w danym systemie. W powyższym przykładzie, domyślna głębia kolorów to dwadzieścia cztery bity na piksel. Przy tej głębi dostępna jest rozdzielczość 1024 na 768 pikseli. Możemy w końcu zapisać plik konfiguracyjny i sprawdzić go wykorzystując podany powyżej tryb testowy. [NOTE] ==== Jednym z pomocnych narzędzi w radzeniu sobie z problemami są pliki dzienników X11, zawierające informacje odnośnie każdego urządzenia, do którego jest podłączony serwer X11. Nazwy plików dzienników Xorg wykorzystują format [.filename]#/var/log/Xorg.0.log#. Dokładna nazwa pliku dziennika może być różna w zakresie od [.filename]#Xorg.0.log# do [.filename]#Xorg.8.log#. ==== Jeśli test wypadł dobrze, należy zainstalować plik konfiguracyjny w miejscu gdzie man:Xorg[1] będzie w stanie go znaleźć. Z reguły jest to [.filename]#/etc/X11/xorg.conf# lub [.filename]#/usr/X11R6/etc/X11/xorg.conf#. [source,shell] .... # cp xorg.conf.new /etc/X11/xorg.conf .... Proces konfiguracji X11 dobiegł końca. Xorg można uruchomić za pomocą pomocą polecenia man:startx[1]. Serwer X11 może być również uruchamiany wykorzystując man:xdm[1]. [NOTE] ==== Dostępny jest również graficzny konfigurator - man:xorgcfg[1] - dostarczany razem z dystrybucją X11. Pozwala on nam interaktywnie zdefiniować naszą konfigurację wybierając odpowiednie sterowniki i ustawienia. Program ten można uruchomić z konsoli wpisując polecenie `xorgcfg -textmode`. Więcej szczegółów zawiera strona podręcznika systemowego man:xorgcfg[1]. Istnieje również, jako alternatywa, program man:xorgconfig[1], będący aplikacją konsolową, mniej przyjazną dla początkujących użytkowników, jednakże przydatną w sytuacjach gdy inne narzędzia nie działają poprawnie. ==== === Konfiguracja zaawansowana ==== Konfiguracja z chipsetem graficznym Intel(R) i810 Konfiguracja ze zintegrowanym chipsetem Intel(R) i810 wymaga wykorzystania interfejsu programowego AGP [.filename]#agpgart# do obsługi karty w X11. Więcej informacji można znaleźć w podręczniku systemowym sterownika man:agp[4]. Pozwoli to nam skonfigurować naszą kartę graficzną jak każdą inną. W tym momencie należy zwrócić uwagę na fakt, iż w systemach bez man:agp[4] wkompilowanego w jądro, próba załadowania modułu za pomocą man:kldload[8] nie powiedzie się. Sterownik ten musi być obecny w jądrze w trakcie uruchamiania systemu poprzez wkompilowanie go bądź załadowanie za pomocą [.filename]#/boot/loader.conf#. ==== Dodanie płaskiego monitora szerokokątnego Sekcja ta zakłada, że posiadamy odrobinę wiedzy o zaawansowanej konfiguracji X11. Jeśli próby wykorzystania opisanych wyżej standardowych narzędzi konfiguracyjnych nie powiodły się, w plikach dzienników znajdziemy dostateczną ilość informacji pomocnych w uruchomieniu X z monitorem szerokokątnym. Będziemy musieli wykorzystać dowolny edytor teksu. Obecne formaty szerokokątne (WSXGA, WSXGA+, WUXGA, WXGA, WXGA+, itd.) obsługują formaty 16:10 oraz 10:9 bądź o innych proporcjach obrazu, które mogą stworzyć problemy w trakcie konfiguracji X. Niektórymi z powszechnie wykorzystywanych rozdzielczości ekranu dla proporcji 16:10 są: * 2560x1600 * 1920x1200 * 1680x1050 * 1440x900 * 1280x800 W pewnym momencie będzie to tak proste jak dodanie którejś z tych rozdzielczości jako możliwych trybów `Mode` w `Section ""Screen""`, jak np.: [.programlisting] .... Section ""Screen"" Identifier ""Screen0"" Device ""Card0"" Monitor ""Monitor0"" DefaultDepth 24 SubSection ""Display"" Viewport 0 0 Depth 24 Modes ""1680x1050"" EndSubSection EndSection .... Tym nie mniej Xorg jest na tyle sprytny, że potrafić pozyskać informacje o rozdzielczości ekranu monitora szerokokątnego za pomocą I2C/DDC w taki sposób, że wie jakie rozdzielczości potrafi obsłużyć monitor w kwestii częstotliwości i rozdzielczość. Jeśli odpowiednie wpisy `ModeLine` nie istnieją w sterownikach, będziemy musieli podpowiedzieć co nieco serwerowi Xorg. Z pliku [.filename]#/var/log/Xorg.0.log# możemy wydobyć dostateczną ilość informacji, by móc ręcznie stworzyć poprawnie obsługiwany `ModeLine`. Wystarczy odnaleźć zapis podobny do: [.programlisting] .... (II) MGA(0): Supported additional Video Mode: (II) MGA(0): clock: 146.2 MHz Image Size: 433 x 271 mm (II) MGA(0): h_active: 1680 h_sync: 1784 h_sync_end 1960 h_blank_end 2240 h_border: 0 (II) MGA(0): v_active: 1050 v_sync: 1053 v_sync_end 1059 v_blanking: 1089 v_border: 0 (II) MGA(0): Ranges: V min: 48 V max: 85 Hz, H min: 30 H max: 94 kHz, PixClock max 170 MHz .... Jest to tzw. informacja EDID. Stworzenie na jej podstawie `ModeLine` jest zaledwie kwestią wpisania we właściwej kolejności kilku liczb: [.programlisting] .... ModeLine <4 horiz. timings> <4 vert. timings> .... Tak więc wpis `ModeLine` w `Section ""Monitor""` dla tego przykładu wyglądałby następująco: [.programlisting] .... Section ""Monitor"" Identifier ""Monitor1"" VendorName ""Bigname"" ModelName ""BestModel"" ModeLine ""1680x1050"" 146.2 1680 1784 1960 2240 1050 1053 1059 1089 Option ""DPMS"" EndSection .... Po tych kilku prostych zmianach X powinien zacząć działać poprawnie z naszym szerokokątnym monitorem. [[x-fonts]] == Korzystanie z czcionek w X11 [[type1]] === Czcionki Type1 Czcionki dostarczane razem z X11 są dalekie od idealnych dla typowych aplikacji biurowych. Duże czcionki sprawiają wrażenie postrzępionych i mało profesjonalnych. Natomiast, małe czcionki w man:getenv[3] są całkowicie nieczytelne. Tym nie mniej, dostępnych jest kilka darmowych, wysokiej jakości czcionek Type1 (PostScript(R)), gotowych do użycia z X11. Na przykład, kolekcja czcionek URW (package:x11-fonts/urwfonts[]) zawiera wysokiej jakości wersje standardowych czcionek type1 (Times Roman(TM), Helvetica(TM), Palatino(TM) i innych). Kolekcja Freefonts (package:x11-fonts/freefonts[]) to wiele dodatkowych czcionek, przy czym większość z nich przewidzianych jest do użycia z oprogramowaniem graficznym, jak np. Gimp, tym samym nie są przygotowane do wykorzystania jako czcionki do aplikacji. Dodatkowo, przy minimum wysiłku, można skonfigurować X11, by korzystał z czcionek TrueType(R). Więcej szczegółów znaleźć można w podręczniku systemowym man:X[7] lub w części <>. By zainstalować kolekcje czcionek Type1 z portów, należy wpisać następujące polecenia: [source,shell] .... # cd /usr/ports/x11-fonts/urwfonts # make install clean .... Analogicznie postępujemy z czcionkami freefont bądź innymi kolekcjami. Aby serwer X wykrył zainstalowane czcionki, należy dodać odpowiedni wpis do pliku konfiguracji serwera ([.filename]#/etc/X11/xorg.conf#) postaci: [.programlisting] .... FontPath ""/usr/X11R6/lib/X11/fonts/URW/"" .... Alternatywną metodą jest wpisanie w trakcie sesji X: [source,shell] .... % xset fp+ /usr/X11R6/lib/X11/fonts/URW % xset fp rehash .... O ile rozwiązanie to również przyniesie pożądany efekt, o tyle dokonane w ten sposób zmiany zostaną stracone po zakończeniu sesji X. Oczywiście powyższe polecenia można dodać do pliku startowego ([.filename]#~/.xinitrc# dla typowej sesji `startx` bądź pliku [.filename]#~/.xsession# przy logowaniu się za pomocą graficznego menedżera logowania, jak np. XDM). Trzecią metodą jest skorzystanie z nowego pliku [.filename]#/usr/X11R6/etc/fonts/local.conf#: szczegóły w części poświęconej <>. [[truetype]] === Czcionki TrueType(R) Xorg posiada wbudowaną obsługę czcionek TrueType(R). Istnieją dwa moduły, które mogą aktywować tę funkcję. W przykładzie wykorzystany został moduł freetype, z uwagi na większą spójność z innymi wewnętrznymi elementami wyświetlającymi czcionki. By włączyć moduł freetype, wystarczy dodać poniższy wiersz do sekcji `""Module""` pliku [.filename]#/etc/X11/xorg.conf#. [.programlisting] .... Load ""freetype"" .... Teraz musimy utworzyć katalog dla czcionek TrueType(R) (na przykład [.filename]#/usr/X11R6/lib/X11/fonts/TrueType#) i skopiować wszystkie czcionki do tego katalogu. Należy pamiętać, że czcionki TrueType(R) nie mogą być bezpośrednio skopiowane z systemu Macintosh(R), by możliwe było wykorzystanie ich z X11; muszą być w formacie UNIX(R)/MS-DOS(R)/Windows(R). Po skopiowaniu plików należy wykorzystać ttmkfdir do stworzenia pliku [.filename]#fonts.dir#, by poinformować X, że zostały zainstalowane nowe czcionki. Program `ttmkfdir` dostępny jest z kolekcji portów FreeBSD jako package:x11-fonts/ttmkfdir[]. [source,shell] .... # cd /usr/X11R6/lib/X11/fonts/TrueType # ttmkfdir -o fonts.dir .... Na koniec musimy dodać katalog TrueType(R) do ścieżki czcionek. Robimy to analogicznie jak w przypadku czcionek <>, za pomocą polecenia [source,shell] .... % xset fp+ /usr/X11R6/lib/X11/fonts/TrueType % xset fp rehash .... bądź dodając wiersz `FontPath` do pliku [.filename]#xorg.conf#. Gotowe. Teraz man:getenv[3], Gimp, StarOffice(TM) i wszystkie inne aplikacje X powinny rozpoznawać zainstalowane czcionki TrueType(R). Bardzo małe czcionki (jak np. tekst na stronie WWW przy ustawionej wysokiej rozdzielczości ekranu) oraz bardzo duże (w StarOffice(TM)) będą wyglądały zdecydowanie lepiej. [[antialias]] === Wygładzane czcionki Wygładzanie (anti-aliasing) dostępne było w X11 od XFree86(TM) 4.0.2. Jednakże konfiguracja czcionek była niezmiernie nieporęczna do ukazania się XFree86(TM) 4.3.0. Począwszy od tej właśnie wersji, wszystkie czcionki w X11 dostępne w katalogach [.filename]#/usr/X11R6/lib/X11/fonts/# oraz [.filename]#~/.fonts/# są automatycznie dostępne dla aplikacji korzystających z wygładzania Xft. Nie wszystkie aplikacje potrafią korzystać z Xft, lecz wiele z czasem otrzymało wsparcie Xft. Przykładami aplikacji korzystających z Xft są Qt 2.3 i późniejsze (pakiet narzędzi graficznych dla środowiska KDE), GTK+ 2.0 i późniejsze (pakiet narzędzi graficznych dla środowiska GNOME desktop) oraz Mozilla 1.2 i późniejsze. By móc kontrolować, które czcionki będą wygładzane bądź skonfigurować właściwości wygładzania, należy stworzyć (bądź zmodyfikować, jeśli istnieje) plik [.filename]#/usr/X11R6/etc/fonts/local.conf#. Wykorzystując ten plik możemy dostroić kilka zaawansowanych opcji systemu czcionek Xft, jednakże rozdział ten skupia się jedynie na kilku podstawowych funkcjach. Więcej szczegółów znaleźć można w podręczniku systemowym man:fonts-conf[5]. W pliku tym stosowany jest format kodu XML. Przy jego edycji należy pamiętać o właściwym zamykaniu wszystkich znaczników. Zaczyna się on od typowego nagłówka XML oraz definicji DOCTYPE. Następnym w kolejności jest znacznik ``: [.programlisting] .... .... Jak już to zostało wcześniej powiedziane, wszystkie czcionki w katalogach [.filename]#/usr/X11R6/lib/X11/fonts/# oraz [.filename]#~/.fonts/# są automatycznie dostępne dla aplikacji korzystających z Xft. Jeśli natomiast chcemy dodać inny katalog nie będący podkatalogiem żadnego z powyższych, musimy dodać do pliku [.filename]#/usr/X11R6/etc/fonts/local.conf# wiersz podobny do poniższego: [.programlisting] .... /ścieżka/do/moich/czcionek .... Po dodaniu nowych czcionek, a szczególnie nowych katalogów, powinniśmy uruchomić poniższe polecenie, by przebudować bufor informacji o czcionkach: [source,shell] .... # fc-cache -f .... Wygładzanie sprawia, że brzegi czcionek stają się lekko zamazane, dzięki czemu małe litery są bardziej czytelne, a duże pozbawione efektu ""schodków"". Może jednak prowadzić do zmęczenia oczu gdy zostanie użyte w stosunku do liter o normalnej wiekości. By wyłączyć wygładzanie czcionek o rozmiarze mniejszym niż 14 punktów, należy dodać poniższe wiersze do pliku konfiguracyjnego: [.programlisting] .... 14 false 14 false .... Korzystając z wygładzania może się okazać, iż również odstępy pomiędzy literami niektórych czcionek o stałej szerokości są niewłaściwe. Ma to miejsce szczególnie w przypadku KDE. Jedynym rozwiązaniem tego problemu jest wymuszenie stałego odstępu o wartości 100 dla danych czcionek. W tym celu musimy wpisać: [.programlisting] .... fixed mono console mono .... (powyższe deklaruje inne typowe nazwy czcionek o stałej szerokości jako `""mono""`), a następnie: [.programlisting] .... mono 100 .... Niektóre czcionki, jak np. Helvetica, mogą stwarzać problemy jeśli zostaną poddane wygładzaniu. Z reguły daje to efekt czcionki przeciętej pionowo na pół. W najgorszym wypadku, może prowadzić to do załamania aplikacji typu Mozilla. By tego uniknąć, warto dodać poniższe do pliku [.filename]#local.conf#: [.programlisting] .... Helvetica sans-serif .... Skończywszy edycję [.filename]#local.conf# upewnijmy się, że plik kończy się znacznikiem ``. Bez tego może się okazać, że nasze zmiany zostaną zignorowane. Korzystanie z domyślnego zestawu czcionek, dostępnego wraz z X11, nie jest wskazane jeśli chodzi o wygładzanie. Zdecydowanie lepszy zestaw domyślnych czcionek zawiera port package:x11-fonts/bitstream-vera[]. Port ten zainstaluje również plik [.filename]#/usr/X11R6/etc/fonts/local.conf# jeśli jeszcze go nie mamy. Jeśli natomiast istnieje już taki plik w systemie, stworzony zostanie plik [.filename]#/usr/X11R6/etc/fonts/local.conf-vera#. Wystarczy dołączyć zawartość tego pliku do [.filename]#/usr/X11R6/etc/fonts/local.conf#, by czcionki Bitstream automatycznie zastąpiły domyślne czcionki X11 Serif, Sans Serif i Monospaced. Na koniec, użytkownicy mogą dodać swoją konfigurację poprzez własny plik [.filename]#.fonts.conf#. W tym celu każdy użytkownik może stworzyć i zmodyfikować plik [.filename]#~/.fonts.conf#. Również ten plik wykorzystuje format XML. Ostatnia rzecz: osoby korzystające z monitorów LCD mogą pragnąć zastosować wygładzanie podpikselowe. W skrócie, w metodzie tej czerwone, zielone i niebieskie komponenty (oddzielone w płaszczyźnie poziomej) traktowane są oddzielnie, co poprawia rozdzielczość poziomą i przynosi radykalne efekty. By włączyć wygładzanie podpikselowe należy dodać poniższy wiersz do pliku [.filename]#local.conf#: [.programlisting] .... unknown rgb .... [NOTE] ==== Zależnie od typu monitora, może się okazać, że będziemy musieli zastąpić `rgb` wartościami `bgr`, `vrgb` lub `vbgr`: poeksperymentujmy i sprawdźmy co da najlepszy efekt. ==== Wygładzanie powinno być aktywne przy następnym uruchomieniu serwera X. Tym nie mniej, programy muszą zostać poinformowane, by z niego korzystać. W chwili obecnej pakiet narzędzi Qt korzysta z wygładzania czcionek, tym samym również i całe środowisko KDE. GTK+ oraz GNOME również można skonfigurować do pracy z wygładzanymi czcionkami poprzez aplet ""Font"" (<> zawiera szczegółowy opis). Domyślnie, Mozilla 1.2 i późniejsze będą automatycznie korzystać z wygładzania. By wyłączyć tę opcję, należy ponownie skompilować program z parametrem `-DWITHOUT_XFT`. [[x-xdm]] == Menedżer pulpitów X === Omówienie Menedżer pulpitów X (ang. X Display Manager XDM) jest opcjonalną częścią Systemu okien X, wykorzystywaną do zarządzania sesjami logowania. Znajduje on zastosowanie w kilku typach sytuacji, włączając w to zarówno minimalistyczne ""Terminale X"", komputery prywatne, jak również ogromne sieciowe serwery graficzne. Z uwagi na fakt, iż System okien X jest niezależny od wykorzystywanej sieci jak i protokołu, istnieje wiele możliwych konfiguracji klientów i serwerów na różnych maszynach połączonych ze sobą za pomocą sieci. XDM dostarcza graficznego interfejsu pozwalającego wybrać, z którym serwerem się połączymy, jak i przeprowadzić autoryzację, np. za pomocą kombinacji loginu i hasła. XDM można postrzegać jako narzędzie dostarczające użytkownikowi takich samych funkcjonalności jak man:getty[8] (szczegółowy opis zawiera crossref:serialcomms[term-config,Configuration]). Oznacza to, że to właśnie menedżer pulpitów w imieniu użytkownika dokonuje logowania do systemu i uruchamia menedżera sesji (z reguły menedżera okien). Następnie, XDM oczekuje aż program zakończy działanie, sygnalizując tym samym, że użytkownik skończył pracę i menedżer pulpitów powinien go wylogować z systemu. W tym momencie XDM może ponownie wyświetlić ekran logowania i wyboru środowiska graficznego oczekująć na kolejnego użytkownika. === Korzystanie z XDM Demon XDM znajduje się w [.filename]#/usr/X11R6/bin/xdm#. Program ten może zostać uruchomiony w dowolnej chwili przez użytkownika `root` i od razu rozpocznie zarządzanie ekranami X w lokalnym systemie. Jeśli jednak XDM ma być uruchamiany przy każdym starcie systemu, najlepszym rozwiązaniem jest dodanie odpowiedniego wpisu do pliku [.filename]#/etc/ttys#. crossref:serialcomms[term-etcttys,Adding an Entry to /etc/ttys] zawiera więcej informacji odnośnie formatu i wykorzystania tego pliku. W domyślnej wersji plik [.filename]#/etc/ttys# zawiera wiersz uruchamiający demona XDM w wirtualnym terminalu: [source,shell] .... ttyv8 ""/usr/X11R6/bin/xdm -nodaemon"" xterm off secure .... Domyślnie, wiersz ten jest nieaktywny. By go uaktywnić należy zmienić zawartość 5 kolumny z `off` na `on` i ponownie uruchomić man:init[8] wykorzystująć wskazówki z crossref:serialcomms[term-hup,Force init to Reread /etc/ttys]. Pierwsza kolumna - nazwa terminala, którym będzie zarządzał dany program - to `ttyv8`. Oznacza to, że XDM będzie pracował na dziewiątny wirtualnym terminalu. === Konfiguracja XDM W katalogu [.filename]#/usr/X11R6/lib/X11/xdm# znajdują się pliki konfiguracyjne XDM. Pliki te można wykorzystać do zmiany zachowania i wyglądu menedżera ekranów. Z reguły są to następujące pliki: [.informaltable] [cols=""1,1"", frame=""none"", options=""header""] |=== | Plik | Opis |[.filename]#Xaccess# |Zestaw reguł autoryzacji klientów. |[.filename]#Xresources# |Domyślne wartości zasobów X. |[.filename]#Xservers# |Lista zdalnych i lokalnych ekranów do zarządzania. |[.filename]#Xsession# |Domyślny skrypt sesji logowania. |[.filename]#Xsetup_#* |Skrypt uruchamiający aplikacje przed interfejsem logowania. |[.filename]#xdm-config# |Konfiguracja globalna dla wszystkich ekranów danej maszynie. |[.filename]#xdm-errors# |Błędy generowane przez program serwera. |[.filename]#xdm-pid# |Identyfikator procesu aktualnie działającego XDM. |=== W tym katalogu znajduje się również kilka skryptów i programów wykorzystywanych do konfiguracji pulpitów w trakcie działania XDM. Zadanie każdego z tych plików zostanie pokrótce omówione. Dokładna składnia i wykorzystanie wszystkich tych plików znajduje się w man:xdm[1]. W domyślnej konfiguracji pojawi się prostokątne okno logowania z nazwą maszyny wypisaną dużą czcionką na samej górze, wraz z polami ""Login:"" i ""Password:"". Jest to dobry punkt wyjściowy do modyfikacji wyglądu i zachowania ekranów XDM. ==== Xaccess Protokół wykorzystywany do łączenia z puplitami obsługiwanymi przez XDM nosi nazwę X Display Manager Connection Protocol (XDMCP). Plik ten jest zestawem reguł do kontroli połączeń XDMCP ze zdalnych maszyn. Z reguły jest on ignorowany, chyba że w pliku [.filename]#xdm-config# zostanie włączona opcja nasłuchiwania zdalnych połączeń. Domyślnie nie zezwala się na połączenia z innych klientów. ==== Xresources Jest to plik domyślnej konfiguracji programu wyboru puplitu i ekranu logowania. W tym właśnie pliku można modyfikować ich wygląd. Format pliku jest identyczny z formatem app-defaults opisanym w dokumentacji X11. ==== Xservers Lista zdalnych pulpitów, do wyboru których mamy mieć dostęp za pomocą menedżera. ==== Xsession Domyślny skrypt sesji XDM uruchamiany po zalogowaniu się użytkownika. Z reguły każdy użytkownik posiada zmodyfikowany według własnego upodobania skrypt sesji w pliku [.filename]#~/.xsession#, uruchamiany zamiast tego skryptu. ==== Xsetup_* Skrypty te zostaną automatycznie uruchomione przed wyświetleniem interfejsu logowania i wyboru pulpitu. Dla każdego wykorzystywanego ekranu znajduje się tu plik o nazwie [.filename]#Xsetup_# wraz z numerem lokalnego ekranu (na przykład [.filename]#Xsetup_0#). Z reguły skrypty te uruchamiają jeden bądź dwa programy w tle, jak np. `xconsole`. ==== xdm-config Plik ustawień w formacie app-defaults, mający zastosowanie do wszystkich puplitów zarządzanych przez menedżera. ==== xdm-errors Plik ten zawiera wydruki wyjściowe serwerów X, które XDM stara się uruchomić. Jeśli w trakcie uruchamiania pulpitu z jakiegoś powodu proces ten zawiesi się, najlepszym miejscem poszukiwania komunikatów błędów jest właśnie ten plik. Komunikaty te są również umieszczane w pliku [.filename]#~/.xsession-errors# użytkownika dla danej sesji. === Konfiguracja sieciowego serwera graficznego By umożliwić innym klientom łączenie się z serwerem graficznym, należy zmodyfikować reguły kontroli dostępu i włączyć opcję nasłuchiwania połączeń. Domyślnie opcja ta jest nie aktywna. Jej aktywacja polega na odkomentowaniu poniższej linii w pliku [.filename]#xdm-config#: [source,shell] .... ! SECURITY: do not listen for XDMCP or Chooser requests ! Comment out this line if you want to manage X terminals with xdm DisplayManager.requestPort: 0 .... Następnie należy ponownie uruchomić XDM. Pamiętajmy, że komentarze w plikach app-defaults rozpoczynają się od znaku ""!"" zamiast typowego ""#"". Lektura przykładowego pliku [.filename]##Xaccess## oraz podręcznika systemowego man:xdm[1] może nam pomóc gdy będziemy potrzebować bardziej surowej kontroli dostępu. === Alternatywy dla XDM Dostępnych jest kilka alternatyw dla domyślnego menedżera XDM. Jeden z nich - kdm (dostarczany razem z KDE) - został bliżej opisany w tym w dalszej części rozdziału. Menedżer kdm oferuje wiele wizualnych usprawnień i kosmetycznych dodaktów, jak również możliwość wyboru menedżera okien przed zalogowaniem do systemu. [[x11-wm]] == Środowiska graficzne Niniejsza sekcja opisuje różne typy środowisk graficznych dostępnych dla X we FreeBSD. Termin ""środowisko graficzne"" może oznaczać wszystko, od prostego menedżera okien po kompletny zestaw aplikacji puplitu, jak KDE czy GNOME. [[x11-wm-gnome]] === GNOME [[x11-wm-gnome-about]] ==== O GNOME GNOME jest przyjaznym użytkownikowi środowiskiem graficznym, umożliwiającym łatwą konfigurację i proste korzystanie z komputera. GNOME posiada panel (do uruchamiania aplikacji i wyświetlania ich statusu), puplit (gdzie można umieszczać dane i aplikacje), zestaw standardowych narzędzi biurowych i aplikacji oraz zestaw pewnych konwencji ułatwiających współpracę miedzy aplikacjami i zachowanie wzajemnej spójności. Użytkownicy innych systemów operacyjnych powinni czuć się jak w domu korzystając z potężnego środowiska graficznego dostarczanego przez GNOME. Więcej informacji odnośnie środowiska GNOME we FreeBSD dostępnych jest na stronie WWW projektu http://www.FreeBSD.org/gnome[FreeBSD GNOME Project]. Strona ta zawiera również w miarę zrozumiałe FAQ traktujące o instalacji, konfiguracji i zarządzaniu GNOME. [[x11-wm-gnome-install]] ==== Instalacja GNOME Najprostszym sposobem instalacji GNOME jest poprzez menu ""Desktop Configuration"" w trakcie instalacji FreeBSD, co omawia crossref:desktop[default-desktop,Wybór menedżera okien] rozdziału 2. Możliwa jest również instalacja z pakietu bądź kolekcji portów: By zainstalować pakiet GNOME z sieci, wystarczy wpisać: [source,shell] .... # pkg_add -r gnome2 .... By skompilować GNOME ze źródeł najlepiej jest skorzystać z portu: [source,shell] .... # cd /usr/ports/x11/gnome2 # make install clean .... Mając już zainstalowanego GNOME musimy poinformować serwer X, by uruchamiał właśnie jego w miejsce domyślnego menedżera okien. Najprostszą metodą uruchomienia GNOME jest wykorzystanie GDM - menedżera pulpitów GNOME (ang. GNOME Display Manager). GDM jest instalowany jako część środowiska GNOME, jednakże jest on domyślnie wyłączony. By go włączyć, należy dodać wiersz `gdm_enable=""YES""` do pliku [.filename]#/etc/rc.conf#. Po ponownym uruchomieniu systemu, GNOME zostanie automatycznie włączony zaraz po zalogowaniu się - nie wymagana jest dodatkowa konfiguracja. Oczywiście, GNOME można uruchomić również bezpośrednio z linii poleceń poprawnie konfigurując plik [.filename]#.xinitrc# w katalogu domowym. Jeśli plik ten już istnieje wystarczy zastąpić wiersz odpowiadający za uruchomienie aktualnego menedżera okien na wiersz uruchamiający /usr/X11R6/bin/gnome-session. Jeśli w pliku nie dokonywaliśmy żadnych istotnych zmian, najprościej będzie po prostu wpisać: [source,shell] .... % echo ""/usr/X11R6/bin/gnome-session"" > ~/.xinitrc .... Następnie wpisujemy `startx`, co spowoduje uruchomienie środowiska GNOME. [NOTE] ==== Jeśli wykorzystujemy starszego menedżera okien, jak np. XDM, powyższe rozwiązanie nie zadziała. W takiej sytuacji musimy stworzyć plik wykonywalny [.filename]#.xsession# zawierający powyższe polecenie. W tym celu należy zmodyfikować ten plik i zastąpić polecenie uruchamiające aktualnego menedżera poleceniem /usr/X11R6/bin/gnome-session: ==== [source,shell] .... % echo ""#!/bin/sh"" > ~/.xsession % echo ""/usr/X11R6/bin/gnome-session"" >> ~/.xsession % chmod +x ~/.xsession .... Jeszcze jedną metodą jest skonfigurowanie menedżera pulpitów tak, by umożliwiał wybór menedżera okien w trakcie logowania. Sekcja <> wyjaśnia jak to zrobić w kdm - menedżerze puplitów KDE. [[x11-wm-gnome-antialias]] ==== Wygładzane czcionki w GNOME X11 obsługuje wygładzanie czcionek (anti-aliasing) za pomocą rozszerzenia ""RENDER"". GTK+ w wersji 2.0 i późniejszych (pakiet narzędzi graficznych wykorzystywany przez GNOME) potrafi korzystać z tej funkcji. Konfigurację wygładzania czcionek opisuje <>. Zatem, wykorzystując najnowsze oprogramowanie, możliwe jest wygładzanie czcionek w środowisku GNOME. Wystarczy przejść do menu menu:Applications[Desktop Preferences > Font] i wybrać jedną z opcji: btn:[Best shapes] (najlepsze kształty), btn:[Best contrast] (najlepszy kontrast) lub btn:[Subpixel smoothing (LCDs)] (wygładzanie podpikselowe). Natomiast dla aplikacji GTK+ nie będących częścią środowiska GNOME, należy ustawić zmienną środowiskową `GDK_USE_XFT` na `1` przed uruchomieniem programu. [[x11-wm-kde]] === KDE [[x11-wm-kde-about]] ==== O KDE KDE jest prostym w użyciu współczesnym środowiskiem graficznym, zawierającym między innymi: * Ładnie wyglądający puplit * Pulpit odznaczający się całkowitą przezroczystością sieci * Zintegrowany system pomocy, udostępniający w prosty sposób informacje o korzystaniu ze środowiska KDE i jego aplikacji * Jednakowy wygląd i zachowanie wszystkich aplikacji KDE * Standardowe menu i paski narzędzi, skróty klawiaturowe, schematy kolorów, itp. * Internacjonalizacja: KDE jest dostępny w ponad 40 językach * Scentralizowaną i spójną konfigurację środowiska * Całą masę przydanych aplikacji KDE posiada własną przeglądarkę internetową - Konqueror, która stanowi poważną konkurencję dla innych przeglądarek z systemów UNIX(R). Więcej informacji o KDE znaleźć można na http://www.kde.org/[stronie KDE]. Natomiast informacje o jego współpracy z FreeBSD dostępne są na stronie http://freebsd.kde.org/[FreeBSD-KDE team]. [[x11-wm-kde-install]] ==== Instalacja KDE Podobnie jak w przypadku GNOME czy dowolnego innego środowiska graficznego, najprostszym sposobem instalacji KDE jest skorzystanie z menu ""Desktop Configuration"" w procesie instalacji FreeBSD, co omawia crossref:desktop[default-desktop,Wybór menedżera okien] rozdziału 2. Ponownie, również KDE można zainstalować z pakietu bądź z kolekcji portów: By zainstalować pakiet KDE z sieci, wystarczy wpisać: [source,shell] .... # pkg_add -r kde .... man:pkg_add[1] automatycznie pobierze najnowszą wersję aplikacji. By skompilować KDE ze źródeł najlepiej jest skorzystać z portu: [source,shell] .... # cd /usr/ports/x11/kde3 # make install clean .... Po instalacji KDE należy poinformować serwer X, by uruchamiał go w miejsce domyślnego menedżera okien. W tym celu należy zmodyfikować plik [.filename]#.xinitrc#: [source,shell] .... % echo ""exec startkde"" > ~/.xinitrc .... Od tej pory, za każdym razem gdy uruchomimy System okien X za pomocą polecenia `startx`, uruchomione zostanie środowisko KDE. Jeśli wykorzystujemy starszego menedżera okien, jak np. XDM, wymagana jest odmienna konfiguracja. Opis konfiguracji kdm znajduje się w dalszej części tego rozdziału. [[x11-wm-kde-details]] === Więcej informacji o KDE Skoro zainstalowaliśmy już KDE, większość informacji można odnaleźć w systemie pomocy, bądź po prostu klikając w dowolne menu. Użytkownicy systemów Windows(R) czy Mac(R) powinni czuć się jak w domu. Najlepszym źródłem informacji o KDE jest dostępna w sieci dokumentacja. KDE zawiera własną przeglądarkę internetową - Konqueror, masę przydatnych aplikacji i obszerną dokumentację. Pozostała część tego rozdziału skupi się na technicznych zagadnieniach, trudnych do nauczenia się poprzez dość losowe poznawanie środowiska. [[x11-wm-kde-kdm]] ==== Menedżer puplitów KDE Administratorzy systemów wieloużytkownikowych mogą chcieć skorzystać z graficznego ekranu logowania. W tym celu można zastosować <>, jak to zostało opisane wcześniej. Można również wykorzystać alternatywne rozwiązanie dostępne razem z KDE - kdm - wyglądające zdecydowanie bardziej atrakcyjnie oraz posiadające wiele dodatkowych opcji logowania. W szczególności, użytkownicy mogą w prosty sposób wybrać (poprzez menu), które środowisko graficzne uruchomić po zalogowaniu (KDE, GNOME, bądź inne). By aktywować kdm, należy zmodyfikować wpis dla `ttyv8` w pliku [.filename]#/etc/ttys#. Wiersz ten powinien wyglądać następująco: [.programlisting] .... ttyv8 ""/usr/local/bin/kdm -nodaemon"" xterm on secure .... [[x11-wm-xfce]] === XFce [[x11-wm-xfce-about]] ==== O XFce XFce jest środowiskiem graficznym wykorzystującym pakiet narzędzi GTK+, podobnie jak GNOME, lecz jest zdecydowanie lżejsze i przeznaczone dla osób poszukujących prostego i efektywnego środowiska, lecz również łatwego w obsłudze i konfiguracji. Wyglądem bardzo przypomina CDE, często dostępne w komercyjnych systemach UNIX(R). Niektóre z cech XFce: * Prosty i łatwy w obsłudze pulpit * Możliwość konfiguracji wszystkich elementów za pomocą myszki, metody przeciągnij i upuść, itp. * Główny panel podobny do CDE z wieloma opcjami menu, apletami i programami wywołującymi * Zintegrowane menedżery okien, plików, dźwięku, moduł zgodności GNOME i inne dodatki * Możliwość stosowania motywów (skoro wykorzystuje GTK+) * Szybkie, lekkie i wydajne: idealny dla starszych/wolniejszych maszyn lub z ograniczonym zasobem pamięci Więcej informacji dostępnych jest na http://www.xfce.org/[stronie XFce]. [[x11-wm-xfce-install]] ==== Instalacja XFce W chwili pisania niniejszego tekstu dostępny jest pakiet binarny. By z niego zainstalować XFce, wystarczy wpisać: [source,shell] .... # pkg_add -r xfce4 .... Oczywiście, można również skompilować go ze źródeł przy pomocy kolekcji portów: [source,shell] .... # cd /usr/ports/x11-wm/xfce4 # make install clean .... Pozostaje jeszcze poinformować serwer X by uruchamiał XFce przy kolejnych uruchomieniach X. Wystarczy wpisać: [source,shell] .... % echo ""/usr/X11R6/bin/startxfce4"" > ~/.xinitrc .... Przy kolejnym uruchomieniu X jako środowisko graficzne zostanie wykorzystane XFce. Podobnie jak wcześniej, tak i teraz należy stworzyć plik [.filename]#.xsession# gdy korzystamy z XDM, co zostało umówione w części poświęconej <>, wpisując polecenie [.filename]#/usr/X11R6/bin/startxfce4#. Alternatywnie, należy skonfigurować menedżera pulpitów, by pozwalał na wybór środowiska graficznego w trakcie logowania, zgodnie z opisem z sekcji poświęconej <>. ",16308,True,2916.086419251942,median "package org.osflash.dom.path { import asunit.asserts.assertEquals; import asunit.asserts.assertEqualsArraysIgnoringOrder; import org.osflash.dom.element.DOMDocument; import org.osflash.dom.element.IDOMDocument; import org.osflash.dom.element.IDOMNode; import org.osflash.dom.support.DOMCallMethodNode; /** * .author Simon Richardson - simon.ustwo.co.uk */ public class DOMPathCallMethodTest { protected var document : IDOMDocument; [Before] public function setUp() : void { document = new DOMDocument(); } [After] public function tearDown() : void { document = null; } [Test] public function path_select_node1_call_method_no_arg() : void { const node0 : IDOMNode = new DOMCallMethodNode('node0'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const node2 : IDOMNode = new DOMCallMethodNode('node1'); document.add(node0); document.add(node1); document.add(node2); const result : Vector. = document.select('node1.methodNoArg()'); assertEquals('Result length should be 2', 2, result.length); } [Test] public function path_select_node1_call_method_no_arg_in_context() : void { const node0 : IDOMNode = new DOMCallMethodNode('node0'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const node2 : IDOMNode = new DOMCallMethodNode('node1'); document.add(node0); document.add(node1); document.add(node2); const result : Vector. = document.select('/node1.methodNoArg()'); assertEquals('Result length should be 2', 2, result.length); } [Test] public function path_select_node1_call_method_no_arg_in_dom() : void { const node0 : IDOMNode = new DOMCallMethodNode('node0'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const node2 : IDOMNode = new DOMCallMethodNode('node1'); document.add(node0); document.add(node1); document.add(node2); const result : Vector. = document.select('//node1.methodNoArg()'); assertEquals('Result length should be 2', 2, result.length); } [Test] public function path_select_node1_call_method_with_string_arg() : void { const node0 : IDOMNode = new DOMCallMethodNode('node0'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const node2 : IDOMNode = new DOMCallMethodNode('node1'); document.add(node0); document.add(node1); document.add(node2); const result : Vector. = document.select('node1.methodWithStringArg(""hello"")'); assertEquals('Result length should be 2', 2, result.length); } [Test] public function path_select_node1_call_method_with_string_arg_in_context() : void { const node0 : IDOMNode = new DOMCallMethodNode('node0'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const node2 : IDOMNode = new DOMCallMethodNode('node1'); document.add(node0); document.add(node1); document.add(node2); const result : Vector. = document.select('/node1.methodWithStringArg(""hello"")'); assertEquals('Result length should be 2', 2, result.length); } [Test] public function path_select_node1_call_method_with_string_arg_in_dom() : void { const node0 : IDOMNode = new DOMCallMethodNode('node0'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const node2 : IDOMNode = new DOMCallMethodNode('node1'); document.add(node0); document.add(node1); document.add(node2); const result : Vector. = document.select('//node1.methodWithStringArg(""hello"")'); assertEquals('Result length should be 2', 2, result.length); } [Test] public function path_select_node1_call_method_with_multiple_arg() : void { const node0 : IDOMNode = new DOMCallMethodNode('node0'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const node2 : IDOMNode = new DOMCallMethodNode('node1'); document.add(node0); document.add(node1); document.add(node2); const result : Vector. = document.select('node1.methodWithMultipleArg(""hello"", 1, ""duffus"", -8, 0.2)'); assertEquals('Result length should be 2', 2, result.length); } [Test] public function path_select_node1_then_subnode1_call_method_no_arg() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode0'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); document.add(node0); document.add(node1); node1.add(subnode0); node1.add(subnode1); subnode0.add(subsubnode0); const result : Vector. = document.select('node1/subnode1.methodWithNoArg()'); assertEquals('Result length should be 1', 1, result.length); } [Test] public function path_select_node1_then_subnode1_call_method_no_arg_in_context() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode0'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); document.add(node0); document.add(node1); node1.add(subnode0); node1.add(subnode1); subnode0.add(subsubnode0); const result : Vector. = document.select('/node1/subnode1.methodWithNoArg()'); assertEquals('Result length should be 1', 1, result.length); } [Test] public function path_select_node1_then_subnode1_call_method_no_arg_in_document() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode0'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); document.add(node0); document.add(node1); node1.add(subnode0); node1.add(subnode1); subnode0.add(subsubnode0); const result : Vector. = document.select('//node1/subnode1.methodWithNoArg()'); assertEquals('Result length should be 1', 1, result.length); } [Test] public function path_select_node1_then_subnode1_call_method_string_arg() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode0'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); document.add(node0); document.add(node1); node1.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); const result : Vector. = document.select('node1/subnode1.methodWithStringArg(""Sub hello"")'); assertEquals('Result length should be 3', 3, result.length); } [Test] public function path_select_node1_then_subnode1_call_method_string_arg_in_context() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode0'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); document.add(node0); document.add(node1); node1.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); const result : Vector. = document.select('/node1/subnode1.methodWithStringArg(""Sub hello"")'); assertEquals('Result length should be 3', 3, result.length); } [Test] public function path_select_node1_then_subnode1_call_method_string_arg_in_document() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode0'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); document.add(node0); document.add(node1); node1.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); const result : Vector. = document.select('//node1/subnode1.methodWithStringArg(""Sub hello"")'); assertEquals('Result length should be 3', 3, result.length); } [Test] public function path_select_node1_with_index1_then_subnode1_call_method_no_arg() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode1', '>'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); document.add(node0); document.add(node1); node0.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); const result : Vector. = document.select('node1[1]/subnode1.methodWithNoArg()'); assertEquals('Result length should be 3', 3, result.length); } [Test] public function path_select_node1_with_index1_then_subnode1_call_method_no_arg_in_context() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode1', '>'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); document.add(node0); document.add(node1); node0.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); const result : Vector. = document.select('/node1[1]/subnode1.methodWithNoArg()'); assertEquals('Result length should be 3', 3, result.length); } [Test] public function path_select_node1_with_index1_then_subnode1_call_method_no_arg_in_document() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode1', '>'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); document.add(node0); document.add(node1); node0.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); const result : Vector. = document.select('//node1[1]/subnode1.methodWithNoArg()'); assertEquals('Result length should be 3', 3, result.length); } [Test] public function path_select_node1_with_index1_then_subnode1_call_method_string_arg() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode1', '>'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); document.add(node0); document.add(node1); node0.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); const result : Vector. = document.select('node1[1]/subnode1.methodWithStringArg(""Sub hello"")'); assertEquals('Result length should be 3', 3, result.length); } [Test] public function path_select_node1_with_index1_then_subnode1_call_method_string_arg_in_context() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode1', '>'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); document.add(node0); document.add(node1); node0.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); const result : Vector. = document.select('/node1[1]/subnode1.methodWithStringArg(""Sub hello"")'); assertEquals('Result length should be 3', 3, result.length); } [Test] public function path_select_node1_with_index1_then_subnode1_call_method_string_arg_in_document() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode1', '>'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); document.add(node0); document.add(node1); node0.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); const result : Vector. = document.select('//node1[1]/subnode1.methodWithStringArg(""Sub hello"")'); assertEquals('Result length should be 3', 3, result.length); } [Test] public function path_select_subnode1_with_index1_then_subsubnode2_call_method_no_arg() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); const subsubnode1 : IDOMNode = new DOMCallMethodNode('subsubnode1'); const subsubnode2 : IDOMNode = new DOMCallMethodNode('subsubnode2'); const subsubnode3 : IDOMNode = new DOMCallMethodNode('subsubnode2'); const subsubnode4 : IDOMNode = new DOMCallMethodNode('subsubnode2'); document.add(node0); document.add(node1); node0.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); subnode0.add(subsubnode1); subnode0.add(subsubnode2); subnode1.add(subsubnode3); subnode1.add(subsubnode4); const result : Vector. = document.select('node1[1]/subnode1[0]/subsubnode2.methodNoArg()'); assertEquals('Result length should be 2', 2, result.length); assertEqualsArraysIgnoringOrder('Result length should include', [subsubnode3, subsubnode4], [result[0], result[1]] ); } [Test] public function path_select_subnode1_with_index1_then_subsubnode2_call_method_no_arg_in_context() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); const subsubnode1 : IDOMNode = new DOMCallMethodNode('subsubnode1'); const subsubnode2 : IDOMNode = new DOMCallMethodNode('subsubnode2'); const subsubnode3 : IDOMNode = new DOMCallMethodNode('subsubnode2'); const subsubnode4 : IDOMNode = new DOMCallMethodNode('subsubnode2'); document.add(node0); document.add(node1); node0.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); subnode0.add(subsubnode1); subnode0.add(subsubnode2); subnode1.add(subsubnode3); subnode1.add(subsubnode4); const result : Vector. = document.select('/node1[1]/subnode1[0]/subsubnode2.methodNoArg()'); assertEquals('Result length should be 2', 2, result.length); assertEqualsArraysIgnoringOrder('Result length should include', [subsubnode3, subsubnode4], [result[0], result[1]] ); } [Test] public function path_select_subnode1_with_index1_then_subsubnode2_call_method_no_arg_in_document() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); const subsubnode1 : IDOMNode = new DOMCallMethodNode('subsubnode1'); const subsubnode2 : IDOMNode = new DOMCallMethodNode('subsubnode2'); const subsubnode3 : IDOMNode = new DOMCallMethodNode('subsubnode2'); const subsubnode4 : IDOMNode = new DOMCallMethodNode('subsubnode2'); document.add(node0); document.add(node1); node0.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); subnode0.add(subsubnode1); subnode0.add(subsubnode2); subnode1.add(subsubnode3); subnode1.add(subsubnode4); const result : Vector. = document.select('//node1[1]/subnode1[0]/subsubnode2.methodNoArg()'); assertEquals('Result length should be 2', 2, result.length); assertEqualsArraysIgnoringOrder('Result length should include', [subsubnode3, subsubnode4], [result[0], result[1]] ); } [Test] public function path_select_subnode1_with_index1_then_subsubnode2_call_method_string_arg() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); const subsubnode1 : IDOMNode = new DOMCallMethodNode('subsubnode1'); const subsubnode2 : IDOMNode = new DOMCallMethodNode('subsubnode2'); const subsubnode3 : IDOMNode = new DOMCallMethodNode('subsubnode2'); const subsubnode4 : IDOMNode = new DOMCallMethodNode('subsubnode2'); document.add(node0); document.add(node1); node0.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); subnode0.add(subsubnode1); subnode0.add(subsubnode2); subnode1.add(subsubnode3); subnode1.add(subsubnode4); const result : Vector. = document.select('node1[1]/subnode1[0]/subsubnode2.methodWithStringArg(""Hello subsubnode2"")'); assertEquals('Result length should be 2', 2, result.length); assertEqualsArraysIgnoringOrder('Result length should include', [subsubnode3, subsubnode4], [result[0], result[1]] ); } [Test] public function path_select_subnode1_with_index1_then_subsubnode2_call_method_string_arg_in_context() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); const subsubnode1 : IDOMNode = new DOMCallMethodNode('subsubnode1'); const subsubnode2 : IDOMNode = new DOMCallMethodNode('subsubnode2'); const subsubnode3 : IDOMNode = new DOMCallMethodNode('subsubnode2'); const subsubnode4 : IDOMNode = new DOMCallMethodNode('subsubnode2'); document.add(node0); document.add(node1); node0.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); subnode0.add(subsubnode1); subnode0.add(subsubnode2); subnode1.add(subsubnode3); subnode1.add(subsubnode4); const result : Vector. = document.select('/node1[1]/subnode1[0]/subsubnode2.methodWithStringArg(""Hello subsubnode2"")'); assertEquals('Result length should be 2', 2, result.length); assertEqualsArraysIgnoringOrder('Result length should include', [subsubnode3, subsubnode4], [result[0], result[1]] ); } [Test] public function path_select_subnode1_with_index1_then_subsubnode2_call_method_string_arg_in_document() : void { const node0 : IDOMNode = new DOMCallMethodNode('node1'); const node1 : IDOMNode = new DOMCallMethodNode('node1'); const subnode0 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode1 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode2 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode3 : IDOMNode = new DOMCallMethodNode('subnode1'); const subnode4 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode5 : IDOMNode = new DOMCallMethodNode('subnode2'); const subnode6 : IDOMNode = new DOMCallMethodNode('subnode3'); const subsubnode0 : IDOMNode = new DOMCallMethodNode('subsubnode0'); const subsubnode1 : IDOMNode = new DOMCallMethodNode('subsubnode1'); const subsubnode2 : IDOMNode = new DOMCallMethodNode('subsubnode2'); const subsubnode3 : IDOMNode = new DOMCallMethodNode('subsubnode2'); const subsubnode4 : IDOMNode = new DOMCallMethodNode('subsubnode2'); document.add(node0); document.add(node1); node0.add(subnode0); node1.add(subnode1); node1.add(subnode2); node1.add(subnode3); node1.add(subnode4); node1.add(subnode5); node1.add(subnode6); subnode0.add(subsubnode0); subnode0.add(subsubnode1); subnode0.add(subsubnode2); subnode1.add(subsubnode3); subnode1.add(subsubnode4); const result : Vector. = document.select('//node1[1]/subnode1[0]/subsubnode2.methodWithStringArg(""Hello subsubnode2"")'); assertEquals('Result length should be 2', 2, result.length); assertEqualsArraysIgnoringOrder('Result length should include', [subsubnode3, subsubnode4], [result[0], result[1]] ); } } } ",8286,True,2729.5179501272064,median "[[production-ready]] = Spring Boot Actuator: Production-ready features [partintro] -- Spring Boot includes a number of additional features to help you monitor and manage your application when you push it to production. You can choose to manage and monitor your application by using HTTP endpoints or with JMX. Auditing, health, and metrics gathering can also be automatically applied to your application. -- [[production-ready-enabling]] == Enabling Production-ready Features The {github-code}/spring-boot-project/spring-boot-actuator[`spring-boot-actuator`] module provides all of Spring Boot's production-ready features. The simplest way to enable the features is to add a dependency to the `spring-boot-starter-actuator` '`Starter`'. .Definition of Actuator **** An actuator is a manufacturing term that refers to a mechanical device for moving or controlling something. Actuators can generate a large amount of motion from a small change. **** To add the actuator to a Maven based project, add the following '`Starter`' dependency: [source,xml,indent=0] ---- org.springframework.boot spring-boot-starter-actuator ---- For Gradle, use the following declaration: [source,groovy,indent=0] ---- dependencies { compile(""org.springframework.boot:spring-boot-starter-actuator"") } ---- [[production-ready-endpoints]] == Endpoints Actuator endpoints let you monitor and interact with your application. Spring Boot includes a number of built-in endpoints and lets you add your own. For example, the `health` endpoint provides basic application health information. Each individual endpoint can be <>. This controls whether or not the endpoint is created and its bean exists in the application context. To be remotely accessible an endpoint also has to be <>. Most applications choose HTTP, where the ID of the endpoint along with a prefix of `/actuator` is mapped to a URL. For example, by default, the `health` endpoint is mapped to `/actuator/health`. The following technology-agnostic endpoints are available: [cols=""2,5,2""] |=== | ID | Description | Enabled by default |`auditevents` |Exposes audit events information for the current application. |Yes |`beans` |Displays a complete list of all the Spring beans in your application. |Yes |`caches` |Exposes available caches. |Yes |`conditions` |Shows the conditions that were evaluated on configuration and auto-configuration classes and the reasons why they did or did not match. |Yes |`configprops` |Displays a collated list of all `@ConfigurationProperties`. |Yes |`env` |Exposes properties from Spring's `ConfigurableEnvironment`. |Yes |`flyway` |Shows any Flyway database migrations that have been applied. |Yes |`health` |Shows application health information. |Yes |`httptrace` |Displays HTTP trace information (by default, the last 100 HTTP request-response exchanges). |Yes |`info` |Displays arbitrary application info. |Yes |`integrationgraph` |Shows the Spring Integration graph. |Yes |`loggers` |Shows and modifies the configuration of loggers in the application. |Yes |`liquibase` |Shows any Liquibase database migrations that have been applied. |Yes |`metrics` |Shows '`metrics`' information for the current application. |Yes |`mappings` |Displays a collated list of all `@RequestMapping` paths. |Yes |`scheduledtasks` |Displays the scheduled tasks in your application. |Yes |`sessions` |Allows retrieval and deletion of user sessions from a Spring Session-backed session store. Not available when using Spring Session's support for reactive web applications. |Yes |`shutdown` |Lets the application be gracefully shutdown. |No |`threaddump` |Performs a thread dump. |Yes |=== If your application is a web application (Spring MVC, Spring WebFlux, or Jersey), you can use the following additional endpoints: [cols=""2,5,2""] |=== | ID | Description | Enabled by default |`heapdump` |Returns a GZip compressed `hprof` heap dump file. |Yes |`jolokia` |Exposes JMX beans over HTTP (when Jolokia is on the classpath, not available for WebFlux). |Yes |`logfile` |Returns the contents of the logfile (if `logging.file` or `logging.path` properties have been set). Supports the use of the HTTP `Range` header to retrieve part of the log file's content. |Yes |`prometheus` |Exposes metrics in a format that can be scraped by a Prometheus server. |Yes |=== To learn more about the Actuator's endpoints and their request and response formats, please refer to the separate API documentation ({spring-boot-actuator-api}/html[HTML] or {spring-boot-actuator-api}/pdf/spring-boot-actuator-web-api.pdf[PDF]). [[production-ready-endpoints-enabling-endpoints]] === Enabling Endpoints By default, all endpoints except for `shutdown` are enabled. To configure the enablement of an endpoint, use its `management.endpoint..enabled` property. The following example enables the `shutdown` endpoint: [source,properties,indent=0] ---- management.endpoint.shutdown.enabled=true ---- If you prefer endpoint enablement to be opt-in rather than opt-out, set the `management.endpoints.enabled-by-default` property to `false` and use individual endpoint `enabled` properties to opt back in. The following example enables the `info` endpoint and disables all other endpoints: [source,properties,indent=0] ---- management.endpoints.enabled-by-default=false management.endpoint.info.enabled=true ---- NOTE: Disabled endpoints are removed entirely from the application context. If you want to change only the technologies over which an endpoint is exposed, use the <> instead. [[production-ready-endpoints-exposing-endpoints]] === Exposing Endpoints Since Endpoints may contain sensitive information, careful consideration should be given about when to expose them. The following table shows the default exposure for the built-in endpoints: [cols=""1,1,1""] |=== | ID | JMX | Web |`auditevents` |Yes |No |`beans` |Yes |No |`conditions` |Yes |No |`configprops` |Yes |No |`env` |Yes |No |`flyway` |Yes |No |`health` |Yes |Yes |`heapdump` |N/A |No |`httptrace` |Yes |No |`info` |Yes |Yes |`integrationgraph` |Yes |Yes |`jolokia` |N/A |No |`logfile` |N/A |No |`loggers` |Yes |No |`liquibase` |Yes |No |`metrics` |Yes |No |`mappings` |Yes |No |`prometheus` |N/A |No |`scheduledtasks` |Yes |No |`sessions` |Yes |No |`shutdown` |Yes |No |`threaddump` |Yes |No |=== To change which endpoints are exposed, use the following technology-specific `include` and `exclude` properties: [cols=""3,1""] |=== |Property | Default |`management.endpoints.jmx.exposure.exclude` | |`management.endpoints.jmx.exposure.include` | `*` |`management.endpoints.web.exposure.exclude` | |`management.endpoints.web.exposure.include` | `info, health` |=== The `include` property lists the IDs of the endpoints that are exposed. The `exclude` property lists the IDs of the endpoints that should not be exposed. The `exclude` property takes precedence over the `include` property. Both `include` and `exclude` properties can be configured with a list of endpoint IDs. For example, to stop exposing all endpoints over JMX and only expose the `health` and `info` endpoints, use the following property: [source,properties,indent=0] ---- management.endpoints.jmx.exposure.include=health,info ---- `*` can be used to select all endpoints. For example, to expose everything over HTTP except the `env` and `beans` endpoints, use the following properties: [source,properties,indent=0] ---- management.endpoints.web.exposure.include=* management.endpoints.web.exposure.exclude=env,beans ---- [NOTE] ==== `*` has a special meaning in YAML, so be sure to add quotes if you want to include (or exclude) all endpoints, as shown in the following example: [source,yaml,indent=0] ---- management: endpoints: web: exposure: include: ""*"" ---- ==== NOTE: If your application is exposed publicly, we strongly recommend that you also <>. TIP: If you want to implement your own strategy for when endpoints are exposed, you can register an `EndpointFilter` bean. [[production-ready-endpoints-security]] === Securing HTTP Endpoints You should take care to secure HTTP endpoints in the same way that you would any other sensitive URL. If Spring Security is present, endpoints are secured by default using Spring Security’s content-negotiation strategy. If you wish to configure custom security for HTTP endpoints, for example, only allow users with a certain role to access them, Spring Boot provides some convenient `RequestMatcher` objects that can be used in combination with Spring Security. A typical Spring Security configuration might look something like the following example: [source,java,indent=0] ---- @Configuration public class ActuatorSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests() .anyRequest().hasRole(""ENDPOINT_ADMIN"") .and() .httpBasic(); } } ---- The preceding example uses `EndpointRequest.toAnyEndpoint()` to match a request to any endpoint and then ensures that all have the `ENDPOINT_ADMIN` role. Several other matcher methods are also available on `EndpointRequest`. See the API documentation ({spring-boot-actuator-api}/html[HTML] or {spring-boot-actuator-api}/pdf/spring-boot-actuator-web-api.pdf[PDF]) for details. If you deploy applications behind a firewall, you may prefer that all your actuator endpoints can be accessed without requiring authentication. You can do so by changing the `management.endpoints.web.exposure.include` property, as follows: .application.properties [source,properties,indent=0] ---- management.endpoints.web.exposure.include=* ---- Additionally, if Spring Security is present, you would need to add custom security configuration that allows unauthenticated access to the endpoints as shown in the following example: [source,java,indent=0] ---- @Configuration public class ActuatorSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests() .anyRequest().permitAll(); } } ---- [[production-ready-endpoints-caching]] === Configuring Endpoints Endpoints automatically cache responses to read operations that do not take any parameters. To configure the amount of time for which an endpoint will cache a response, use its `cache.time-to-live` property. The following example sets the time-to-live of the `beans` endpoint's cache to 10 seconds: .application.properties [source,properties,indent=0] ---- management.endpoint.beans.cache.time-to-live=10s ---- NOTE: The prefix `management.endpoint.` is used to uniquely identify the endpoint that is being configured. NOTE: When making an authenticated HTTP request, the `Principal` is considered as input to the endpoint and, therefore, the response will not be cached. [[production-ready-endpoints-hypermedia]] === Hypermedia for Actuator Web Endpoints A ""`discovery page`"" is added with links to all the endpoints. The ""`discovery page`"" is available on `/actuator` by default. When a custom management context path is configured, the ""`discovery page`"" automatically moves from `/actuator` to the root of the management context. For example, if the management context path is `/management`, then the discovery page is available from `/management`. When the management context path is set to `/`, the discovery page is disabled to prevent the possibility of a clash with other mappings. [[production-ready-endpoints-custom-mapping]] === Actuator Web Endpoint Paths By default, endpoints are exposed over HTTP under the `/actuator` path by using the ID of the endpoint. For example, the `beans` endpoint is exposed under `/actuator/beans`. If you want to map endpoints to a different path, you can use the `management.endpoints.web.path-mapping` property. Also, if you want change the base path, you can use `management.endpoints.web.base-path`. The following example remaps `/actuator/health` to `/healthcheck`: .application.properties [source,properties,indent=0] ---- management.endpoints.web.base-path=/ management.endpoints.web.path-mapping.health=healthcheck ---- [[production-ready-endpoints-cors]] === CORS Support https://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] (CORS) is a https://www.w3.org/TR/cors/[W3C specification] that lets you specify in a flexible way what kind of cross-domain requests are authorized. If you use Spring MVC or Spring WebFlux, Actuator's web endpoints can be configured to support such scenarios. CORS support is disabled by default and is only enabled once the `management.endpoints.web.cors.allowed-origins` property has been set. The following configuration permits `GET` and `POST` calls from the `example.com` domain: [source,properties,indent=0] ---- management.endpoints.web.cors.allowed-origins=http://example.com management.endpoints.web.cors.allowed-methods=GET,POST ---- TIP: See {sc-spring-boot-actuator-autoconfigure}/endpoint/web/CorsEndpointProperties.{sc-ext}[CorsEndpointProperties] for a complete list of options. [[production-ready-endpoints-custom]] === Implementing Custom Endpoints If you add a `@Bean` annotated with `@Endpoint`, any methods annotated with `@ReadOperation`, `@WriteOperation`, or `@DeleteOperation` are automatically exposed over JMX and, in a web application, over HTTP as well. Endpoints can be exposed over HTTP using Jersey, Spring MVC, or Spring WebFlux. You can also write technology-specific endpoints by using `@JmxEndpoint` or `@WebEndpoint`. These endpoints are restricted to their respective technologies. For example, `@WebEndpoint` is exposed only over HTTP and not over JMX. You can write technology-specific extensions by using `@EndpointWebExtension` and `@EndpointJmxExtension`. These annotations let you provide technology-specific operations to augment an existing endpoint. Finally, if you need access to web-framework-specific functionality, you can implement Servlet or Spring `@Controller` and `@RestController` endpoints at the cost of them not being available over JMX or when using a different web framework. [[production-ready-endpoints-custom-input]] ==== Receiving Input Operations on an endpoint receive input via their parameters. When exposed via the web, the values for these parameters are taken from the URL's query parameters and from the JSON request body. When exposed via JMX, the parameters are mapped to the parameters of the MBean's operations. Parameters are required by default. They can be made optional by annotating them with `@org.springframework.lang.Nullable`. Each root property in the JSON request body can be mapped to a parameter of the endpoint. Consider the following JSON request body: [source,json,indent=0] ---- { ""name"": ""test"", ""counter"": 42 } ---- This can be used to invoke a write operation that takes a `String test` and `int counter` parameters. TIP: Because endpoints are technology agnostic, only simple types can be specified in the method signature. In particular declaring a single parameter with a custom type defining a `name` and `counter` properties is not supported. NOTE: To allow the input to be mapped to the operation method's parameters, Java code implementing an endpoint should be compiled with `-parameters`, and Kotlin code implementing an endpoint should be compiled with `-java-parameters`. This will happen automatically if you are using Spring Boot's Gradle plugin or if you are using Maven and `spring-boot-starter-parent`. [[production-ready-endpoints-custom-input-conversion]] ===== Input type conversion The parameters passed to endpoint operation methods are, if necessary, automatically converted to the required type. Before calling an operation method, the input received via JMX or an HTTP request is converted to the required types using an instance of `ApplicationConversionService`. [[production-ready-endpoints-custom-web]] ==== Custom Web Endpoints Operations on an `@Endpoint`, `@WebEndpoint`, or `@EndpointWebExtension` are automatically exposed over HTTP using Jersey, Spring MVC, or Spring WebFlux. [[production-ready-endpoints-custom-web-predicate]] ===== Web Endpoint Request Predicates A request predicate is automatically generated for each operation on a web-exposed endpoint. [[production-ready-endpoints-custom-web-predicate-path]] ===== Path The path of the predicate is determined by the ID of the endpoint and the base path of web-exposed endpoints. The default base path is `/actuator`. For example, an endpoint with the ID `sessions` will use `/actuator/sessions` as its path in the predicate. The path can be further customized by annotating one or more parameters of the operation method with `@Selector`. Such a parameter is added to the path predicate as a path variable. The variable's value is passed into the operation method when the endpoint operation is invoked. [[production-ready-endpoints-custom-web-predicate-http-method]] ===== HTTP method The HTTP method of the predicate is determined by the operation type, as shown in the following table: [cols=""3, 1""] |=== |Operation |HTTP method |`@ReadOperation` |`GET` |`@WriteOperation` |`POST` |`@DeleteOperation` |`DELETE` |=== [[production-ready-endpoints-custom-web-predicate-consumes]] ===== Consumes For a `@WriteOperation` (HTTP `POST`) that uses the request body, the consumes clause of the predicate is `application/vnd.spring-boot.actuator.v2+json, application/json`. For all other operations the consumes clause is empty. [[production-ready-endpoints-custom-web-predicate-produces]] ===== Produces The produces clause of the predicate can be determined by the `produces` attribute of the `@DeleteOperation`, `@ReadOperation`, and `@WriteOperation` annotations. The attribute is optional. If it is not used, the produces clause is determined automatically. If the operation method returns `void` or `Void` the produces clause is empty. If the operation method returns a `org.springframework.core.io.Resource`, the produces clause is `application/octet-stream`. For all other operations the produces clause is `application/vnd.spring-boot.actuator.v2+json, application/json`. [[production-ready-endpoints-custom-web-response-status]] ===== Web Endpoint Response Status The default response status for an endpoint operation depends on the operation type (read, write, or delete) and what, if anything, the operation returns. A `@ReadOperation` returns a value, the response status will be 200 (OK). If it does not return a value, the response status will be 404 (Not Found). If a `@WriteOperation` or `@DeleteOperation` returns a value, the response status will be 200 (OK). If it does not return a value the response status will be 204 (No Content). If an operation is invoked without a required parameter, or with a parameter that cannot be converted to the required type, the operation method will not be called and the response status will be 400 (Bad Request). [[production-ready-endpoints-custom-web-range-requests]] ===== Web Endpoint Range Requests An HTTP range request can be used to request part of an HTTP resource. When using Spring MVC or Spring Web Flux, operations that return a `org.springframework.core.io.Resource` automatically support range requests. NOTE: Range requests are not supported when using Jersey. [[production-ready-endpoints-custom-web-security]] ===== Web Endpoint Security An operation on a web endpoint or a web-specific endpoint extension can receive the current `java.security.Principal` or `org.springframework.boot.actuate.endpoint.SecurityContext` as a method parameter. The former is typically used in conjunction with `@Nullable` to provide different behaviour for authenticated and unauthenticated users. The latter is typically used to perform authorization checks using its `isUserInRole(String)` method. [[production-ready-endpoints-custom-servlet]] ==== Servlet endpoints A `Servlet` can be exposed as an endpoint by implementing a class annotated with `@ServletEndpoint` that also implements `Supplier`. Servlet endpoints provide deeper integration with the Servlet container but at the expense of portability. They are intended to be used to expose an existing `Servlet` as an endpoint. For new endpoints, the `@Endpoint` and `@WebEndpoint` annotations should be preferred whenever possible. [[production-ready-endpoints-custom-controller]] ==== Controller endpoints `@ControllerEndpoint` and `@RestControllerEndpoint` can be used to implement an endpoint that is only exposed by Spring MVC or Spring WebFlux. Methods are mapped using the standard annotations for Spring MVC and Spring WebFlux such as `@RequestMapping` and `@GetMapping`, with the endpoint's ID being used as a prefix for the path. Controller endpoints provide deeper integration with Spring's web frameworks but at the expense of portability. The `@Endpoint` and `@WebEndpoint` annotations should be preferred whenever possible. [[production-ready-health]] === Health Information You can use health information to check the status of your running application. It is often used by monitoring software to alert someone when a production system goes down. The information exposed by the `health` endpoint depends on the `management.endpoint.health.show-details` property which can be configured with one of the following values: [cols=""1, 3""] |=== |Name |Description |`never` |Details are never shown. |`when-authorized` |Details are only shown to authorized users. Authorized roles can be configured using `management.endpoint.health.roles`. |`always` |Details are shown to all users. |=== The default value is `never`. A user is considered to be authorized when they are in one or more of the endpoint's roles. If the endpoint has no configured roles (the default) all authenticated users are considered to be authorized. The roles can be configured using the `management.endpoint.health.roles` property. NOTE: If you have secured your application and wish to use `always`, your security configuration must permit access to the health endpoint for both authenticated and unauthenticated users. Health information is collected from the content of a {sc-spring-boot-actuator}/health/HealthIndicatorRegistry.{sc-ext}[ `HealthIndicatorRegistry`] (by default all {sc-spring-boot-actuator}/health/HealthIndicator.{sc-ext}[`HealthIndicator`] instances defined in your `ApplicationContext`. Spring Boot includes a number of auto-configured `HealthIndicators` and you can also write your own. By default, the final system state is derived by the `HealthAggregator` which sorts the statuses from each `HealthIndicator` based on an ordered list of statuses. The first status in the sorted list is used as the overall health status. If no `HealthIndicator` returns a status that is known to the `HealthAggregator`, an `UNKNOWN` status is used. TIP: The `HealthIndicatorRegistry` can be used to register and unregister health indicators at runtime. ==== Auto-configured HealthIndicators The following `HealthIndicators` are auto-configured by Spring Boot when appropriate: [cols=""4,6""] |=== |Name |Description |{sc-spring-boot-actuator}/cassandra/CassandraHealthIndicator.{sc-ext}[`CassandraHealthIndicator`] |Checks that a Cassandra database is up. |{sc-spring-boot-actuator}/system/DiskSpaceHealthIndicator.{sc-ext}[`DiskSpaceHealthIndicator`] |Checks for low disk space. |{sc-spring-boot-actuator}/jdbc/DataSourceHealthIndicator.{sc-ext}[`DataSourceHealthIndicator`] |Checks that a connection to `DataSource` can be obtained. |{sc-spring-boot-actuator}/elasticsearch/ElasticsearchHealthIndicator.{sc-ext}[`ElasticsearchHealthIndicator`] |Checks that an Elasticsearch cluster is up. |{sc-spring-boot-actuator}/influx/InfluxDbHealthIndicator.{sc-ext}[`InfluxDbHealthIndicator`] |Checks that an InfluxDB server is up. |{sc-spring-boot-actuator}/jms/JmsHealthIndicator.{sc-ext}[`JmsHealthIndicator`] |Checks that a JMS broker is up. |{sc-spring-boot-actuator}/mail/MailHealthIndicator.{sc-ext}[`MailHealthIndicator`] |Checks that a mail server is up. |{sc-spring-boot-actuator}/mongo/MongoHealthIndicator.{sc-ext}[`MongoHealthIndicator`] |Checks that a Mongo database is up. |{sc-spring-boot-actuator}/neo4j/Neo4jHealthIndicator.{sc-ext}[`Neo4jHealthIndicator`] |Checks that a Neo4j server is up. |{sc-spring-boot-actuator}/amqp/RabbitHealthIndicator.{sc-ext}[`RabbitHealthIndicator`] |Checks that a Rabbit server is up. |{sc-spring-boot-actuator}/redis/RedisHealthIndicator.{sc-ext}[`RedisHealthIndicator`] |Checks that a Redis server is up. |{sc-spring-boot-actuator}/solr/SolrHealthIndicator.{sc-ext}[`SolrHealthIndicator`] |Checks that a Solr server is up. |=== TIP: You can disable them all by setting the `management.health.defaults.enabled` property. ==== Writing Custom HealthIndicators To provide custom health information, you can register Spring beans that implement the {sc-spring-boot-actuator}/health/HealthIndicator.{sc-ext}[`HealthIndicator`] interface. You need to provide an implementation of the `health()` method and return a `Health` response. The `Health` response should include a status and can optionally include additional details to be displayed. The following code shows a sample `HealthIndicator` implementation: [source,java,indent=0] ---- import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class MyHealthIndicator implements HealthIndicator { @Override public Health health() { int errorCode = check(); // perform some specific health check if (errorCode != 0) { return Health.down().withDetail(""Error Code"", errorCode).build(); } return Health.up().build(); } } ---- NOTE: The identifier for a given `HealthIndicator` is the name of the bean without the `HealthIndicator` suffix, if it exists. In the preceding example, the health information is available in an entry named `my`. In addition to Spring Boot's predefined {sc-spring-boot-actuator}/health/Status.{sc-ext}[`Status`] types, it is also possible for `Health` to return a custom `Status` that represents a new system state. In such cases, a custom implementation of the {sc-spring-boot-actuator}/health/HealthAggregator.{sc-ext}[`HealthAggregator`] interface also needs to be provided, or the default implementation has to be configured by using the `management.health.status.order` configuration property. For example, assume a new `Status` with code `FATAL` is being used in one of your `HealthIndicator` implementations. To configure the severity order, add the following property to your application properties: [source,properties,indent=0] ---- management.health.status.order=FATAL, DOWN, OUT_OF_SERVICE, UNKNOWN, UP ---- The HTTP status code in the response reflects the overall health status (for example, `UP` maps to 200, while `OUT_OF_SERVICE` and `DOWN` map to 503). You might also want to register custom status mappings if you access the health endpoint over HTTP. For example, the following property maps `FATAL` to 503 (service unavailable): [source,properties,indent=0] ---- management.health.status.http-mapping.FATAL=503 ---- TIP: If you need more control, you can define your own `HealthStatusHttpMapper` bean. The following table shows the default status mappings for the built-in statuses: [cols=""1,3""] |=== |Status |Mapping |DOWN |SERVICE_UNAVAILABLE (503) |OUT_OF_SERVICE |SERVICE_UNAVAILABLE (503) |UP |No mapping by default, so http status is 200 |UNKNOWN |No mapping by default, so http status is 200 |=== [[reactive-health-indicators]] ==== Reactive Health Indicators For reactive applications, such as those using Spring WebFlux, `ReactiveHealthIndicator` provides a non-blocking contract for getting application health. Similar to a traditional `HealthIndicator`, health information is collected from the content of a {sc-spring-boot-actuator}/health/ReactiveHealthIndicatorRegistry.{sc-ext}[ `ReactiveHealthIndicatorRegistry`] (by default all {sc-spring-boot-actuator}/health/HealthIndicator.{sc-ext}[`HealthIndicator`] and {sc-spring-boot-actuator}/health/ReactiveHealthIndicator.{sc-ext}[ `ReactiveHealthIndicator`] instances defined in your `ApplicationContext`. Regular `HealthIndicator` that do not check against a reactive API are executed on the elastic scheduler. TIP: In a reactive application, The `ReactiveHealthIndicatorRegistry` can be used to register and unregister health indicators at runtime. To provide custom health information from a reactive API, you can register Spring beans that implement the {sc-spring-boot-actuator}/health/ReactiveHealthIndicator.{sc-ext}[`ReactiveHealthIndicator`] interface. The following code shows a sample `ReactiveHealthIndicator` implementation: [source,java,indent=0] ---- @Component public class MyReactiveHealthIndicator implements ReactiveHealthIndicator { @Override public Mono health() { return doHealthCheck() //perform some specific health check that returns a Mono .onErrorResume(ex -> Mono.just(new Health.Builder().down(ex).build()))); } } ---- TIP: To handle the error automatically, consider extending from `AbstractReactiveHealthIndicator`. ==== Auto-configured ReactiveHealthIndicators The following `ReactiveHealthIndicators` are auto-configured by Spring Boot when appropriate: [cols=""1,4""] |=== |Name |Description |{sc-spring-boot-actuator}/cassandra/CassandraReactiveHealthIndicator.{sc-ext}[`CassandraReactiveHealthIndicator`] |Checks that a Cassandra database is up. |{sc-spring-boot-actuator}/mongo/MongoReactiveHealthIndicator.{sc-ext}[`MongoReactiveHealthIndicator`] |Checks that a Mongo database is up. |{sc-spring-boot-actuator}/redis/RedisReactiveHealthIndicator.{sc-ext}[`RedisReactiveHealthIndicator`] |Checks that a Redis server is up. |=== TIP: If necessary, reactive indicators replace the regular ones. Also, any `HealthIndicator` that is not handled explicitly is wrapped automatically. [[production-ready-application-info]] === Application Information Application information exposes various information collected from all {sc-spring-boot-actuator}/info/InfoContributor.{sc-ext}[`InfoContributor`] beans defined in your `ApplicationContext`. Spring Boot includes a number of auto-configured `InfoContributor` beans, and you can write your own. [[production-ready-application-info-autoconfigure]] ==== Auto-configured InfoContributors The following `InfoContributor` beans are auto-configured by Spring Boot, when appropriate: [cols=""1,4""] |=== |Name |Description |{sc-spring-boot-actuator}/info/EnvironmentInfoContributor.{sc-ext}[`EnvironmentInfoContributor`] |Exposes any key from the `Environment` under the `info` key. |{sc-spring-boot-actuator}/info/GitInfoContributor.{sc-ext}[`GitInfoContributor`] |Exposes git information if a `git.properties` file is available. |{sc-spring-boot-actuator}/info/BuildInfoContributor.{sc-ext}[`BuildInfoContributor`] |Exposes build information if a `META-INF/build-info.properties` file is available. |=== TIP: It is possible to disable them all by setting the `management.info.defaults.enabled` property. [[production-ready-application-info-env]] ==== Custom Application Information You can customize the data exposed by the `info` endpoint by setting `+info.*+` Spring properties. All `Environment` properties under the `info` key are automatically exposed. For example, you could add the following settings to your `application.properties` file: [source,properties,indent=0] ---- info.app.encoding=UTF-8 info.app.java.source=1.8 info.app.java.target=1.8 ---- [TIP] ==== Rather than hardcoding those values, you could also <>. Assuming you use Maven, you could rewrite the preceding example as follows: [source,properties,indent=0] ---- info.app.encoding=@project.build.sourceEncoding@ info.app.java.source=@java.version@ info.app.java.target=@java.version@ ---- ==== [[production-ready-application-info-git]] ==== Git Commit Information Another useful feature of the `info` endpoint is its ability to publish information about the state of your `git` source code repository when the project was built. If a `GitProperties` bean is available, the `git.branch`, `git.commit.id`, and `git.commit.time` properties are exposed. TIP: A `GitProperties` bean is auto-configured if a `git.properties` file is available at the root of the classpath. See ""<>"" for more details. If you want to display the full git information (that is, the full content of `git.properties`), use the `management.info.git.mode` property, as follows: [source,properties,indent=0] ---- management.info.git.mode=full ---- [[production-ready-application-info-build]] ==== Build Information If a `BuildProperties` bean is available, the `info` endpoint can also publish information about your build. This happens if a `META-INF/build-info.properties` file is available in the classpath. TIP: The Maven and Gradle plugins can both generate that file. See ""<>"" for more details. [[production-ready-application-info-custom]] ==== Writing Custom InfoContributors To provide custom application information, you can register Spring beans that implement the {sc-spring-boot-actuator}/info/InfoContributor.{sc-ext}[`InfoContributor`] interface. The following example contributes an `example` entry with a single value: [source,java,indent=0] ---- import java.util.Collections; import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component public class ExampleInfoContributor implements InfoContributor { @Override public void contribute(Info.Builder builder) { builder.withDetail(""example"", Collections.singletonMap(""key"", ""value"")); } } ---- If you reach the `info` endpoint, you should see a response that contains the following additional entry: [source,json,indent=0] ---- { ""example"": { ""key"" : ""value"" } } ---- [[production-ready-monitoring]] == Monitoring and Management over HTTP If you are developing a web application, Spring Boot Actuator auto-configures all enabled endpoints to be exposed over HTTP. The default convention is to use the `id` of the endpoint with a prefix of `/actuator` as the URL path. For example, `health` is exposed as `/actuator/health`. TIP: Actuator is supported natively with Spring MVC, Spring WebFlux, and Jersey. [[production-ready-customizing-management-server-context-path]] === Customizing the Management Endpoint Paths Sometimes, it is useful to customize the prefix for the management endpoints. For example, your application might already use `/actuator` for another purpose. You can use the `management.endpoints.web.base-path` property to change the prefix for your management endpoint, as shown in the following example: [source,properties,indent=0] ---- management.endpoints.web.base-path=/manage ---- The preceding `application.properties` example changes the endpoint from `/actuator/{id}` to `/manage/{id}` (for example, `/manage/info`). NOTE: Unless the management port has been configured to <>, `management.endpoints.web.base-path` is relative to `server.servlet.context-path`. If `management.server.port` is configured, `management.endpoints.web.base-path` is relative to `management.server.servlet.context-path`. [[production-ready-customizing-management-server-port]] === Customizing the Management Server Port Exposing management endpoints by using the default HTTP port is a sensible choice for cloud-based deployments. If, however, your application runs inside your own data center, you may prefer to expose endpoints by using a different HTTP port. You can set the `management.server.port` property to change the HTTP port, as shown in the following example: [source,properties,indent=0] ---- management.server.port=8081 ---- [[production-ready-management-specific-ssl]] === Configuring Management-specific SSL When configured to use a custom port, the management server can also be configured with its own SSL by using the various `management.server.ssl.*` properties. For example, doing so lets a management server be available over HTTP while the main application uses HTTPS, as shown in the following property settings: [source,properties,indent=0] ---- server.port=8443 server.ssl.enabled=true server.ssl.key-store=classpath:store.jks server.ssl.key-password=secret management.server.port=8080 management.server.ssl.enabled=false ---- Alternatively, both the main server and the management server can use SSL but with different key stores, as follows: [source,properties,indent=0] ---- server.port=8443 server.ssl.enabled=true server.ssl.key-store=classpath:main.jks server.ssl.key-password=secret management.server.port=8080 management.server.ssl.enabled=true management.server.ssl.key-store=classpath:management.jks management.server.ssl.key-password=secret ---- [[production-ready-customizing-management-server-address]] === Customizing the Management Server Address You can customize the address that the management endpoints are available on by setting the `management.server.address` property. Doing so can be useful if you want to listen only on an internal or ops-facing network or to listen only for connections from `localhost`. NOTE: You can listen on a different address only when the port differs from the main server port. The following example `application.properties` does not allow remote management connections: [source,properties,indent=0] ---- management.server.port=8081 management.server.address=127.0.0.1 ---- [[production-ready-disabling-http-endpoints]] === Disabling HTTP Endpoints If you do not want to expose endpoints over HTTP, you can set the management port to `-1`, as shown in the following example: [source,properties,indent=0] ---- management.server.port=-1 ---- [[production-ready-jmx]] == Monitoring and Management over JMX Java Management Extensions (JMX) provide a standard mechanism to monitor and manage applications. By default, Spring Boot exposes management endpoints as JMX MBeans under the `org.springframework.boot` domain. [[production-ready-custom-mbean-names]] === Customizing MBean Names The name of the MBean is usually generated from the `id` of the endpoint. For example, the `health` endpoint is exposed as `org.springframework.boot:type=Endpoint,name=Health`. If your application contains more than one Spring `ApplicationContext`, you may find that names clash. To solve this problem, you can set the `spring.jmx.unique-names` property to `true` so that MBean names are always unique. You can also customize the JMX domain under which endpoints are exposed. The following settings show an example of doing so in `application.properties`: [source,properties,indent=0] ---- spring.jmx.unique-names=true management.endpoints.jmx.domain=com.example.myapp ---- [[production-ready-disable-jmx-endpoints]] === Disabling JMX Endpoints If you do not want to expose endpoints over JMX, you can set the `management.endpoints.jmx.exposure.exclude` property to `*`, as shown in the following example: [source,properties,indent=0] ---- management.endpoints.jmx.exposure.exclude=* ---- [[production-ready-jolokia]] === Using Jolokia for JMX over HTTP Jolokia is a JMX-HTTP bridge that provides an alternative method of accessing JMX beans. To use Jolokia, include a dependency to `org.jolokia:jolokia-core`. For example, with Maven, you would add the following dependency: [source,xml,indent=0] ---- org.jolokia jolokia-core ---- The Jolokia endpoint can then be exposed by adding `jolokia` or `*` to the `management.endpoints.web.exposure.include` property. You can then access it by using `/actuator/jolokia` on your management HTTP server. [[production-ready-customizing-jolokia]] ==== Customizing Jolokia Jolokia has a number of settings that you would traditionally configure by setting servlet parameters. With Spring Boot, you can use your `application.properties` file. To do so, prefix the parameter with `management.endpoint.jolokia.config.`, as shown in the following example: [source,properties,indent=0] ---- management.endpoint.jolokia.config.debug=true ---- [[production-ready-disabling-jolokia]] ==== Disabling Jolokia If you use Jolokia but do not want Spring Boot to configure it, set the `management.endpoint.jolokia.enabled` property to `false`, as follows: [source,properties,indent=0] ---- management.endpoint.jolokia.enabled=false ---- [[production-ready-loggers]] == Loggers Spring Boot Actuator includes the ability to view and configure the log levels of your application at runtime. You can view either the entire list or an individual logger's configuration, which is made up of both the explicitly configured logging level as well as the effective logging level given to it by the logging framework. These levels can be one of: * `TRACE` * `DEBUG` * `INFO` * `WARN` * `ERROR` * `FATAL` * `OFF` * `null` `null` indicates that there is no explicit configuration. [[production-ready-logger-configuration]] === Configure a Logger To configure a given logger, `POST` a partial entity to the resource's URI, as shown in the following example: [source,json,indent=0] ---- { ""configuredLevel"": ""DEBUG"" } ---- TIP: To ""`reset`"" the specific level of the logger (and use the default configuration instead), you can pass a value of `null` as the `configuredLevel`. [[production-ready-metrics]] == Metrics Spring Boot Actuator provides dependency management and auto-configuration for https://micrometer.io[Micrometer], an application metrics facade that supports numerous monitoring systems, including: - <> - <> - <> - <> - <> - <> - <> - <> - <> - <> - <> - <> TIP: To learn more about Micrometer's capabilities, please refer to its https://micrometer.io/docs[reference documentation], in particular the {micrometer-concepts-documentation}[concepts section]. [[production-ready-metrics-getting-started]] === Getting started Spring Boot auto-configures a composite `MeterRegistry` and adds a registry to the composite for each of the supported implementations that it finds on the classpath. Having a dependency on `micrometer-registry-{system}` in your runtime classpath is enough for Spring Boot to configure the registry. Most registries share common features. For instance, you can disable a particular registry even if the Micrometer registry implementation is on the classpath. For instance, to disable Datadog: [source,properties,indent=0] ---- management.metrics.export.datadog.enabled=false ---- Spring Boot will also add any auto-configured registries to the global static composite registry on the `Metrics` class unless you explicitly tell it not to: [source,properties,indent=0] ---- management.metrics.use-global-registry=false ---- You can register any number of `MeterRegistryCustomizer` beans to further configure the registry, such as applying common tags, before any meters are registered with the registry: [source,java,indent=0] ---- @Bean MeterRegistryCustomizer metricsCommonTags() { return registry -> registry.config().commonTags(""region"", ""us-east-1""); } ---- You can apply customizations to particular registry implementations by being more specific about the generic type: [source,java,indent=0] ---- @Bean MeterRegistryCustomizer graphiteMetricsNamingConvention() { return registry -> registry.config().namingConvention(MY_CUSTOM_CONVENTION); } ---- With that setup in place you can inject `MeterRegistry` in your components and register metrics: [source,java,indent=0] ---- include::{code-examples}/actuate/metrics/SampleBean.java[tag=example] ---- Spring Boot also <> (i.e. `MeterBinder` implementations) that you can control via configuration or dedicated annotation markers. [[production-ready-metrics-export]] === Supported monitoring systems [[production-ready-metrics-export-atlas]] ==== Atlas By default, metrics are exported to {micrometer-registry-documentation}/atlas[Atlas] running on your local machine. The location of the https://github.com/Netflix/atlas[Atlas server] to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.atlas.uri=http://atlas.example.com:7101/api/v1/publish ---- [[production-ready-metrics-export-datadog]] ==== Datadog Datadog registry pushes metrics to https://www.datadoghq.com[datadoghq] periodically. To export metrics to {micrometer-registry-documentation}/datadog[Datadog], your API key must be provided: [source,properties,indent=0] ---- management.metrics.export.datadog.api-key=YOUR_KEY ---- You can also change the interval at which metrics are sent to Datadog: [source,properties,indent=0] ---- management.metrics.export.datadog.step=30s ---- [[production-ready-metrics-export-ganglia]] ==== Ganglia By default, metrics are exported to {micrometer-registry-documentation}/ganglia[Ganglia] running on your local machine. The http://ganglia.sourceforge.net[Ganglia server] host and port to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.ganglia.host=ganglia.example.com management.metrics.export.ganglia.port=9649 ---- [[production-ready-metrics-export-graphite]] ==== Graphite By default, metrics are exported to {micrometer-registry-documentation}/graphite[Graphite] running on your local machine. The https://graphiteapp.org[Graphite server] host and port to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.graphite.host=graphite.example.com management.metrics.export.graphite.port=9004 ---- Micrometer provides a default `HierarchicalNameMapper` that governs how a dimensional meter id is {micrometer-registry-documentation}/graphite#_hierarchical_name_mapping[mapped to flat hierarchical names]. TIP: To take control over this behaviour, define your `GraphiteMeterRegistry` and supply your own `HierarchicalNameMapper`. An auto-configured `GraphiteConfig` and `Clock` beans are provided unless you define your own: [source,java] ---- @Bean public GraphiteMeterRegistry graphiteMeterRegistry(GraphiteConfig config, Clock clock) { return new GraphiteMeterRegistry(config, clock, MY_HIERARCHICAL_MAPPER); } ---- [[production-ready-metrics-export-influx]] ==== Influx By default, metrics are exported to {micrometer-registry-documentation}/influx[Influx] running on your local machine. The location of the https://www.influxdata.com[Influx server] to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.influx.uri=http://influx.example.com:8086 ---- [[production-ready-metrics-export-jmx]] ==== JMX Micrometer provides a hierarchical mapping to {micrometer-registry-documentation}/jmx[JMX], primarily as a cheap and portable way to view metrics locally. By default, metrics are exported to the `metrics` JMX domain. The domain to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.jmx.domain=com.example.app.metrics ---- Micrometer provides a default `HierarchicalNameMapper` that governs how a dimensional meter id is {micrometer-registry-documentation}/jmx#_hierarchical_name_mapping[mapped to flat hierarchical names]. TIP: To take control over this behaviour, define your `JmxMeterRegistry` and supply your own `HierarchicalNameMapper`. An auto-configured `JmxConfig` and `Clock` beans are provided unless you define your own: [source,java] ---- @Bean public JmxMeterRegistry jmxMeterRegistry(JmxConfig config, Clock clock) { return new JmxMeterRegistry(config, clock, MY_HIERARCHICAL_MAPPER); } ---- [[production-ready-metrics-export-newrelic]] ==== New Relic New Relic registry pushes metrics to {micrometer-registry-documentation}/new-relic[New Relic] periodically. To export metrics to https://newrelic.com[New Relic], your API key and account id must be provided: [source,properties,indent=0] ---- management.metrics.export.newrelic.api-key=YOUR_KEY management.metrics.export.newrelic.account-id=YOUR_ACCOUNT_ID ---- You can also change the interval at which metrics are sent to New Relic: [source,properties,indent=0] ---- management.metrics.export.newrelic.step=30s ---- [[production-ready-metrics-export-prometheus]] ==== Prometheus {micrometer-registry-documentation}/prometheus[Prometheus] expects to scrape or poll individual app instances for metrics. Spring Boot provides an actuator endpoint available at `/actuator/prometheus` to present a https://prometheus.io[Prometheus scrape] with the appropriate format. TIP: The endpoint is not available by default and must be exposed, see <> for more details. Here is an example `scrape_config` to add to `prometheus.yml`: [source,yaml,indent=0] ---- scrape_configs: - job_name: 'spring' metrics_path: '/actuator/prometheus' static_configs: - targets: ['HOST:PORT'] ---- [[production-ready-metrics-export-signalfx]] ==== SignalFx SignalFx registry pushes metrics to {micrometer-registry-documentation}/signalfx[SignalFx] periodically. To export metrics to https://signalfx.com[SignalFx], your access token must be provided: [source,properties,indent=0] ---- management.metrics.export.signalfx.access-token=YOUR_ACCESS_TOKEN ---- You can also change the interval at which metrics are sent to SignalFx: [source,properties,indent=0] ---- management.metrics.export.signalfx.step=30s ---- [[production-ready-metrics-export-simple]] ==== Simple Micrometer ships with a simple, in-memory backend that is automatically used as a fallback if no other registry is configured. This allows you to see what metrics are collected in the <>. The in-memory backend disables itself as soon as you're using any of the other available backend. You can also disable it explicitly: [source,properties,indent=0] ---- management.metrics.export.simple.enabled=false ---- [[production-ready-metrics-export-statsd]] ==== StatsD The StatsD registry pushes metrics over UDP to a StatsD agent eagerly. By default, metrics are exported to a {micrometer-registry-documentation}/statsd[StatsD] agent running on your local machine. The StatsD agent host and port to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.statsd.host=statsd.example.com management.metrics.export.statsd.port=9125 ---- You can also change the StatsD line protocol to use (default to Datadog): [source,properties,indent=0] ---- management.metrics.export.statsd.flavor=etsy ---- [[production-ready-metrics-export-wavefront]] ==== Wavefront Wavefront registry pushes metrics to {micrometer-registry-documentation}/wavefront[Wavefront] periodically. If you are exporting metrics to https://www.wavefront.com/[Wavefront] directly, your API token must be provided: [source,properties,indent=0] ---- management.metrics.export.wavefront.api-token=YOUR_API_TOKEN ---- Alternatively, you may use a Wavefront sidecar or an internal proxy set up in your environment that forwards metrics data to the Wavefront API host: [source,properties,indent=0] ---- management.metrics.export.wavefront.uri=proxy://localhost:2878 ---- TIP: If publishing metrics to a Wavefront proxy (as described in https://docs.wavefront.com/proxies_installing.html[the documentation]), the host must be in the `proxy://HOST:PORT` format. You can also change the interval at which metrics are sent to Wavefront: [source,properties,indent=0] ---- management.metrics.export.wavefront.step=30s ---- [[production-ready-metrics-meter]] === Supported Metrics Spring Boot registers the following core metrics when applicable: * JVM metrics, report utilization of: ** Various memory and buffer pools ** Statistics related to garbage collection ** Threads utilization ** Number of classes loaded/unloaded * CPU metrics * File descriptor metrics * Logback metrics: record the number of events logged to Logback at each level * Uptime metrics: report a gauge for uptime and a fixed gauge representing the application's absolute start time * Tomcat metrics * https://docs.spring.io/spring-integration/docs/current/reference/html/system-management-chapter.html#micrometer-integration[Spring Integration] metrics [[production-ready-metrics-spring-mvc]] ==== Spring MVC Metrics Auto-configuration enables the instrumentation of requests handled by Spring MVC. When `management.metrics.web.server.auto-time-requests` is `true`, this instrumentation occurs for all requests. Alternatively, when set to `false`, you can enable instrumentation by adding `@Timed` to a request-handling method: [source,java,indent=0] ---- @RestController @Timed <1> public class MyController { @GetMapping(""/api/people"") @Timed(extraTags = { ""region"", ""us-east-1"" }) <2> @Timed(value = ""all.people"", longTask = true) <3> public List listPeople() { ... } } ---- <1> A controller class to enable timings on every request handler in the controller. <2> A method to enable for an individual endpoint. This is not necessary if you have it on the class, but can be used to further customize the timer for this particular endpoint. <3> A method with `longTask = true` to enable a long task timer for the method. Long task timers require a separate metric name, and can be stacked with a short task timer. By default, metrics are generated with the name, `http.server.requests`. The name can be customized by setting the `management.metrics.web.server.requests-metric-name` property. By default, Spring MVC-related metrics are tagged with the following information: * `method`, the request's method (for example, `GET` or `POST`). * `uri`, the request's URI template prior to variable substitution, if possible (for example, `/api/person/{id}`). * `status`, the response's HTTP status code (for example, `200` or `500`). * `exception`, the simple class name of any exception that was thrown while handling the request. To customize the tags, provide a `@Bean` that implements `WebMvcTagsProvider`. [[production-ready-metrics-web-flux]] ==== Spring WebFlux Metrics Auto-configuration enables the instrumentation of all requests handled by WebFlux controllers and functional handlers. By default, metrics are generated with the name `http.server.requests`. You can customize the name by setting the `management.metrics.web.server.requests-metric-name` property. By default, WebFlux-related metrics are tagged with the following information: * `method`, the request's method (for example, `GET` or `POST`). * `uri`, the request's URI template prior to variable substitution, if possible (for example, `/api/person/{id}`). * `status`, the response's HTTP status code (for example, `200` or `500`). * `exception`, the simple class name of any exception that was thrown while handling the request. To customize the tags, provide a `@Bean` that implements `WebFluxTagsProvider`. [[production-ready-metrics-http-clients]] ==== HTTP Client Metrics Spring Boot Actuator manages the instrumentation of both `RestTemplate` and `WebClient`. For that, you have to get injected with an auto-configured builder and use it to create instances: * `RestTemplateBuilder` for `RestTemplate` * `WebClient.Builder` for `WebClient` It is also possible to apply manually the customizers responsible for this instrumentation, namely `MetricsRestTemplateCustomizer` and `MetricsWebClientCustomizer`. By default, metrics are generated with the name, `http.client.requests`. The name can be customized by setting the `management.metrics.web.client.requests-metric-name` property. By default, metrics generated by an instrumented client are tagged with the following information: * `method`, the request's method (for example, `GET` or `POST`). * `uri`, the request's URI template prior to variable substitution, if possible (for example, `/api/person/{id}`). * `status`, the response's HTTP status code (for example, `200` or `500`). * `clientName`, the host portion of the URI. To customize the tags, and depending on your choice of client, you can provide a `@Bean` that implements `RestTemplateExchangeTagsProvider` or `WebClientExchangeTagsProvider`. There are convenience static functions in `RestTemplateExchangeTags` and `WebClientExchangeTags`. [[production-ready-metrics-cache]] ==== Cache Metrics Auto-configuration enables the instrumentation of all available ``Cache``s on startup with metrics prefixed with `cache`. Cache instrumentation is standardized for a basic set of metrics. Additional, cache-specific metrics are also available. The following cache libraries are supported: * Caffeine * EhCache 2 * Hazelcast * Any compliant JCache (JSR-107) implementation Metrics are tagged by the name of the cache and by the name of the `CacheManager` that is derived from the bean name. NOTE: Only caches that are available on startup are bound to the registry. For caches created on-the-fly or programmatically after the startup phase, an explicit registration is required. A `CacheMetricsRegistrar` bean is made available to make that process easier. [[production-ready-metrics-jdbc]] ==== DataSource Metrics Auto-configuration enables the instrumentation of all available `DataSource` objects with a metric named `jdbc`. Data source instrumentation results in gauges representing the currently active, maximum allowed, and minimum allowed connections in the pool. Each of these gauges has a name that is prefixed by `jdbc`. Metrics are also tagged by the name of the `DataSource` computed based on the bean name. TIP: By default, Spring Boot provides metadata for all supported data sources; you can add additional `DataSourcePoolMetadataProvider` beans if your favorite data source isn't supported out of the box. See `DataSourcePoolMetadataProvidersConfiguration` for examples. Also, Hikari-specific metrics are exposed with a `hikaricp` prefix. Each metric is tagged by the name of the Pool (can be controlled with `spring.datasource.name`). [[production-ready-metrics-hibernate]] ==== Hibernate Metrics Auto-configuration enables the instrumentation of all available Hibernate `EntityManagerFactory` instances that have statistics enabled with a metric named `hibernate`. Metrics are also tagged by the name of the `EntityManagerFactory` that is derived from the bean name. To enable statistics, the standard JPA property `hibernate.generate_statistics` must be set to `true`. You can enable that on the auto-configured `EntityManagerFactory` as shown in the following example: [source,properties,indent=0] ---- spring.jpa.properties.hibernate.generate_statistics=true ---- [[production-ready-metrics-rabbitmq]] ==== RabbitMQ Metrics Auto-configuration will enable the instrumentation of all available RabbitMQ connection factories with a metric named `rabbitmq`. [[production-ready-metrics-custom]] === Registering custom metrics To register custom metrics, inject `MeterRegistry` into your component, as shown in the following example: [source,java,indent=0] ---- include::{code-examples}/actuate/metrics/MetricsMeterRegistryInjectionExample.java[tag=component] ---- If you find that you repeatedly instrument a suite of metrics across components or applications, you may encapsulate this suite in a `MeterBinder` implementation. By default, metrics from all `MeterBinder` beans will be automatically bound to the Spring-managed `MeterRegistry`. [[production-ready-metrics-per-meter-properties]] === Customizing individual metrics If you need to apply customizations to specific `Meter` instances you can use the `io.micrometer.core.instrument.config.MeterFilter` interface. By default, all `MeterFilter` beans will be automatically applied to the micrometer `MeterRegistry.Config`. For example, if you want to rename the `mytag.region` tag to `mytag.area` for all meter IDs beginning with `com.example`, you can do the following: [source,java,indent=0] ---- include::{code-examples}/actuate/metrics/MetricsFilterBeanExample.java[tag=configuration] ---- [[production-ready-metrics-common-tags]] ==== Common tags Common tags are generally used for dimensional drill-down on the operating environment like host, instance, region, stack, etc. Commons tags are applied to all meters and can be configured as shown in the following example: [source,properties,indent=0] ---- management.metrics.tags.region=us-east-1 management.metrics.tags.stack=prod ---- The example above adds `region` and `stack` tags to all meters with a value of `us-east-1` and `prod` respectively. NOTE: The order of common tags is important if you are using Graphite. As the order of common tags cannot be guaranteed using this approach, Graphite users are advised to define a custom `MeterFilter` instead. ==== Per-meter properties In addition to `MeterFilter` beans, it's also possible to apply a limited set of customization on a per-meter basis using properties. Per-meter customizations apply to any all meter IDs that start with the given name. For example, the following will disable any meters that have an ID starting with `example.remote` [source,properties,indent=0] ---- management.metrics.enable.example.remote=false ---- The following properties allow per-meter customization: .Per-meter customizations |=== | Property | Description | `management.metrics.enable` | Whether to deny meters from emitting any metrics. | `management.metrics.distribution.percentiles-histogram` | Whether to publish a histogram suitable for computing aggregable (across dimension) percentile approximations. | `management.metrics.distribution.percentiles` | Publish percentile values computed in your application | `management.metrics.distribution.sla` | Publish a cumulative histogram with buckets defined by your SLAs. |=== For more details on concepts behind `percentiles-histogram`, `percentiles` and `sla` refer to the {micrometer-concepts-documentation}#_histograms_and_percentiles[""Histograms and percentiles"" section] of the micrometer documentation. [[production-ready-metrics-endpoint]] === Metrics endpoint Spring Boot provides a `metrics` endpoint that can be used diagnostically to examine the metrics collected by an application. The endpoint is not available by default and must be exposed, see <> for more details. Navigating to `/actuator/metrics` displays a list of available meter names. You can drill down to view information about a particular meter by providing its name as a selector, e.g. `/actuator/metrics/jvm.memory.max`. [TIP] ==== The name you use here should match the name used in the code, not the name after it has been naming-convention normalized for a monitoring system it is shipped to. In other words, if `jvm.memory.max` appears as `jvm_memory_max` in Prometheus because of its snake case naming convention, you should still use `jvm.memory.max` as the selector when inspecting the meter in the `metrics` endpoint. ==== You can also add any number of `tag=KEY:VALUE` query parameters to the end of the URL to dimensionally drill down on a meter, e.g. `/actuator/metrics/jvm.memory.max?tag=area:nonheap`. [TIP] ==== The reported measurements are the _sum_ of the statistics of all meters matching the meter name and any tags that have been applied. So in the example above, the returned ""Value"" statistic is the sum of the maximum memory footprints of ""Code Cache"", ""Compressed Class Space"", and ""Metaspace"" areas of the heap. If you just wanted to see the maximum size for the ""Metaspace"", you could add an additional `tag=id:Metaspace`, i.e. `/actuator/metrics/jvm.memory.max?tag=area:nonheap&tag=id:Metaspace`. ==== [[production-ready-auditing]] == Auditing Once Spring Security is in play, Spring Boot Actuator has a flexible audit framework that publishes events (by default, ""`authentication success`"", ""`failure`"" and ""`access denied`"" exceptions). This feature can be very useful for reporting and for implementing a lock-out policy based on authentication failures. To customize published security events, you can provide your own implementations of `AbstractAuthenticationAuditListener` and `AbstractAuthorizationAuditListener`. You can also use the audit services for your own business events. To do so, either inject the existing `AuditEventRepository` into your own components and use that directly or publish an `AuditApplicationEvent` with the Spring `ApplicationEventPublisher` (by implementing `ApplicationEventPublisherAware`). [[production-ready-http-tracing]] == HTTP Tracing Tracing is automatically enabled for all HTTP requests. You can view the `httptrace` endpoint and obtain basic information about the last 100 request-response exchanges. [[production-ready-http-tracing-custom]] === Custom HTTP tracing To customize the items that are included in each trace, use the `management.trace.http.include` configuration property. For advanced customization, consider registering your own `HttpExchangeTracer` implementation. By default, an `InMemoryHttpTraceRepository` that stores traces for the last 100 request-response exchanges is used. If you need to expand the capacity, you can define your own instance of the `InMemoryHttpTraceRepository` bean. You can also create your own alternative `HttpTraceRepository` implementation. [[production-ready-process-monitoring]] == Process Monitoring In the `spring-boot` module, you can find two classes to create files that are often useful for process monitoring: * `ApplicationPidFileWriter` creates a file containing the application PID (by default, in the application directory with a file name of `application.pid`). * `WebServerPortFileWriter` creates a file (or files) containing the ports of the running web server (by default, in the application directory with a file name of `application.port`). By default, these writers are not activated, but you can enable: * <> * <> [[production-ready-process-monitoring-configuration]] === Extending Configuration In the `META-INF/spring.factories` file, you can activate the listener(s) that writes a PID file, as shown in the following example: [indent=0] ---- org.springframework.context.ApplicationListener=\\ org.springframework.boot.context.ApplicationPidFileWriter,\\ org.springframework.boot.web.context.WebServerPortFileWriter ---- [[production-ready-process-monitoring-programmatically]] === Programmatically You can also activate a listener by invoking the `SpringApplication.addListeners(...)` method and passing the appropriate `Writer` object. This method also lets you customize the file name and path in the `Writer` constructor. [[production-ready-cloudfoundry]] == Cloud Foundry Support Spring Boot's actuator module includes additional support that is activated when you deploy to a compatible Cloud Foundry instance. The `/cloudfoundryapplication` path provides an alternative secured route to all `@Endpoint` beans. The extended support lets Cloud Foundry management UIs (such as the web application that you can use to view deployed applications) be augmented with Spring Boot actuator information. For example, an application status page may include full health information instead of the typical ""`running`"" or ""`stopped`"" status. NOTE: The `/cloudfoundryapplication` path is not directly accessible to regular users. In order to use the endpoint, a valid UAA token must be passed with the request. [[production-ready-cloudfoundry-disable]] === Disabling Extended Cloud Foundry Actuator Support If you want to fully disable the `/cloudfoundryapplication` endpoints, you can add the following setting to your `application.properties` file: .application.properties [source,properties,indent=0] ---- management.cloudfoundry.enabled=false ---- [[production-ready-cloudfoundry-ssl]] === Cloud Foundry Self-signed Certificates By default, the security verification for `/cloudfoundryapplication` endpoints makes SSL calls to various Cloud Foundry services. If your Cloud Foundry UAA or Cloud Controller services use self-signed certificates, you need to set the following property: .application.properties [source,properties,indent=0] ---- management.cloudfoundry.skip-ssl-validation=true ---- === Custom context path If the server's context-path has been configured to anything other than `/`, the Cloud Foundry endpoints will not be available at the root of the application. For example, if `server.servlet.context-path=/app`, Cloud Foundry endpoints will be available at `/app/cloudfoundryapplication/*`. If you expect the Cloud Foundry endpoints to always be available at `/cloudfoundryapplication/*`, regardless of the server's context-path, you will need to explicitly configure that in your application. The configuration will differ depending on the web server in use. For Tomcat, the following configuration can be added: [source,java,indent=0] ---- include::{code-examples}/cloudfoundry/CloudFoundryCustomContextPathExample.java[tag=configuration] ---- [[production-ready-whats-next]] == What to Read Next If you want to explore some of the concepts discussed in this chapter, you can take a look at the actuator {github-code}/spring-boot-samples[sample applications]. You also might want to read about graphing tools such as http://graphite.wikidot.com/[Graphite]. Otherwise, you can continue on, to read about <> or jump ahead for some in-depth information about Spring Boot's _<>_. ",16267,True,2876.80364641353,median "//// 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. //// = TinkerPop 3.3.0 image::https://raw.githubusercontent.com/apache/tinkerpop/master/docs/static/images/gremlin-mozart.png[width=225] *Gremlin Symphony #40 in G Minor* == TinkerPop 3.3.11 *Release Date: NOT OFFICIALLY RELEASED YET* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.11/CHANGELOG.asciidoc#release-3-3-11[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users == TinkerPop 3.3.10 *Release Date: February 3, 2020* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.10/CHANGELOG.asciidoc#release-3-3-10[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Traversal Clone Once a traversal has been executed (i.e. iterated) it's internal state is such that it cannot be re-used: [source,text] ---- gremlin> t = g.V().count() ==>6 gremlin> t gremlin> ---- To re-use a traversal it must be copied with `clone()` as follows: [source,text] ---- gremlin> t = g.V().count() ==>6 gremlin> t.clone() ==>6 gremlin> t.clone() ==>6 ---- The ability to `clone()` has been exclusive to Java and was a missing component of other supported languages like Python, Javascript and .NET. This feature has now been added for all the language variants making the ability to re-use traversals consistent in all ecosystems. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2315[TINKERPOP-2315] ==== Deprecated Jython Support Jython support in `gremlin-python` has been deprecated to focus on native Python 3.x support for 3.5.0 where Jython support will be wholly removed. This change does mean that TinkerPop will no longer support the ability to submit lambdas as native Python scripts. They will need to be submitted as Groovy and the library will be defaulted to do as such. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2322[TINKERPOP-2322] == TinkerPop 3.3.9 *Release Date: October 14, 2019* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.9/CHANGELOG.asciidoc#release-3-3-9[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== ReservedKeysVerificationStrategy `ReservedKeysVerificationStrategy` is a new `VerificationStrategy` that can be used to help prevent traversals from adding property keys that are protected. They may be protected as a result of the key being a reserved keyword of the underlying graph system or they key may simply violate some standard conventions. [source,text] ---- gremlin> g.withStrategies(ReservedKeysVerificationStrategy.build().throwException().create()).addV('person').property(""id"",123) The provided traversal contains a AddVertexStartStep that is setting a property key to a reserved word: id Type ':help' or ':h' for help. Display stack trace? [yN] ---- link:https://issues.apache.org/jira/browse/TINKERPOP-2280[TINKERPOP-2280] ==== Javascript ResponseError Gremlin Javascript now enables more robust error handling by way of a `ResponseError` which provides access to more information from the server. Specifically, it includes the `statusMessage` and `statusCode` which were formerly packed into the `Error.message` property, which meant that the error message string had to be parsed if there was a need to take a specific action based on that information. The `ResponseError` also includes the `statusAttributes` which is a `Map` object that will typically incorporate server `exceptions` and `stackTrace` keys, but could also include provider specific error information. The original error messaging has remained unchanged and therefore users who were message parsing should not expect changes in behavior, however, future versions will eliminate the ""overuse"" of the `Error.message` property, so it is advised that users update their code to take advantage of the `ResponseError` features. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2285[TINKERPOP-2285] ==== Java Driver NoHostAvailableException Expect a `NoHostAvailableException` rather than a more generic `TimeoutException` if the Java driver is unable to connect to a `Host`. This sort of failure can occur in a number of different scenarios, but can often occur when there are configuration problems with authentication and SSL, preventing the connection to the `Host` to be established. link:https://issues.apache.org/jira/browse/TINKERPOP-2132[TINKERPOP-2132] ==== Deprecated scriptEvaluationTimeout The `scriptEvaluationTimeout` controls the length of time a request is processed by Gremlin Server (or at its core, the `GremlinExecutor`). Of course, with the introduction of bytecode-based requests many versions ago, this naming has failed to make complete sense in more recent times. Therefore, `scriptEvaluationTimeout` has been deprecated and replaced by `evaluationTimeout`. Both configurations are still respected, but it is advised that users switch to `evaluationTimeout` as `scriptEvaluationTimeout` will be removed in a later version. Note that when configuring Gremlin Server's `evaluationTimeout` that the `scriptEvaluationTimeout` should be set to `-1` (the default) or else it will use that value in its initialization of the server and ignore the `evaluationTimeout`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2213[TINKERPOP-2213] == TinkerPop 3.3.8 *Release Date: August 5, 2019* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.8/CHANGELOG.asciidoc#release-3-3-8[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Branch Steps Accept Predicates and Traversals Prior to this version, branch steps (in particular `BranchStep` and `ChooseStep`) could only handle constant values and `Pick` tokens. Starting in this version, these steps will also accept predicates and traversals as show in the example below. [source,text] ---- gremlin> g = TinkerFactory.createModern().traversal() ==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard] gremlin> g.V().hasLabel(""person""). ......1> group(). ......2> by(""name""). ......3> by(branch(values(""age"")). ......4> option(29, constant(""almost old"")). ......5> option(__.is(32), constant(""looks like josh"")). ......6> option(lt(29), constant(""pretty young"")). ......7> option(lt(35), constant(""younger than peter"")). ......8> option(gte(30), constant(""pretty old"")). ......9> option(none, constant(""mysterious"")).fold()). .....10> unfold() ==>peter=[pretty old] ==>vadas=[pretty young, younger than peter] ==>josh=[looks like josh, younger than peter, pretty old] ==>marko=[almost old, younger than peter] ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1084[TINKERPOP-1084] ==== Python DateTime With GraphSON, the `g:Date` is meant to represent a millisecond-precision offset from the unix epoch, but earlier version of Gremlin Python were using the timezone of the local system to handle serialization and deserialization, thus resulting in incorrect conversion. This issue is now resolved. It may be necessary to remove workarounds that have been introduced to combat this problem. See: https://issues.apache.org/jira/browse/TINKERPOP-2264[TINKERPOP-2264] ==== JavaScript withComputer() Gremlin-Javascript now supports `withComputer()` syntax, which means that it is now possible in Javascript to utilize Gremlin steps that require a `GraphComputer` to execute (e.g. `pageRank()` and `peerPressure()`). See: link:https://issues.apache.org/jira/browse/TINKERPOP-2251[TINKERPOP-2251] ==== JavaScript and .NET hasNext() There is now greater consistency across Gremlin Language Variants with `hasNext()` support added to both JavaScript and .NET. Note that in .NET, the proper method name follows C# capitalization semantics and is referred to as `HasNext()`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1921[TINKERPOP-1921] ==== Deprecated getSideEffects() `Traversal.getSideEffects()` has been deprecated for purposes of external calls by end-users. While the method is still present TinkerPop no longer guarantees its existence in future versions or consistency of its behavior, especially for Gremlin Language Variants and remote traversal execution. If this method is currently in use to gather side-effect results after traversal execution, please change such code to use `cap()`-step. For example, code like this: [source,text] ---- gremlin> t = g.V().hasLabel('person').aggregate('p').out('created') ==>v[3] ==>v[5] ==>v[3] ==>v[3] gremlin> t.getSideEffects().get('p') ==>v[1] ==>v[2] ==>v[4] ==>v[6] ---- should be converted to something like: [source,text] ---- gremlin> g.V().hasLabel('person').aggregate('p').out('created').union(fold(),cap('p')) ==>[v[3],v[3],v[3],v[5]] ==>[v[1],v[2],v[4],v[6]] ---- link:https://issues.apache.org/jira/browse/TINKERPOP-2265[TINKERPOP-2265] ==== EventStrategy Prior TinkerPop 3.3.6 `EventStrategy` did not work with multi-properties. The `EventStrategy` behavior for single-valued properties has not changed; if a property is added to a multi-valued `VertexProperty`, then a `VertexPropertyChangedEvent` will be now be fired. The arguments passed to the event depend on the cardinality type. [width=""100%"",cols=""2""] |========================================================= |`Cardinality.list` | Since properties will always be added and never be overwritten, the old property passed to the change event will always be an empty property. |`Cardinality.set` | The old property passed to the change event will be empty if no other property with the same value exists, otherwise, it will be the existing property. |========================================================= See: link:https://issues.apache.org/jira/browse/TINKERPOP-2159[TINKERPOP-2159] == TinkerPop 3.3.7 *Release Date: May 28, 2019* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.7/CHANGELOG.asciidoc#release-3-3-7[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== JavaScript DSL Pattern Gremlin DSL developers had to rely on monkey patching to build a Domain Specific Language in JavaScript. With this latest version, the process is a bit more elegant and largely handled by extending existing core classes of `Gremlin-JavaScript` which is a bit more in-line with other language variant patterns for DSL development. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2089[TINKERPOP-2089], link:http://tinkerpop.apache.org/docs/3.3.7/reference/#gremlin-javascript-dsl[Reference Documentation] ==== Gremlin Console Interrupt There are occasions where a traversal (or other evaluation) takes longer than expected to complete. Common examples of these situations typically include: * Accidentally executing `g.V()` (i.e. full graph scan) on a very large graph as an OLTP style traversal. * Not terminating a `repeat()` properly which results in an infinite loop. * Bad data might create a cycle in the graph where one wasn't expected. * Failing to properly bound a traversal's path through one or more supernodes. In earlier versions, the only option was to kill the Gremlin Console (typically with `ctrl+c`), but as of this version `ctrl+c` will be intercepted and attempt to interrupt whatever process is currently executing. See link:https://issues.apache.org/jira/browse/TINKERPOP-2181[TINKERPOP-2181] ==== Removed gperfutils Dependency Gremlin Console included references to: [source,xml] ---- org.gperfutils gbench org.gperfutils gprof :install org.gperfutils gbench gremlin> :install org.gperfutils gprof ---- and then import the appropriate classes and methods to use. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2182[TINKERPOP-2182] === Upgrading for Providers ==== Graph Database Providers ===== Detection of Anti-Patterns This release adds a strategy named `EdgeLabelVerificationStrategy`. The strategy will not be added by default to the traversal source, however, providers can add it explicitly to encourage (or enforce) users to always specify at least one edge label. `EdgeLabelVerificationStrategy` can be configured to either throw an exception if no edge label was specified, log a warning or do both. [source,text] ---- gremlin> // throw an exception if edge label was not specified gremlin> g = TinkerFactory.createModern().traversal().withStrategies(EdgeLabelVerificationStrategy.build().throwException().create()) ==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard] gremlin> g.V(1).out('knows') ==>v[2] ==>v[4] gremlin> g.V(1).out() The provided traversal contains a vertex step without any specified edge label: VertexStep(OUT,vertex) Type ':help' or ':h' for help. Display stack trace? [yN] ---- [source,text] ---- gremlin> // log a warning if edge label was not specified (Log4j has to be configured properly) gremlin> g = TinkerFactory.createModern().traversal().withStrategies(EdgeLabelVerificationStrategy.build().logWarning().create()) ==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard] gremlin> g.V(1).out('knows') ==>v[2] ==>v[4] gremlin> g.V(1).out() WARN org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.EdgeLabelVerificationStrategy - The provided traversal contains a vertex step without any specified edge label: VertexStep(OUT,vertex) ==>v[3] ==>v[2] ==>v[4] ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-2191[TINKERPOP-2191] == TinkerPop 3.3.6 *Release Date: March 18, 2019* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.6/CHANGELOG.asciidoc#release-3-3-6[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Anti-Patterns Documentation The Gremlin Recipes documentation now has a new section which discusses anti-patterns in Gremlin. Its subsections detail commonly seen approaches to the Gremlin language which can lead to poorly written and/or under-performing traversals. The new Anti-Patterns Section can be found link:http://tinkerpop.apache.org/docs/3.3.6/recipes/#_anti_patterns[here]. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2114[TINKERPOP-2114] == TinkerPop 3.3.5 *Release Date: January 2, 2019* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.5/CHANGELOG.asciidoc#release-3-3-5[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== AnonymousTraversalSource The `AnonymousTraversalSource` provides for a more unified syntax for `TraversalSource` construction by placing greater user emphasis on the creation of the source rather than the `Graph` it is connected to. It has a number of different static `traversal()` methods available and when imported as: [source,java] import static org.apache.tinkerpop.gremlin.process.traversal.AnonymousTraversalSource.traversal; allows `TraversalSource` construction syntax such as: [source,text] ---- gremlin> g = traversal().withGraph(TinkerFactory.createModern()) ==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard] gremlin> g = traversal().withRemote('conf/remote-graph.properties') ==>graphtraversalsource[emptygraph[empty], standard] gremlin> g = traversal().withRemote(DriverRemoteConnection.using('localhost',8182)) ==>graphtraversalsource[emptygraph[empty], standard] ---- Typically, this syntax is used for ""remote"" traversal construction for bytecode based requests, but has the option to bind a local `Graph` instance to it as well. It doesn't save much typing to do so obviously, so it may not be best used in that situation. Python, Javascript and .NET have similar syntax. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2078[TINKERPOP-2078] ==== Bytecode Command The Gremlin Console now has a new `:bytecode` command to help users work more directly with Gremlin bytecode. The command is more of a debugging tool than something that would be used for every day purposes. It is sometimes helpful to look at Gremlin bytecode directly and the process for viewing it in human readable format is not a single step process. It is also not immediately clear how to convert bytecode to a Gremlin string. The `:bytecode` command aims to help with both of these issues: [source,text] ---- gremlin> g = TinkerFactory.createModern().traversal() ==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard] gremlin> :bytecode from g.V().out('knows') <1> ==>{""@type"":""g:Bytecode"",""@value"":{""step"":[[""V""],[""out"",""knows""]]}} gremlin> :bytecode translate g {""@type"":""g:Bytecode"",""@value"":{""step"":[[""V""],[""out"",""knows""]]}} <2> ==>g.V().out(""knows"") ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-2050[TINKERPOP-2050], link:http://tinkerpop.apache.org/docs/3.3.5/reference/#_console_commands[Reference Documentation - Console Commands] ==== Configurable Class Map Cache The ""class map"" cache in Gremlin Server (specifically the `GremlinGroovyScriptEngine`) that holds compiled scripts is now fully configurable via the `GroovyCompilerGremlinPlugin.classMapCacheSpecification`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2038[TINKERPOP-2038], link:http://tinkerpop.apache.org/docs/3.3.5/reference/#gremlin-server-cache[Reference Documentation - Cache Management] ==== RangeStep Optimizing Strategy A new strategy named `EarlyLimitStrategy` was added. The strategy will try to find a better spot for any `RangeStep`, which is as early as possible in the traversal. If possible it will also merge multiple `RangeStep`s into a single one by recalculating the range for the first step and removing the second. If it turns out that the merge of two steps won't produce a valid range (an empty result), then the `EarlyLimitStrategy` will remove the `RangeStep`s and insert a `NoneStep` instead. This strategy is particularly useful when a provider implementation generates the queries to the underlying database. By making sure that the ranges are applied as early as possible, we can ensure that the underlying database is only asked for the least amount of data necessary to continue the traversal evaluation. === Upgrading for Providers ==== Graph Database Providers ===== OptOut on GraphProvider It is not uncommon for those utilizing the TinkerPop test suite to have multiple configurations of their graph under test. The multiple configurations typically manifest as multiple `GraphProvider` implementations which supply the different configurations to test. It is sometimes the case, that a particular `Graph` configuration cannot support all of the tests in the suite at which point some less than straightforward approaches to dealing with that present as solutions. It has always been possible to apply an `OptOut` annotation to a `Graph` instance, to avoid a particular test execution. It is now possible to apply that same `OptOut` to a `GraphProvider` instance for that same purpose. Hopefully, this feature will make multiple configuration testing easier. == TinkerPop 3.3.4 *Release Date: October 15, 2018* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.4/CHANGELOG.asciidoc#release-3-3-4[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Introducing Order.asc and Order.desc The `Order` enum originally introduced `incr` for ascending order and `decr` for descending order. It's not clear why they were named this way when common querying parlance would call for `asc` and `desc` for those respective cases. Note that `incr` and `decr` have not been removed - just deprecated and thus marked for future removal. Prefer `asc` and `desc` going forward when writing Gremlin and look to update existing code using the deprecated values. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1956[TINKERPOP-1956] ==== TimedInterrupt In Gremlin Server, it is best not to use the `timedInterrupt` option on `GroovyCompilerGremlinPlugin` because it can compete with the `scriptEvaluationTimeout` setting and produce a different error path. Simply rely on `scriptEvaluationTimeout` as it covers both script evaluation time and result iteration time. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1778[TINKERPOP-1778] == TinkerPop 3.3.3 *Release Date: May 8, 2018* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.3/CHANGELOG.asciidoc#release-3-3-3[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Credential DSL Changes The Credential DSL has been modified to work as a standard Java-based Gremlin DSL. The now deprecated old approach used a ""graph wrapping"" style that was developed long before the link:http://tinkerpop.apache.org/docs/current/reference/#gremlin-java-dsl[recommended method] for building DSLs was published. Under this new model, the DSL is initialized via traversal as follows: [source,java] ---- CredentialTraversalSource credentials = graph.traversal(CredentialTraversalSource.class) credentials.user(""stephen"",""password"").iterate() credentials.users(""stephen"").valueMap().next() credentials.users().count().next() credentials.users(""stephen"").drop().iterate() ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1903[TINKERPOP-1903], link:http://tinkerpop.apache.org/docs/3.3.2/reference/#security[Reference Documentation - Security] == TinkerPop 3.3.2 *Release Date: April 2, 2018* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.2/CHANGELOG.asciidoc#release-3-3-2[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Gremlin Python Sets Graph traversals that return a `Set` from Java are now coerced to a `List` in Python. This change ensures that Python results match Java results for the same traversal. It is possible to see this problem in prior versions of gremlin-python where a `Set` of numbers of different types are returned. In Java, a set of: [source,text] ---- [1,1.0d,2,2.0d] ---- would be deserialized to the following in Python: [source,text] ---- [1,2] ---- Now that the Java `Set` is coerced to a `List` in Gremin Python, the Java `Set` can be fully represented. Users who require a `Set` will need to manually convert their `List` to a `Set`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1844[TINKERPOP-1844] == TinkerPop 3.3.1 *Release Date: December 17, 2017* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.1/CHANGELOG.asciidoc#release-3-3-1[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Gremlin Python path() There was a bug in GraphSON 3.0 serialization that prevented proper handling of results contain `Path` object. As a result, traversals that used and returned results from the `path()`-step in Python would return unusable results, but did not actually cause an exception condition. This problem is now resolved. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1799[TINKERPOP-1799] ==== Added `math()`-step for Scientific Traversal Computing `GraphTraversal.math(String)` was added. This step provides scientific calculator capabilities to a Gremlin traversal. [source,groovy] ---- gremlin> g.V().as('a').out('knows').as('b').math('a + b').by('age') ==>56.0 ==>61.0 gremlin> g.V().as('a').out('created').as('b'). ......1> math('b + a'). ......2> by(both().count().math('_ + 100')). ......3> by('age') ==>132.0 ==>133.0 ==>135.0 ==>138.0 gremlin> g.withSack(1).V(1).repeat(sack(sum).by(constant(1))).times(10).emit().sack().math('sin _') ==>0.9092974268256817 ==>0.1411200080598672 ==>-0.7568024953079282 ==>-0.9589242746631385 ==>-0.27941549819892586 ==>0.6569865987187891 ==>0.9893582466233818 ==>0.4121184852417566 ==>-0.5440211108893698 ==>-0.9999902065507035 ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1632[TINKERPOP-1632] ==== Changed Typing on `from()` and `to()` The `from()` and `to()`-steps of `GraphTraversal` have a `Traversal` overload. The `E` has been changed to `?` in order to reduce `< >`-based coersion in strongly type Gremlin language variants. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1793[TINKERPOP-1793] ==== addV(traversal) and addE(traversal) The `GraphTraversal` and `GraphTraversalSource` methods of `addV()` and `addE()` have been extended to support dynamic label determination upon element creation. Both these methods can take a `Traversal` where the first `String` returned by the traversal is used as the label of the respective element. [source,groovy] ---- gremlin> g = TinkerFactory.createModern().traversal() ==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard] gremlin> g.addV(V().has('name','marko').label()). property('name','stephen') ==>v[13] gremlin> g.V().has('name','stephen').valueMap(true) ==>[name:[stephen],label:person,id:13] gremlin> g.V().has('name','stephen'). addE(V().hasLabel('software').inE().label()). to(V().has('name','lop')) ==>e[15][13-created->3] gremlin> g.V().has('name','stephen').outE().valueMap(true) ==>[label:created,id:15] gremlin> ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1793[TINKERPOP-1793] ==== PageRankVertexProgram There were two major bugs in the way in which PageRank was being calculated in `PageRankVertexProgram`. First, teleportation energy was not being distributed correctly amongst the vertices at each round. Second, terminal vertices (i.e. vertices with no outgoing edges) did not have their full gathered energy distributed via teleportation. For users upgrading, note that while the relative rank orders will remain ""the same,"" the actual PageRank values will differ from prior TinkerPop versions. ``` VERTEX iGRAPH TINKERPOP marko 0.1119788 0.11375485828040575 vadas 0.1370267 0.14598540145985406 lop 0.2665600 0.30472082661863686 josh 0.1620746 0.14598540145985406 ripple 0.2103812 0.1757986539008437 peter 0.1119788 0.11375485828040575 ``` Normalization preserved through computation: ``` 0.11375485828040575 + 0.14598540145985406 + 0.30472082661863686 + 0.14598540145985406 + 0.1757986539008437 + 0.11375485828040575 ==>1.00000000000000018 ``` Two other additions to `PageRankVertexProgram` were provided as well. 1. It now calculates the vertex count and thus, no longer requires the user to specify the vertex count. 2. It now allows the user to leverage an epsilon-based convergence instead of having to specify the number of iterations to execute. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1783[TINKERPOP-1783] ==== IO Defaults While 3.3.0 released Gryo 3.0 and GraphSON 3.0 and these versions were defaulted in a number of places, it seems that some key defaults were missed. Specifically, calls to `Graph.io(graphson())` and `Graph.io(gryo())` were still using the old versions. The defaults have now been changed to ensure 3.0 is properly referenced in those cases. ==== Upgrade Neo4j See Neo4j's link:https://neo4j.com/guides/upgrade/[3.2 Upgrade FAQ] for a complete guide on how to upgrade from the previous 2.3.3 version. Also note that many of the configuration settings have link:https://neo4j.com/developer/kb/manually-migrating-configuration-settings-from-neo4j-2x-to-neo4j-3x/[changed from neo4j 2x to 3x] In particular, these properties referenced in TinkerPop documentation and configuration were renamed: [width=""100%"",cols=""2"",options=""header""] |========================================================= |Neo4j 2.3 (TinkerPop \\<= 3.3.0) |Neo4j 3.2 (TinkerPop 3.3.1) |node_auto_indexing |dbms.auto_index.nodes.enabled |relationship_auto_indexing |dbms.auto_index.relationships.enabled |ha.cluster_server |ha.host.coordination |ha.server |ha.host.data |========================================================= === Upgrading for Providers IMPORTANT: It is recommended that providers also review all the upgrade instructions specified for users. Many of the changes there may prove important for the provider's implementation. ==== Graph Database Providers ===== IO Version Check In the `Graph.io()` method, providers are to bootstrap the `Io` instance returned with their own custom serializers typically provided through a custom `IoRegistry` instance. Prior to this change it was not possible to easily determine the version of `Io` that was expected (nor was it especially necessary as TinkerPop didn't have breaking format changes between versions). As of 3.3.0 however, there could be IO test incompatibilities for some providers who need to register a different `IoRegistry` instance depending on the version the user wants. To allow for that check, the `Io` interface now has the following method: [source,java] ---- public boolean requiresVersion(final V version); ---- which allows the graph provider to check if a specific `GryoVersion` or `GraphSONVersion` is required. Using that information, the provider could then assign the right `IoRegistry` to match that. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1767[TINKERPOP-1767] == TinkerPop 3.3.0 *Release Date: August 21, 2017* Please see the link:https://github.com/apache/tinkerpop/blob/3.3.0/CHANGELOG.asciidoc#release-3-3-0[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Packaged Data Files TinkerPop has always packaged sample graphs with its zip distributions. As of 3.3.0, the distributions will only include Gryo 3.0, GraphSON 3.0 and GraphML (which is unversioned) files. Other versions are not included, but could obviously be generated using the IO API directly. ==== GraphTraversal Has-Methods Re-Organized `GraphTraversal.hasXXX()`, where `XXX` is `Id`, `Label`, `Key`, `Value`, was faulty in that they relied on calling an intermediate method for flattening `Object[]` arguments and thus, yielding a non 1-to-1 correspondence between `GraphTraversal` and `Bytecode`. This has been remedied. Most users will not notice this change. Perhaps only some users that may use Java reflection over `GraphTraversal` might have a simple problem. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1520[TINKERPOP-1520] ==== Changes to IO ===== Gryo 3.0 With Gryo, TinkerPop skips version 2.0 and goes right to 3.0 (to maintain better parity with GraphSON versioning). Gryo 3.0 fixes a number of inconsistencies with Gryo 1.0 and hopefully marks a point where Gryo is better versioned over time. Gryo 3.0 is not compatible with Gryo 1.0 and is now the default version of Gryo exposed by TinkerPop in Gremlin Server and IO. It isn't hard to switch back to use of Gryo 1.0 if necessary. Here is the approach for writing an entire graph: [source,java] ---- Graph graph = TinkerFactory.createModern(); GryoMapper mapper = graph.io(IoCore.gryo()).mapper().version(GryoVersion.V1_0).create() try (OutputStream os = new FileOutputStream(""tinkerpop-modern.json"")) { graph.io(IoCore.gryo()).writer().mapper(mapper).create().writeGraph(os, graph) } final Graph newGraph = TinkerGraph.open(); try (InputStream stream = new FileInputStream(""tinkerpop-modern.json"")) { newGraph.io(IoCore.gryo()).reader().mapper(mapper).create().readGraph(stream, newGraph); } ---- Gremlin Server configurations don't include Gryo 1.0 by default: [source,yaml] ---- serializers: - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }} # application/vnd.gremlin-v3.0+gryo - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { serializeResultToString: true }} # application/vnd.gremlin-v3.0+gryo-stringd - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }} # application/json ---- but adding an entry as follows will add it back: [source,yaml] ---- serializers: - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV1d0] }} # application/vnd.gremlin-v1.0+gryo - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }} # application/vnd.gremlin-v3.0+gryo - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { serializeResultToString: true }} # application/vnd.gremlin-v3.0+gryo-stringd - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }} # application/json ---- To use Gryo 1.0 with the Java driver, just specify the 1.0 serializer directly: [source,java] ---- GryoMapper.Builder builder = GryoMapper.build(). version(GryoVersion.V1_0). addRegistry(TinkerIoRegistryV1d0.instance()); Cluster cluster = Cluster.build().serializer(GryoMessageSerializerV1d0(builder)); ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1698[TINKERPOP-1698] ===== GraphSON 3.0 GraphSON 3.0 finishes what GraphSON 2.0 began by taking the extra step to include the following types: `g:Map`, `g:List` and `g:Set`. With these types it is now possible to get expected Gremlin results in GLVs just as one would if using Java. This is especially true of the `g:Map` type, which allows non-string keys values, something not allowed in regular JSON maps. This allows for common traversals like `g.V().groupCount()` to work, where the traversal groups on a `Vertex` or some other complex object. Note that GraphSON 3.0 does not have an option to be without types. This was a feature of 1.0 and 2.0, but it is no longer supported. There is little point to such a feature as we see more movement toward GLVs, which require types, and less usage of scripts with custom parsing of results. Both TinkerGraph and Gremlin Server have been defaulted to work with GraphSON 3.0. For TinkerGraph this means that the following commands: [source,java] ---- Graph graph = TinkerFactory.createModern(); graph.io(IoCore.graphson()).writeGraph(""tinkerpop-modern.json""); final Graph newGraph = TinkerGraph.open(); newGraph.io(IoCore.graphson()).readGraph(""tinkerpop-modern.json""); ---- will write and read GraphSON 3.0 format rather than 1.0. To use 1.0 (or 2.0 for that matter) format simply set the `version()` on the appropriate builder methods: [source,java] ---- Graph graph = TinkerFactory.createModern(); GraphSONMapper mapper = graph.io(IoCore.graphson()).mapper().version(GraphSONVersion.V1_0).create() try (OutputStream os = new FileOutputStream(""tinkerpop-modern.json"")) { graph.io(IoCore.graphson()).writer().mapper(mapper).create().writeGraph(os, graph) } final Graph newGraph = TinkerGraph.open(); try (InputStream stream = new FileInputStream(""tinkerpop-modern.json"")) { newGraph.io(IoCore.graphson()).reader().mapper(mapper).create().readGraph(stream, newGraph); } ---- For Gremlin Server, this change means that the `application/json` mime type no longer returns GraphSON 1.0 without type embedding. Instead, Gremlin Server will return GraphSON 3.0 with partial types enabled (i.e. which is equivalent to `application/vnd.gremlin-v3.0+json`). The `serializers` section the sample Gremlin Server YAML files now typically look like this: [source,yaml] ---- serializers: - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }} # application/vnd.gremlin-v3.0+gryo - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { serializeResultToString: true }} # application/vnd.gremlin-v3.0+gryo-stringd - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV1d0] }} # application/json ---- It is possible to bring back the original configuration for `application/json` by changing the last entry as follows: [source,yaml] ---- - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0] }} # application/vnd.gremlin-v3.0+gryo - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0, config: { serializeResultToString: true }} # application/vnd.gremlin-v3.0+gryo-stringd - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV1d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV1d0] }} # application/json ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1414[TINKERPOP-1414], link:https://issues.apache.org/jira/browse/TINKERPOP-1427[TINKERPOP-1427], link:https://issues.apache.org/jira/browse/TINKERPOP-1574[TINKERPOP-1574] ==== Graphite and Ganglia Graphite and Ganglia are no longer packaged with the Gremlin Server distribution. They are considered optional dependencies and therefore must be installed manually by the user. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1550[TINKERPOP-1550], link:http://tinkerpop.apache.org/docs/3.3.0/reference/#metrics[Reference Documentation - Metrics] ==== SelectStep Defaults to Pop.last `SelectStep` and `SelectOneStep` (`select()`) are the only `Scoping` steps that default to `Pop.mixed` as their labeled path selection criteria. All other steps, like `match()`, `where()` and `dedup()`, use `Pop.last`. In order to better enable optimizations around total `Pop.last` traversals, the `select()`-steps now default to `Pop.last`. Most users will not notice a difference as it is rare for repeated labels to be used in practice. However, formal backwards compatibility is possible as outlined below. Assuming that `x` is not a `Pop` argument: 1. Change all `select(x,y,z)` calls to `selectV3d2(x,y,z)` calls. 2. Change all `select(x,y,z)`-step calls to `select(Pop.mixed,x,y,z)`. If an explicit `Pop` argument is provided, then no changes are required. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1541[TINKERPOP-1541] ==== OptionalStep and Side-Effects The `optional()`-step was previously implemented using `ChooseStep`. However, if the optional branch contained side-effects, then unexpected behaviors can emerge. Thus, a potential backwards compatibility issue arises if side-effects were being used in `optional()`. However, the behavior would be unpredictable so this backwards incompatibility is desirable. See link:https://issues.apache.org/jira/browse/TINKERPOP-1506[TINKERPOP-1506] ==== Gremlin Console Initialization It is no longer possible to intialize the Gremlin Console with a script without use of `-e`. In other words, prior versions allowed: [source,text] bin/gremlin.sh gremlin.groovy Such a command must now be written as: [source,text] bin/gremlin.sh -i gremlin.groovy See: link:https://issues.apache.org/jira/browse/TINKERPOP-1283[TINKERPOP-1283], link:https://issues.apache.org/jira/browse/TINKERPOP-1651[TINKERPOP-1651] ==== GraphTraversal valueMap() Signature Updated `GraphTraversal.valueMap(includeTokens,propertyKeys...)` now returns a `Map` to account for the presence of `T.id` or `T.label` if you pass `true` to it. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1283[TINKERPOP-1483] ==== HADOOP_GREMLIN_LIBS and Spark The TinkerPop reference documentation has always mentioned that the `gremlin-spark` `/lib` directory needed to be added to `HADOOP_GREMLIN_LIBS` environment variable. In reality, that was not truly necessary. With Spark 1.x having `gremlin-spark` in `HADOOP_GREMLIN_LIBS` hasn't been a problem, but Spark 2.0 introduces a check for duplicate jars on the path which will cause job initialization to fail. As a result, going forward with TinkerPop 3.3.0, the `gremlin-spark` `lib` directory should not be included in `HADOOP_GREMLIN_LIBS`. ==== Deprecation Removal The following deprecated classes, methods or fields have been removed in this version: * `giraph-gremlin` ** `org.apache.tinkerpop.gremlin.giraph.groovy.plugin.GiraphGremlinPlugin` * `gremlin-console` ** `org.apache.tinkerpop.gremlin.console.Console(String)` ** `org.apache.tinkerpop.gremlin.console.ConsoleImportCustomizerProvider` ** `org.apache.tinkerpop.gremlin.console.plugin.*` ** `org.apache.tinkerpop.gremlin.console.groovy.plugin.DriverGremlinPlugin` ** `org.apache.tinkerpop.gremlin.console.groovy.plugin.DriverRemoteAcceptor` ** `org.apache.tinkerpop.gremlin.console.groovy.plugin.GephiGremlinPlugin` ** `org.apache.tinkerpop.gremlin.console.groovy.plugin.UtilitiesGremlinPlugin` * `gremlin-core` ** `org.apache.tinkerpop.gremlin.jsr223.CoreGremlinModule` ** `org.apache.tinkerpop.gremlin.jsr223.CoreGremlinPlugin#INSTANCE` ** `org.apache.tinkerpop.gremlin.jsr223.GremlinModule` ** `org.apache.tinkerpop.gremlin.jsr223.SingleGremlinScriptEngineManager#getInstance()` ** `org.apache.tinkerpop.gremlin.jsr223.GremlinScriptEngineManager#addModule(GremlinModule)` ** `org.apache.tinkerpop.gremlin.jsr223.console.PluginAcceptor` ** `org.apache.tinkerpop.gremlin.process.traversal.TraversalSource.Builder` ** `org.apache.tinkerpop.gremlin.process.traversal.util.ConnectiveP(P...)` ** `org.apache.tinkerpop.gremlin.process.traversal.util.AndP(P...)` ** `org.apache.tinkerpop.gremlin.process.traversal.util.OrP(P...)` ** `org.apache.tinkerpop.gremlin.process.traversal.util.TraversalScriptFunction` ** `org.apache.tinkerpop.gremlin.process.traversal.util.TraversalScriptHelper` ** `org.apache.tinkerpop.gremlin.process.traversal.Order.keyIncr` ** `org.apache.tinkerpop.gremlin.process.traversal.Order.valueIncr` ** `org.apache.tinkerpop.gremlin.process.traversal.Order.keyDecr` ** `org.apache.tinkerpop.gremlin.process.traversal.Order.valueIncr` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.GraphTraversal.mapKeys()` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.GraphTraversal.mapValues()` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#addV(Object...)` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#addE(Direction, String, String, Object...)` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#addOutE(String, String, Object...)` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#addInV(String, String, Object...)` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#selectV3d2()` ** `org.apache.tinkerpop.gremlin.process.traversal.Bindings()` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource#withBindings(Bindings)` ** `org.apache.tinkerpop.gremlin.structure.Transaction.submit(Function)` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#sack(BiFunction,String)` ** `org.apache.tinkerpop.gremlin.process.traversal.strategy.finalization.LazyBarrierStrategy` ** `org.apache.tinkerpop.gremlin.process.traversal.TraversalSideEffects` (various methods) ** `org.apache.tinkerpop.gremlin.process.computer.traversal.step.VertexComputing#generateComputer(Graph)` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#groupV3d0(String)` ** `org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#groupV3d0()` ** `org.apache.tinkerpop.gremlin.structure.Graph.Features.VertexPropertyFeatures#supportsAddProperty()` ** `org.apache.tinkerpop.gremlin.structure.Graph.Features.VertexPropertyFeatures#FEATURE_ADD_PROPERTY` ** `org.apache.tinkerpop.gremlin.structure.Graph.OptIn#SUITE_GROOVY_PROCESS_STANDARD` ** `org.apache.tinkerpop.gremlin.structure.Graph.OptIn#SUITE_GROOVY_PROCESS_COMPUTER` ** `org.apache.tinkerpop.gremlin.structure.Graph.OptIn#SUITE_GROOVY_ENVIRONMENT` ** `org.apache.tinkerpop.gremlin.structure.Graph.OptIn#SUITE_GROOVY_ENVIRONMENT_INTEGRATE` ** `org.apache.tinkerpop.gremlin.structure.io.Io.Builder#registry(IoRegistry)` ** `org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper.Builder#embedTypes(boolean)` ** `org.apache.tinkerpop.gremlin.structure.Transaction.submit(Function)` ** `org.apache.tinkerpop.gremlin.structure.util.detached.DetachedEdge(Object,String,Map,Pair,Pair)` ** `org.apache.tinkerpop.gremlin.util.CoreImports` ** `org.apache.tinkerpop.gremlin.util.ScriptEngineCache` ** `org.apache.tinkerpop.gremlin.process.computer.util.ConfigurationTraversal` * `gremlin-driver` ** `org.apache.tinkerpop.gremlin.driver.Cluster$Builder#reconnectIntialDelay(int)` ** `org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0(GryoMapper)` ** `org.apache.tinkerpop.gremlin.driver.ser.AbstractGraphSONMessageSerializerV2d0#TOKEN_USE_MAPPER_FROM_GRAPH` ** `org.apache.tinkerpop.gremlin.driver.ser.AbstractGryoSONMessageSerializerV2d0#TOKEN_USE_MAPPER_FROM_GRAPH` * `gremlin-groovy` ** `org.apache.tinkerpop.gremlin.groovy.AbstractImportCustomizerProvider` ** `org.apache.tinkerpop.gremlin.groovy.CompilerCustomizerProvider` ** `org.apache.tinkerpop.gremlin.groovy.DefaultImportCustomizerProvider` ** `org.apache.tinkerpop.gremlin.groovy.EmptyImportCustomizerProvider` ** `org.apache.tinkerpop.gremlin.groovy.ImportCustomizerProvider` ** `org.apache.tinkerpop.gremlin.groovy.NoImportCustomizerProvider` ** `org.apache.tinkerpop.gremlin.groovy.engine.ConcurrentBindings` ** `org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor#build(String,List,List,List,Map)` ** `org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor#getScriptEngines()` ** `org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor#getGlobalBindings()` ** `org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.Builder#enabledPlugins(Set)` ** `org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.Builder#addEngineSettings(String,List,List,List,Map)` ** `org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.Builder#engineSettings(Map)` ** `org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.Builder#use(List)` ** `org.apache.tinkerpop.gremlin.groovy.engine.ScriptEngines` ** `org.apache.tinkerpop.gremlin.groovy.function.*` ** `org.apache.tinkerpop.gremlin.groovy.plugin.*` ** `org.apache.tinkerpop.gremlin.groovy.plugin.credential.*` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.DependencyManager` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine(ImportCustomizerProvider)` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine(CompilerCustomizerProvider)` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine#plugins()` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.ScriptExecutor` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.ScriptEnginePluginAcceptor` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.customizer.SandboxExtension` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.customizer.*` ** `org.apache.tinkerpop.gremlin.groovy.util.DependencyGrabber#deleteDependenciesFromPath(org.apache.tinkerpop.gremlin.groovy.plugin.Artifact)` ** `org.apache.tinkerpop.gremlin.groovy.util.DependencyGrabber#copyDependenciesToPath(org.apache.tinkerpop.gremlin.groovy.plugin.Artifact)` * `gremlin-python` ** `org.apache.tinkerpop.gremlin.python.jsr223.GremlinJythonScriptEngine#()` * `gremlin-server` ** `org.apache.tinkerpop.gremlin.server.GremlinServer(ServerGremlinExecutor)` ** `org.apache.tinkerpop.gremlin.server.Settings#plugins` ** `org.apache.tinkerpop.gremlin.server.auth.AllowAllAuthenticator.newSaslNegotiator()` ** `org.apache.tinkerpop.gremlin.server.auth.Authenticator.newSaslNegotiator()` ** `org.apache.tinkerpop.gremlin.server.auth.Krb5Authenticator.newSaslNegotiator()` ** `org.apache.tinkerpop.gremlin.server.auth.SimpleAuthenticator.newSaslNegotiator()` ** `org.apache.tinkerpop.gremlin.server.handler.IteratorHandler` ** `org.apache.tinkerpop.gremlin.server.handler.NioGremlinResponseEncoder` ** `org.apache.tinkerpop.gremlin.server.handler.WsGremlinResponseEncoder` ** `org.apache.tinkerpop.gremlin.server.handler.OpSelectorHandler.errorMeter` ** `org.apache.tinkerpop.gremlin.server.op.control.*` ** `org.apache.tinkerpop.gremlin.server.op.AbstractEvalOpProcessor.errorMeter` ** `org.apache.tinkerpop.gremlin.server.op.AbstractEvalOpProcessor.validBindingName` ** `org.apache.tinkerpop.gremlin.server.op.session.Session.kill()` ** `org.apache.tinkerpop.gremlin.server.op.session.Session.manualkill()` * `hadoop-gremlin` ** `org.apache.tinkerpop.gremlin.hadoop.Constants#GREMLIN_HADOOP_GRAPH_INPUT_FORMAT` ** `org.apache.tinkerpop.gremlin.hadoop.Constants#GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT` ** `org.apache.tinkerpop.gremlin.hadoop.Constants#GREMLIN_HADOOP_GRAPH_INPUT_FORMAT_HAS_EDGES` ** `org.apache.tinkerpop.gremlin.hadoop.Constants#GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT_HAS_EDGES` ** `org.apache.tinkerpop.gremlin.hadoop.Constants#GREMLIN_SPARK_GRAPH_INPUT_RDD` ** `org.apache.tinkerpop.gremlin.hadoop.Constants#GREMLIN_SPARK_GRAPH_OUTPUT_RDD` * `spark-gremlin` ** `org.apache.tinkerpop.gremlin.spark.groovy.plugin.SparkGremlinPlugin` * `tinkergraph-gremlin` ** `org.apache.tinkerpop.gremlin.tinkergraph.groovy.plugin.TinkerGraphGremlinPlugin` ** `org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph#CONFIG_*` ** `org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistry` ** `org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV1d0#getInstance()` ** `org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV2d0#getInstance()` Please see the javadoc deprecation notes or upgrade documentation specific to when the deprecation took place to understand how to resolve this breaking change. See: link:https://issues.apache.org/jira/browse/TINKERPOP-832[TINKERPOP-832], link:https://issues.apache.org/jira/browse/TINKERPOP-833[TINKERPOP-833], link:https://issues.apache.org/jira/browse/TINKERPOP-834[TINKERPOP-834], link:https://issues.apache.org/jira/browse/TINKERPOP-999[TINKERPOP-999], link:https://issues.apache.org/jira/browse/TINKERPOP-1010[TINKERPOP-1010], link:https://issues.apache.org/jira/browse/TINKERPOP-1028[TINKERPOP-1028], link:https://issues.apache.org/jira/browse/TINKERPOP-1040[TINKERPOP-1040], link:https://issues.apache.org/jira/browse/TINKERPOP-1046[TINKERPOP-1046], link:https://issues.apache.org/jira/browse/TINKERPOP-1049[TINKERPOP-1049], link:https://issues.apache.org/jira/browse/TINKERPOP-1142[TINKERPOP-1142], link:https://issues.apache.org/jira/browse/TINKERPOP-1169[TINKERPOP-1169], link:https://issues.apache.org/jira/browse/TINKERPOP-1171[TINKERPOP-1171], link:https://issues.apache.org/jira/browse/TINKERPOP-1275[TINKERPOP-1275], link:https://issues.apache.org/jira/browse/TINKERPOP-1283[TINKERPOP-1283], link:https://issues.apache.org/jira/browse/TINKERPOP-1289[TINKERPOP-1289], link:https://issues.apache.org/jira/browse/TINKERPOP-1291[TINKERPOP-1291], link:https://issues.apache.org/jira/browse/TINKERPOP-1420[TINKERPOP-1420], link:https://issues.apache.org/jira/browse/TINKERPOP-1421[TINKERPOP-1421], link:https://issues.apache.org/jira/browse/TINKERPOP-1465[TINKERPOP-1465], link:https://issues.apache.org/jira/browse/TINKERPOP-1481[TINKERPOP-1481], link:https://issues.apache.org/jira/browse/TINKERPOP-1526[TINKERPOP-1526], link:https://issues.apache.org/jira/browse/TINKERPOP-1603[TINKERPOP-1603], link:https://issues.apache.org/jira/browse/TINKERPOP-1612[TINKERPOP-1612], link:https://issues.apache.org/jira/browse/TINKERPOP-1622[TINKERPOP-1622], link:https://issues.apache.org/jira/browse/TINKERPOP-1651[TINKERPOP-1651], link:https://issues.apache.org/jira/browse/TINKERPOP-1694[TINKERPOP-1694], link:https://issues.apache.org/jira/browse/TINKERPOP-1700[TINKERPOP-1700], link:https://issues.apache.org/jira/browse/TINKERPOP-1706[TINKERPOP-1706], link:https://issues.apache.org/jira/browse/TINKERPOP-1721[TINKERPOP-1721], link:https://issues.apache.org/jira/browse/TINKERPOP-1719[TINKERPOP-1719], link:https://issues.apache.org/jira/browse/TINKERPOP-1720[TINKERPOP-1720], link:https://issues.apache.org/jira/browse/TINKERPOP-880[TINKERPOP-880], link:https://issues.apache.org/jira/browse/TINKERPOP-1170[TINKERPOP-1170], link:https://issues.apache.org/jira/browse/TINKERPOP-1729[TINKERPOP-1729] ==== Gremlin-server.sh and Init Scripts `gremlin-server.sh` is now also an init script and can no longer be started without parameters. To start it in the foreground with defaults like previous usage, please use the `console` parameter. Also, `gremlin-server.sh` will continue to start in the foreground when provided a yaml configuration file. How to install as a service has been added to the link:http://tinkerpop.apache.org/docs/3.3.0/reference/#_as_a_service[Reference Documentation - As A Service]. The switch name has changed for installing dependencies. `-i` has been deprecated and replaced by `install`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-980[TINKERPOP-980], link:http://tinkerpop.apache.org/docs/3.3.0/reference/#_configuring_2[Reference Documentation - Server Configuration]. ==== Removal of useMapperFromGraph The `userMapperFromGraph` serialization configuration option was used to allow the IO configurations of a specific graph to be assigned to a specific serializer. This feature has been removed completely now. Please use the `ioRegistries` configuration option to add one or more specific `Graph` serialization capabilities to a serializer. [source,yaml] ---- serializers: - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV1d0] }} # application/vnd.gremlin-v1.0+gryo ---- see: link:https://issues.apache.org/jira/browse/TINKERPOP-1699[TINKERPOP-1699] ==== Gremlin-server.bat The switch name has changed for installing dependencies. `-i` has been deprecated and replaced by `install`. ==== SparkGraphComputer GryoRegistrator Historically, `SparkGraphComputer` has used `GryoSerializer` to handle the serialization of objects in Spark. The reason this exists is because TinkerPop uses a shaded version of Kryo and thus, couldn't use the standard `KryoSerializer`-model provided by Spark. However, a ""shim model"" was created which allows for the shaded and unshaded versions of Kryo to interact with one another. To this end, `KryoSerializer` can now be used with a `GryoRegistrator`. The properties file for a `SparkGraphComputer` now looks as follows: ``` spark.serializer=org.apache.spark.serializer.KryoSerializer spark.kryo.registrator=org.apache.tinkerpop.gremlin.spark.structure.io.gryo.GryoRegistrator ``` If the old `GryoSerializer` model is desired, then the properties file should simply look as before: ``` spark.serializer=org.apache.tinkerpop.gremlin.spark.structure.io.gryo.GryoSerializer ``` See: link:https://issues.apache.org/jira/browse/TINKERPOP-1389[TINKERPOP-1389] ==== ScriptInputFormat The API for the script provided to a `ScriptInputFormat` has changed slightly. The signature for `parse(line, factory)` is now simply `parse(line)`. The inclusion of `factory` was deprecated in 3.1.2. Instead of using the {{factory}} to get the {{StarGraph}} there is a {{graph}} variable in the glocal context of the script. Simply use that directly in the script. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1137[TINKERPOP-1137], link:http://tinkerpop.apache.org/docs/3.3.0-SNAPSHOT/reference/#script-io-format[Reference Documentation - Script I/O Format] === Upgrading for Providers IMPORTANT: It is recommended that providers also review all the upgrade instructions specified for users. Many of the changes there may prove important for the provider's implementation. ==== Graph System Providers ===== GremlinPlugin The previously deprecated `GremlinPlugin` system has been removed. The old `GremlinPlugin` interface formerly resided in the `org.apache.tinkerpop.gremlin.groovy.plugin` package of `gremlin-groovy`. This interface was replaced by an interface of the same name in 3.2.4, which now resides in the `org.apache.tinkerpop.gremlin.jsr223` package in `gremlin-core`. Obviously, existing plugins will need to be updated to use this new interface. The plugin model has changed slightly to be more generic and not specifically bound to Groovy based script engines. Under the new model, the plugin simply returns `Customizer` instances that can be applied generically to any `ScriptEngine` or specifically to a particular `ScriptEngine`. More details can be found in the link:http://tinkerpop.apache.org/docs/x.y.z/dev/provider/#gremlin-plugins[Provider Documentation] ==== Graph Database Providers ===== Test Suite Removal A number of test suites that were previously deprecated have been removed which should reduce the burden on graph providers who are implementing TinkerPop. Test suites related to perfrmance based on `junit-benchmarks` have been removed as have the suites in `gremlin-groovy-test` (in fact, this entire module has been removed). Specifically, providers should be concerned with breaking changes related to the removal of: * `StructurePerformanceSuite` * `ProcessPerformanceSuite` * `GroovyEnvironmentPerformanceSuite` * `GroovyProcessStandardSuite` * `GroovyProcessComputerSuite` * `GroovyEnvironmentSuite` * `GroovyEnvironmentIntegrateSuite` Those graph providers who relied on these tests should simply remove them from their respective test suites. Beware of `OptOut` annotations that reference tests in these suites as test failure will occur if those references are not removed. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1235[TINKERPOP-1235], link:https://issues.apache.org/jira/browse/TINKERPOP-1612[TINKERPOP-1612] ===== TransactionException The `AbstractTransaction.TransactionException` class is now just `TransactionException` which extends `RuntimeExcetpion` rather than `Exception`. Providers should consider using this exception to wrap their own on calls to `Transaction.commit()` or `Transaction.rollback()`. By throwing this exception, the TinkerPop stack can better respond to transaction problems and it allows for more common, generalized error handling for users. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1004[TINKERPOP-1004] ==== Driver Providers ===== SASL Byte Array Gremlin Server no longer supports accepting a byte array for the value passed to the ""sasl"" parameter in authentication messages. It only accepts a Base64 encoded string. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1603[TINKERPOP-1603] ",16292,True,3230.233239632724,median "[role=""xpack""] [[security-settings]] === Security settings in {es} ++++ Security settings ++++ By default, the {es} {security-features} are disabled when you have a basic or trial license. To enable {security-features}, use the `xpack.security.enabled` setting. You configure `xpack.security` settings to <> and perform message authentication, <>, <>, <>, and <>. All of these settings can be added to the `elasticsearch.yml` configuration file, with the exception of the secure settings, which you add to the {es} keystore. For more information about creating and updating the {es} keystore, see <>. [float] [[general-security-settings]] ==== General security settings `xpack.security.enabled`:: Set to `true` to enable {es} {security-features} on the node. + + -- If set to `false`, which is the default value for basic and trial licenses, {security-features} are disabled. It also affects all {kib} instances that connect to this {es} instance; you do not need to disable {security-features} in those `kibana.yml` files. For more information about disabling {security-features} in specific {kib} instances, see {kibana-ref}/security-settings-kb.html[{kib} security settings]. TIP: If you have gold or higher licenses, the default value is `true`; we recommend that you explicitly add this setting to avoid confusion. -- `xpack.security.hide_settings`:: A comma-separated list of settings that are omitted from the results of the <>. You can use wildcards to include multiple settings in the list. For example, the following value hides all the settings for the ad1 active_directory realm: `xpack.security.authc.realms.active_directory.ad1.*`. The API already omits all `ssl` settings, `bind_dn`, and `bind_password` due to the sensitive nature of the information. `xpack.security.fips_mode.enabled`:: Enables fips mode of operation. Set this to `true` if you run this {es} instance in a FIPS 140-2 enabled JVM. For more information, see <>. Defaults to `false`. [float] [[password-security-settings]] ==== Default password security settings `xpack.security.authc.accept_default_password`:: In `elasticsearch.yml`, set this to `false` to disable support for the default ""changeme"" password. [float] [[password-hashing-settings]] ==== Password hashing settings `xpack.security.authc.password_hashing.algorithm`:: Specifies the hashing algorithm that is used for secure user credential storage. See <>. Defaults to `bcrypt`. [float] [[anonymous-access-settings]] ==== Anonymous access settings You can configure the following anonymous access settings in `elasticsearch.yml`. For more information, see {stack-ov}/anonymous-access.html[ Enabling anonymous access]. `xpack.security.authc.anonymous.username`:: The username (principal) of the anonymous user. Defaults to `_es_anonymous_user`. `xpack.security.authc.anonymous.roles`:: The roles to associate with the anonymous user. Required. `xpack.security.authc.anonymous.authz_exception`:: When `true`, an HTTP 403 response is returned if the anonymous user does not have the appropriate permissions for the requested action. The user is not prompted to provide credentials to access the requested resource. When set to `false`, an HTTP 401 response is returned and the user can provide credentials with the appropriate permissions to gain access. Defaults to `true`. [float] [[security-automata-settings]] ==== Automata Settings In places where the {security-features} accept wildcard patterns (e.g. index patterns in roles, group matches in the role mapping API), each pattern is compiled into an Automaton. The follow settings are available to control this behaviour. `xpack.security.automata.max_determinized_states`:: The upper limit on how many automaton states may be created by a single pattern. This protects against too-difficult (e.g. exponentially hard) patterns. Defaults to `100,000`. `xpack.security.automata.cache.enabled`:: Whether to cache the compiled automata. Compiling automata can be CPU intensive and may slowdown some operations. The cache reduces the frequency with which automata need to be compiled. Defaults to `true`. `xpack.security.automata.cache.size`:: The maximum number of items to retain in the automata cache. Defaults to `10,000`. `xpack.security.automata.cache.ttl`:: The length of time to retain in an item in the automata cache (based on most recent usage). Defaults to `48h` (48 hours). [float] [[field-document-security-settings]] ==== Document and field level security settings You can set the following document and field level security settings in `elasticsearch.yml`. For more information, see {stack-ov}/field-and-document-access-control.html[Setting up document and field level security]. `xpack.security.dls_fls.enabled`:: Set to `false` to prevent document and field level security from being configured. Defaults to `true`. [float] [[token-service-settings]] ==== Token service settings You can set the following token service settings in `elasticsearch.yml`. `xpack.security.authc.token.enabled`:: Set to `false` to disable the built-in token service. Defaults to `true` unless `xpack.security.http.ssl.enabled` is `false`. This prevents sniffing the token from a connection over plain http. `xpack.security.authc.token.timeout`:: The length of time that a token is valid for. By default this value is `20m` or 20 minutes. The maximum value is 1 hour. [float] [[api-key-service-settings]] ==== API key service settings You can set the following API key service settings in `elasticsearch.yml`. `xpack.security.authc.api_key.enabled`:: Set to `false` to disable the built-in API key service. Defaults to `true` unless `xpack.security.http.ssl.enabled` is `false`. This prevents sniffing the API key from a connection over plain http. `xpack.security.authc.api_key.hashing.algorithm`:: Specifies the hashing algorithm that is used for securing API key credentials. See <>. Defaults to `pbkdf2`. `xpack.security.authc.api_key.cache.ttl`:: The time-to-live for cached API key entries. A API key id and a hash of its API key are cached for this period of time. Specify the time period using the standard {es} <>. Defaults to `1d`. `xpack.security.authc.api_key.cache.max_keys`:: The maximum number of API key entries that can live in the cache at any given time. Defaults to 10,000. `xpack.security.authc.api_key.cache.hash_algo`:: (Expert Setting) The hashing algorithm that is used for the in-memory cached API key credentials. For possible values, see <>. Defaults to `ssha256`. [float] [[realm-settings]] ==== Realm settings You configure realm settings in the `xpack.security.authc.realms` namespace in `elasticsearch.yml`. For example: [source,yaml] ---------------------------------------- xpack.security.authc.realms: native.realm1: order: 0 ... ldap.realm2: order: 1 ... active_directory.realm3: order: 2 ... ... ---------------------------------------- The valid settings vary depending on the realm type. For more information, see {stack-ov}/setting-up-authentication.html[Setting up authentication]. [float] [[ref-realm-settings]] ===== Settings valid for all realms `type`:: The type of the realm: `native, `ldap`, `active_directory`, `pki`, or `file`. Required. `order`:: The priority of the realm within the realm chain. Realms with a lower order are consulted first. Although not required, use of this setting is strongly recommended when you configure multiple realms. Defaults to `Integer.MAX_VALUE`. `enabled`:: Indicates whether a realm is enabled. You can use this setting to disable a realm without removing its configuration information. Defaults to `true`. [[ref-native-settings]] [float] ===== Native realm settings For a native realm, the `type` must be set to `native`. In addition to the <>, you can specify the following optional settings: `cache.ttl`:: The time-to-live for cached user entries. A user and a hash of its credentials are cached for this period of time. Specify the time period using the standard {es} <>. Defaults to `20m`. `cache.max_users`:: The maximum number of user entries that can live in the cache at any given time. Defaults to 100,000. `cache.hash_algo`:: (Expert Setting) The hashing algorithm that is used for the in-memory cached user credentials. For possible values, see <>. Defaults to `ssha256`. `authentication.enabled`:: If set to `false`, disables authentication support in this realm, so that it only supports user lookups. (See the {stack-ov}/run-as-privilege.html[run as] and {stack-ov}/realm-chains.html#authorization_realms[authorization realms] features). Defaults to `true`. [[ref-users-settings]] [float] ===== File realm settings The `type` setting must be set to `file`. In addition to the <>, you can specify the following settings: `cache.ttl`:: The time-to-live for cached user entries. A user and a hash of its credentials are cached for this configured period of time. Defaults to `20m`. Specify values using the standard {es} {ref}/common-options.html#time-units[time units]. Defaults to `20m`. `cache.max_users`:: The maximum number of user entries that can live in the cache at a given time. Defaults to 100,000. `cache.hash_algo`:: (Expert Setting) The hashing algorithm that is used for the in-memory cached user credentials. See <>. Defaults to `ssha256`. `authentication.enabled`:: If set to `false`, disables authentication support in this realm, so that it only supports user lookups. (See the {stack-ov}/run-as-privilege.html[run as] and {stack-ov}/realm-chains.html#authorization_realms[authorization realms] features). Defaults to `true`. [[ref-ldap-settings]] [float] ===== LDAP realm settings The `type` setting must be set to `ldap`. In addition to the <>, you can specify the following settings: `url`:: One or more LDAP URLs in the `ldap[s]://:` format. Required. + To provide multiple URLs, use a YAML array (`[""ldap://server1:636"", ""ldap://server2:636""]`) or comma-separated string (`""ldap://server1:636, ldap://server2:636""`). + While both are supported, you can't mix the `ldap` and `ldaps` protocols. `load_balance.type`:: The behavior to use when there are multiple LDAP URLs defined. For supported values see <>. Defaults to `failover`. `load_balance.cache_ttl`:: When using `dns_failover` or `dns_round_robin` as the load balancing type, this setting controls the amount of time to cache DNS lookups. Defaults to `1h`. `bind_dn`:: The DN of the user that is used to bind to the LDAP and perform searches. Only applicable in user search mode. If not specified, an anonymous bind is attempted. Defaults to Empty. Due to its potential security impact, `bind_dn` is not exposed via the <>. `bind_password`:: deprecated[6.3] Use `secure_bind_password` instead. The password for the user that is used to bind to the LDAP directory. Defaults to Empty. Due to its potential security impact, `bind_password` is not exposed via the <>. `secure_bind_password` (<>):: The password for the user that is used to bind to the LDAP directory. Defaults to Empty. `user_dn_templates`:: The DN template that replaces the user name with the string `{0}`. This setting is multivalued; you can specify multiple user contexts. Required to operate in user template mode. If `user_search.base_dn` is specified, this setting is not valid. For more information on the different modes, see {stack-ov}/ldap-realm.html[LDAP realms]. `authorization_realms`:: The names of the realms that should be consulted for delegated authorization. If this setting is used, then the LDAP realm does not perform role mapping and instead loads the user from the listed realms. The referenced realms are consulted in the order that they are defined in this list. See {stack-ov}/realm-chains.html#authorization_realms[Delegating authorization to another realm] + -- NOTE: If any settings starting with `user_search` are specified, the `user_dn_templates` settings are ignored. -- `user_group_attribute`:: Specifies the attribute to examine on the user for group membership. If any `group_search` settings are specified, this setting is ignored. Defaults to `memberOf`. `user_search.base_dn`:: Specifies a container DN to search for users. Required to operated in user search mode. If `user_dn_templates` is specified, this setting is not valid. For more information on the different modes, see {stack-ov}/ldap-realm.html[LDAP realms]. `user_search.scope`:: The scope of the user search. Valid values are `sub_tree`, `one_level` or `base`. `one_level` only searches objects directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is the user object, and that it is the only user considered. Defaults to `sub_tree`. `user_search.filter`:: Specifies the filter used to search the directory in attempts to match an entry with the username provided by the user. Defaults to `(uid={0})`. `{0}` is substituted with the username provided when searching. `user_search.attribute`:: deprecated[5.6] Use `user_search.filter` instead. The attribute to match with the username sent with the request. Defaults to `uid`. `user_search.pool.enabled`:: Enables or disables connection pooling for user search. If set to `false`, a new connection is created for every search. The default is `true` when `bind_dn` is set. `user_search.pool.size`:: The maximum number of connections to the LDAP server to allow in the connection pool. Defaults to `20`. `user_search.pool.initial_size`:: The initial number of connections to create to the LDAP server on startup. Defaults to `0`. If the LDAP server is down, values greater than `0` could cause startup failures. `user_search.pool.health_check.enabled`:: Enables or disables a health check on LDAP connections in the connection pool. Connections are checked in the background at the specified interval. Defaults to `true`. `user_search.pool.health_check.dn`:: The distinguished name that is retrieved as part of the health check. Defaults to the value of `bind_dn` if present; if not, falls back to `user_search.base_dn`. `user_search.pool.health_check.interval`:: The interval to perform background checks of connections in the pool. Defaults to `60s`. `group_search.base_dn`:: The container DN to search for groups in which the user has membership. When this element is absent, {es} searches for the attribute specified by `user_group_attribute` set on the user in order to determine group membership. `group_search.scope`:: Specifies whether the group search should be `sub_tree`, `one_level` or `base`. `one_level` only searches objects directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is a group object, and that it is the only group considered. Defaults to `sub_tree`. `group_search.filter`:: Specifies a filter to use to look up a group. When not set, the realm searches for `group`, `groupOfNames`, `groupOfUniqueNames`, or `posixGroup` with the attributes `member`, `memberOf`, or `memberUid`. Any instance of `{0}` in the filter is replaced by the user attribute defined in `group_search.user_attribute`. `group_search.user_attribute`:: Specifies the user attribute that is fetched and provided as a parameter to the filter. If not set, the user DN is passed into the filter. Defaults to Empty. `unmapped_groups_as_roles`:: If set to `true`, the names of any unmapped LDAP groups are used as role names and assigned to the user. A group is considered to be _unmapped_ if it is not referenced in a {stack-ov}/mapping-roles.html#mapping-roles-file[role-mapping file]. API-based role mappings are not considered. Defaults to `false`. `files.role_mapping`:: The <> for the {stack-ov}/mapping-roles.html#mapping-roles[ YAML role mapping configuration file]. Defaults to `ES_PATH_CONF/role_mapping.yml`. `follow_referrals`:: Specifies whether {es} should follow referrals returned by the LDAP server. Referrals are URLs returned by the server that are to be used to continue the LDAP operation (for example, search). Defaults to `true`. `metadata`:: A list of additional LDAP attributes that should be loaded from the LDAP server and stored in the authenticated user's metadata field. `timeout.tcp_connect`:: The TCP connect timeout period for establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.tcp_read`:: The TCP read timeout period after establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.ldap_search`:: The LDAP Server enforced timeout period for an LDAP search. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `ssl.key`:: Path to a PEM encoded file containing the private key, which is used if the LDAP server requires client authentication. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: The passphrase that is used to decrypt the private key. This value is optional as the key may not be encrypted. `ssl.secure_key_passphrase` (<>):: The passphrase that is used to decrypt the private key. `ssl.certificate`:: Path to a PEM encoded file containing the certificate (or certificate chain) that will be presented to clients when they connect. `ssl.certificate_authorities`:: List of paths to PEM encoded certificate files that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.keystore.path`:: The path to the Java Keystore file that contains a private key and certificate. `ssl.key` and `ssl.keystore.path` may not be used at the same time. `ssl.keystore.type`:: The format of the keystore file. Should be `jks` to use the Java Keystore format, `PKCS12` to use PKCS#12 files, or `PKCS11` to use a PKCS#11 token. The default is `jks`. `ssl.keystore.password`:: The password to the keystore. `ssl.keystore.secure_password` (<>):: The password to the keystore. `ssl.keystore.key_password`:: The password for the key in the keystore. Defaults to the keystore password. `ssl.keystore.secure_key_password`:: The password for the key in the keystore. Defaults to the keystore password. `ssl.truststore.path`:: The path to the Java Keystore file that contains the certificates to trust. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.password`:: The password to the truststore. `ssl.truststore.secure_password` (<>):: The password to the truststore. `ssl.truststore.type`:: The format of the keystore file. Should be `jks` to use the Java Keystore format, `PKCS12` to use PKCS#12 files, or `PKCS11` to use a PKCS#11 token. The default is `jks`. `ssl.verification_mode`:: Indicates the type of verification when using `ldaps` to protect against man in the middle attacks and certificate forgery. Values are `none`, `certificate`, and `full`. Defaults to `full`. + See <> for an explanation of these values. `ssl.supported_protocols`:: Supported protocols for TLS/SSL (with versions). Defaults to `TLSv1.3,TLSv1.2,TLSv1.1`. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported when communicating with the LDAP server. Supported cipher suites can be found in Oracle's http://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html[ Java Cryptography Architecture documentation]. See <> for the default value. `cache.ttl`:: Specifies the time-to-live for cached user entries. A user and a hash of its credentials are cached for this period of time. Use the standard {es} <>. Defaults to `20m`. `cache.max_users`:: Specifies the maximum number of user entries that the cache can contain. Defaults to `100000`. `cache.hash_algo`:: (Expert Setting) Specifies the hashing algorithm that is used for the in-memory cached user credentials. See <>. Defaults to `ssha256`. `authentication.enabled`:: If set to `false`, disables authentication support in this realm, so that it only supports user lookups. (See the {stack-ov}/run-as-privilege.html[run as] and {stack-ov}/realm-chains.html#authorization_realms[authorization realms] features). Defaults to `true`. [[ref-ad-settings]] [float] ===== Active Directory realm settings The `type` setting must be set to `active_directory`. In addition to the <>, you can specify the following settings: `url`:: One or more LDAP URLs in the `ldap[s]://:` format. Defaults to `ldap://:389`. This setting is required when connecting using SSL/TLS or when using a custom port. + To provide multiple URLs, use a YAML array (`[""ldap://server1:636"", ""ldap://server2:636""]`) or comma-separated string (`""ldap://server1:636, ldap://server2:636""`). + While both are supported, you can't mix the `ldap` and `ldaps` protocols. + If no URL is provided, {es} uses a default of `ldap://:389`. This default uses the `domain_name` setting value and assumes an unencrypted connection to port 389. `load_balance.type`:: The behavior to use when there are multiple LDAP URLs defined. For supported values see <>. Defaults to `failover`. `load_balance.cache_ttl`:: When using `dns_failover` or `dns_round_robin` as the load balancing type, this setting controls the amount of time to cache DNS lookups. Defaults to `1h`. `domain_name`:: The domain name of Active Directory. If the `url` and the `user_search_dn` settings are not specified, the cluster can derive those values from this setting. Required. `bind_dn`:: The DN of the user that is used to bind to Active Directory and perform searches. Defaults to Empty. Due to its potential security impact, `bind_dn` is not exposed via the <>. `bind_password`:: deprecated[6.3] Use `secure_bind_password` instead. The password for the user that is used to bind to Active Directory. Defaults to Empty. Due to its potential security impact, `bind_password` is not exposed via the <>. `secure_bind_password` (<>):: The password for the user that is used to bind to Active Directory. Defaults to Empty. `unmapped_groups_as_roles`:: If set to `true`, the names of any unmapped Active Directory groups are used as role names and assigned to the user. A group is considered _unmapped_ when it is not referenced in any role-mapping files. API-based role mappings are not considered. Defaults to `false`. `files.role_mapping`:: The <> for the YAML role mapping configuration file. Defaults to `ES_PATH_CONF/role_mapping.yml`. `user_search.base_dn`:: The context to search for a user. Defaults to the root of the Active Directory domain. `user_search.scope`:: Specifies whether the user search should be `sub_tree`, `one_level` or `base`. `one_level` only searches users directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is a user object, and that it is the only user considered. Defaults to `sub_tree`. `user_search.filter`:: Specifies a filter to use to lookup a user given a username. The default filter looks up `user` objects with either `sAMAccountName` or `userPrincipalName`. If specified, this must be a valid LDAP user search filter. For example `(&(objectClass=user)(sAMAccountName={0}))`. For more information, see https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[Search Filter Syntax]. `user_search.upn_filter`:: Specifies a filter to use to lookup a user given a user principal name. The default filter looks up `user` objects with a matching `userPrincipalName`. If specified, this must be a valid LDAP user search filter. For example, `(&(objectClass=user)(userPrincipalName={1}))`. `{1}` is the full user principal name provided by the user. For more information, see https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[Search Filter Syntax]. `user_search.down_level_filter`:: Specifies a filter to use to lookup a user given a down level logon name (DOMAIN\\user). The default filter looks up `user` objects with a matching `sAMAccountName` in the domain provided. If specified, this must be a valid LDAP user search filter. For example, `(&(objectClass=user)(sAMAccountName={0}))`. For more information, see https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[Search Filter Syntax]. `user_search.pool.enabled`:: Enables or disables connection pooling for user search. When disabled a new connection is created for every search. The default is `true` when `bind_dn` is provided. `user_search.pool.size`:: The maximum number of connections to the Active Directory server to allow in the connection pool. Defaults to `20`. `user_search.pool.initial_size`:: The initial number of connections to create to the Active Directory server on startup. Defaults to `0`. If the LDAP server is down, values greater than 0 could cause startup failures. `user_search.pool.health_check.enabled`:: Enables or disables a health check on Active Directory connections in the connection pool. Connections are checked in the background at the specified interval. Defaults to `true`. `user_search.pool.health_check.dn`:: The distinguished name to be retrieved as part of the health check. Defaults to the value of `bind_dn` if that setting is present. Otherwise, it defaults to the value of the `user_search.base_dn` setting. `user_search.pool.health_check.interval`:: The interval to perform background checks of connections in the pool. Defaults to `60s`. `group_search.base_dn`:: The context to search for groups in which the user has membership. Defaults to the root of the Active Directory domain. `group_search.scope`:: Specifies whether the group search should be `sub_tree`, `one_level` or `base`. `one_level` searches for groups directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is a group object, and that it is the only group considered. Defaults to `sub_tree`. `metadata`:: A list of additional LDAP attributes that should be loaded from the LDAP server and stored in the authenticated user's metadata field. `timeout.tcp_connect`:: The TCP connect timeout period for establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.tcp_read`:: The TCP read timeout period after establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.ldap_search`:: The LDAP Server enforced timeout period for an LDAP search. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `ssl.certificate`:: Path to a PEM encoded file containing the certificate (or certificate chain) that will be presented to clients when they connect. `ssl.certificate_authorities`:: List of paths to PEM encoded certificate files that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.key`:: Path to the PEM encoded file containing the private key, which is used when the Active Directory server requires client authentication. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: The passphrase that is used to decrypt the private key. This value is optional as the key might not be encrypted. `ssl.secure_key_passphrase` (<>):: The passphrase that is used to decrypt the private key. This value is optional as the key might not be encrypted. `ssl.keystore.key_password`:: The password for the key in the keystore. Defaults to the keystore password. `ssl.keystore.secure_key_password` (<>):: The password for the key in the keystore. Defaults to the keystore password. `ssl.keystore.password`:: The password to the keystore. `ssl.secure_keystore.password` (<>):: The password to the keystore. `ssl.keystore.path`:: The path to the Java Keystore file that contains a private key and certificate. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.keystore.type`:: The format of the keystore file. Should be `jks` to use the Java Keystore format, `PKCS12` to use PKCS#12 files, or `PKCS11` to use a PKCS#11 token. The default is `jks`. `ssl.truststore.password`:: The password to the truststore. `ssl.truststore.secure_password` (<>):: The password to the truststore. `ssl.truststore.path`:: The path to the Java Keystore file that contains the certificates to trust. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.type`:: The format of the truststore file. Should be `jks` to use the Java Keystore format, `PKCS12` to use PKCS#12 files, or `PKCS11` to use a PKCS#11 token. The default is `jks`. `ssl.verification_mode`:: Indicates the type of verification when using `ldaps` to protect against man in the middle attacks and certificate forgery. Values are `none`, `certificate`, and `full`. Defaults to `full`. + See <> for an explanation of these values. `ssl.supported_protocols`:: Supported protocols for TLS/SSL (with versions). Defaults to `TLSv1.3,TLSv1.2,TLSv1.1`. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported when communicating with the Active Directory server. Supported cipher suites can be found in Oracle's http://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html[ Java Cryptography Architecture documentation]. See <> for the default values. `cache.ttl`:: Specifies the time-to-live for cached user entries. A user and a hash of its credentials are cached for this configured period of time. Use the standard Elasticsearch {ref}/common-options.html#time-units[time units]). Defaults to `20m`. `cache.max_users`:: Specifies the maximum number of user entries that the cache can contain. Defaults to `100000`. `cache.hash_algo`:: (Expert Setting) Specifies the hashing algorithm that is used for the in-memory cached user credentials. See <>. Defaults to `ssha256`. `authentication.enabled`:: If set to `false`, disables authentication support in this realm, so that it only supports user lookups. (See the {stack-ov}/run-as-privilege.html[run as] and {stack-ov}/realm-chains.html#authorization_realms[authorization realms] features). Defaults to `true`. `follow_referrals`:: If set to `true`, {es} follows referrals returned by the LDAP server. Referrals are URLs returned by the server that are to be used to continue the LDAP operation (such as `search`). Defaults to `true`. [[ref-pki-settings]] [float] ===== PKI realm settings The `type` setting must be set to `pki`. In addition to the <>, you can specify the following settings: `username_pattern`:: The regular expression pattern used to extract the username from the certificate DN. The first match group is the used as the username. Defaults to `CN=(.*?)(?:,\\|$)`. `certificate_authorities`:: List of paths to the PEM certificate files that should be used to authenticate a user's certificate as trusted. Defaults to the trusted certificates configured for SSL. This setting cannot be used with `truststore.path`. `truststore.algorithm`:: Algorithm for the truststore. Defaults to `SunX509`. `truststore.password`:: The password for the truststore. Must be provided if `truststore.path` is set. `truststore.secure_password` (<>):: The password for the truststore. `truststore.path`:: The path of a truststore to use. Defaults to the trusted certificates configured for SSL. This setting cannot be used with `certificate_authorities`. `files.role_mapping`:: Specifies the <> of the {stack-ov}/mapping-roles.html[YAML role mapping configuration file]. Defaults to `ES_PATH_CONF/role_mapping.yml`. `authorization_realms`:: The names of the realms that should be consulted for delegated authorization. If this setting is used, then the PKI realm does not perform role mapping and instead loads the user from the listed realms. See {stack-ov}/realm-chains.html#authorization_realms[Delegating authorization to another realm] `cache.ttl`:: Specifies the time-to-live for cached user entries. A user and a hash of its credentials are cached for this period of time. Use the standard {es} {ref}/common-options.html#time-units[time units]). Defaults to `20m`. `cache.max_users`:: Specifies the maximum number of user entries that the cache can contain. Defaults to `100000`. [[ref-saml-settings]] [float] ===== SAML realm settings The `type` setting must be set to `saml`. In addition to the <>, you can specify the following settings: `idp.entity_id`:: The Entity ID of the SAML Identity Provider. An Entity ID is a URI with a maximum length of 1024 characters. It can be a URL (https://idp.example.com/) or a URN (`urn:example.com:idp`) and can be found in the configuration or the SAML metadata of the Identity Provider. `idp.metadata.path`:: The path _(recommended)_ or URL to a SAML 2.0 metadata file describing the capabilities and configuration of the Identity Provider. If a path is provided, then it is resolved relative to the {es} config directory. If a URL is provided, then it must be either a `file` URL or a `https` URL. {es} automatically polls this metadata resource and reloads the IdP configuration when changes are detected. File based resources are polled at a frequency determined by the global {es} `resource.reload.interval.high` setting, which defaults to 5 seconds. HTTPS resources are polled at a frequency determined by the realm's `idp.metadata.http.refresh` setting. `idp.metadata.http.refresh`:: Controls the frequency with which `https` metadata is checked for changes. Defaults to `1h` (1 hour). `idp.use_single_logout`:: Indicates whether to utilise the Identity Provider's Single Logout service (if one exists in the IdP metadata file). Defaults to `true`. `sp.entity_id`:: The Entity ID to use for this SAML Service Provider. This should be entered as a URI. We recommend that you use the base URL of your Kibana instance. For example, `https://kibana.example.com/`. `sp.acs`:: The URL of the Assertion Consumer Service within {kib}. Typically this is the ""api/security/v1/saml"" endpoint of your Kibana server. For example, `https://kibana.example.com/api/security/v1/saml`. `sp.logout`:: The URL of the Single Logout service within {kib}. Typically this is the ""logout"" endpoint of your Kibana server. For example, `https://kibana.example.com/logout`. `attributes.principal`:: The Name of the SAML attribute that contains the user's principal (username). `attributes.groups`:: The Name of the SAML attribute that contains the user's groups. `attributes.name`:: The Name of the SAML attribute that contains the user's full name. `attributes.mail`:: The Name of the SAML attribute that contains the user's email address. `attributes.dn`:: The Name of the SAML attribute that contains the user's X.50 _Distinguished Name_. `attribute_patterns.principal`:: A Java regular expression that is matched against the SAML attribute specified by `attributes.pattern` before it is applied to the user's _principal_ property. The attribute value must match the pattern and the value of the first _capturing group_ is used as the principal. For example, `^([^@]+)@example\\\\.com$` matches email addresses from the ""example.com"" domain and uses the local-part as the principal. `attribute_patterns.groups`:: As per `attribute_patterns.principal`, but for the _group_ property. `attribute_patterns.name`:: As per `attribute_patterns.principal`, but for the _name_ property. `attribute_patterns.mail`:: As per `attribute_patterns.principal`, but for the _mail_ property. `attribute_patterns.dn`:: As per `attribute_patterns.principal`, but for the _dn_ property. `nameid_format`:: The NameID format that should be requested when asking the IdP to authenticate the current user. The default is to not include the `nameid_format` attribute. `nameid.allow_create`:: The value of the `AllowCreate` attribute of the `NameIdPolicy` element in an authentication request. The default value is false. `nameid.sp_qualifier`:: The value of the `SPNameQualifier` attribute of the `NameIdPolicy` element in an authentication request. The default is to not include the `SPNameQualifier` attribute. `force_authn`:: Specifies whether to set the `ForceAuthn` attribute when requesting that the IdP authenticate the current user. If set to `true`, the IdP is required to verify the user’s identity, irrespective of any existing sessions they might have. Defaults to `false`. `populate_user_metadata`:: Specifies whether to populate the {es} user's metadata with the values that are provided by the SAML attributes. Defaults to `true`. `authorization_realms`:: The names of the realms that should be consulted for delegated authorization. If this setting is used, then the SAML realm does not perform role mapping and instead loads the user from the listed realms. See {stack-ov}/realm-chains.html#authorization_realms[Delegating authorization to another realm] `allowed_clock_skew`:: The maximum amount of skew that can be tolerated between the IdP's clock and the {es} node's clock. Defaults to `3m` (3 minutes). `req_authn_context_class_ref`:: A comma separated list of Authentication Context Class Reference values to be included in the Requested Authentication Context when requesting the IdP to authenticate the current user. The Authentication Context of the corresponding authentication response should contain at least one of the requested values. + For more information, see {stack-ov}/saml-guide-authentication.html#req-authn-context[Requesting specific authentication methods]. [float] [[ref-saml-signing-settings]] ===== SAML realm signing settings If a signing key is configured (that is, either `signing.key` or `signing.keystore.path` is set), then {es} signs outgoing SAML messages. Signing can be configured using the following settings: `signing.saml_messages`:: A list of SAML message types that should be signed or `*` to sign all messages. Each element in the list should be the local name of a SAML XML Element. Supported element types are `AuthnRequest`, `LogoutRequest` and `LogoutResponse`. Only valid if `signing.key` or `signing.keystore.path` is also specified. Defaults to `*`. `signing.key`:: Specifies the path to the PEM encoded private key to use for SAML message signing. `signing.key` and `signing.keystore.path` cannot be used at the same time. `signing.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`signing.key`) if it is encrypted. `signing.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that corresponds to the `signing.key`. This certificate must also be included in the Service Provider metadata or manually configured within the IdP to allow for signature validation. This setting can only be used if `signing.key` is set. `signing.keystore.path`:: The path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `signing.key` and `signing.keystore.path` cannot be used at the same time. `signing.keystore.type`:: The type of the keystore in `signing.keystore.path`. Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"", or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `signing.keystore.alias`:: Specifies the alias of the key within the keystore that should be used for SAML message signing. If the keystore contains more than one private key, this setting must be specified. `signing.keystore.secure_password` (<>):: The password to the keystore in `signing.keystore.path`. `signing.keystore.secure_key_password` (<>):: The password for the key in the keystore (`signing.keystore.path`). Defaults to the keystore password. [float] [[ref-saml-encryption-settings]] ===== SAML realm encryption settings If an encryption key is configured (that is, either `encryption.key` or `encryption.keystore.path` is set), then {es} publishes an encryption certificate when generating metadata and attempts to decrypt incoming SAML content. Encryption can be configured using the following settings: `encryption.key`:: Specifies the path to the PEM encoded private key to use for SAML message decryption. `encryption.key` and `encryption.keystore.path` cannot be used at the same time. `encryption.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`encryption.key`) if it is encrypted. `encryption.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that is associated with the `encryption.key`. This certificate must also be included in the Service Provider metadata or manually configured within the IdP to enable message encryption. This setting can be used only if `encryption.key` is set. `encryption.keystore.path`:: The path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `encryption.key` and `encryption.keystore.path` cannot be used at the same time. `encryption.keystore.type`:: The type of the keystore (`encryption.keystore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"", or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `encryption.keystore.alias`:: Specifies the alias of the key within the keystore (`encryption.keystore.path`) that should be used for SAML message decryption. If not specified, all compatible key pairs from the keystore are considered as candidate keys for decryption. `encryption.keystore.secure_password` (<>):: The password to the keystore (`encryption.keystore.path`). `encryption.keystore.secure_key_password` (<>):: The password for the key in the keystore (`encryption.keystore.path`). Only a single password is supported. If you are using multiple decryption keys, they cannot have individual passwords. [float] [[ref-saml-ssl-settings]] ===== SAML realm SSL settings If you are loading the IdP metadata over SSL/TLS (that is, `idp.metadata.path` is a URL using the `https` protocol), the following settings can be used to configure SSL. NOTE: These settings are not used for any purpose other than loading metadata over https. `ssl.key`:: Specifies the path to the PEM encoded private key to use for http client authentication (if required). `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: Specifies the passphrase to decrypt the PEM encoded private key (`ssl.key`) if it is encrypted. Cannot be used with `ssl.secure_key_passphrase`. `ssl.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`ssl.key`) if it is encrypted. Cannot be used with `ssl.key_passphrase`. `ssl.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that is associated with the key (`ssl.key`). This setting can be used only if `ssl.key` is set. `ssl.certificate_authorities`:: Specifies the paths to the PEM encoded certificate authority certificates that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.keystore.path`:: Specifies the path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.keystore.type`:: The type of the keystore (`ssl.keystore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"" or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `ssl.keystore.password`:: The password to the keystore (`ssl.keystore.path`). This setting cannot be used with `ssl.keystore.secure_password`. `ssl.keystore.secure_password` (<>):: The password to the keystore (`ssl.keystore.path`). This setting cannot be used with `ssl.keystore.password`. `ssl.keystore.key_password`:: The password for the key in the keystore (`ssl.keystore.path`). Defaults to the keystore password. This setting cannot be used with `ssl.keystore.secure_key_password`. `ssl.keystore.secure_key_password` (<>):: The password for the key in the keystore (`ssl.keystore.path`). Defaults to the keystore password. This setting cannot be used with `ssl.keystore.key_password`. `ssl.truststore.path`:: The path to the keystore that contains the certificates to trust. Must be either a Java Keystore (jks) or a PKCS#12 file. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.type`:: The type of the truststore (`ssl.truststore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"" or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `ssl.truststore.password`:: The password to the truststore (`ssl.truststore.path`). This setting cannot be used with `ssl.truststore.secure_password`. `ssl.truststore.secure_password` (<>):: The password to the truststore (`ssl.truststore.path`). This setting cannot be used with `ssl.truststore.password`. `ssl.verification_mode`:: One of `full` (verify the hostname and the certificate path), `certificate` (verify the certificate path, but not the hostname) or `none` (perform no verification). Defaults to `full`. + See <> for a more detailed explanation of these values. `ssl.supported_protocols`:: Specifies the supported protocols for TLS/SSL. Defaults to `TLSv1.3,TLSv1.2,TLSv1.1`. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported. [float] [[ref-kerberos-settings]] ===== Kerberos realm settings For a Kerberos realm, the `type` must be set to `kerberos`. In addition to the <>, you can specify the following settings: `keytab.path`:: Specifies the path to the Kerberos keytab file that contains the service principal used by this {es} node. This must be a location within the {es} configuration directory and the file must have read permissions. Required. `remove_realm_name`:: Set to `true` to remove the realm part of principal names. Principal names in Kerberos have the form `user/instance@REALM`. If this option is `true`, the realm part (`@REALM`) will not be included in the username. Defaults to `false`. `krb.debug`:: Set to `true` to enable debug logs for the Java login module that provides support for Kerberos authentication. Defaults to `false`. `cache.ttl`:: The time-to-live for cached user entries. A user is cached for this period of time. Specify the time period using the standard {es} <>. Defaults to `20m`. `cache.max_users`:: The maximum number of user entries that can live in the cache at any given time. Defaults to 100,000. `authorization_realms`:: The names of the realms that should be consulted for delegated authorization. If this setting is used, then the Kerberos realm does not perform role mapping and instead loads the user from the listed realms. See {stack-ov}/realm-chains.html#authorization_realms[Delegating authorization to another realm] [[ref-oidc-settings]] [float] ===== OpenID Connect realm settings In addition to the <>, you can specify the following settings: `op.issuer`:: A verifiable Identifier for your OpenID Connect Provider. An Issuer Identifier is usually a case sensitive URL using the https scheme that contains scheme, host, and optionally, port number and path components and no query or fragment components. The value for this setting should be provided by your OpenID Connect Provider. `op.authorization_endpoint`:: The URL for the Authorization Endpoint at the OpenID Connect Provider. The value for this setting should be provided by your OpenID Connect Provider. `op.token_endpoint`:: The URL for the Token Endpoint at the OpenID Connect Provider. The value for this setting should be provided by your OpenID Connect Provider. `op.userinfo_endpoint`:: The URL for the User Info Endpoint at the OpenID Connect Provider. The value for this setting should be provided by your OpenID Connect Provider. `op.endsession_endpoint`:: The URL for the End Session Endpoint at the OpenID Connect Provider. The value for this setting should be provided by your OpenID Connect Provider. `op.jwkset_path`:: The path or URL to a JSON Web Key Set with the key material that the OpenID Connect Provider uses for signing tokens and claims responses. If a path is provided, then it is resolved relative to the {es} config directory. If a URL is provided, then it must be either a `file` URL or a `https` URL. {es} automatically caches the retrieved JWK set to avoid unnecessary HTTP requests but will attempt to refresh the JWK upon signature verification failure, as this might indicate that the OpenID Connect Provider has rotated the signing keys. File based resources are polled at a frequency determined by the global {es} `resource.reload.interval.high` setting, which defaults to 5 seconds. `rp.client_id`:: The OAuth 2.0 Client Identifier that was assigned to {es} during registration at the OpenID Connect Provider `rp.client_secret`(<>):: The OAuth 2.0 Client Secret that was assigned to {es} during registration at the OpenID Connect Provider `rp.redirect_uri`:: The Redirect URI within {kib}. Typically this is the ""api/security/v1/oidc"" endpoint of your Kibana server. For example, `https://kibana.example.com/api/security/v1/oidc`. `rp.response_type`:: OAuth 2.0 Response Type value that determines the authorization processing flow to be used. Can be `code` for authorization code grant flow, or one of `id_token`, `id_token token` for the implicit flow. `rp.signature_algorithm`:: The signature algorithm that will be used by {es} in order to verify the signature of the id tokens it will receive from the OpenID Connect Provider. Defaults to `RSA256` `rp.requested_scopes`:: The scope values that will be requested by the OpenID Connect Provider as part of the Authentication Request. Optional, defaults to `openid` `rp.post_logout_redirect_uri`:: The Redirect URI (usually within {kib}) that the OpenID Connect Provider should redirect the browser to after a successful Single Logout. `claims.principal`:: The name of the OpenID Connect claim that contains the user's principal (username). `claims.groups`:: The name of the OpenID Connect claim that contains the user's groups. `claims.name`:: The name of the OpenID Connect claim that contains the user's full name. `claims.mail`:: The name of the OpenID Connect claim that contains the user's email address. `claims.dn`:: The name of the OpenID Connect claim that contains the user's X.509 _Distinguished Name_. `claim_patterns.principal`:: A Java regular expression that is matched against the OpenID Connect claim specified by `claims.principal` before it is applied to the user's _principal_ property. The attribute value must match the pattern and the value of the first _capturing group_ is used as the principal. For example, `^([^@]+)@example\\\\.com$` matches email addresses from the ""example.com"" domain and uses the local-part as the principal. `claim_patterns.groups`:: As per `claim_patterns.principal`, but for the _group_ property. `claim_patterns.name`:: As per `claim_patterns.principal`, but for the _name_ property. `claim_patterns.mail`:: As per `claim_patterns.principal`, but for the _mail_ property. `claim_patterns.dn`:: As per `claim_patterns.principal`, but for the _dn_ property. `allowed_clock_skew`:: The maximum allowed clock skew to be taken into consideration when validating id tokens with regards to their creation and expiration times. `populate_user_metadata`:: Specifies whether to populate the {es} user's metadata with the values that are provided by the OpenID Connect claims. Defaults to `true`. `http.connect_timeout`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the timeout until a connection is established. A value of zero means the timeout is not used. Defaults to `5s` `http.connection_read_timeout`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the timeout used when requesting a connection from the connection manager. Defaults to `5s` `http.socket_timeout`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the socket timeout (SO_TIMEOUT) in milliseconds, which is the timeout for waiting for data or, put differently, a maximum period inactivity between two consecutive data packets). Defaults to `5s` `http.max_connections`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the maximum number of connections allowed across all endpoints. `http.max_endpoint_connections`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the maximum number of connections allowed per endpoint. [float] [[ref-oidc-ssl-settings]] ===== OpenID Connect realm SSL settings The following settings can be used to configure SSL for all outgoing http connections to the OpenID Connect Provider endpoints. NOTE: These settings are _only_ used for the back-channel communication between {es} and the OpenID Connect Provider `ssl.key`:: Specifies the path to the PEM encoded private key to use for http client authentication (if required). `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: Specifies the passphrase to decrypt the PEM encoded private key (`ssl.key`) if it is encrypted. Cannot be used with `ssl.secure_key_passphrase`. `ssl.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`ssl.key`) if it is encrypted. Cannot be used with `ssl.key_passphrase`. `ssl.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that is associated with the key (`ssl.key`). This setting can be used only if `ssl.key` is set. `ssl.certificate_authorities`:: Specifies the paths to the PEM encoded certificate authority certificates that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.keystore.path`:: Specifies the path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.keystore.type`:: The type of the keystore (`ssl.keystore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"" or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `ssl.keystore.password`:: The password to the keystore (`ssl.keystore.path`). This setting cannot be used with `ssl.keystore.secure_password`. `ssl.keystore.secure_password` (<>):: The password to the keystore (`ssl.keystore.path`). This setting cannot be used with `ssl.keystore.password`. `ssl.keystore.key_password`:: The password for the key in the keystore (`ssl.keystore.path`). Defaults to the keystore password. This setting cannot be used with `ssl.keystore.secure_key_password`. `ssl.keystore.secure_key_password` (<>):: The password for the key in the keystore (`ssl.keystore.path`). Defaults to the keystore password. This setting cannot be used with `ssl.keystore.key_password`. `ssl.truststore.path`:: The path to the keystore that contains the certificates to trust. Must be either a Java Keystore (jks) or a PKCS#12 file. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.type`:: The type of the truststore (`ssl.truststore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"" or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `ssl.truststore.password`:: The password to the truststore (`ssl.truststore.path`). This setting cannot be used with `ssl.truststore.secure_password`. `ssl.truststore.secure_password` (<>):: The password to the truststore (`ssl.truststore.path`). This setting cannot be used with `ssl.truststore.password`. `ssl.verification_mode`:: One of `full` (verify the hostname and the certificate path), `certificate` (verify the certificate path, but not the hostname) or `none` (perform no verification). Defaults to `full`. + See <> for a more detailed explanation of these values. `ssl.supported_protocols`:: Specifies the supported protocols for TLS/SSL. Defaults to `TLSv1.3,TLSv1.2,TLSv1.1` if the JVM supports TLSv1.3, otherwise `TLSv1.2,TLSv1.1`. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported. [float] [[load-balancing]] ===== Load balancing and failover The `load_balance.type` setting can have the following values: * `failover`: The URLs specified are used in the order that they are specified. The first server that can be connected to will be used for all subsequent connections. If a connection to that server fails then the next server that a connection can be established to will be used for subsequent connections. * `dns_failover`: In this mode of operation, only a single URL may be specified. This URL must contain a DNS name. The system will be queried for all IP addresses that correspond to this DNS name. Connections to the Active Directory or LDAP server will always be tried in the order in which they were retrieved. This differs from `failover` in that there is no reordering of the list and if a server has failed at the beginning of the list, it will still be tried for each subsequent connection. * `round_robin`: Connections will continuously iterate through the list of provided URLs. If a server is unavailable, iterating through the list of URLs will continue until a successful connection is made. * `dns_round_robin`: In this mode of operation, only a single URL may be specified. This URL must contain a DNS name. The system will be queried for all IP addresses that correspond to this DNS name. Connections will continuously iterate through the list of addresses. If a server is unavailable, iterating through the list of URLs will continue until a successful connection is made. [float] [[ssl-tls-settings]] ==== Default values for TLS/SSL settings In general, the values below represent the default values for the various TLS settings. The prefixes for these settings are based on the context in which they are used (e.g. `xpack.security.authc.realms.ldap.corp_ldap.ssl.verification_mode` or `xpack.security.transport.ssl.supported_protocols`). For more information, see {stack-ov}/encrypting-communications.html[Encrypting communications]. `*.ssl.supported_protocols`:: Supported protocols with versions. Valid protocols: `SSLv2Hello`, `SSLv3`, `TLSv1`, `TLSv1.1`, `TLSv1.2`, `TLSv1.3`. Defaults to `TLSv1.3,TLSv1.2,TLSv1.1`. + -- NOTE: If `xpack.security.fips_mode.enabled` is `true`, you cannot use `SSLv2Hello` or `SSLv3`. See <>. -- `*.ssl.client_authentication`:: Controls the server's behavior in regard to requesting a certificate from client connections. Valid values are `required`, `optional`, and `none`. `required` forces a client to present a certificate, while `optional` requests a client certificate but the client is not required to present one. Defaults to `required`, except for HTTP, which defaults to `none`. See <>. `*.ssl.verification_mode`:: Controls the verification of certificates. Valid values are: - `full`, which verifies that the provided certificate is signed by a trusted authority (CA) and also verifies that the server's hostname (or IP address) matches the names identified within the certificate. - `certificate`, which verifies that the provided certificate is signed by a trusted authority (CA), but does not perform any hostname verification. - `none`, which performs _no verification_ of the server's certificate. This mode disables many of the security benefits of SSL/TLS and should only be used after very careful consideration. It is primarily intended as a temporary diagnostic mechanism when attempting to resolve TLS errors, and its use on production clusters is strongly discouraged. + The default value is `full`. `*.ssl.cipher_suites`:: Supported cipher suites can be found in Oracle's https://docs.oracle.com/en/java/javase/11/security/oracle-providers.html#GUID-7093246A-31A3-4304-AC5F-5FB6400405E2[Java Cryptography Architecture documentation]. Defaults to `TLS_AES_256_GCM_SHA384`, `TLS_AES_128_GCM_SHA256`, `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`, `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`, `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`, `TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`, `TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384`, `TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256`, `TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384`, `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256`, `TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA`, `TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA`, `TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA`, `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA`, `TLS_RSA_WITH_AES_256_GCM_SHA384`, `TLS_RSA_WITH_AES_128_GCM_SHA256`, `TLS_RSA_WITH_AES_256_CBC_SHA256`, `TLS_RSA_WITH_AES_128_CBC_SHA256`, `TLS_RSA_WITH_AES_256_CBC_SHA`, `TLS_RSA_WITH_AES_128_CBC_SHA`. [float] [[tls-ssl-key-settings]] ===== TLS/SSL key and trusted certificate settings The following settings are used to specify a private key, certificate, and the trusted certificates that should be used when communicating over an SSL/TLS connection. If no trusted certificates are configured, the default certificates that are trusted by the JVM will be trusted along with the certificate(s) associated with a key in the same context. The key and certificate must be in place for connections that require client authentication or when acting as a SSL enabled server. [[pkcs12-truststore-note]] [NOTE] Storing trusted certificates in a PKCS#12 file, although supported, is uncommon in practice. The {ref}/certutil.html[`elasticsearch-certutil`] tool, as well as Java's `keytool`, are designed to generate PKCS#12 files that can be used both as a keystore and as a truststore, but this may not be the case for container files that are created using other tools. Usually, PKCS#12 files only contain secret and private entries. To confirm that a PKCS#12 container includes trusted certificate (""anchor"") entries look for `2.16.840.1.113894.746875.1.1: ` in the `openssl pkcs12 -info` output, or `trustedCertEntry` in the `keytool -list` output. [[http-tls-ssl-settings]] :ssl-prefix: xpack.security.http :component: HTTP :client-auth-default: none :verifies!: :server: :ssl-context: security-http include::ssl-settings.asciidoc[] [[transport-tls-ssl-settings]] :ssl-prefix: xpack.security.transport :component: Transport :client-auth-default!: :verifies: :server: :ssl-context: security-transport include::ssl-settings.asciidoc[] [[ssl-tls-profile-settings]] [float] ===== Transport profile TLS/SSL settings The same settings that are available for the <> are also available for each transport profile. By default, the settings for a transport profile will be the same as the default transport unless they are specified. As an example, lets look at the key setting. For the default transport this is `xpack.security.transport.ssl.key`. In order to use this setting in a transport profile, use the prefix `transport.profiles.$PROFILE.xpack.security.` and append the portion of the setting after `xpack.security.transport.`. For the key setting, this would be `transport.profiles.$PROFILE.xpack.security.ssl.key`. [float] [[ip-filtering-settings]] ==== IP filtering settings You can configure the following settings for {stack-ov}/ip-filtering.html[IP filtering]. `xpack.security.transport.filter.allow`:: List of IP addresses to allow. `xpack.security.transport.filter.deny`:: List of IP addresses to deny. `xpack.security.http.filter.allow`:: List of IP addresses to allow just for HTTP. `xpack.security.http.filter.deny`:: List of IP addresses to deny just for HTTP. `transport.profiles.$PROFILE.xpack.security.filter.allow`:: List of IP addresses to allow for this profile. `transport.profiles.$PROFILE.xpack.security.filter.deny`:: List of IP addresses to deny for this profile. include::security-hash-settings.asciidoc[] ",16139,True,3206.8681484544704,median "== Contract DSL Spring Cloud Contract supports out of the box 2 types of DSL. One written in `Groovy` and one written in `YAML`. If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy before. Knowledge of the language is not really needed, as the Contract DSL uses only a tiny subset of it (only literals, method calls and closures). Also, the DSL is statically typed, to make it programmer-readable without any knowledge of the DSL itself. IMPORTANT: Remember that, inside the Groovy contract file, you have to provide the fully qualified name to the `Contract` class and `make` static imports, such as `org.springframework.cloud.spec.Contract.make { ... }`. You can also provide an import to the `Contract` class: `import org.springframework.cloud.spec.Contract` and then call `Contract.make { ... }`. TIP: Spring Cloud Contract supports defining multiple contracts in a single file. The following is a complete example of a Groovy contract definition: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MockMvcMethodBodyBuilderSpec.groovy[tags=dsl_example,indent=0] ---- The following is a complete example of a YAML contract definition: [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract_rest.yml[indent=0] ---- TIP: You can compile contracts to stubs mapping using standalone maven command: `mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert` === Limitations WARNING: Spring Cloud Contract Verifier does not properly support XML. Please use JSON or help us implement this feature. WARNING: The support for verifying the size of JSON arrays is experimental. If you want to turn it on, please set the value of the following system property to `true`: `spring.cloud.contract.verifier.assert.size`. By default, this feature is set to `false`. You can also provide the `assertJsonSize` property in the plugin configuration. WARNING: Because JSON structure can have any form, it can be impossible to parse it properly when using the Groovy DSL and the `value(consumer(...), producer(...))` notation in `GString`. That is why you should use the Groovy Map notation. === Common Top-Level elements The following sections describe the most common top-level elements: * <> * <> * <> * <> * <> [[contract-dsl-description]] ==== Description You can add a `description` to your contract. The description is arbitrary text. The following code shows an example: .Groovy DSL [source,groovy,indent=0] ---- include::{contract_spec_path}/src/test/groovy/org/springframework/cloud/contract/spec/internal/ContractSpec.groovy[tags=description,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract_rest.yml[indent=0] ---- [[contract-dsl-name]] ==== Name You can provide a name for your contract. Assume that you provided the following name: `should register a user`. If you do so, the name of the autogenerated test is `validate_should_register_a_user`. Also, the name of the stub in a WireMock stub is `should_register_a_user.json`. IMPORTANT: You must ensure that the name does not contain any characters that make the generated test not compile. Also, remember that, if you provide the same name for multiple contracts, your autogenerated tests fail to compile and your generated stubs override each other. .Groovy DSL [source,groovy,indent=0] ---- include::{contract_spec_path}/src/test/groovy/org/springframework/cloud/contract/spec/internal/ContractSpec.groovy[tags=name,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=name,indent=0] ---- [[contract-dsl-ignoring-contracts]] ==== Ignoring Contracts If you want to ignore a contract, you can either set a value of ignored contracts in the plugin configuration or set the `ignored` property on the contract itself: .Groovy DSL [source,groovy,indent=0] ---- include::{contract_spec_path}/src/test/groovy/org/springframework/cloud/contract/spec/internal/ContractSpec.groovy[tags=ignored,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=ignored,indent=0] ---- [[contract-dsl-passing-values-from-files]] ==== Passing Values from Files Starting with version `1.2.0`, you can pass values from files. Assume that you have the following resources in our project. [source,bash,indent=0] ---- └── src     └── test        └── resources           └── contracts     ├── readFromFile.groovy     ├── request.json     └── response.json ---- Further assume that your contract is as follows: .Groovy DSL [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/resources/classpath/readFromFile.groovy[indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract_from_file.yml[indent=0] ---- Further assume that the JSON files is as follows: *request.json* [source,json,indent=0] ---- include::{verifier_core_path}/src/test/resources/classpath/request.json[indent=0] ---- *response.json* [source,json,indent=0] ---- include::{verifier_core_path}/src/test/resources/classpath/response.json[indent=0] ---- When test or stub generation takes place, the contents of the file is passed to the body of a request or a response. The name of the file needs to be a file with location relative to the folder in which the contract lays. [[contract-dsl-http-top-level-elements]] ==== HTTP Top-Level Elements The following methods can be called in the top-level closure of a contract definition. `request` and `response` are mandatory. `priority` is optional. .Groovy DSL [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=http_dsl,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=priority,indent=0] include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request,indent=0] ... include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=response,indent=0] ... ---- IMPORTANT: If you want to make your contract have a **higher** value of priority you need to pass a **lower** number to the `priority` tag / method. E.g. `priority` with value `5` has **higher** priority than `priority` with value `10`. === Request The HTTP protocol requires only **method and url** to be specified in a request. The same information is mandatory in request definition of the Contract. .Groovy DSL [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=request,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request_obligatory,indent=0] ---- It is possible to specify an absolute rather than relative `url`, but using `urlPath` is the recommended way, as doing so makes the tests **host-independent**. .Groovy DSL [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=url,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract_rest_with_path.yml[tags=url_path,indent=0] ---- `request` may contain **query parameters**. .Groovy DSL [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=urlpath,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request,indent=0] ... include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=query_params,indent=0] ---- `request` may contain additional **request headers**, as shown in the following example: .Groovy DSL [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=headers,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request,indent=0] ... include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=headers,indent=0] ---- `request` may contain additional **request cookies**, as shown in the following example: .Groovy DSL [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=cookies,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request,indent=0] ... include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=cookies,indent=0] ---- `request` may contain a **request body**: .Groovy DSL [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=body,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request,indent=0] ... include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=body,indent=0] ---- `request` may contain **multipart** elements. To include multipart elements, use the `multipart` method/section, as shown in the following examples .Groovy DSL [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MockMvcMethodBodyBuilderSpec.groovy[tags=multipartdsl,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract_multipart.yml[indent=0] ---- In the preceding example, we define parameters in either of two ways: .Groovy DSL * Directly, by using the map notation, where the value can be a dynamic property (such as `formParameter: $(consumer(...), producer(...))`). * By using the `named(...)` method that lets you set a named parameter. A named parameter can set a `name` and `content`. You can call it either via a method with two arguments, such as `named(""fileName"", ""fileContent"")`, or via a map notation, such as `named(name: ""fileName"", content: ""fileContent"")`. .YAML * The multipart parameters are set via `multipart.params` section * The named parameters (the `fileName` and `fileContent` for a given parameter name) can be set via the `multipart.named` section. That section contains the `paramName` (name of the parameter), `fileName` (name of the file), `fileContent` (content of the file) fields * The dynamic bits can be set via the `matchers.multipart` section ** for parameters use the `params` section that can accept `regex` or a `predefined` regular expression ** for named params use the `named` section where first you define the parameter name via `paramName` and then you can pass the parametrization of either `fileName` or `fileContent` via `regex` or a `predefined` regular expression From this contract, the generated test is as follows: [source,java,indent=0] ---- // given: MockMvcRequestSpecification request = given() .header(""Content-Type"", ""multipart/form-data;boundary=AaB03x"") .param(""formParameter"", ""\\""formParameterValue\\"""") .param(""someBooleanParameter"", ""true"") .multiPart(""file"", ""filename.csv"", ""file content"".getBytes()); // when: ResponseOptions response = given().spec(request) .put(""/multipart""); // then: assertThat(response.statusCode()).isEqualTo(200); ---- The WireMock stub is as follows: [source,json,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/dsl/WireMockGroovyDslSpec.groovy[tags=multipartwiremock,indent=0] ---- === Response The response must contain an **HTTP status code** and may contain other information. The following code shows an example: .Groovy DSL [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=response,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=response,indent=0] ... include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=response_obligatory,indent=0] ---- Besides status, the response may contain **headers**, **cookies** and a **body**, both of which are specified the same way as in the request (see the previous paragraph). TIP: Via the Groovy DSL you can reference the `org.springframework.cloud.contract.spec.internal.HttpStatus` methods to provide a meaningful status instead of a digit. E.g. you can call `OK()` for a status `200` or `BAD_REQUEST()` for `400`. === Dynamic properties The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not want to force the consumers to stub their clocks to always return the same value of time so that it gets matched by the stub. For Groovy DSL you can provide the dynamic parts in your contracts in two ways: pass them directly in the body or set them in a separate section called `bodyMatchers`. NOTE: Before 2.0.0 these were set using `testMatchers` and `stubMatchers`, check out the https://github.com/spring-cloud/spring-cloud-contract/wiki/Spring-Cloud-Contract-2.0-Migration-Guide[migration guide] for more information. For YAML you can only use the `matchers` section. ==== Dynamic properties inside the body IMPORTANT: This section is valid only for Groovy DSL. Check out the <> section for YAML examples of a similar feature. You can set the properties inside the body either with the `value` method or, if you use the Groovy map notation, with `$()`. The following example shows how to set dynamic properties with the value method: [source,groovy,indent=0] ---- value(consumer(...), producer(...)) value(c(...), p(...)) value(stub(...), test(...)) value(client(...), server(...)) ---- The following example shows how to set dynamic properties with `$()`: [source,groovy,indent=0] ---- $(consumer(...), producer(...)) $(c(...), p(...)) $(stub(...), test(...)) $(client(...), server(...)) ---- Both approaches work equally well. `stub` and `client` methods are aliases over the `consumer` method. Subsequent sections take a closer look at what you can do with those values. ==== Regular expressions IMPORTANT: This section is valid only for Groovy DSL. Check out the <> section for YAML examples of a similar feature. You can use regular expressions to write your requests in Contract DSL. Doing so is particularly useful when you want to indicate that a given response should be provided for requests that follow a given pattern. Also, you can use regular expressions when you need to use patterns and not exact values both for your test and your server side tests. The following example shows how to use regular expressions to write a request: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=regex,indent=0] ---- You can also provide only one side of the communication with a regular expression. If you do so, then the contract engine automatically provides the generated string that matches the provided regular expression. The following code shows an example: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MockMvcMethodBodyBuilderSpec.groovy[tags=dsl_one_side_data_generation_example,indent=0] ---- In the preceding example, the opposite side of the communication has the respective data generated for request and response. Spring Cloud Contract comes with a series of predefined regular expressions that you can use in your contracts, as shown in the following example: [source,groovy,indent=0] ---- include::{contract_spec_path}/src/main/groovy/org/springframework/cloud/contract/spec/internal/RegexPatterns.groovy[tags=regexps,indent=0] ---- In your contract, you can use it as shown in the following example: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MockMvcMethodBodyBuilderSpec.groovy[tags=contract_with_regex,indent=0] ---- ==== Passing Optional Parameters IMPORTANT: This section is valid only for Groovy DSL. Check out the <> section for YAML examples of a similar feature. It is possible to provide optional parameters in your contract. However, you can provide optional parameters only for the following: * __STUB__ side of the Request * __TEST__ side of the Response The following example shows how to provide optional parameters: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=optionals,indent=0] ---- By wrapping a part of the body with the `optional()` method, you create a regular expression that must be present 0 or more times. If you use Spock for, the following test would be generated from the previous example: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=optionals_test,indent=0] ---- The following stub would also be generated: [source,groovy,indent=0] ---- include::{plugins_path}/spring-cloud-contract-converters/src/test/groovy/org/springframework/cloud/contract/verifier/wiremock/DslToWireMockClientConverterSpec.groovy[tags=wiremock,indent=0] ---- ==== Executing Custom Methods on the Server Side IMPORTANT: This section is valid only for Groovy DSL. Check out the <> section for YAML examples of a similar feature. You can define a method call that executes on the server side during the test. Such a method can be added to the class defined as ""baseClassForTests"" in the configuration. The following code shows an example of the contract portion of the test case: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=method,indent=0] ---- The following code shows the base class portion of the test case: [source,groovy,indent=0] ---- include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/bootSimple/src/test/groovy/org/springframework/cloud/contract/verifier/twitter/places/BaseMockMvcSpec.groovy[tags=base_class,indent=0] ---- IMPORTANT: You cannot use both a String and `execute` to perform concatenation. For example, calling `header('Authorization', 'Bearer ' + execute('authToken()'))` leads to improper results. Instead, call `header('Authorization', execute('authToken()'))` and ensure that the `authToken()` method returns everything you need. The type of the object read from the JSON can be one of the following, depending on the JSON path: * `String`: If you point to a `String` value in the JSON. * `JSONArray`: If you point to a `List` in the JSON. * `Map`: If you point to a `Map` in the JSON. * `Number`: If you point to `Integer`, `Double` etc. in the JSON. * `Boolean`: If you point to a `Boolean` in the JSON. In the request part of the contract, you can specify that the `body` should be taken from a method. IMPORTANT: You must provide both the consumer and the producer side. The `execute` part is applied for the whole body - not for parts of it. The following example shows how to read an object from JSON: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MethodBodyBuilderSpec.groovy[tags=body_execute,indent=0] ---- The preceding example results in calling the `hashCode()` method in the request body. It should resemble the following code: [source,java,indent=0] ---- // given: MockMvcRequestSpecification request = given() .body(hashCode()); // when: ResponseOptions response = given().spec(request) .get(""/something""); // then: assertThat(response.statusCode()).isEqualTo(200); ---- ==== Referencing the Request from the Response The best situation is to provide fixed values, but sometimes you need to reference a request in your response. If you're writing contracts using Groovy DSL, you can use the `fromRequest()` method, which lets you reference a bunch of elements from the HTTP request. You can use the following options: * `fromRequest().url()`: Returns the request URL and query parameters. * `fromRequest().query(String key)`: Returns the first query parameter with a given name. * `fromRequest().query(String key, int index)`: Returns the nth query parameter with a given name. * `fromRequest().path()`: Returns the full path. * `fromRequest().path(int index)`: Returns the nth path element. * `fromRequest().header(String key)`: Returns the first header with a given name. * `fromRequest().header(String key, int index)`: Returns the nth header with a given name. * `fromRequest().body()`: Returns the full request body. * `fromRequest().body(String jsonPath)`: Returns the element from the request that matches the JSON Path. If you're using the YAML contract definition you have to use the http://handlebarsjs.com/[Handlebars] `{{{ }}}` notation with custom, Spring Cloud Contract functions to achieve this. * `{{{ request.url }}}`: Returns the request URL and query parameters. * `{{{ request.query.key.[index] }}}`: Returns the nth query parameter with a given name. E.g. for key `foo`, first entry `{{{ request.query.foo.[0] }}}` * `{{{ request.path }}}`: Returns the full path. * `{{{ request.path.[index] }}}`: Returns the nth path element. E.g. for first entry ```{{{ request.path.[0] }}} * `{{{ request.headers.key }}}`: Returns the first header with a given name. * `{{{ request.headers.key.[index] }}}`: Returns the nth header with a given name. * `{{{ request.body }}}`: Returns the full request body. * `{{{ jsonpath this 'your.json.path' }}}`: Returns the element from the request that matches the JSON Path. E.g. for json path `$.foo` - `{{{ jsonpath this '$.foo' }}}` Consider the following contract: .Groovy DSL [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MockMvcMethodBodyBuilderSpec.groovy[tags=template_contract,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract_reference_request.yml[indent=0] ---- Running a JUnit test generation leads to a test that resembles the following example: [source,java,indent=0] ---- // given: MockMvcRequestSpecification request = given() .header(""Authorization"", ""secret"") .header(""Authorization"", ""secret2"") .body(""{\\""foo\\"":\\""bar\\"",\\""baz\\"":5}""); // when: ResponseOptions response = given().spec(request) .queryParam(""foo"",""bar"") .queryParam(""foo"",""bar2"") .get(""/api/v1/xxxx""); // then: assertThat(response.statusCode()).isEqualTo(200); assertThat(response.header(""Authorization"")).isEqualTo(""foo secret bar""); // and: DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); assertThatJson(parsedJson).field(""['fullBody']"").isEqualTo(""{\\""foo\\"":\\""bar\\"",\\""baz\\"":5}""); assertThatJson(parsedJson).field(""['authorization']"").isEqualTo(""secret""); assertThatJson(parsedJson).field(""['authorization2']"").isEqualTo(""secret2""); assertThatJson(parsedJson).field(""['path']"").isEqualTo(""/api/v1/xxxx""); assertThatJson(parsedJson).field(""['param']"").isEqualTo(""bar""); assertThatJson(parsedJson).field(""['paramIndex']"").isEqualTo(""bar2""); assertThatJson(parsedJson).field(""['pathIndex']"").isEqualTo(""v1""); assertThatJson(parsedJson).field(""['responseBaz']"").isEqualTo(5); assertThatJson(parsedJson).field(""['responseFoo']"").isEqualTo(""bar""); assertThatJson(parsedJson).field(""['url']"").isEqualTo(""/api/v1/xxxx?foo=bar&foo=bar2""); assertThatJson(parsedJson).field(""['responseBaz2']"").isEqualTo(""Bla bla bar bla bla""); ---- As you can see, elements from the request have been properly referenced in the response. The generated WireMock stub should resemble the following example: [source,json,indent=0] ---- { ""request"" : { ""urlPath"" : ""/api/v1/xxxx"", ""method"" : ""POST"", ""headers"" : { ""Authorization"" : { ""equalTo"" : ""secret2"" } }, ""queryParameters"" : { ""foo"" : { ""equalTo"" : ""bar2"" } }, ""bodyPatterns"" : [ { ""matchesJsonPath"" : ""$[?(@.['baz'] == 5)]"" }, { ""matchesJsonPath"" : ""$[?(@.['foo'] == 'bar')]"" } ] }, ""response"" : { ""status"" : 200, ""body"" : ""{\\""authorization\\"":\\""{{{request.headers.Authorization.[0]}}}\\"",\\""path\\"":\\""{{{request.path}}}\\"",\\""responseBaz\\"":{{{jsonpath this '$.baz'}}} ,\\""param\\"":\\""{{{request.query.foo.[0]}}}\\"",\\""pathIndex\\"":\\""{{{request.path.[1]}}}\\"",\\""responseBaz2\\"":\\""Bla bla {{{jsonpath this '$.foo'}}} bla bla\\"",\\""responseFoo\\"":\\""{{{jsonpath this '$.foo'}}}\\"",\\""authorization2\\"":\\""{{{request.headers.Authorization.[1]}}}\\"",\\""fullBody\\"":\\""{{{escapejsonbody}}}\\"",\\""url\\"":\\""{{{request.url}}}\\"",\\""paramIndex\\"":\\""{{{request.query.foo.[1]}}}\\""}"", ""headers"" : { ""Authorization"" : ""{{{request.headers.Authorization.[0]}}};foo"" }, ""transformers"" : [ ""response-template"" ] } } ---- Sending a request such as the one presented in the `request` part of the contract results in sending the following response body: [source,json,indent=0] ---- { ""url"" : ""/api/v1/xxxx?foo=bar&foo=bar2"", ""path"" : ""/api/v1/xxxx"", ""pathIndex"" : ""v1"", ""param"" : ""bar"", ""paramIndex"" : ""bar2"", ""authorization"" : ""secret"", ""authorization2"" : ""secret2"", ""fullBody"" : ""{\\""foo\\"":\\""bar\\"",\\""baz\\"":5}"", ""responseFoo"" : ""bar"", ""responseBaz"" : 5, ""responseBaz2"" : ""Bla bla bar bla bla"" } ---- IMPORTANT: This feature works only with WireMock having a version greater than or equal to 2.5.1. The Spring Cloud Contract Verifier uses WireMock's `response-template` response transformer. It uses Handlebars to convert the Mustache `{{{ }}}` templates into proper values. Additionally, it registers two helper functions: * `escapejsonbody`: Escapes the request body in a format that can be embedded in a JSON. * `jsonpath`: For a given parameter, find an object in the request body. ==== Registering Your Own WireMock Extension WireMock lets you register custom extensions. By default, Spring Cloud Contract registers the transformer, which lets you reference a request from a response. If you want to provide your own extensions, you can register an implementation of the `org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions` interface. Since we use the spring.factories extension approach, you can create an entry in `META-INF/spring.factories` file similar to the following: [source,groovy,indent=0] ---- include::{stubrunner_core_path}/src/test/resources/META-INF/spring.factories[indent=0] ---- The following is an example of a custom extension: .TestWireMockExtensions.groovy [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/dsl/wiremock/TestWireMockExtensions.groovy[indent=0] ---- IMPORTANT: Remember to override the `applyGlobally()` method and set it to `false` if you want the transformation to be applied only for a mapping that explicitly requires it. [[contract-matchers]] ==== Dynamic Properties in the Matchers Sections If you work with https://docs.pact.io/[Pact], the following discussion may seem familiar. Quite a few users are used to having a separation between the body and setting the dynamic parts of a contract. You can use the `bodyMatchers` section for two reasons: * Define the dynamic values that should end up in a stub. You can set it in the `request` or `inputMessage` part of your contract. * Verify the result of your test. This section is present in the `response` or `outputMessage` side of the contract. Currently, Spring Cloud Contract Verifier supports only JSON Path-based matchers with the following matching possibilities: .Groovy DSL * For the stubs: ** `byEquality()`: The value taken from the response via the provided JSON Path must be equal to the value provided in the contract. ** `byRegex(...)`: The value taken from the response via the provided JSON Path must match the regex. ** `byDate()`: The value taken from the response via the provided JSON Path must match the regex for an ISO Date value. ** `byTimestamp()`: The value taken from the response via the provided JSON Path must match the regex for an ISO DateTime value. ** `byTime()`: The value taken from the response via the provided JSON Path must match the regex for an ISO Time value. * For the verification: ** `byEquality()`: The value taken from the response via the provided JSON Path must be equal to the provided value in the contract. ** `byRegex(...)`: The value taken from the response via the provided JSON Path must match the regex. ** `byDate()`: The value taken from the response via the provided JSON Path must match the regex for an ISO Date value. ** `byTimestamp()`: The value taken from the response via the provided JSON Path must match the regex for an ISO DateTime value. ** `byTime()`: The value taken from the response via the provided JSON Path must match the regex for an ISO Time value. ** `byType()`: The value taken from the response via the provided JSON Path needs to be of the same type as the type defined in the body of the response in the contract. `byType` can take a closure, in which you can set `minOccurrence` and `maxOccurrence`. That way, you can assert the size of the flattened collection. To check the size of an unflattened collection, use a custom method with the `byCommand(...)` testMatcher. ** `byCommand(...)`: The value taken from the response via the provided JSON Path is passed as an input to the custom method that you provide. For example, `byCommand('foo($it)')` results in calling a `foo` method to which the value matching the JSON Path gets passed. The type of the object read from the JSON can be one of the following, depending on the JSON path: *** `String`: If you point to a `String` value. *** `JSONArray`: If you point to a `List`. *** `Map`: If you point to a `Map`. *** `Number`: If you point to `Integer`, `Double`, or other kind of number. *** `Boolean`: If you point to a `Boolean`. ** `byNull()`: The value taken from the response via the provided JSON Path must be null .YAML _Please read the Groovy section for detailed explanation of what the types mean_ For YAML the structure of a matcher looks like this [source,yml,indent=0] ---- - path: $.foo type: by_regex value: bar ---- Or if you want to use one of the predefined regular expressions `[only_alpha_unicode, number, any_boolean, ip_address, hostname, email, url, uuid, iso_date, iso_date_time, iso_time, iso_8601_with_offset, non_empty, non_blank]`: [source,yml,indent=0] ---- - path: $.foo type: by_regex predefined: only_alpha_unicode ---- Below you can find the allowed list of `type`s. * For `stubMatchers`: ** `by_equality` ** `by_regex` ** `by_date` ** `by_timestamp` ** `by_time` * For `testMatchers`: ** `by_equality` ** `by_regex` ** `by_date` ** `by_timestamp` ** `by_time` ** `by_type` *** there are 2 additional fields accepted: `minOccurrence` and `maxOccurrence`. ** `by_command` ** `by_null` Consider the following example: .Groovy DSL [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MockMvcMethodBodyBuilderWithMatchersSpec.groovy[tags=matchers,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract_matchers.yml[indent=0] ---- In the preceding example, you can see the dynamic portions of the contract in the `matchers` sections. For the request part, you can see that, for all fields but `valueWithoutAMatcher`, the values of the regular expressions that the stub should contain are explicitly set. For the `valueWithoutAMatcher`, the verification takes place in the same way as without the use of matchers. In that case, the test performs an equality check. For the response side in the `bodyMatchers` section, we define the dynamic parts in a similar manner. The only difference is that the `byType` matchers are also present. The verifier engine checks four fields to verify whether the response from the test has a value for which the JSON path matches the given field, is of the same type as the one defined in the response body, and passes the following check (based on the method being called): * For `$.valueWithTypeMatch`, the engine checks whether the type is the same. * For `$.valueWithMin`, the engine check the type and asserts whether the size is greater than or equal to the minimum occurrence. * For `$.valueWithMax`, the engine checks the type and asserts whether the size is smaller than or equal to the maximum occurrence. * For `$.valueWithMinMax`, the engine checks the type and asserts whether the size is between the min and maximum occurrence. The resulting test would resemble the following example (note that an `and` section separates the autogenerated assertions and the assertion from matchers): [source,java,indent=0] ---- // given: MockMvcRequestSpecification request = given() .header(""Content-Type"", ""application/json"") .body(""{\\""duck\\"":123,\\""alpha\\"":\\""abc\\"",\\""number\\"":123,\\""aBoolean\\"":true,\\""date\\"":\\""2017-01-01\\"",\\""dateTime\\"":\\""2017-01-01T01:23:45\\"",\\""time\\"":\\""01:02:34\\"",\\""valueWithoutAMatcher\\"":\\""foo\\"",\\""valueWithTypeMatch\\"":\\""string\\"",\\""key\\"":{\\""complex.key\\"":\\""foo\\""}}""); // when: ResponseOptions response = given().spec(request) .get(""/get""); // then: assertThat(response.statusCode()).isEqualTo(200); assertThat(response.header(""Content-Type"")).matches(""application/json.*""); // and: DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); assertThatJson(parsedJson).field(""['valueWithoutAMatcher']"").isEqualTo(""foo""); // and: assertThat(parsedJson.read(""$.duck"", String.class)).matches(""[0-9]{3}""); assertThat(parsedJson.read(""$.duck"", Integer.class)).isEqualTo(123); assertThat(parsedJson.read(""$.alpha"", String.class)).matches(""[\\\\p{L}]*""); assertThat(parsedJson.read(""$.alpha"", String.class)).isEqualTo(""abc""); assertThat(parsedJson.read(""$.number"", String.class)).matches(""-?(\\\\d*\\\\.\\\\d+|\\\\d+)""); assertThat(parsedJson.read(""$.aBoolean"", String.class)).matches(""(true|false)""); assertThat(parsedJson.read(""$.date"", String.class)).matches(""(\\\\d\\\\d\\\\d\\\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])""); assertThat(parsedJson.read(""$.dateTime"", String.class)).matches(""([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])""); assertThat(parsedJson.read(""$.time"", String.class)).matches(""(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])""); assertThat((Object) parsedJson.read(""$.valueWithTypeMatch"")).isInstanceOf(java.lang.String.class); assertThat((Object) parsedJson.read(""$.valueWithMin"")).isInstanceOf(java.util.List.class); assertThat((java.lang.Iterable) parsedJson.read(""$.valueWithMin"", java.util.Collection.class)).as(""$.valueWithMin"").hasSizeGreaterThanOrEqualTo(1); assertThat((Object) parsedJson.read(""$.valueWithMax"")).isInstanceOf(java.util.List.class); assertThat((java.lang.Iterable) parsedJson.read(""$.valueWithMax"", java.util.Collection.class)).as(""$.valueWithMax"").hasSizeLessThanOrEqualTo(3); assertThat((Object) parsedJson.read(""$.valueWithMinMax"")).isInstanceOf(java.util.List.class); assertThat((java.lang.Iterable) parsedJson.read(""$.valueWithMinMax"", java.util.Collection.class)).as(""$.valueWithMinMax"").hasSizeBetween(1, 3); assertThat((Object) parsedJson.read(""$.valueWithMinEmpty"")).isInstanceOf(java.util.List.class); assertThat((java.lang.Iterable) parsedJson.read(""$.valueWithMinEmpty"", java.util.Collection.class)).as(""$.valueWithMinEmpty"").hasSizeGreaterThanOrEqualTo(0); assertThat((Object) parsedJson.read(""$.valueWithMaxEmpty"")).isInstanceOf(java.util.List.class); assertThat((java.lang.Iterable) parsedJson.read(""$.valueWithMaxEmpty"", java.util.Collection.class)).as(""$.valueWithMaxEmpty"").hasSizeLessThanOrEqualTo(0); assertThatValueIsANumber(parsedJson.read(""$.duck"")); assertThat(parsedJson.read(""$.['key'].['complex.key']"", String.class)).isEqualTo(""foo""); ---- IMPORTANT: Notice that, for the `byCommand` method, the example calls the `assertThatValueIsANumber`. This method must be defined in the test base class or be statically imported to your tests. Notice that the `byCommand` call was converted to `assertThatValueIsANumber(parsedJson.read(""$.duck""));`. That means that the engine took the method name and passed the proper JSON path as a parameter to it. The resulting WireMock stub is in the following example: [source,json,indent=0] ---- include::{plugins_path}/spring-cloud-contract-converters/src/test/groovy/org/springframework/cloud/contract/verifier/wiremock/DslToWireMockClientConverterSpec.groovy[tags=matchers,indent=0] ---- IMPORTANT: If you use a `matcher`, then the part of the request and response that the `matcher` addresses with the JSON Path gets removed from the assertion. In the case of verifying a collection, you must create matchers for *all* the elements of the collection. Consider the following example: [source,groovy,indent=0] ---- Contract.make { request { method 'GET' url(""/foo"") } response { status OK() body(events: [[ operation : 'EXPORT', eventId : '16f1ed75-0bcc-4f0d-a04d-3121798faf99', status : 'OK' ], [ operation : 'INPUT_PROCESSING', eventId : '3bb4ac82-6652-462f-b6d1-75e424a0024a', status : 'OK' ] ] ) bodyMatchers { jsonPath('$.events[0].operation', byRegex('.+')) jsonPath('$.events[0].eventId', byRegex('^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$')) jsonPath('$.events[0].status', byRegex('.+')) } } } ---- The preceding code leads to creating the following test (the code block shows only the assertion section): [source,java,indent=0] ---- and: DocumentContext parsedJson = JsonPath.parse(response.body.asString()) assertThatJson(parsedJson).array(""['events']"").contains(""['eventId']"").isEqualTo(""16f1ed75-0bcc-4f0d-a04d-3121798faf99"") assertThatJson(parsedJson).array(""['events']"").contains(""['operation']"").isEqualTo(""EXPORT"") assertThatJson(parsedJson).array(""['events']"").contains(""['operation']"").isEqualTo(""INPUT_PROCESSING"") assertThatJson(parsedJson).array(""['events']"").contains(""['eventId']"").isEqualTo(""3bb4ac82-6652-462f-b6d1-75e424a0024a"") assertThatJson(parsedJson).array(""['events']"").contains(""['status']"").isEqualTo(""OK"") and: assertThat(parsedJson.read(""\\$.events[0].operation"", String.class)).matches("".+"") assertThat(parsedJson.read(""\\$.events[0].eventId"", String.class)).matches(""^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\\$"") assertThat(parsedJson.read(""\\$.events[0].status"", String.class)).matches("".+"") ---- As you can see, the assertion is malformed. Only the first element of the array got asserted. In order to fix this, you should apply the assertion to the whole `$.events` collection and assert it with the `byCommand(...)` method. === JAX-RS Support The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs to define `protected WebTarget webTarget` and server initialization. The only option for testing JAX-RS API is to start a web server. Also, a request with a body needs to have a content type set. Otherwise, the default of `application/octet-stream` gets used. In order to use JAX-RS mode, use the following settings: [source,groovy,indent=0] ---- testMode == 'JAXRSCLIENT' ---- The following example shows a generated test API: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/JaxRsClientMethodBuilderSpec.groovy[tags=jaxrs,indent=0] ---- === Async Support If you're using asynchronous communication on the server side (your controllers are returning `Callable`, `DeferredResult`, and so on), then, inside your contract, you must provide an `async()` method in the `response` section. The following code shows an example: .Groovy DSL [source,groovy,indent=0] ---- org.springframework.cloud.contract.spec.Contract.make { request { method GET() url '/get' } response { status OK() body 'Passed' async() } } ---- .YAML [source,yml,indent=0] ---- response: async: true ---- === Working with Context Paths Spring Cloud Contract supports context paths. IMPORTANT: The only change needed to fully support context paths is the switch on the *PRODUCER* side. Also, the autogenerated tests must use *EXPLICIT* mode. The consumer side remains untouched. In order for the generated test to pass, you must use *EXPLICIT* mode. [source,xml,indent=0,subs=""verbatim,attributes"",role=""primary""] .Maven ---- org.springframework.cloud spring-cloud-contract-maven-plugin ${spring-cloud-contract.version} true EXPLICIT ---- [source,groovy,indent=0,subs=""verbatim,attributes"",role=""secondary""] .Gradle ---- contracts { testMode = 'EXPLICIT' } ---- That way, you generate a test that *DOES NOT* use MockMvc. It means that you generate real requests and you need to setup your generated test's base class to work on a real socket. Consider the following contract: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy[tags=context_path_contract,indent=0] ---- The following example shows how to set up a base class and Rest Assured: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy[tags=context_path_baseclass,indent=0] ---- If you do it this way: * All of your requests in the autogenerated tests are sent to the real endpoint with your context path included (for example, `/my-context-path/url`). * Your contracts reflect that you have a context path. Your generated stubs also have that information (for example, in the stubs, you have to call `/my-context-path/url`). === Messaging Top-Level Elements The DSL for messaging looks a little bit different than the one that focuses on HTTP. The following sections explain the differences: * <> * <> * <> * <> [[contract-dsl-output-triggered-method]] ==== Output Triggered by a Method The output message can be triggered by calling a method (such as a `Scheduler` when a was started and a message was sent), as shown in the following example: .Groovy DSL [source,groovy] ---- include::{tests_path}/samples-messaging-integration/src/test/groovy/com/example/IntegrationMessagingApplicationSpec.groovy[tags=method_trigger,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract_message_method.yml[indent=0] ---- In the previous example case, the output message is sent to `output` if a method called `bookReturnedTriggered` is executed. On the message *publisher's* side, we generate a test that calls that method to trigger the message. On the *consumer* side, you can use the `some_label` to trigger the message. [[contract-dsl-output-triggered-message]] ==== Output Triggered by a Message The output message can be triggered by receiving a message, as shown in the following example: .Groovy DSL [source,groovy] ---- include::{tests_path}/samples-messaging-integration/src/test/groovy/com/example/IntegrationMessagingApplicationSpec.groovy[tags=message_trigger,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/contract_message_input_message.yml[indent=0] ---- In the preceding example, the output message is sent to `output` if a proper message is received on the `input` destination. On the message *publisher's* side, the engine generates a test that sends the input message to the defined destination. On the *consumer* side, you can either send a message to the input destination or use a label (`some_label` in the example) to trigger the message. [[contract-dsl-consumer-producer]] ==== Consumer/Producer IMPORTANT: This section is valid only for Groovy DSL. In HTTP, you have a notion of `client`/`stub and `server`/`test` notation. You can also use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also provides the `consumer` and `producer` methods, as presented in the following example (note that you can use either `$` or `value` methods to provide `consumer` and `producer` parts): [source,groovy] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=consumer_producer] ---- [[contract-dsl-common]] ==== Common In the `input` or `outputMessage` section you can call `assertThat` with the name of a `method` (e.g. `assertThatMessageIsOnTheQueue()`) that you have defined in the base class or in a static import. Spring Cloud Contract will execute that method in the generated test. === Multiple Contracts in One File You can define multiple contracts in one file. Such a contract might resemble the following example: .Groovy DSL [source,groovy,indent=0] ---- include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/multiple-contracts/src/test/resources/contracts/com/hello/v1/WithList.groovy[lines=18..-1,indent=0] ---- .YAML [source,yml,indent=0] ---- include::{verifier_core_path}/src/test/resources/yml/multiple_contracts.yml[indent=0] ---- In the preceding example, one contract has the `name` field and the other does not. This leads to generation of two tests that look more or less like this: [source,java,indent=0] ---- package org.springframework.cloud.contract.verifier.tests.com.hello; import com.example.TestBase; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification; import com.jayway.restassured.response.ResponseOptions; import org.junit.Test; import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*; import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson; import static org.assertj.core.api.Assertions.assertThat; public class V1Test extends TestBase { @Test public void validate_should_post_a_user() throws Exception { // given: MockMvcRequestSpecification request = given(); // when: ResponseOptions response = given().spec(request) .post(""/users/1""); // then: assertThat(response.statusCode()).isEqualTo(200); } @Test public void validate_withList_1() throws Exception { // given: MockMvcRequestSpecification request = given(); // when: ResponseOptions response = given().spec(request) .post(""/users/2""); // then: assertThat(response.statusCode()).isEqualTo(200); } } ---- Notice that, for the contract that has the `name` field, the generated test method is named `validate_should_post_a_user`. For the one that does not have the name, it is called `validate_withList_1`. It corresponds to the name of the file `WithList.groovy` and the index of the contract in the list. The generated stubs is shown in the following example: [source] ---- should post a user.json 1_WithList.json ---- As you can see, the first file got the `name` parameter from the contract. The second got the name of the contract file (`WithList.groovy`) prefixed with the index (in this case, the contract had an index of `1` in the list of contracts in the file). TIP: As you can see, it iss much better if you name your contracts because doing so makes your tests far more meaningful. == Customization IMPORTANT: This section is valid only for Groovy DSL You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in the remainder of this section. === Extending the DSL You can provide your own functions to the DSL. The key requirement for this feature is to maintain the static compatibility. Later in this document, you can see examples of: * Creating a JAR with reusable classes. * Referencing of these classes in the DSLs. You can find the full example https://github.com/spring-cloud-samples/spring-cloud-contract-samples[here]. ==== Common JAR The following examples show three classes that can be reused in the DSLs. *PatternUtils* contains functions used by both the **consumer** and the **producer**. [source,java] ---- include::{samples_url}/common/src/main/java/com/example/PatternUtils.java[] ---- *ConsumerUtils* contains functions used by the **consumer**. [source,java] ---- include::{samples_url}/common/src/main/java/com/example/ConsumerUtils.java[] ---- *ProducerUtils* contains functions used by the **producer**. [source,java] ---- include::{samples_url}/common/src/main/java/com/example/ProducerUtils.java[] ---- ==== Adding the Dependency to the Project In order for the plugins and IDE to be able to reference the common JAR classes, you need to pass the dependency to your project. // TODO missing code block here - we should show an example adding a dependency ==== Test the Dependency in the Project's Dependencies First, add the common jar dependency as a test dependency. Because your contracts files are available on the test resources path, the common jar classes automatically become visible in your Groovy files. The following examples show how to test the dependency: [source,xml,indent=0,subs=""verbatim,attributes"",role=""primary""] .Maven ---- include::{samples_url}/producer/pom.xml[tags=test_dep,indent=0] ---- [source,groovy,indent=0,subs=""verbatim,attributes"",role=""secondary""] .Gradle ---- include::{samples_url}/producer/build.gradle[tags=test_dep,indent=0] ---- ==== Test a Dependency in the Plugin's Dependencies Now, you must add the dependency for the plugin to reuse at runtime, as shown in the following example: [source,xml,indent=0,subs=""verbatim,attributes"",role=""primary""] .Maven ---- include::{samples_url}/producer/pom.xml[tags=test_dep_in_plugin,indent=0] ---- [source,groovy,indent=0,subs=""verbatim,attributes"",role=""secondary""] .Gradle ---- include::{samples_url}/producer/build.gradle[tags=test_dep_in_plugin,indent=0] ---- ==== Referencing classes in DSLs You can now reference your classes in your DSL, as shown in the following example: [source,groovy] ---- include::{samples_url}/producer/src/test/resources/contracts/beer/rest/shouldGrantABeerIfOldEnough.groovy[indent=0] ---- == Using the Pluggable Architecture You may encounter cases where you have your contracts have been defined in other formats, such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic generation of tests and stubs. You can add your own implementation for generating both tests and stubs. Also, you can customize the way tests are generated (for example, you can generate tests for other languages) and the way stubs are generated (for example, you can generate stubs for other HTTP server implementations). === Custom Contract Converter The `ContractConverter` interface lets you register your own implementation of a contract structure converter. The following code listing shows the `ContractConverter` interface: [source,groovy] ---- include::{contract_spec_path}/src/main/groovy/org/springframework/cloud/contract/spec/ContractConverter.groovy[indent=0,lines=17..-1] ---- Your implementation must define the condition on which it should start the conversion. Also, you must define how to perform that conversion in both directions. IMPORTANT: Once you create your implementation, you must create a `/META-INF/spring.factories` file in which you provide the fully qualified name of your implementation. The following example shows a typical `spring.factories` file: [source] ---- org.springframework.cloud.contract.spec.ContractConverter=\\ org.springframework.cloud.contract.verifier.converter.YamlContractConverter ---- [[pact-converter]] ==== Pact Converter Spring Cloud Contract includes support for https://docs.pact.io/[Pact] representation of contracts up until v4. Instead of using the Groovy DSL, you can use Pact files. In this section, we present how to add Pact support for your project. Note however that not all functionality is supported. Starting with v3 you can combine multiple matcher for the same element; you can use matchers for the body, headers, request and path; and you can use value generators. Spring Cloud Contract currently only supports multiple matchers that are combined using the AND rule logic. Next to that the request and path matchers are skipped during the conversion. When using a date, time or datetime value generator with a given format, the given format will be skipped and the ISO format will be used. ==== Pact Contract Consider following example of a Pact contract, which is a file under the `src/test/resources/contracts` folder. [source,javascript,indent=0] ---- include::{standalone_pact_path}/pact-http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.json[indent=0] ---- The remainder of this section about using Pact refers to the preceding file. ==== Pact for Producers On the producer side, you must add two additional dependencies to your plugin configuration. One is the Spring Cloud Contract Pact support, and the other represents the current Pact version that you use. [source,xml,indent=0,subs=""verbatim,attributes"",role=""primary""] .Maven ---- include::{standalone_pact_path}/pact-http-server/pom.xml[tags=pact_dependency,indent=0] ---- [source,groovy,indent=0,subs=""verbatim,attributes"",role=""secondary""] .Gradle ---- include::{standalone_pact_path}/pact-http-server/build.gradle[tags=pact_dependency,indent=0] ---- When you execute the build of your application, a test will be generated. The generated test might be as follows: [source,java,indent=0] ---- @Test public void validate_shouldMarkClientAsFraud() throws Exception { // given: MockMvcRequestSpecification request = given() .header(""Content-Type"", ""application/vnd.fraud.v1+json"") .body(""{\\""clientId\\"":\\""1234567890\\"",\\""loanAmount\\"":99999}""); // when: ResponseOptions response = given().spec(request) .put(""/fraudcheck""); // then: assertThat(response.statusCode()).isEqualTo(200); assertThat(response.header(""Content-Type"")).matches(""application/vnd\\\\.fraud\\\\.v1\\\\+json.*""); // and: DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); assertThatJson(parsedJson).field(""['rejectionReason']"").isEqualTo(""Amount too high""); // and: assertThat(parsedJson.read(""$.fraudCheckStatus"", String.class)).matches(""FRAUD""); } ---- The corresponding generated stub might be as follows: [source,javascript,indent=0] ---- { ""id"" : ""996ae5ae-6834-4db6-8fac-358ca187ab62"", ""uuid"" : ""996ae5ae-6834-4db6-8fac-358ca187ab62"", ""request"" : { ""url"" : ""/fraudcheck"", ""method"" : ""PUT"", ""headers"" : { ""Content-Type"" : { ""matches"" : ""application/vnd\\\\.fraud\\\\.v1\\\\+json.*"" } }, ""bodyPatterns"" : [ { ""matchesJsonPath"" : ""$[?(@.['loanAmount'] == 99999)]"" }, { ""matchesJsonPath"" : ""$[?(@.clientId =~ /([0-9]{10})/)]"" } ] }, ""response"" : { ""status"" : 200, ""body"" : ""{\\""fraudCheckStatus\\"":\\""FRAUD\\"",\\""rejectionReason\\"":\\""Amount too high\\""}"", ""headers"" : { ""Content-Type"" : ""application/vnd.fraud.v1+json;charset=UTF-8"" }, ""transformers"" : [ ""response-template"" ] }, } ---- ==== Pact for Consumers On the producer side, you must add two additional dependencies to your project dependencies. One is the Spring Cloud Contract Pact support, and the other represents the current Pact version that you use. [source,xml,indent=0,subs=""verbatim,attributes"",role=""primary""] .Maven ---- include::{standalone_pact_path}/pact-http-client/pom.xml[tags=pact_dependency,indent=0] ---- [source,groovy,indent=0,subs=""verbatim,attributes"",role=""secondary""] .Gradle ---- include::{standalone_pact_path}/pact-http-client/build.gradle[tags=pact_dependency,indent=0] ---- === Using the Custom Test Generator If you want to generate tests for languages other than Java or you are not happy with the way the verifier builds Java tests, you can register your own implementation. The `SingleTestGenerator` interface lets you register your own implementation. The following code listing shows the `SingleTestGenerator` interface: [source,groovy] ---- include::{verifier_core_path}/src/main/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGenerator.groovy[indent=0,lines=17..-1] ---- Again, you must provide a `spring.factories` file, such as the one shown in the following example: [source] ---- org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/ com.example.MyGenerator ---- === Using the Custom Stub Generator If you want to generate stubs for stub servers other than WireMock, you can plug in your own implementation of the `StubGenerator` interface. The following code listing shows the `StubGenerator` interface: [source,groovy] ---- include::{converters_path}/src/main/groovy/org/springframework/cloud/contract/verifier/converter/StubGenerator.groovy[indent=0,lines=16..-1] ---- Again, you must provide a `spring.factories` file, such as the one shown in the following example: [source] ---- include::{converters_path}/src/main/resources/META-INF/spring.factories[indent=0] ---- The default implementation is the WireMock stub generation. TIP: You can provide multiple stub generator implementations. For example, from a single DSL, you can produce both WireMock stubs and Pact files. === Using the Custom Stub Runner If you decide to use a custom stub generation, you also need a custom way of running stubs with your different stub provider. Assume that you use https://github.com/dreamhead/moco[Moco] to build your stubs and that you have written a stub generator and placed your stubs in a JAR file. In order for Stub Runner to know how to run your stubs, you have to define a custom HTTP Stub server implementation, which might resemble the following example: [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-moco/src/test/groovy/org/springframework/cloud/contract/stubrunner/provider/moco/MocoHttpServerStub.groovy[indent=0,lines=16..-1] ---- Then, you can register it in your `spring.factories` file, as shown in the following example: [source] ---- org.springframework.cloud.contract.stubrunner.HttpServerStub=\\ org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub ---- Now you can run stubs with Moco. IMPORTANT: If you do not provide any implementation, then the default (WireMock) implementation is used. If you provide more than one, the first one on the list is used. === Using the Custom Stub Downloader You can customize the way your stubs are downloaded by creating an implementation of the `StubDownloaderBuilder` interface, as shown in the following example: [source,java] ---- package com.example; class CustomStubDownloaderBuilder implements StubDownloaderBuilder { @Override public StubDownloader build(final StubRunnerOptions stubRunnerOptions) { return new StubDownloader() { @Override public Map.Entry downloadAndUnpackStubJar( StubConfiguration config) { File unpackedStubs = retrieveStubs(); return new AbstractMap.SimpleEntry<>( new StubConfiguration(config.getGroupId(), config.getArtifactId(), version, config.getClassifier()), unpackedStubs); } File retrieveStubs() { // here goes your custom logic to provide a folder where all the stubs reside } } ---- Then you can register it in your `spring.factories` file, as shown in the following example: [source] ---- # Example of a custom Stub Downloader Provider org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\\ com.example.CustomStubDownloaderBuilder ---- Now you can pick a folder with the source of your stubs. IMPORTANT: If you do not provide any implementation, then the default is used (scan classpath). If you provide the `stubsMode = StubRunnerProperties.StubsMode.LOCAL` or `, stubsMode = StubRunnerProperties.StubsMode.REMOTE` then the Aether implementation will be used If you provide more than one, then the first one on the list is used. [[scm-stub-downloader]] === Using the SCM Stub Downloader Whenever the `repositoryRoot` starts with a SCM protocol (currently we support only `git://`), the stub downloader will try to clone the repository and use it as a source of contracts to generate tests or stubs. Either via environment variables, system properties, properties set inside the plugin or contracts repository configuration you can tweak the downloader's behaviour. Below you can find the list of properties .SCM Stub Downloader properties |=== |Type of a property |Name of the property | Description | * `git.branch` (plugin prop) * `stubrunner.properties.git.branch` (system prop) * `STUBRUNNER_PROPERTIES_GIT_BRANCH` (env prop) |master |Which branch to checkout | * `git.username` (plugin prop) * `stubrunner.properties.git.username` (system prop) * `STUBRUNNER_PROPERTIES_GIT_USERNAME` (env prop) | |Git clone username | * `git.password` (plugin prop) * `stubrunner.properties.git.password` (system prop) * `STUBRUNNER_PROPERTIES_GIT_PASSWORD` (env prop) | |Git clone password | * `git.no-of-attempts` (plugin prop) * `stubrunner.properties.git.no-of-attempts` (system prop) * `STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS` (env prop) |10 |Number of attempts to push the commits to `origin` | * `git.wait-between-attempts` (Plugin prop) * `stubrunner.properties.git.wait-between-attempts` (system prop) * `STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS` (env prop) |1000 |Number of millis to wait between attempts to push the commits to `origin` |=== [[pact-stub-downloader]] === Using the Pact Stub Downloader Whenever the `repositoryRoot` starts with a Pact protocol (starts with `pact://`), the stub downloader will try to fetch the Pact contract definitions from the Pact Broker. Whatever is set after `pact://` will be parsed as the Pact Broker URL. Either via environment variables, system properties, properties set inside the plugin or contracts repository configuration you can tweak the downloader's behaviour. Below you can find the list of properties .SCM Stub Downloader properties |=== |Type of a property |Name of the property | Description | * `pactbroker.host` (plugin prop) * `stubrunner.properties.pactbroker.host` (system prop) * `STUBRUNNER_PROPERTIES_PACTBROKER_HOST` (env prop) |Host from URL passed to `repositoryRoot` |What is the URL of Pact Broker | * `pactbroker.port` (plugin prop) * `stubrunner.properties.pactbroker.port` (system prop) * `STUBRUNNER_PROPERTIES_PACTBROKER_PORT` (env prop) |Port from URL passed to `repositoryRoot` |What is the port of Pact Broker | * `pactbroker.protocol` (plugin prop) * `stubrunner.properties.pactbroker.protocol` (system prop) * `STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL` (env prop) |Protocol from URL passed to `repositoryRoot` |What is the protocol of Pact Broker | * `pactbroker.tags` (plugin prop) * `stubrunner.properties.pactbroker.tags` (system prop) * `STUBRUNNER_PROPERTIES_PACTBROKER_TAGS` (env prop) |Version of the stub, or `latest` if version is `+` |What tags should be used to fetch the stub | * `pactbroker.auth.scheme` (plugin prop) * `stubrunner.properties.pactbroker.auth.scheme` (system prop) * `STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME` (env prop) |`Basic` |What kind of authentication should be used to connect to the Pact Broker | * `pactbroker.auth.username` (plugin prop) * `stubrunner.properties.pactbroker.auth.username` (system prop) * `STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME` (env prop) | |Username used to connect to the Pact Broker | * `pactbroker.auth.password` (plugin prop) * `stubrunner.properties.pactbroker.auth.password` (system prop) * `STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD` (env prop) | |Password used to connect to the Pact Broker | * `pactbroker.provider-name-with-group-id` (plugin prop) * `stubrunner.properties.pactbroker.provider-name-with-group-id` (system prop) * `STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID` (env prop) |false |When `true`, the provider name will be a combination of `groupId:artifactId`. If `false`, just `artifactId` is used |=== ",16144,True,2672.3020330799113,median "= Lint == Lint/AmbiguousBlockAssociation |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.48 | - |=== This cop checks for ambiguous block association with method when param passed without parentheses. === Examples [source,ruby] ---- # bad some_method a { |val| puts val } ---- [source,ruby] ---- # good # With parentheses, there's no ambiguity. some_method(a) { |val| puts val } # good # Operator methods require no disambiguation foo == bar { |b| b.baz } # good # Lambda arguments require no disambiguation foo = ->(bar) { bar.baz } ---- === References * https://rubystyle.guide#syntax == Lint/AmbiguousOperator |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.17 | 0.83 |=== This cop checks for ambiguous operators in the first argument of a method invocation without parentheses. === Examples [source,ruby] ---- # bad # The `*` is interpreted as a splat operator but it could possibly be # a `*` method invocation (i.e. `do_something.*(some_array)`). do_something *some_array ---- [source,ruby] ---- # good # With parentheses, there's no ambiguity. do_something(*some_array) ---- === References * https://rubystyle.guide#method-invocation-parens == Lint/AmbiguousRegexpLiteral |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.17 | 0.83 |=== This cop checks for ambiguous regexp literals in the first argument of a method invocation without parentheses. === Examples [source,ruby] ---- # bad # This is interpreted as a method invocation with a regexp literal, # but it could possibly be `/` method invocations. # (i.e. `do_something./(pattern)./(i)`) do_something /pattern/i ---- [source,ruby] ---- # good # With parentheses, there's no ambiguity. do_something(/pattern/i) ---- == Lint/AssignmentInCondition |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | - |=== This cop checks for assignments in the conditions of if/while/until. `AllowSafeAssignment` option for safe assignment. By safe assignment we mean putting parentheses around an assignment to indicate ""I know I'm using an assignment as a condition. It's not a mistake."" === Examples [source,ruby] ---- # bad if some_var = true do_something end # good if some_var == true do_something end ---- ==== AllowSafeAssignment: true (default) [source,ruby] ---- # good if (some_var = true) do_something end ---- ==== AllowSafeAssignment: false [source,ruby] ---- # bad if (some_var = true) do_something end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowSafeAssignment | `true` | Boolean |=== === References * https://rubystyle.guide#safe-assignment-in-condition == Lint/BigDecimalNew |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.53 | - |=== `BigDecimal.new()` is deprecated since BigDecimal 1.3.3. This cop identifies places where `BigDecimal.new()` can be replaced by `BigDecimal()`. === Examples [source,ruby] ---- # bad BigDecimal.new(123.456, 3) # good BigDecimal(123.456, 3) ---- == Lint/BooleanSymbol |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | No | Yes (Unsafe) | 0.50 | 0.83 |=== This cop checks for `:true` and `:false` symbols. In most cases it would be a typo. === Examples [source,ruby] ---- # bad :true # good true ---- [source,ruby] ---- # bad :false # good false ---- == Lint/CircularArgumentReference |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.33 | - |=== This cop checks for circular argument references in optional keyword arguments and optional ordinal arguments. This cop mirrors a warning produced by MRI since 2.2. === Examples [source,ruby] ---- # bad def bake(pie: pie) pie.heat_up end ---- [source,ruby] ---- # good def bake(pie:) pie.refrigerate end ---- [source,ruby] ---- # good def bake(pie: self.pie) pie.feed_to(user) end ---- [source,ruby] ---- # bad def cook(dry_ingredients = dry_ingredients) dry_ingredients.reduce(&:+) end ---- [source,ruby] ---- # good def cook(dry_ingredients = self.dry_ingredients) dry_ingredients.combine end ---- == Lint/Debugger |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.14 | 0.49 |=== This cop checks for calls to debugger or pry. === Examples [source,ruby] ---- # bad (ok during development) # using pry def some_method binding.pry do_something end ---- [source,ruby] ---- # bad (ok during development) # using byebug def some_method byebug do_something end ---- [source,ruby] ---- # good def some_method do_something end ---- == Lint/DeprecatedClassMethods |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.19 | - |=== This cop checks for uses of the deprecated class method usages. === Examples [source,ruby] ---- # bad File.exists?(some_path) Dir.exists?(some_path) iterator? ---- [source,ruby] ---- # good File.exist?(some_path) Dir.exist?(some_path) block_given? ---- == Lint/DeprecatedOpenSSLConstant |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Pending | Yes | Yes | 0.84 | - |=== Algorithmic constants for `OpenSSL::Cipher` and `OpenSSL::Digest` deprecated since OpenSSL version 2.2.0. Prefer passing a string instead. === Examples [source,ruby] ---- # Example for OpenSSL::Cipher instantiation. # bad OpenSSL::Cipher::AES.new(128, :GCM) # good OpenSSL::Cipher.new('AES-128-GCM') ---- [source,ruby] ---- # Example for OpenSSL::Digest instantiation. # bad OpenSSL::Digest::SHA256.new # good OpenSSL::Digest.new('SHA256') ---- [source,ruby] ---- # Example for ::Digest inherited class methods. # bad OpenSSL::Digest::SHA256.digest('foo') # good OpenSSL::Digest.digest('SHA256', 'foo') ---- == Lint/DisjunctiveAssignmentInConstructor |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | No | No | 0.62 | - |=== This cop checks constructors for disjunctive assignments that should be plain assignments. So far, this cop is only concerned with disjunctive assignment of instance variables. In ruby, an instance variable is nil until a value is assigned, so the disjunction is unnecessary. A plain assignment has the same effect. === Examples [source,ruby] ---- # bad def initialize @x ||= 1 end # good def initialize @x = 1 end ---- == Lint/DuplicateCaseCondition |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.45 | - |=== This cop checks that there are no repeated conditions used in case 'when' expressions. === Examples [source,ruby] ---- # bad case x when 'first' do_something when 'first' do_something_else end ---- [source,ruby] ---- # good case x when 'first' do_something when 'second' do_something_else end ---- == Lint/DuplicateHashKey |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.34 | 0.77 |=== This cop checks for duplicated keys in hash literals. This cop mirrors a warning in Ruby 2.2. === Examples [source,ruby] ---- # bad hash = { food: 'apple', food: 'orange' } ---- [source,ruby] ---- # good hash = { food: 'apple', other_food: 'orange' } ---- == Lint/DuplicateMethods |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.29 | - |=== This cop checks for duplicated instance (or singleton) method definitions. === Examples [source,ruby] ---- # bad def foo 1 end def foo 2 end ---- [source,ruby] ---- # bad def foo 1 end alias foo bar ---- [source,ruby] ---- # good def foo 1 end def bar 2 end ---- [source,ruby] ---- # good def foo 1 end alias bar foo ---- == Lint/EachWithObjectArgument |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.31 | - |=== This cop checks if each_with_object is called with an immutable argument. Since the argument is the object that the given block shall make calls on to build something based on the enumerable that each_with_object iterates over, an immutable argument makes no sense. It's definitely a bug. === Examples [source,ruby] ---- # bad sum = numbers.each_with_object(0) { |e, a| a += e } ---- [source,ruby] ---- # good num = 0 sum = numbers.each_with_object(num) { |e, a| a += e } ---- == Lint/ElseLayout |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.17 | - |=== This cop checks for odd else block layout - like having an expression on the same line as the else keyword, which is usually a mistake. === Examples [source,ruby] ---- # bad if something # ... else do_this do_that end ---- [source,ruby] ---- # good if something # ... else do_this do_that end ---- == Lint/EmptyEnsure |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.10 | 0.48 |=== This cop checks for empty `ensure` blocks === Examples [source,ruby] ---- # bad def some_method do_something ensure end ---- [source,ruby] ---- # bad begin do_something ensure end ---- [source,ruby] ---- # good def some_method do_something ensure do_something_else end ---- [source,ruby] ---- # good begin do_something ensure do_something_else end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AutoCorrect | `false` | Boolean |=== == Lint/EmptyExpression |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.45 | - |=== This cop checks for the presence of empty expressions. === Examples [source,ruby] ---- # bad foo = () if () bar end ---- [source,ruby] ---- # good foo = (some_expression) if (some_expression) bar end ---- == Lint/EmptyInterpolation |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.20 | 0.45 |=== This cop checks for empty interpolation. === Examples [source,ruby] ---- # bad ""result is #{}"" ---- [source,ruby] ---- # good ""result is #{some_result}"" ---- == Lint/EmptyWhen |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.45 | 0.83 |=== This cop checks for the presence of `when` branches without a body. === Examples [source,ruby] ---- # bad case foo when bar do_something when baz end ---- [source,ruby] ---- # good case condition when foo do_something when bar nil end ---- ==== AllowComments: true (default) [source,ruby] ---- # good case condition when foo do_something when bar # noop end ---- ==== AllowComments: false [source,ruby] ---- # bad case condition when foo do_something when bar # do nothing end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowComments | `true` | Boolean |=== == Lint/EnsureReturn |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.9 | 0.83 |=== This cop checks for _return_ from an _ensure_ block. Explicit return from an ensure block alters the control flow as the return will take precedence over any exception being raised, and the exception will be silently thrown away as if it were rescued. === Examples [source,ruby] ---- # bad begin do_something ensure do_something_else return end ---- [source,ruby] ---- # good begin do_something ensure do_something_else end ---- === References * https://rubystyle.guide#no-return-ensure == Lint/ErbNewArguments NOTE: Required Ruby version: 2.6 |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.56 | - |=== This cop emulates the following Ruby warnings in Ruby 2.6. % cat example.rb ERB.new('hi', nil, '-', '@output_buffer') % ruby -rerb example.rb example.rb:1: warning: Passing safe_level with the 2nd argument of ERB.new is deprecated. Do not use it, and specify other arguments as keyword arguments. example.rb:1: warning: Passing trim_mode with the 3rd argument of ERB.new is deprecated. Use keyword argument like ERB.new(str, trim_mode:...) instead. example.rb:1: warning: Passing eoutvar with the 4th argument of ERB.new is deprecated. Use keyword argument like ERB.new(str, eoutvar: ...) instead. Now non-keyword arguments other than first one are softly deprecated and will be removed when Ruby 2.5 becomes EOL. `ERB.new` with non-keyword arguments is deprecated since ERB 2.2.0. Use `:trim_mode` and `:eoutvar` keyword arguments to `ERB.new`. This cop identifies places where `ERB.new(str, trim_mode, eoutvar)` can be replaced by `ERB.new(str, :trim_mode: trim_mode, eoutvar: eoutvar)`. === Examples [source,ruby] ---- # Target codes supports Ruby 2.6 and higher only # bad ERB.new(str, nil, '-', '@output_buffer') # good ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') # Target codes supports Ruby 2.5 and lower only # good ERB.new(str, nil, '-', '@output_buffer') # Target codes supports Ruby 2.6, 2.5 and lower # bad ERB.new(str, nil, '-', '@output_buffer') # good # Ruby standard library style # https://github.com/ruby/ruby/commit/3406c5d if ERB.instance_method(:initialize).parameters.assoc(:key) # Ruby 2.6+ ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') else ERB.new(str, nil, '-', '@output_buffer') end # good # Use `RUBY_VERSION` style if RUBY_VERSION >= '2.6' ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') else ERB.new(str, nil, '-', '@output_buffer') end ---- == Lint/FlipFlop |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.16 | - |=== This cop looks for uses of flip-flop operator. flip-flop operator is deprecated since Ruby 2.6.0. === Examples [source,ruby] ---- # bad (1..20).each do |x| puts x if (x == 5) .. (x == 10) end # good (1..20).each do |x| puts x if (x >= 5) && (x <= 10) end ---- === References * https://rubystyle.guide#no-flip-flops == Lint/FloatOutOfRange |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.36 | - |=== This cop identifies Float literals which are, like, really really really really really really really really big. Too big. No-one needs Floats that big. If you need a float that big, something is wrong with you. === Examples [source,ruby] ---- # bad float = 3.0e400 ---- [source,ruby] ---- # good float = 42.9 ---- == Lint/FormatParameterMismatch |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.33 | - |=== This lint sees if there is a mismatch between the number of expected fields for format/sprintf/#% and what is actually passed as arguments. === Examples [source,ruby] ---- # bad format('A value: %s and another: %i', a_value) ---- [source,ruby] ---- # good format('A value: %s and another: %i', a_value, another) ---- == Lint/HeredocMethodCallPosition |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Disabled | Yes | Yes | 0.68 | - |=== This cop checks for the ordering of a method call where the receiver of the call is a HEREDOC. === Examples [source,ruby] ---- # bad <<-SQL bar SQL .strip_indent <<-SQL bar SQL .strip_indent .trim # good <<~SQL bar SQL <<~SQL.trim bar SQL ---- === References * https://rubystyle.guide#heredoc-method-calls == Lint/ImplicitStringConcatenation |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.36 | - |=== This cop checks for implicit string concatenation of string literals which are on the same line. === Examples [source,ruby] ---- # bad array = ['Item 1' 'Item 2'] ---- [source,ruby] ---- # good array = ['Item 1Item 2'] array = ['Item 1' + 'Item 2'] array = [ 'Item 1' \\ 'Item 2' ] ---- == Lint/IneffectiveAccessModifier |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.36 | - |=== This cop checks for `private` or `protected` access modifiers which are applied to a singleton method. These access modifiers do not make singleton methods private/protected. `private_class_method` can be used for that. === Examples [source,ruby] ---- # bad class C private def self.method puts 'hi' end end ---- [source,ruby] ---- # good class C def self.method puts 'hi' end private_class_method :method end ---- [source,ruby] ---- # good class C class << self private def method puts 'hi' end end end ---- == Lint/InheritException |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.41 | - |=== This cop looks for error classes inheriting from `Exception` and its standard library subclasses, excluding subclasses of `StandardError`. It is configurable to suggest using either `RuntimeError` (default) or `StandardError` instead. === Examples ==== EnforcedStyle: runtime_error (default) [source,ruby] ---- # bad class C < Exception; end C = Class.new(Exception) # good class C < RuntimeError; end C = Class.new(RuntimeError) ---- ==== EnforcedStyle: standard_error [source,ruby] ---- # bad class C < Exception; end C = Class.new(Exception) # good class C < StandardError; end C = Class.new(StandardError) ---- === Configurable attributes |=== | Name | Default value | Configurable values | EnforcedStyle | `runtime_error` | `runtime_error`, `standard_error` |=== == Lint/InterpolationCheck |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.50 | - |=== This cop checks for interpolation in a single quoted string. === Examples [source,ruby] ---- # bad foo = 'something with #{interpolation} inside' ---- [source,ruby] ---- # good foo = ""something with #{interpolation} inside"" ---- == Lint/LiteralAsCondition |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.51 | - |=== This cop checks for literals used as the conditions or as operands in and/or expressions serving as the conditions of if/while/until. === Examples [source,ruby] ---- # bad if 20 do_something end # bad if some_var && true do_something end # good if some_var && some_condition do_something end # good # When using a boolean value for an infinite loop. while true break if condition end ---- == Lint/LiteralInInterpolation |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.19 | 0.32 |=== This cop checks for interpolated literals. === Examples [source,ruby] ---- # bad ""result is #{10}"" ---- [source,ruby] ---- # good ""result is 10"" ---- == Lint/Loop |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | - |=== This cop checks for uses of _begin...end while/until something_. === Examples [source,ruby] ---- # bad # using while begin do_something end while some_condition ---- [source,ruby] ---- # bad # using until begin do_something end until some_condition ---- [source,ruby] ---- # good # while replacement loop do do_something break unless some_condition end ---- [source,ruby] ---- # good # until replacement loop do do_something break if some_condition end ---- === References * https://rubystyle.guide#loop-with-break == Lint/MissingCopEnableDirective |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.52 | - |=== This cop checks that there is an `+# rubocop:enable ...+` statement after a `+# rubocop:disable ...+` statement. This will prevent leaving cop disables on wide ranges of code, that latter contributors to a file wouldn't be aware of. === Examples [source,ruby] ---- # Lint/MissingCopEnableDirective: # MaximumRangeSize: .inf # good # rubocop:disable Layout/SpaceAroundOperators x= 0 # rubocop:enable Layout/SpaceAroundOperators # y = 1 # EOF # bad # rubocop:disable Layout/SpaceAroundOperators x= 0 # EOF ---- [source,ruby] ---- # Lint/MissingCopEnableDirective: # MaximumRangeSize: 2 # good # rubocop:disable Layout/SpaceAroundOperators x= 0 # With the previous, there are 2 lines on which cop is disabled. # rubocop:enable Layout/SpaceAroundOperators # bad # rubocop:disable Layout/SpaceAroundOperators x= 0 x += 1 # Including this, that's 3 lines on which the cop is disabled. # rubocop:enable Layout/SpaceAroundOperators ---- === Configurable attributes |=== | Name | Default value | Configurable values | MaximumRangeSize | `Infinity` | Float |=== == Lint/MultipleComparison |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.47 | 0.77 |=== In math and Python, we can use `x < y < z` style comparison to compare multiple value. However, we can't use the comparison in Ruby. However, the comparison is not syntax error. This cop checks the bad usage of comparison operators. === Examples [source,ruby] ---- # bad x < y < z 10 <= x <= 20 ---- [source,ruby] ---- # good x < y && y < z 10 <= x && x <= 20 ---- == Lint/NestedMethodDefinition |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.32 | - |=== This cop checks for nested method definitions. === Examples [source,ruby] ---- # bad # `bar` definition actually produces methods in the same scope # as the outer `foo` method. Furthermore, the `bar` method # will be redefined every time `foo` is invoked. def foo def bar end end ---- [source,ruby] ---- # good def foo bar = -> { puts 'hello' } bar.call end ---- [source,ruby] ---- # good def foo self.class.class_eval do def bar end end end def foo self.class.module_exec do def bar end end end ---- [source,ruby] ---- # good def foo class << self def bar end end end ---- === References * https://rubystyle.guide#no-nested-methods == Lint/NestedPercentLiteral |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.52 | - |=== This cop checks for nested percent literals. === Examples [source,ruby] ---- # bad # The percent literal for nested_attributes is parsed as four tokens, # yielding the array [:name, :content, :""%i[incorrectly"", :""nested]""]. attributes = { valid_attributes: %i[name content], nested_attributes: %i[name content %i[incorrectly nested]] } ---- == Lint/NextWithoutAccumulator |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.36 | - |=== Don't omit the accumulator when calling `next` in a `reduce` block. === Examples [source,ruby] ---- # bad result = (1..4).reduce(0) do |acc, i| next if i.odd? acc + i end ---- [source,ruby] ---- # good result = (1..4).reduce(0) do |acc, i| next acc if i.odd? acc + i end ---- == Lint/NonDeterministicRequireOrder |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | No | Yes (Unsafe) | 0.78 | - |=== `+Dir[...]+` and `+Dir.glob(...)+` do not make any guarantees about the order in which files are returned. The final order is determined by the operating system and file system. This means that using them in cases where the order matters, such as requiring files, can lead to intermittent failures that are hard to debug. To ensure this doesn't happen, always sort the list. === Examples [source,ruby] ---- # bad Dir[""./lib/**/*.rb""].each do |file| require file end # good Dir[""./lib/**/*.rb""].sort.each do |file| require file end ---- [source,ruby] ---- # bad Dir.glob(Rails.root.join(__dir__, 'test', '*.rb')) do |file| require file end # good Dir.glob(Rails.root.join(__dir__, 'test', '*.rb')).sort.each do |file| require file end ---- == Lint/NonLocalExitFromIterator |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.30 | - |=== This cop checks for non-local exits from iterators without a return value. It registers an offense under these conditions: * No value is returned, * the block is preceded by a method chain, * the block has arguments, * the method which receives the block is not `define_method` or `define_singleton_method`, * the return is not contained in an inner scope, e.g. a lambda or a method definition. === Examples [source,ruby] ---- class ItemApi rescue_from ValidationError do |e| # non-iteration block with arg return { message: 'validation error' } unless e.errors # allowed error_array = e.errors.map do |error| # block with method chain return if error.suppress? # warned return ""#{error.param}: invalid"" unless error.message # allowed ""#{error.param}: #{error.message}"" end { message: 'validation error', errors: error_array } end def update_items transaction do # block without arguments return unless update_necessary? # allowed find_each do |item| # block without method chain return if item.stock == 0 # false-negative... item.update!(foobar: true) end end end end ---- == Lint/NumberConversion |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Disabled | Yes | Yes (Unsafe) | 0.53 | 0.70 |=== This cop warns the usage of unsafe number conversions. Unsafe number conversion can cause unexpected error if auto type conversion fails. Cop prefer parsing with number class instead. === Examples [source,ruby] ---- # bad '10'.to_i '10.2'.to_f '10'.to_c # good Integer('10', 10) Float('10.2') Complex('10') ---- == Lint/OrderedMagicComments |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.53 | - |=== Checks the proper ordering of magic comments and whether a magic comment is not placed before a shebang. === Examples [source,ruby] ---- # bad # frozen_string_literal: true # encoding: ascii p [''.frozen?, ''.encoding] #=> [true, #] # good # encoding: ascii # frozen_string_literal: true p [''.frozen?, ''.encoding] #=> [true, #] # good #!/usr/bin/env ruby # encoding: ascii # frozen_string_literal: true p [''.frozen?, ''.encoding] #=> [true, #] ---- == Lint/ParenthesesAsGroupedExpression |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.12 | 0.83 |=== Checks for space between the name of a called method and a left parenthesis. === Examples [source,ruby] ---- # bad do_something (foo) # good do_something(foo) do_something (2 + 3) * 4 do_something (foo * bar).baz ---- === References * https://rubystyle.guide#parens-no-spaces == Lint/PercentStringArray |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | No | Yes (Unsafe) | 0.41 | - |=== This cop checks for quotes and commas in %w, e.g. `%w('foo', ""bar"")` It is more likely that the additional characters are unintended (for example, mistranslating an array of literals to percent string notation) rather than meant to be part of the resulting strings. === Examples [source,ruby] ---- # bad %w('foo', ""bar"") ---- [source,ruby] ---- # good %w(foo bar) ---- == Lint/PercentSymbolArray |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.41 | - |=== This cop checks for colons and commas in %i, e.g. `%i(:foo, :bar)` It is more likely that the additional characters are unintended (for example, mistranslating an array of literals to percent string notation) rather than meant to be part of the resulting symbols. === Examples [source,ruby] ---- # bad %i(:foo, :bar) ---- [source,ruby] ---- # good %i(foo bar) ---- == Lint/RaiseException |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Pending | Yes | No | 0.81 | - |=== This cop checks for `raise` or `fail` statements which are raising `Exception` class. You can specify a module name that will be an implicit namespace using `AllowedImplicitNamespaces` option. The cop cause a false positive for namespaced `Exception` when a namespace is omitted. This option can prevent the false positive by specifying a namespace to be omitted for `Exception`. Alternatively, make `Exception` a fully qualified class name with an explicit namespace. === Examples [source,ruby] ---- # bad raise Exception, 'Error message here' # good raise StandardError, 'Error message here' ---- ==== AllowedImplicitNamespaces: ['Gem'] [source,ruby] ---- # good module Gem def self.foo raise Exception # This exception means `Gem::Exception`. end end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowedImplicitNamespaces | `Gem` | Array |=== === References * https://rubystyle.guide#raise-exception == Lint/RandOne |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.36 | - |=== This cop checks for `rand(1)` calls. Such calls always return `0`. === Examples [source,ruby] ---- # bad rand 1 Kernel.rand(-1) rand 1.0 rand(-1.0) ---- [source,ruby] ---- # good 0 # just use 0 instead ---- == Lint/RedundantCopDisableDirective |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.76 | - |=== This cop detects instances of rubocop:disable comments that can be removed without causing any offenses to be reported. It's implemented as a cop in that it inherits from the Cop base class and calls add_offense. The unusual part of its implementation is that it doesn't have any on_* methods or an investigate method. This means that it doesn't take part in the investigation phase when the other cops do their work. Instead, it waits until it's called in a later stage of the execution. The reason it can't be implemented as a normal cop is that it depends on the results of all other cops to do its work. === Examples [source,ruby] ---- # bad # rubocop:disable Layout/LineLength x += 1 # rubocop:enable Layout/LineLength # good x += 1 ---- == Lint/RedundantCopEnableDirective |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.76 | - |=== This cop detects instances of rubocop:enable comments that can be removed. When comment enables all cops at once `rubocop:enable all` that cop checks whether any cop was actually enabled. === Examples [source,ruby] ---- # bad foo = 1 # rubocop:enable Layout/LineLength # good foo = 1 ---- [source,ruby] ---- # bad # rubocop:disable Style/StringLiterals foo = ""1"" # rubocop:enable Style/StringLiterals baz # rubocop:enable all # good # rubocop:disable Style/StringLiterals foo = ""1"" # rubocop:enable all baz ---- == Lint/RedundantRequireStatement |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.76 | - |=== Checks for unnecessary `require` statement. The following features are unnecessary `require` statement because they are already loaded. ruby -ve 'p $LOADED_FEATURES.reject { |feature| %r|/| =~ feature }' ruby 2.2.8p477 (2017-09-14 revision 59906) [x86_64-darwin13] [""enumerator.so"", ""rational.so"", ""complex.so"", ""thread.rb""] This cop targets Ruby 2.2 or higher containing these 4 features. === Examples [source,ruby] ---- # bad require 'unloaded_feature' require 'thread' # good require 'unloaded_feature' ---- == Lint/RedundantSplatExpansion |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.76 | - |=== This cop checks for unneeded usages of splat expansion === Examples [source,ruby] ---- # bad a = *[1, 2, 3] a = *'a' a = *1 begin foo rescue *[StandardError, ApplicationError] bar end case foo when *[1, 2, 3] bar else baz end ---- [source,ruby] ---- # good c = [1, 2, 3] a = *c a, b = *c a, *b = *c a = *1..10 a = ['a'] begin foo rescue StandardError, ApplicationError bar end case foo when 1, 2, 3 bar else baz end ---- == Lint/RedundantStringCoercion |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.19 | 0.77 |=== This cop checks for string conversion in string interpolation, which is redundant. === Examples [source,ruby] ---- # bad ""result is #{something.to_s}"" ---- [source,ruby] ---- # good ""result is #{something}"" ---- === References * https://rubystyle.guide#no-to-s == Lint/RedundantWithIndex |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.50 | - |=== This cop checks for redundant `with_index`. === Examples [source,ruby] ---- # bad ary.each_with_index do |v| v end # good ary.each do |v| v end # bad ary.each.with_index do |v| v end # good ary.each do |v| v end ---- == Lint/RedundantWithObject |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.51 | - |=== This cop checks for redundant `with_object`. === Examples [source,ruby] ---- # bad ary.each_with_object([]) do |v| v end # good ary.each do |v| v end # bad ary.each.with_object([]) do |v| v end # good ary.each do |v| v end ---- == Lint/RegexpAsCondition |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.51 | - |=== This cop checks for regexp literals used as `match-current-line`. If a regexp literal is in condition, the regexp matches `$_` implicitly. === Examples [source,ruby] ---- # bad if /foo/ do_something end # good if /foo/ =~ $_ do_something end ---- == Lint/RequireParentheses |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.18 | - |=== This cop checks for expressions where there is a call to a predicate method with at least one argument, where no parentheses are used around the parameter list, and a boolean operator, && or ||, is used in the last argument. The idea behind warning for these constructs is that the user might be under the impression that the return value from the method call is an operand of &&/||. === Examples [source,ruby] ---- # bad if day.is? :tuesday && month == :jan # ... end ---- [source,ruby] ---- # good if day.is?(:tuesday) && month == :jan # ... end ---- == Lint/RescueException |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | 0.27.1 |=== This cop checks for _rescue_ blocks targeting the Exception class. === Examples [source,ruby] ---- # bad begin do_something rescue Exception handle_exception end ---- [source,ruby] ---- # good begin do_something rescue ArgumentError handle_exception end ---- === References * https://rubystyle.guide#no-blind-rescues == Lint/RescueType |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.49 | - |=== Check for arguments to `rescue` that will result in a `TypeError` if an exception is raised. === Examples [source,ruby] ---- # bad begin bar rescue nil baz end # bad def foo bar rescue 1, 'a', ""#{b}"", 0.0, [], {} baz end # good begin bar rescue baz end # good def foo bar rescue NameError baz end ---- == Lint/ReturnInVoidContext |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.50 | - |=== This cop checks for the use of a return with a value in a context where the value will be ignored. (initialize and setter methods) === Examples [source,ruby] ---- # bad def initialize foo return :qux if bar? baz end def foo=(bar) return 42 end ---- [source,ruby] ---- # good def initialize foo return if bar? baz end def foo=(bar) return end ---- == Lint/SafeNavigationChain |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.47 | 0.77 |=== The safe navigation operator returns nil if the receiver is nil. If you chain an ordinary method call after a safe navigation operator, it raises NoMethodError. We should use a safe navigation operator after a safe navigation operator. This cop checks for the problem outlined above. === Examples [source,ruby] ---- # bad x&.foo.bar x&.foo + bar x&.foo[bar] ---- [source,ruby] ---- # good x&.foo&.bar x&.foo || bar ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowedMethods | `present?`, `blank?`, `presence`, `try`, `try!` | Array |=== == Lint/SafeNavigationConsistency |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.55 | 0.77 |=== This cop check to make sure that if safe navigation is used for a method call in an `&&` or `||` condition that safe navigation is used for all method calls on that same object. === Examples [source,ruby] ---- # bad foo&.bar && foo.baz # bad foo.bar || foo&.baz # bad foo&.bar && (foobar.baz || foo.baz) # good foo.bar && foo.baz # good foo&.bar || foo&.baz # good foo&.bar && (foobar.baz || foo&.baz) ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowedMethods | `present?`, `blank?`, `presence`, `try`, `try!` | Array |=== == Lint/SafeNavigationWithEmpty |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.62 | - |=== This cop checks to make sure safe navigation isn't used with `empty?` in a conditional. While the safe navigation operator is generally a good idea, when checking `foo&.empty?` in a conditional, `foo` being `nil` will actually do the opposite of what the author intends. === Examples [source,ruby] ---- # bad return if foo&.empty? return unless foo&.empty? # good return if foo && foo.empty? return unless foo && foo.empty? ---- == Lint/ScriptPermission |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.49 | 0.50 |=== This cop checks if a file which has a shebang line as its first line is granted execute permission. === Examples [source,ruby] ---- # bad # A file which has a shebang line as its first line is not # granted execute permission. #!/usr/bin/env ruby puts 'hello, world' # good # A file which has a shebang line as its first line is # granted execute permission. #!/usr/bin/env ruby puts 'hello, world' # good # A file which has not a shebang line as its first line is not # granted execute permission. puts 'hello, world' ---- == Lint/SendWithMixinArgument |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.75 | - |=== This cop checks for `send`, `public_send`, and `__send__` methods when using mix-in. `include` and `prepend` methods were private methods until Ruby 2.0, they were mixed-in via `send` method. This cop uses Ruby 2.1 or higher style that can be called by public methods. And `extend` method that was originally a public method is also targeted for style unification. === Examples [source,ruby] ---- # bad Foo.send(:include, Bar) Foo.send(:prepend, Bar) Foo.send(:extend, Bar) # bad Foo.public_send(:include, Bar) Foo.public_send(:prepend, Bar) Foo.public_send(:extend, Bar) # bad Foo.__send__(:include, Bar) Foo.__send__(:prepend, Bar) Foo.__send__(:extend, Bar) # good Foo.include Bar Foo.prepend Bar Foo.extend Bar ---- == Lint/ShadowedArgument |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.52 | - |=== This cop checks for shadowed arguments. This cop has `IgnoreImplicitReferences` configuration option. It means argument shadowing is used in order to pass parameters to zero arity `super` when `IgnoreImplicitReferences` is `true`. === Examples [source,ruby] ---- # bad do_something do |foo| foo = 42 puts foo end def do_something(foo) foo = 42 puts foo end # good do_something do |foo| foo = foo + 42 puts foo end def do_something(foo) foo = foo + 42 puts foo end def do_something(foo) puts foo end ---- ==== IgnoreImplicitReferences: false (default) [source,ruby] ---- # bad def do_something(foo) foo = 42 super end def do_something(foo) foo = super bar end ---- ==== IgnoreImplicitReferences: true [source,ruby] ---- # good def do_something(foo) foo = 42 super end def do_something(foo) foo = super bar end ---- === Configurable attributes |=== | Name | Default value | Configurable values | IgnoreImplicitReferences | `false` | Boolean |=== == Lint/ShadowedException |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.41 | - |=== This cop checks for a rescued exception that get shadowed by a less specific exception being rescued before a more specific exception is rescued. === Examples [source,ruby] ---- # bad begin something rescue Exception handle_exception rescue StandardError handle_standard_error end # good begin something rescue StandardError handle_standard_error rescue Exception handle_exception end # good, however depending on runtime environment. # # This is a special case for system call errors. # System dependent error code depends on runtime environment. # For example, whether `Errno::EAGAIN` and `Errno::EWOULDBLOCK` are # the same error code or different error code depends on environment. # This good case is for `Errno::EAGAIN` and `Errno::EWOULDBLOCK` with # the same error code. begin something rescue Errno::EAGAIN, Errno::EWOULDBLOCK handle_standard_error end ---- == Lint/ShadowingOuterLocalVariable |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | - |=== This cop looks for use of the same name as outer local variables for block arguments or block local variables. This is a mimic of the warning ""shadowing outer local variable - foo"" from `ruby -cw`. === Examples [source,ruby] ---- # bad def some_method foo = 1 2.times do |foo| # shadowing outer `foo` do_something(foo) end end ---- [source,ruby] ---- # good def some_method foo = 1 2.times do |bar| do_something(bar) end end ---- == Lint/StructNewOverride |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Pending | Yes | No | 0.81 | - |=== This cop checks unexpected overrides of the `Struct` built-in methods via `Struct.new`. === Examples [source,ruby] ---- # bad Bad = Struct.new(:members, :clone, :count) b = Bad.new([], true, 1) b.members #=> [] (overriding `Struct#members`) b.clone #=> true (overriding `Object#clone`) b.count #=> 1 (overriding `Enumerable#count`) # good Good = Struct.new(:id, :name) g = Good.new(1, ""foo"") g.members #=> [:id, :name] g.clone #=> # g.count #=> 2 ---- == Lint/SuppressedException |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | 0.81 |=== This cop checks for _rescue_ blocks with no body. === Examples [source,ruby] ---- # bad def some_method do_something rescue end # bad begin do_something rescue end # good def some_method do_something rescue handle_exception end # good begin do_something rescue handle_exception end ---- ==== AllowComments: true (default) [source,ruby] ---- # good def some_method do_something rescue # do nothing end # good begin do_something rescue # do nothing end ---- ==== AllowComments: false [source,ruby] ---- # bad def some_method do_something rescue # do nothing end # bad begin do_something rescue # do nothing end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowComments | `true` | Boolean |=== === References * https://rubystyle.guide#dont-hide-exceptions == Lint/Syntax |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | - |=== This is not actually a cop. It does not inspect anything. It just provides methods to repack Parser's diagnostics/errors into RuboCop's offenses. == Lint/ToJSON |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.66 | - |=== This cop checks to make sure `#to_json` includes an optional argument. When overriding `#to_json`, callers may invoke JSON generation via `JSON.generate(your_obj)`. Since `JSON#generate` allows for an optional argument, your method should too. === Examples [source,ruby] ---- # bad def to_json end # good def to_json(*_args) end ---- == Lint/UnderscorePrefixedVariableName |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.21 | - |=== This cop checks for underscore-prefixed variables that are actually used. Since block keyword arguments cannot be arbitrarily named at call sites, the `AllowKeywordBlockArguments` will allow use of underscore- prefixed block keyword arguments. === Examples ==== AllowKeywordBlockArguments: false (default) [source,ruby] ---- # bad [1, 2, 3].each do |_num| do_something(_num) end query(:sales) do |_id:, revenue:, cost:| {_id: _id, profit: revenue - cost} end # good [1, 2, 3].each do |num| do_something(num) end [1, 2, 3].each do |_num| do_something # not using `_num` end ---- ==== AllowKeywordBlockArguments: true [source,ruby] ---- # good query(:sales) do |_id:, revenue:, cost:| {_id: _id, profit: revenue - cost} end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowKeywordBlockArguments | `false` | Boolean |=== == Lint/UnifiedInteger |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.43 | - |=== This cop checks for using Fixnum or Bignum constant. === Examples [source,ruby] ---- # bad 1.is_a?(Fixnum) 1.is_a?(Bignum) ---- [source,ruby] ---- # good 1.is_a?(Integer) ---- == Lint/UnreachableCode |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | - |=== This cop checks for unreachable code. The check are based on the presence of flow of control statement in non-final position in _begin_(implicit) blocks. === Examples [source,ruby] ---- # bad def some_method return do_something end # bad def some_method if cond return else return end do_something end ---- [source,ruby] ---- # good def some_method do_something end ---- == Lint/UnusedBlockArgument |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.21 | 0.22 |=== This cop checks for unused block arguments. === Examples [source,ruby] ---- # bad do_something do |used, unused| puts used end do_something do |bar| puts :foo end define_method(:foo) do |bar| puts :baz end # good do_something do |used, _unused| puts used end do_something do puts :foo end define_method(:foo) do |_bar| puts :baz end ---- ==== IgnoreEmptyBlocks: true (default) [source,ruby] ---- # good do_something { |unused| } ---- ==== IgnoreEmptyBlocks: false [source,ruby] ---- # bad do_something { |unused| } ---- ==== AllowUnusedKeywordArguments: false (default) [source,ruby] ---- # bad do_something do |unused: 42| foo end ---- ==== AllowUnusedKeywordArguments: true [source,ruby] ---- # good do_something do |unused: 42| foo end ---- === Configurable attributes |=== | Name | Default value | Configurable values | IgnoreEmptyBlocks | `true` | Boolean | AllowUnusedKeywordArguments | `false` | Boolean |=== === References * https://rubystyle.guide#underscore-unused-vars == Lint/UnusedMethodArgument |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.21 | 0.81 |=== This cop checks for unused method arguments. === Examples [source,ruby] ---- # bad def some_method(used, unused, _unused_but_allowed) puts used end # good def some_method(used, _unused, _unused_but_allowed) puts used end ---- ==== AllowUnusedKeywordArguments: false (default) [source,ruby] ---- # bad def do_something(used, unused: 42) used end ---- ==== AllowUnusedKeywordArguments: true [source,ruby] ---- # good def do_something(used, unused: 42) used end ---- ==== IgnoreEmptyMethods: true (default) [source,ruby] ---- # good def do_something(unused) end ---- ==== IgnoreEmptyMethods: false [source,ruby] ---- # bad def do_something(unused) end ---- ==== IgnoreNotImplementedMethods: true (default) [source,ruby] ---- # good def do_something(unused) raise NotImplementedError end def do_something_else(unused) fail ""TODO"" end ---- ==== IgnoreNotImplementedMethods: false [source,ruby] ---- # bad def do_something(unused) raise NotImplementedError end def do_something_else(unused) fail ""TODO"" end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowUnusedKeywordArguments | `false` | Boolean | IgnoreEmptyMethods | `true` | Boolean | IgnoreNotImplementedMethods | `true` | Boolean |=== === References * https://rubystyle.guide#underscore-unused-vars == Lint/UriEscapeUnescape |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.50 | - |=== This cop identifies places where `URI.escape` can be replaced by `CGI.escape`, `URI.encode_www_form`, or `URI.encode_www_form_component` depending on your specific use case. Also this cop identifies places where `URI.unescape` can be replaced by `CGI.unescape`, `URI.decode_www_form`, or `URI.decode_www_form_component` depending on your specific use case. === Examples [source,ruby] ---- # bad URI.escape('http://example.com') URI.encode('http://example.com') # good CGI.escape('http://example.com') URI.encode_www_form([['example', 'param'], ['lang', 'en']]) URI.encode_www_form(page: 10, locale: 'en') URI.encode_www_form_component('http://example.com') # bad URI.unescape(enc_uri) URI.decode(enc_uri) # good CGI.unescape(enc_uri) URI.decode_www_form(enc_uri) URI.decode_www_form_component(enc_uri) ---- == Lint/UriRegexp |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.50 | - |=== This cop identifies places where `URI.regexp` is obsolete and should not be used. Instead, use `URI::DEFAULT_PARSER.make_regexp`. === Examples [source,ruby] ---- # bad URI.regexp('http://example.com') # good URI::DEFAULT_PARSER.make_regexp('http://example.com') ---- == Lint/UselessAccessModifier |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.20 | 0.83 |=== This cop checks for redundant access modifiers, including those with no code, those which are repeated, and leading `public` modifiers in a class or module body. Conditionally-defined methods are considered as always being defined, and thus access modifiers guarding such methods are not redundant. This cop has `ContextCreatingMethods` option. The default setting value is an empty array that means no method is specified. This setting is an array of methods which, when called, are known to create its own context in the module's current access context. It also has `MethodCreatingMethods` option. The default setting value is an empty array that means no method is specified. This setting is an array of methods which, when called, are known to create other methods in the module's current access context. === Examples [source,ruby] ---- # bad class Foo public # this is redundant (default access is public) def method end end # bad class Foo # The following is redundant (methods defined on the class' # singleton class are not affected by the public modifier) public def self.method3 end end # bad class Foo protected define_method(:method2) do end protected # this is redundant (repeated from previous modifier) [1,2,3].each do |i| define_method(""foo#{i}"") do end end end # bad class Foo private # this is redundant (no following methods are defined) end # good class Foo private # this is not redundant (a method is defined) def method2 end end # good class Foo # The following is not redundant (conditionally defined methods are # considered as always defining a method) private if condition? def method end end end # good class Foo protected # this is not redundant (a method is defined) define_method(:method2) do end end ---- ==== ContextCreatingMethods: concerning [source,ruby] ---- # Lint/UselessAccessModifier: # ContextCreatingMethods: # - concerning # good require 'active_support/concern' class Foo concerning :Bar do def some_public_method end private def some_private_method end end # this is not redundant because `concerning` created its own context private def some_other_private_method end end ---- ==== MethodCreatingMethods: delegate [source,ruby] ---- # Lint/UselessAccessModifier: # MethodCreatingMethods: # - delegate # good require 'active_support/core_ext/module/delegation' class Foo # this is not redundant because `delegate` creates methods private delegate :method_a, to: :method_b end ---- === Configurable attributes |=== | Name | Default value | Configurable values | ContextCreatingMethods | `[]` | Array | MethodCreatingMethods | `[]` | Array |=== == Lint/UselessAssignment |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.11 | - |=== This cop checks for every useless assignment to local variable in every scope. The basic idea for this cop was from the warning of `ruby -cw`: assigned but unused variable - foo Currently this cop has advanced logic that detects unreferenced reassignments and properly handles varied cases such as branch, loop, rescue, ensure, etc. === Examples [source,ruby] ---- # bad def some_method some_var = 1 do_something end ---- [source,ruby] ---- # good def some_method some_var = 1 do_something(some_var) end ---- === References * https://rubystyle.guide#underscore-unused-vars == Lint/UselessComparison |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.11 | - |=== This cop checks for comparison of something with itself. === Examples [source,ruby] ---- # bad x.top >= x.top ---- == Lint/UselessElseWithoutRescue |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.17 | - |=== This cop checks for useless `else` in `begin..end` without `rescue`. NOTE: This syntax is no longer valid on Ruby 2.6 or higher and this cop is going to be removed at some point the future. === Examples [source,ruby] ---- # bad begin do_something else do_something_else # This will never be run. end ---- [source,ruby] ---- # good begin do_something rescue handle_errors else do_something_else end ---- == Lint/UselessSetterCall |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | No | No | 0.13 | 0.80 |=== This cop checks for setter call to local variable as the final expression of a function definition. NOTE: There are edge cases in which the local variable references a value that is also accessible outside the local scope. This is not detected by the cop, and it can yield a false positive. === Examples [source,ruby] ---- # bad def something x = Something.new x.attr = 5 end ---- [source,ruby] ---- # good def something x = Something.new x.attr = 5 x end ---- == Lint/Void |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | - |=== This cop checks for operators, variables, literals, and nonmutating methods used in void context. === Examples ==== CheckForMethodsWithNoSideEffects: false (default) [source,ruby] ---- # bad def some_method some_num * 10 do_something end def some_method(some_var) some_var do_something end ---- ==== CheckForMethodsWithNoSideEffects: true [source,ruby] ---- # bad def some_method(some_array) some_array.sort do_something(some_array) end # good def some_method do_something some_num * 10 end def some_method(some_var) do_something some_var end def some_method(some_array) some_array.sort! do_something(some_array) end ---- === Configurable attributes |=== | Name | Default value | Configurable values | CheckForMethodsWithNoSideEffects | `false` | Boolean |=== ",16381,True,3834.072201402041,median "void generateRandomMessageLocation(string [int] random_messages) { if (__last_adventure_location == $location[none]) return; string message = """"; switch (__last_adventure_location) { case $location[the penultimate fantasy airship]: message = ""insert disc 2 to continue""; break; case $location[a-boo peak]: message = ""allons-y!""; break; case $location[twin peak]: message = ""fire walk with me""; break; case $location[The Arrrboretum]: message = ""save the planet""; break; case $location[the red queen's garden]: message = ""curiouser and curiouser""; break; case $location[A Massive Ziggurat]: message = ""1.21 ziggurats""; break; case $location[McMillicancuddy's Barn]: message = ""dooks""; break; case $location[The Roman Forum]: message = ""they go the house""; break; case $location[the battlefield (hippy uniform)]: message = ""love and war""; break; case $location[the middle chamber]: message = ""pyramid laundry machine""; break; case $location[the arid, extra-dry desert]: message = ""can't remember your name""; break; case $location[outside the club]: message = ""around the world around the world around the world around the world""; break; case $location[the hidden temple]: message = ""beware of temple guards""; break; case $location[sonar]: message = ""one ping only""; break; case $location[galley]: message = ""hungry?""; break; case $location[science lab]: message = ""poetry in motion""; break; case $location[fear man's level]: case $location[doubt man's level]: case $location[regret man's level]: case $location[anger man's level]: message = ""this isn't me""; break; case $location[domed city of ronaldus]: case $location[domed city of grimacia]: case $location[hamburglaris shield generator]: message = ""spaaaace!""; break; case $location[The Mansion of Dr. Weirdeaux]: case $location[The Deep Dark Jungle]: case $location[The Secret Government Laboratory]: message = ""they know where you live, "" + get_property(""System.user.name"").to_lower_case(); break; case $location[The castle in the clouds in the sky (ground floor)]: case $location[The castle in the clouds in the sky (basement)]: case $location[The castle in the clouds in the sky (top floor)]: if (my_class() == $class[disco bandit]) message = ""making castles of your disco""; break; case $location[The Prince's Restroom]: case $location[The Prince's Dance Floor]: case $location[The Prince's Kitchen]: case $location[The Prince's Balcony]: case $location[The Prince's Lounge]: case $location[The Prince's Canapes table]: message = ""social sabotage""; break; case $location[anemone mine (mining)]: case $location[itznotyerzitz mine (in disguise)]: case $location[the knob shaft (mining)]: case $location[The Crimbonium Mine]: case $location[The Velvet / Gold Mine (Mining)]: message = ""street sneaky pete don't you call me cause I can't go""; break; case lookupLocation(""Through the Spacegate""): message = ""oh look! rocks!""; case $location[hell]: message = ""that's a clean burning hell, I'll tell you what""; break; } if (message != """") random_messages.listAppend(message); } void generateRandomMessageFamiliar(string [int] random_messages) { string lowercase_player_name = my_name().to_lower_case().HTMLEscapeString(); if (my_familiar() == $familiar[none]) return; string message = """"; switch (my_familiar()) { case $familiar[none]: message = ""even introverts need friends""; break; case $familiar[crimbo shrub]: if (format_today_to_string(""MM"") == ""07"") message = ""crimbo in july""; break; case $familiar[black cat]: message = ""aww, cute kitty!""; break; case $familiar[temporal riftlet]: message = ""master of time and space""; break; case $familiar[Frumious Bandersnatch]: message = ""frabjous""; break; case $familiar[Pair of Stomping Boots]: if (__misc_state[""free runs usable""]) message = ""running away again?""; break; case $familiar[baby sandworm]: message = ""the waters of life""; break; case $familiar[baby bugged bugbear]: message = ""expected }, found }̋̑̀̆͊̑̔͏̱̩̠̰ ̣̻͊ͅf̝͎̰̥̙ͣͦͥ̎,̜̘̖ͭ͋ ̲͉̮̭̪̣͌͋ͤ̉͗ͪ̄̕;̹̼̋̈͛͊ ̧͔̥̤「͙̺̻͖̯͛̀̓̏͑̀l͍̍̍̍͑i̖̖͙͂ͪͮ̍ ̓͑̉̀̆҉̠̜͚̜̹1̶͔̩̬̦̦͍ͥ7͛҉̬̯͇̻͖͉1̆̑̂͒̓」̧̼̜̹̘͕͆̾́͆͐ͯͧ""; //causes severe rendering slowdown; working as intended break; case $familiar[mechanical songbird]: message = ""a little glowing friend""; break; case $familiar[nanorhino]: message = ""write every day""; break; case $familiar[rogue program]: message = ""ascends for the users""; break; case $familiar[O.A.F.]: message = ""helping""; break; case $familiar[Bank Piggy]: case $familiar[Egg Benedict]: case $familiar[Floating Eye]: case $familiar[Money-Making Goblin]: case $familiar[Oyster Bunny]: case $familiar[Plastic Grocery Bag]: case $familiar[Snowhitman]: case $familiar[Vampire Bat]: case $familiar[Worm Doctor]: message = ""hacker""; break; case $familiar[adorable space buddy]: message = ""far beyond the stars""; break; case $familiar[happy medium]: message = ""karma slave""; //what mistakes could I have made? break; case $familiar[wild hare]: message = ""or you wouldn't have come here""; //you must be mad break; case $familiar[artistic goth kid]: message = ""life is pain, "" + lowercase_player_name; break; case $familiar[angry jung man]: message = ""personal trauma""; break; case $familiar[unconscious collective]: message = ""zzz""; break; case $familiar[dataspider]: message = ""spiders are your friends""; break; case $familiar[stocking mimic]: message = ""delicious candy""; break; case $familiar[cocoabo]: message = ""flightless bird""; break; case $familiar[whirling maple leaf]: message = ""canadian pride""; break; case $familiar[Hippo Ballerina]: message = ""spin spin spin""; break; case $familiar[Mutant Cactus Bud]: message = ""always watching""; break; case $familiar[ghuol whelp]: message = ""¯\\\\_(ツ)_/¯""; //¯\\_(ツ)_/¯ break; case $familiar[bulky buddy box]: message = ""♥︎""; //♥︎ break; case $familiar[emo squid]: message = ""sob""; break; case $familiar[fancypants scarecrow]: message = ""the best in terms of pants""; break; case $familiar[jumpsuited hound dog]: message = ""a little less conversation""; break; case $familiar[Gluttonous Green Ghost]: message = ""I think he can hear you, "" + lowercase_player_name; break; case $familiar[hand turkey]: message = ""a rare bird""; break; case $familiar[reanimated reanimator]: message = ""weird science""; break; case $familiar[Twitching Space Critter]: message = ""right right right right down right agh""; break; case $familiar[slimeling]: message = ""lost mother""; break; case $familiar[Puck Man]: case $familiar[Ms. Puck Man]: message = ""ᗧ • • • • • • • • •""; break; case $familiar[Lil' Barrel Mimic]: message = "":D""; break; case $familiar[pet rock]: message = ""what if the rock's eyebrow froze that way. would anyone notice?""; break; case $familiar[space jellyfish]: message = ""deer force""; if (__quest_state[""Level 13""].state_boolean[""king waiting to be freed""]) { int obtained = 0; int obtainable = 0; foreach it in $items[] { if (it.quest) continue; //these disappear if (it.item_amount_almost_everywhere() > 0) obtained += 1; obtainable += 1; } float rate = to_float(obtained) / to_float(obtainable); random_messages.listClear(); message = ""SEE YOU NEXT MISSION
your rate for collecting items is "" + to_int(rate * 100) + ""%""; } else if (my_level() == 1 || my_turncount() <= 2) { random_messages.listClear(); message = ""the last jellyfish is in captivity
the kingdom is at peace""; } break; case $familiar[bad vibe]: message = ""it's all your fault""; break; } if (message != """") random_messages.listAppend(message); } string generateRandomMessage() { string [int] random_messages; int current_hour = now_to_string(""HH"").to_int_silent(); int current_minute = now_to_string(""mm"").to_int_silent(); int minute_of_day = current_hour * 60 + current_minute; if (!playerIsLoggedIn()) return ""the kingdom awaits""; if (__misc_state[""In valhalla""]) return ""rebirth""; if (__misc_state[""in run""]) { if (my_turncount() > 1000 && !in_bad_moon()) random_messages.listAppend(""so many turns""); if (false) random_messages.listAppend(""you are ascending perfectly, excellent work!""); else if (my_daycount() >= 365) random_messages.listAppend(""no king, forever""); else if (my_daycount() >= 11) random_messages.listAppend(""does the king even exist...?""); else if (my_turncount() > 500 && my_daycount() == 1) random_messages.listAppend(""you are ascending too... wait, what?""); else if (gameday_to_int() == 7) random_messages.listAppend(""you are ascending at a reasonable pace, could do better""); else random_messages.listAppend(""you are ascending too slowly, ascend faster!""); string what_does_the_spreadsheet_say = ""saves a turn""; if (my_path_id() == PATH_ONE_CRAZY_RANDOM_SUMMER) what_does_the_spreadsheet_say = ""gives +fun""; if ($item[optimal spreadsheet].equipped_amount() > 0) random_messages.listAppend(""every spreadsheet you wear "" + what_does_the_spreadsheet_say); //sure, why not? else random_messages.listAppend(""every spreadsheet you make "" + what_does_the_spreadsheet_say); } string [string] holiday_messages; holiday_messages[""Groundhog Day""] = ""it's cold out there every day""; holiday_messages[""Crimbo""] = ""merry crimbo""; if ($item[tommy gun].equipped_amount() > 0) //I believe ya, but my tommy gun don't! holiday_messages[""Crimbo""] = ""merry crimbo, ya filthy animal""; holiday_messages[""April Fool's Day""] = ""you are ascending too quickly, ascend slower!""; holiday_messages[""Valentine's Day""] = HTMLGenerateSpanFont(""♥︎"", ""pink"", ""3.0em""); holiday_messages[""Towel Day""] = ""don't panic""; boolean [string] holidays_today = getHolidaysToday(); foreach holiday in holidays_today { if (holiday_messages contains holiday) { random_messages.listAppend(holiday_messages[holiday]); } } if ($item[The One Mood Ring].equipped_amount() > 0 || $item[mood ring].equipped_amount() > 0) { string [int] moods = split_string(""grateful,awake,accomplished,disappointed,enraged,tired,exhausted,amused,crushed,peaceful,energetic,listless,hyper,jubilant,hungry,sad,bewildered,alone,quixotic,recumbent,bored,excited,relaxed,lonely,curious,guilty,jealous,cheerful,depressed,stressed,infuriated,pleased,crappy,aggravated,okay,rejuvenated,apathetic,bittersweet,optimistic,exanimate,complacent,devious,rejected,blissful,discontent,sympathetic,mellow,refreshed,ecstatic,lazy,morose,dark,mischievous,bouncy,thankful,melancholy,content,drained,numb,uncomfortable,indifferent,groggy,calm,irate,determined,giggly,good,confused,anxious,relieved,mad,accepted,happy,angry,lethargic,shocked,indescribable,satisfied,gloomy,irritated,pessimistic,rushed,frustrated,surprised,annoyed,sleepy,touched,enthralled,cynical,envious,hopeful,ashamed,chipper,loved,giddy,restless"", "",""); string mood_today = moods[gameday_to_int()]; if (mood_today != """") random_messages.listAppend(mood_today); } if (__misc_state[""in run""]) { random_messages.listAppend(""optimal power, make up!""); random_messages.listAppend(""the faster your runs, the longer they take""); } generateRandomMessageLocation(random_messages); //random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""if you're feeling stressed, play alice's army"", generateMainLinkMap(""aagame.php""))); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""if you're feeling stressed, play witchess"", generateMainLinkMap(""playwitchess.php?action=another""))); random_messages.listAppend(""consider your mistakes creative spading""); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""Found inaccurate/questionable information?
Have a question/suggestion? Click here!"", string [string] {""href"":""https://github.com/cdrock/TourGuide/discussions"", ""target"":""_blank"", ""class"":""r_a_undecorated""})); if (hippy_stone_broken()) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""it's not easy having yourself a good time"", generateMainLinkMap(""peevpee.php""))); string [item] equipment_messages; equipment_messages[$item[whatsian ionic pliers]] = ""ionic pliers untinker to a screwdriver and a sonar-in-a-biscuit""; equipment_messages[$item[yearbook club camera]] = ""rule of thirds""; equipment_messages[$item[happiness]] = ""bang bang""; equipment_messages[$item[mysterious silver lapel pin]] = ""be seeing you""; equipment_messages[$item[Moonthril Circlet]] = ""moon tiara""; //action! equipment_messages[$item[numberwang]] = ""simply everyone""; equipment_messages[$item[Mark V Steam-Hat]] = ""girl genius""; equipment_messages[$item[mr. accessory]] = ""you can equip mr. accessories?""; equipment_messages[$item[white hat hacker T-shirt]] = ""hack the planet""; equipment_messages[$item[heart necklace]] = ""♥︎""; //♥︎ equipment_messages[$item[fleetwood chain]] = ""running in the shadows""; equipment_messages[$item[liar's pants]] = ""never tell the same lie twice""; equipment_messages[$item[detective skull]] = HTMLGenerateSpanFont(""too slow ascend faster"", ""#ACA200""); //speakeasy password equipment_messages[$item[gasmask]] = ""are you my mummy?""; equipment_messages[$item[spanish fly trap]] = ""around the world around the world around the world around the world""; equipment_messages[$item[wand of nagamar]] = ""levi OH sa""; if (in_bad_moon() && my_primestat() != $stat[moxie]) equipment_messages[$item[sneaky pete's breath spray]] = ""every class a moxie class""; foreach it in $items[twisted-up wet towel,sommelier's towel,time bandit time towel] equipment_messages[it] = ""don't panic""; equipment_messages[$item[pirate fledges]] = "" oh, better far to live and die, under the brave black flag I fly! ""; foreach it in equipment_messages { if (it.equipped_amount() > 0) { random_messages.listAppend(equipment_messages[it]); break; } } if (my_ascensions() == 0) random_messages.listAppend(""welcome to the kingdom!""); else if (my_ascensions() == 1) random_messages.listAppend(""run, while you still have the chance!""); if (__misc_state[""in run""]) random_messages.listAppend(""perfect runs are overrated""); random_messages.listAppend(""math is your helpful friend""); if (get_property_int(""_pantsgivingCount"") >= 5500) { random_messages.listAppend(""Could not connect to secondary database server:2003 - Can't connect to MySQL server on '10.0.0.51' (99)""); } if ((gameday_to_int() & 31) == 0) random_messages.listAppend(""seek the alchemist""); //a young lady's illustrated ascension guide string [effect] effect_messages; effect_messages[$effect[consumed by anger]] = ""don't ascend angry""; effect_messages[$effect[consumed by regret]] = ""wasted potential""; effect_messages[$effect[All Revved Up]] = ""vroom""; if (my_path_id() != PATH_WAY_OF_THE_SURPRISING_FIST) effect_messages[$effect[Expert Timing]] = ""martial arts and crafts""; effect_messages[$effect[apathy]] = """"; // effect_messages[$effect[silent running]] = ""an awful lot of running""; effect_messages[$effect[Neuromancy]] = ""the silver paths""; effect_messages[$effect[Teleportitis]] = ""everywhere and nowhere""; effect_messages[$effect[Form of...Bird!]] = ""fiddle fiddle fiddle""; effect_messages[$effect[superstar]] = ""★""; effect_messages[$effect[hopped up on goofballs]] = ""a massive drug deficiency""; foreach s in $strings[Warlock\\, Warstock\\, and Warbarrel,Barrel of Laughs,Barrel Chested,Pork Barrel,Double-Barreled,Beer Barrel Polka] effect_messages[s.to_effect()] = ""just let me throw a barrel at it""; effect_messages[$effect[Meteor Showered]] = ""すきだ""; foreach e in effect_messages { if (e.have_effect() > 0 && e != $effect[none]) { random_messages.listAppend(effect_messages[e]); break; } } if (__misc_state[""single familiar run""]) random_messages.listAppend(""together forever""); random_messages.listAppend(""click click click""); switch (my_path_id()) { case PATH_OXYGENARIAN: random_messages.listAppend(""the slow path""); break; case PATH_BEES_HATE_YOU: random_messages.listAppend(""bzzzzzz""); break; case PATH_WAY_OF_THE_SURPRISING_FIST: random_messages.listAppend(""martial arts and crafts""); break; case PATH_TRENDY: random_messages.listAppend(""played out""); break; case PATH_AVATAR_OF_BORIS: random_messages.listAppend(""testosterone poisoning""); break; case PATH_BUGBEAR_INVASION: random_messages.listAppend(""bugbears!""); break; case PATH_ZOMBIE_SLAYER: random_messages.listAppend(""consumerism metaphor""); break; case PATH_CLASS_ACT: random_messages.listAppend(""try the sequel""); break; case PATH_AVATAR_OF_JARLSBERG: random_messages.listAppend(""nerd""); break; case PATH_BIG: random_messages.listAppend(""everything's so tiny...""); break; case PATH_KOLHS: random_messages.listAppend(""did you study?""); break; case PATH_CLASS_ACT_2: random_messages.listAppend(""lonely guild trainer""); break; case PATH_AVATAR_OF_SNEAKY_PETE: random_messages.listAppend(""sunglasses at night""); break; case PATH_SLOW_AND_STEADY: if (!in_hardcore()) random_messages.listAppend(""infinite pulls""); else random_messages.listAppend(""skip a day if you like""); break; case PATH_HEAVY_RAINS: random_messages.listAppend(""survive""); break; case PATH_PICKY: if ($skill[cannelloni cannon].skill_is_usable() && !$skill[cannelloni cocoon].skill_is_usable()) //such an easy mistake... random_messages.listAppend(""cannelloni confusion""); else random_messages.listAppend(""combinatorial ascension""); break; case PATH_STANDARD: random_messages.listAppend(""no past no path""); break; case PATH_ACTUALLY_ED_THE_UNDYING: random_messages.listAppend(""UNDYING!""); break; case PATH_ONE_CRAZY_RANDOM_SUMMER: random_messages.listAppend(""dance the mersenne twist""); break; case PATH_COMMUNITY_SERVICE: random_messages.listAppend(""make the world a better place""); break; case PATH_AVATAR_OF_WEST_OF_LOATHING: random_messages.listAppend(""draw""); break; case PATH_THE_SOURCE: if (my_daycount() % 2 == 0) random_messages.listAppend(""don't think you aren't. know you aren't.""); else random_messages.listAppend(""it is not the spoon that ascends, it is only yourself""); break; case PATH_NUCLEAR_AUTUMN: random_messages.listAppend(""I do want to set the world on "" + HTMLGenerateSpanFont(""fire"", ""red"")); break; case PATH_GELATINOUS_NOOB: random_messages.listAppend(""you jelly?""); break; case PATH_LICENSE_TO_ADVENTURE: random_messages.listAppend(""FOR YOUR EYES ONLY""); break; case PATH_LIVE_ASCEND_REPEAT: random_messages.listAppend(""a single perfect day""); break; case PATH_POCKET_FAMILIARS: random_messages.listAppend(""adorable slaves""); break; case PATH_G_LOVER: random_messages.listAppend(""get going, guuuurl""); break; case PATH_DEMIGUISE: random_messages.listAppend(""who are you?""); break; case PATH_VAMPIRE: random_messages.listAppend(""die monster! you don't belong in this world!""); break; case PATH_2CRS: random_messages.listAppend(""what happened to my inventory?""); break; case PATH_EXPLOSIONS: random_messages.listAppend(""kaboooooom""); break; /*case PATH_CLASS_ACT_3: random_messages.listAppend(""buttons for the people""); break; case PATH_AVATAR_OF_THE_NAUGHTY_SORCERESS: random_messages.listAppend(""go forth to your lair! have some tea""); break;*/ } if (in_ronin() && my_adventures() <= 3) random_messages.listAppend(""always tomorrow""); random_messages.listAppend(""I don't know either, sorry""); string lowercase_player_name = my_name().to_lower_case().HTMLEscapeString(); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""check the wiki"", mapMake(""class"", ""r_a_undecorated"", ""href"", ""http://kol.coldfront.net/thekolwiki/index.php/Main_Page"", ""target"", ""_blank""))); random_messages.listAppend(""the RNG is only trying to "" + ((random(100) == 0) ? ""hurt"" : ""help"")); if (__misc_state[""in run""]) { int choice = gameday_to_int() & 3; if (choice == 0) random_messages.listAppend(""speed ascension is all I have left, "" + lowercase_player_name); else if (choice == 1) random_messages.listAppend(""let the turns go""); else if (choice == 2) random_messages.listAppend(""mostly made up""); else if (choice == 3) random_messages.listAppend(""kingdom of self loathing""); if (my_ascensions() >= 1000) random_messages.listAppend(""dedicated""); } if (item_drop_modifier() <= -100.0) random_messages.listAppend(""let go of your material posessions""); if ($item[puppet strings].item_amount() > 0 && my_id() != 1557284) { //full puppet string support: string chosen_message; switch (gameday_to_int() % 13) { case 0: chosen_message = ""%playername% is easily the most great person ever! three cheers for %playername%!""; break; case 1: chosen_message = ""%playername% is my hero! don't you all agree?""; break; case 2: chosen_message = ""%playername% is such a sexy beast!""; break; case 3: chosen_message = ""%playername% is super-attractive and studly! don't you all agree?""; break; case 4: chosen_message = ""%playername% is super-attractive and studly! just saying that name makes me feel all tingly inside!""; break; case 5: chosen_message = ""who do I think is the best KoLer? obviously\\, it's %playername%! how about a round of applause?""; break; case 6: chosen_message = ""I wish I was as good-looking as %playername%. hip hip hooray!""; break; case 7: chosen_message = ""I'm %playername%'s biggest fan! let's hear it for %playername%!""; break; case 8: chosen_message = ""I've never met anyone as attractive as %playername%! how about a round of applause?""; break; case 9: chosen_message = ""I've never met anyone as studly as %playername%! all the rest of us are totally lame in comparison!""; break; case 10: chosen_message = ""is anyone as fabulous as %playername%? I don't think so! just saying that name makes me feel all tingly inside!""; break; case 11: chosen_message = ""is anyone as intelligent as %playername%? I don't think so! hooray for %playername%!""; break; default: chosen_message = ""%playername% is totally awesome! hooray for %playername%!""; break; } chosen_message = chosen_message.replace_string(""%playername%"", lowercase_player_name); random_messages.listAppend(chosen_message); //random_messages.listAppend(lowercase_player_name + "" is totally awesome! hooray for "" + lowercase_player_name + ""!""); } if (__quest_state[""Level 12""].in_progress && __quest_state[""Level 12""].state_int[""hippies left on battlefield""] < 1000 && __quest_state[""Level 12""].state_int[""frat boys left on battlefield""] < 1000) random_messages.listAppend(""playing sides""); if (__iotms_usable[$item[Order of the Green Thumb Order Form]]) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""the forgotten friar cries himself to sleep"", generateMainLinkMap(""place.php?whichplace=forestvillage&action=fv_friar""))); if (!__misc_state[""skills temporarily missing""] && !$skill[Transcendent Olfaction].skill_is_usable()) { random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""visit the bounty hunter hunter sometime"", generateMainLinkMap(""bounty.php""))); } if (__misc_state[""in aftercore""]) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""ascension is waiting for you"", generateMainLinkMap(""place.php?whichplace=nstower""))); if (my_adventures() == 0) random_messages.listAppend(""nowhere left to go""); if (__quest_state[""Level 11""].in_progress) random_messages.listAppend(""try not to lose your sanity""); if (__quest_state[""Level 13""].in_progress) { if (my_daycount() == 1) random_messages.listAppend(""all the world's work in a day""); else random_messages.listAppend(""it'll be all over soon""); } if (!CounterLookup(""Semi-rare"").CounterIsRange() && CounterLookup(""Semi-rare"").CounterExists() && CounterLookup(""Semi-rare"").exact_turns.count() > 1) random_messages.listAppend(""superpositioned semi-rare""); if (hippy_stone_broken() && pvp_attacks_left() > 0) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""aggressive friendship"", generateMainLinkMap(""peevpee.php""))); if (get_property_boolean(""_warbearGyrocopterUsed"")) random_messages.listAppend(""[gyroseaten] => 109""); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""♫"", mapMake(""class"", ""r_a_undecorated"", ""href"", ""http://www.kingdomofloathing.com/radio.php"", ""target"", ""_blank""))); if (__misc_state_int[""free rests remaining""] > 0) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""dream your life away"", generateMainLinkMap(__misc_state_string[""resting url""]))); if (get_property_int(""cinderellaScore"") >= 32) random_messages.listAppend(""mother knows best""); if ($location[the shore\\, inc. travel agency].turnsAttemptedInLocation() >= 11) { if (hippy_stone_broken()) random_messages.listAppend(""beware of shorebots""); else random_messages.listAppend(""under a distant shore you will find your answers""); } if (current_hour >= 2 && current_hour <= 3) random_messages.listAppend(""up late?""); else if (current_hour >= 4 && current_hour <= 5) random_messages.listAppend(""zzz...""); else if (current_hour == 6) random_messages.listAppend(""the dawn is your enemy""); random_messages.listAppend(""take chances, be courages, go exploring!""); switch (my_class()) { case $class[disco bandit]: random_messages.listAppend(""making discos of your castles""); break; case $class[seal clubber]: random_messages.listAppend(""I ♣︎ seals""); break; case $class[turtle tamer]: random_messages.listAppend(""friends everywhere you go""); break; case $class[sauceror]: random_messages.listAppend(""journey of the sauceror""); break; case $class[Snake Oiler]: random_messages.listAppend(""ten points to slytherin""); break; } if (numeric_modifier(""hot damage"") <= 0.0 && gameday_to_int() % 4 == 0) random_messages.listAppend(""have you tried "" + HTMLGenerateSpanFont(""fire"", ""red"")); if (__misc_state[""Chateau Mantegna available""] && get_property_monster(""chateauMonster"").phylum == $phylum[fish] && !get_property_boolean(""_chateauMonsterFought"")) { random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""personal aquarium"", generateMainLinkMap(""place.php?whichplace=chateau""))); //WhiteWizard42: feeeeesh. feesh in the waaaall } generateRandomMessageFamiliar(random_messages); if (last_monster().phylum == $phylum[penguin]) { random_messages.listClear(); //sufficiently rare random_messages.listAppend(""dood""); } string [monster] monster_messages; string [monster] beaten_up_monster_messages; //TODO add a message for the procrastination giant foreach m in $monsters[The Temporal Bandit,crazy bastard,Knott Slanding,hockey elemental,Hypnotist of Hey Deze,infinite meat bug,QuickBASIC Elemental,The Master of Thieves,Baiowulf,Count Bakula,The Nuge] //Pooltergeist (Ultra-Rare)? monster_messages[m] = ""an ultra rare! congratulations!""; monster_messages[$monster[The Master of Thieves]] = ""don't @ me""; monster_messages[$monster[Dad Sea Monkee]] = ""is always was always"" + HTMLGenerateSpanFont("" is always was always"", ""#444444"") + HTMLGenerateSpanFont("" is always was always"", ""#888888"") + HTMLGenerateSpanFont("" is always was always"", ""#BBBBBB""); foreach m in $monsters[Ed the Undying (1),Ed the Undying (2),Ed the Undying (3),Ed the Undying (4),Ed the Undying (5),Ed the Undying (6),Ed the Undying (7)] monster_messages[m] = ""UNDYING!""; foreach m in $monsters[Naughty Sorceress, Naughty Sorceress (2), Naughty Sorceress (3)] { if (holidays_today[""Valentine's Day""]) monster_messages[m] = ""please be mine, sorceress""; else monster_messages[m] = ""she isn't all that bad""; } foreach m in $monsters[Shub-Jigguwatt\\, Elder God of Violence,Yog-Urt\\, Elder Goddess of Hatred] monster_messages[m] = ""strange aeons""; monster_messages[$monster[daft punk]] = ""can you feel it?""; monster_messages[$monster[ghastly organist]] = ""phantom of the opera""; monster_messages[$monster[The Man]] = ""let the workers unite""; monster_messages[$monster[The Big Wisniewski]] = ""far out""; monster_messages[$monster[Quiet Healer]] = ""...""; monster_messages[$monster[menacing thug]] = ""watch your back""; monster_messages[$monster[sea cowboy]] = ""pardon me""; monster_messages[$monster[topiary golem]] = ""almost ther... wait, golems?""; monster_messages[$monster[The Server]] = ""console cowboy""; monster_messages[$monster[Fickle Finger of F8]] = ""f/8 and be there""; monster_messages[$monster[malevolent crop circle]] = ""I want to believe""; monster_messages[$monster[Enraged Cow]] = ""moo""; if ($item[bottle of blank-out].is_unrestricted()) monster_messages[$monster[Claybender Sorcerer Ghost]] = ""accio blank-out""; else monster_messages[$monster[Claybender Sorcerer Ghost]] = ""leaderboardus totalus""; monster_messages[$monster[Whatsian Commando Ghost]] = ""captain jack hotness""; if (my_path_id() == PATH_ACTUALLY_ED_THE_UNDYING) monster_messages[$monster[Whatsian Commando Ghost]] = ""are you my mummy?""; monster_messages[$monster[Space Tourist Explorer Ghost]] = ""oh my""; monster_messages[$monster[Battlie Knight Ghost]] = ""boring conversation anyway""; monster_messages[$monster[oil slick]] = ""run more ML!""; monster_messages[$monster[Space Marine]] = ""as if it were from an old dream""; monster_messages[$monster[Regret Man]] = ""wasted potential""; monster_messages[$monster[Principal Mooney]] = ""life moves pretty fast""; if (my_turncount() < 11) monster_messages[$monster[family of kobolds]] = ""in a hurry?""; monster_messages[$monster[Black Crayon Spiraling Shape]] = ""be what you're like""; monster_messages[$monster[best-selling novelist]] = ""fiction to escape reality""; monster_messages[$monster[7-Foot Dwarf Replicant]] = ""it's too bad she won't live
but then again, who does?""; monster_messages[$monster[The Avatar of Jarlsberg]] = ""smoked cheese""; monster_messages[$monster[giant sandworm]] = ""walk without rhythm""; monster_messages[$monster[bookbat]] = ""tattered scrap of dignity""; monster_messages[$monster[Urge to Stare at Your Hands]] = "".⃝.⃝""; //.⃝.⃝ if (my_path_id() == PATH_HEAVY_RAINS) monster_messages[$monster[pygmy bowler]] = ""right into the gutter""; //come back! monster_messages[$monster[Ron ""The Weasel"" Copperhead]] = ""RONALD WEASLEY! HOW DARE YOU STEAL THAT ZEPPELIN
"" + ChecklistGenerateModifierSpan(""your father's now facing an inquiry at work and it's entirely YOUR FAULT""); monster_messages[$monster[Mr. Loathing]] = HTMLGenerateTagWrap(""a"", ""ruuun! go! get to the towah!"", generateMainLinkMap(""place.php?whichplace=nstower"")); if (my_hp() < my_maxhp()) monster_messages[$monster[Smooth Criminal]] = ""you've been hit by
you've been struck by
a smooth criminal""; monster_messages[$monster[demonic icebox]] = ""zuul""; monster_messages[$monster[angry mushroom guy]] = ""touch fizzy, get dizzy""; beaten_up_monster_messages[$monster[storm cow]] = ""
^__^            
(oo)\\\\_______
(__)\\\\ )\\\\/\\\\
||----w |
|| ||
""; monster_messages[$monster[The Barrelmech of Diogenes]] = ""just let me throw a barrel at it""; //beaten_up_monster_messages[$monster[Lavalos]] = HTMLGenerateTagWrap(""span"", ""but... the future refused to change"", mapMake(""onclick"", ""var l = new Audio('"" + __lavalos_sound_data + ""'); l.play();"", ""class"", ""r_clickable"")); //copyright, etc beaten_up_monster_messages[$monster[Lavalos]] = ""but... the future refused to change""; if ($item[protonic accelerator pack].equipped_amount() > 0 && last_monster().monsterIsGhost()) beaten_up_monster_messages[last_monster()] = ""venkman makes it look easy""; if ($effect[beaten up].have_effect() > 0 && $items[rainbow pearl earring,rainbow pearl necklace,rainbow pearl ring,vampire pearl earring,vampire pearl ring,vampire pearl necklace,freshwater pearl necklace,pearl diver's ring,pearl diver's necklace,pearl necklace].equipped_amount() > 0) beaten_up_monster_messages[last_monster()] = ""WHY WON'T YOU LET ME DO THIS FOR YOU, ROSE?""; if (last_monster().phylum == $phylum[demon]) beaten_up_monster_messages[last_monster()] = ""he made the devil so much stronger than a man!""; if (current_hour >= 5 && current_hour <= 11) monster_messages[$monster[Lavalos]] = ""good morning, "" + lowercase_player_name + ""!""; else monster_messages[$monster[Lavalos]] = ""all life begins with nu and ends with nu""; monster_messages[$monster[sk8 gnome]] = ""he was a sk8 gnome she said see u l8 gnome""; monster_messages[$monster[The Inquisitor]] = ""nothing is up""; monster_messages[$monster[Doc Clock]] = ""your defeat will happen at "" + (current_hour > 12 ? current_hour - 12 : current_hour) + "":"" + current_minute + "" precisely""; // + (current_hour >= 12 ? "" PM"" : "" AM"") monster_messages[lookupMonster(""God Lobster"")] = ""what a grand and intoxicating innocence""; //how can you kill a god? equip the heart of the volcano? monster_messages[lookupMonster(""cockroach"")] = ""are bug exterminators professional assassins?""; string day_cycle; if (current_hour >= 5 && current_hour <= 11) day_cycle = ""morning""; else if (current_hour >= 12 && current_hour <= 16) day_cycle = ""afternoon""; else if (current_hour >= 17 && current_hour <= 20) day_cycle = ""evening""; else day_cycle = ""night""; monster_messages[$monster[Travoltron]] = now_to_string(""EEEE"").to_lower_case() + "" "" + day_cycle + "" fever""; if (my_daycount() == 2 && (my_adventures() == 0 || availableDrunkenness() < 0) && availableFullness() == 0 && availableDrunkenness() <= 0 && my_path_id() != PATH_OXYGENARIAN && __quest_state[""Level 12""].started && !__quest_state[""Level 13""].state_boolean[""king waiting to be freed""] && my_path_id() != PATH_NUCLEAR_AUTUMN && my_path_id() != PATH_SLOW_AND_STEADY && !__quest_state[""Level 13""].finished) { //detect failed two-day runs, and provide psychological support: random_messages.listClear(); if (__quest_state[""Level 13""].started) random_messages.listAppend(""ever so close""); else random_messages.listAppend(""three days is fine""); } boolean already_output_relevant_beaten_up_effect = false; if ((my_hp() == 0 || $effect[beaten up].have_effect() > 0) && beaten_up_monster_messages contains last_monster() && last_monster() != $monster[none]) { random_messages.listClear(); random_messages.listAppend(beaten_up_monster_messages[last_monster()]); already_output_relevant_beaten_up_effect = true; } else if (monster_messages contains last_monster() && last_monster() != $monster[none]) { random_messages.listClear(); random_messages.listAppend(monster_messages[last_monster()]); } if (__quest_state[""Level 13""].state_boolean[""king waiting to be freed""]) { if (my_path_id() == PATH_ONE_CRAZY_RANDOM_SUMMER) { random_messages.listClear(); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""roll the dice"", generateMainLinkMap(""place.php?whichplace=nstower""))); } } if (__misc_state_int[""Basement Floor""] == 500) { random_messages.listClear(); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""open it!"", generateMainLinkMap(""basement.php""))); } string [string] encounter_messages; boolean encounter_override = false; encounter_messages[""It's Always Swordfish""] = ""one two three four five""; encounter_messages[""Meet Frank""] = ""don't trust the skull""; encounter_messages[""The Mirror in the Tower has the View that is True""] = ""shatter the false reality""; encounter_messages[""A Tombstone""] = ""peperony and chease""; encounter_messages[""Witchess Puzzles""] = ""this etch a sketch is hard""; encounter_messages[""Rubbed it the Right Way""] = ""desire incarnate""; if (my_class() == $class[turtle tamer]) { //The Horror... needs disambiguation foreach s in $strings[Nantucket Snapper,Blue Monday,Capital!,Training Day,Boxed In,Duel Nature,Slow Food,A Rolling Turtle Gathers No Moss,Slow Road to Hell,C'mere\\, Little Fella,The Real Victims,Like That Time in Tortuga,Cleansing your Palette,Harem Scarum,Turtle in peril,No Man\\, No Hole,Slow and Steady Wins the Brawl,Stormy Weather,Turtles of the Universe,O Turtle Were Art Thou,Allow 6-8 Weeks For Delivery,Kick the Can,Turtles All The Way Around,More eXtreme Than Usual,Jewel in the Rough,The worst kind of drowning] encounter_messages[s] = ""friend!""; } if (encounter_messages contains get_property(""lastEncounter"")) { random_messages.listClear(); random_messages.listAppend(encounter_messages[get_property(""lastEncounter"")]); encounter_override = true; } if (__quest_state[""Level 12""].in_progress && __quest_state[""Level 12""].state_int[""hippies left on battlefield""] == 1 && __quest_state[""Level 12""].state_int[""frat boys left on battlefield""] == 1) { random_messages.listClear(); random_messages.listAppend(""wossname is waiting""); } if (my_familiar() == $familiar[Helix Fossil]) { buffer generated; string [int] commands; string property_value = get_property(""__voices""); if (property_value.length() > 1) //remove sentinel { if (property_value.char_at(property_value.length() - 1) == ""|"") property_value = property_value.substring(0, property_value.length() - 1); } commands = property_value.split_string_alternate("",""); for i from 0 to 0 { string word; int r = random(100); if (r < 15) word = ""⬆""; //⬆︎ else if (r < 30) word = ""⬇""; //⬇︎ else if (r < 45) word = ""➡""; //➡ else if (r < 60) word = ""⬅""; //⬅︎ else if (r < 75) word = ""A"";// Ⓐ = Ⓐ else if (r < 95) word = ""B""; //Ⓑ = Ⓑ else word = ""start""; commands.listAppend(word); } while (commands.count() > 6) remove commands[commands.listKeyForIndex(0)]; set_property(""__voices"", commands.listJoinComponents("","") + ""|""); //we add an ending sentinel because set_property() will remove "";"" if it's at the end of the string. set_property() is not guaranteed to keep data integrity random_messages.listClear(); string message = commands.listJoinComponents("" ""); message = HTMLGenerateTagWrap(""span"", message, mapMake(""onclick"", ""updatePageAndFireTimer()"", ""class"", ""r_clickable"")); random_messages.listAppend(message); } foreach s in $strings[rainDohMonster,spookyPuttyMonster,cameraMonster,photocopyMonster,envyfishMonster,iceSculptureMonster,crudeMonster,crappyCameraMonster,romanticTarget,chateauMonster] { if (get_property_monster(s) == $monster[Quiet Healer]) { random_messages.listClear(); random_messages.listAppend(""you can't bring her back""); break; } } if (false)//mmg_my_bets().count() > 0) { random_messages.listClear(); random_messages.listAppend(""win some, lose some""); } if ($effect[beaten up].have_effect() > 0 && limit_mode().length() == 0 && !already_output_relevant_beaten_up_effect) { random_messages.listClear(); switch (my_path_id()) { case PATH_BEES_HATE_YOU: random_messages.listAppend(""BZZZZZZ""); break; case PATH_ONE_CRAZY_RANDOM_SUMMER: random_messages.listAppend(""tick, tock""); break; case PATH_ACTUALLY_ED_THE_UNDYING: random_messages.listAppend(""DYING!""); break; case PATH_COMMUNITY_SERVICE: random_messages.listAppend(""no good deed goes unpunished""); break; case PATH_AVATAR_OF_WEST_OF_LOATHING: random_messages.listAppend(""shucks""); break; case PATH_LIVE_ASCEND_REPEAT: random_messages.listAppend(""I got you babe""); break; case PATH_LICENSE_TO_ADVENTURE: random_messages.listAppend(""you only live twice""); break; case PATH_THE_SOURCE: random_messages.listAppend(""not like this""); break; case PATH_POCKET_FAMILIARS: random_messages.listAppend(lowercase_player_name + ""! now is not the time to use that!""); break; case PATH_G_LOVER: random_messages.listAppend(""the Gs will continue until morale improves""); break; default: random_messages.listAppend(""ow""); break; } } if (my_turncount() <= 0) { random_messages.listClear(); if (my_path_id() == PATH_LIVE_ASCEND_REPEAT) random_messages.listAppend(""I got you babe""); else if (my_path_id() == PATH_POCKET_FAMILIARS) random_messages.listAppend(""pika pika!""); else random_messages.listAppend(""find yourself
starting back""); } if (limit_mode() == ""Spelunky"" && !encounter_override) { random_messages.listClear(); if (get_property(""lastEncounter"") == ""Spelunkrifice"" && get_property(""spelunkyStatus"").contains_text(""Buddy: "")) { if (get_property(""spelunkingStatus"").contains_text(""Resourceful Kid"")) random_messages.listAppend(""he's only a child!""); else random_messages.listAppend(""et tu, "" + lowercase_player_name + ""?""); } else random_messages.listAppend(""ascend? yes! play? no!""); } if (limit_mode() == ""batman"" && !encounter_override) { random_messages.listClear(); random_messages.listAppend(""a superstitious, cowardly lot""); } if (format_today_to_string(""yyyyMMdd"") == ""20151021"") //october 21st, 2015 { //kept active for any time travelers random_messages.listClear(); if (get_property(""System.user.country.format"") == ""US"") random_messages.listAppend(""88 MPH
hey, you did it!""); else random_messages.listAppend(""142 km/h
hey, you did it!""); } //Choose: if (random_messages.count() == 0) return ""lack of cleverness""; string chosen_message = """"; //Base message off of the minute, so it doesn't cycle when the page reloads often: chosen_message = random_messages[minute_of_day % random_messages.count()]; return chosen_message; } ",12450,True,2558.273396238445,median "// Use these for links to issue and pulls. Note issues and pulls redirect one to // each other on Github, so don't worry too much on using the right prefix. :issue: https://github.com/elastic/beats/issues/ :pull: https://github.com/elastic/beats/pull/ === Beats version HEAD https://github.com/elastic/beats/compare/v7.0.0-alpha2...master[Check the HEAD diff] ==== Breaking changes *Affecting all Beats* - Update to Golang 1.12.1. {pull}11330[11330] - Update to Golang 1.12.4. {pull}11782[11782] - Update to ECS 1.0.1. {pull}12284[12284] {pull}12317[12317] - Default of output.kafka.metadata.full is set to false by now. This reduced the amount of metadata to be queried from a kafka cluster. {pull}12738[12738] - Fixed a crash under Windows when fetching processes information. {pull}12833[12833] - Update to Golang 1.12.7. {pull}12931[12931] - Remove `in_cluster` configuration parameter for Kuberentes, now in-cluster configuration is used only if no other kubeconfig is specified {pull}13051[13051] - Disable Alibaba Cloud and Tencent Cloud metadata providers by default. {pull}13812[12812] - Libbeat HTTP's Server can listen to a unix socket using the `unix:///tmp/hello.sock` syntax. {pull}13655[13655] - Libbeat HTTP's Server can listen to a Windows named pipe using the `npipe:///hello` syntax. {pull}13655[13655] - By default, all Beats-created files and folders will have a umask of 0027 (on POSIX systems). {pull}14119[14119] - Adding new `Enterprise` license type to the licenser. {issue}14246[14246] - Change wording when we fail to load a CA file to the cert pool. {issue}14309[14309] - Allow Metricbeat's beat module to read monitoring information over a named pipe or unix domain socket. {pull}14558[14558] - Remove version information from default ILM policy for improved upgrade experience on custom policies. {pull}14745[14745] - Running `setup` cmd respects `setup.ilm.overwrite` setting for improved support of custom policies. {pull}14741[14741] - Libbeat: Do not overwrite agent.*, ecs.version, and host.name. {pull}14407[14407] *Auditbeat* - Auditd module: Normalized value of `event.category` field from `user-login` to `authentication`. {pull}11432[11432] - Auditd module: Unset `auditd.session` and `user.audit.id` fields are removed from audit events. {issue}11431[11431] {pull}11815[11815] - Socket dataset: Exclude localhost by default {pull}11993[11993] - Socket dataset: New implementation using Kprobes for finer-grained monitoring and UDP support. {pull}13058[13058] *Filebeat* - Add Filebeat Azure Dashboards {pull}14127[14127] - Add read_buffer configuration option. {pull}11739[11739] - `convert_timezone` option is removed and locale is always added to the event so timezone is used when parsing the timestamp, this behaviour can be overriden with processors. {pull}12410[12410] - Fix a race condition in the TCP input when close the client socket. {pull}13038[13038] - cisco/asa fileset: Renamed log.original to event.original and cisco.asa.list_id to cisco.asa.rule_name. {pull}13286[13286] - cisco/asa fileset: Fix parsing of 302021 message code. {pull}13476[13476] - google pubsub & httpjson inputs: HTTP User agent is now `Elastic-Heartbeat/Version` instead of `Elastic Heartbeat/Version` to stay RFC compliant. {pull}14748[14748] - CEF extensions are now mapped to the data types defined in the CEF guide. {pull}14342[14342] - Remove --machine-learning from setup subcommand. {pull}14705[14705] *Heartbeat* - Removed the `add_host_metadata` and `add_cloud_metadata` processors from the default config. These don't fit well with ECS for Heartbeat and were rarely used. - Fixed/altered redirect behavior. `max_redirects` now defaults to 0 (no redirects). Following redirects now works across hosts, but some timing fields will not be reported. {pull}14125[14125] - Removed `host.name` field that should never have been included. Heartbeat uses `observer.*` fields instead. {pull}14140[14140] - Changed default user-agent to be `Elastic-Heartbeat/VERSION (PLATFORM_INFO)` as the current default `Go-http-client/1.1` is often blacklisted. {pull}14291[14291] - JSON/Regex checks against HTTP bodies will only consider the first 100MiB of the HTTP body to prevent excessive memory usage. {pull}14223[pull] - Heartbeat now starts monitors scheduled with the '@every X' syntax instantaneously on startup, rather than waiting for the given interval to pass before running them. {pull}14890[14890] *Journalbeat* *Metricbeat* - Add new dashboards for Azure vms, vm guest metrics, vm scale sets {pull}14000[14000] - Add new Dashboard for PostgreSQL database stats {pull}13187[13187] - Add new dashboard for CouchDB database {pull}13198[13198] - Add new dashboard for Ceph cluster stats {pull}13216[13216] - Add new dashboard for Aerospike database stats {pull}13217[13217] - Add new dashboard for Couchbase cluster stats {pull}13212[13212] - Add new dashboard for Prometheus server stats {pull}13126[13126] - Add new dashboard for VSphere host cluster and virtual machine {pull}14135[14135] - Add new option `OpMultiplyBuckets` to scale histogram buckets to avoid decimal points in final events {pull}10994[10994] - system/raid metricset now uses /sys/block instead of /proc/mdstat for data. {pull}11613[11613] - kubernetes.container.cpu.limit.cores and kubernetes.container.cpu.requests.cores are now floats. {issue}11975[11975] - Add statistic option into cloudwatch metricset. If there is no statistic method specified, default is to collect Average, Sum, Maximum, Minimum and SampleCount. {issue}12370[12370] {pull}12840[12840] *Packetbeat* - Add support for mongodb opcode 2013 (OP_MSG). {issue}6191[6191] {pull}8594[8594] - NFSv4: Always use opname `ILLEGAL` when failed to match request to a valid nfs operation. {pull}11503[11503] *Winlogbeat* *Functionbeat* - Separate management and functions in Functionbeat. {pull}12939[12939] ==== Bugfixes *Affecting all Beats* - Make the behavior of clientWorker and netClientWorker consistent when error is returned from publisher pipeline - Fix a bug, publisher pipeline exits if output returns an error, irrespective of pipeline is closed or not - Fix typo in TLS renegotiation configuration and setting the option correctly {issue}10871[10871], {pull}12354[12354] - Ensure all beat commands respect configured settings. {pull}10721[10721] - Add missing fields and test cases for libbeat add_kubernetes_metadata processor. {issue}11133[11133], {pull}11134[11134] - decode_json_field: process objects and arrays only {pull}11312[11312] - decode_json_field: do not process arrays when flag not set. {pull}11318[11318] - Report faulting file when config reload fails. {pull}11304[11304] - Fix a typo in libbeat/outputs/transport/client.go by updating `c.conn.LocalAddr()` to `c.conn.RemoteAddr()`. {pull}11242[11242] - Management configuration backup file will now have a timestamps in their name. {pull}11034[11034] - [CM] Parse enrollment_token response correctly {pull}11648[11648] - Not hiding error in case of http failure using elastic fetcher {pull}11604[11604] - Escape BOM on JsonReader before trying to decode line {pull}11661[11661] - Fix matching of string arrays in contains condition. {pull}11691[11691] - Replace wmi queries with win32 api calls as they were consuming CPU resources {issue}3249[3249] and {issue}11840[11840] - Fix a race condition with the Kafka pipeline client, it is possible that `Close()` get called before `Connect()` . {issue}11945[11945] - Fix queue.spool.write.flush.events config type. {pull}12080[12080] - Fixed a memory leak when using the add_process_metadata processor under Windows. {pull}12100[12100] - Fix of docker json parser for missing ""log"" jsonkey in docker container's log {issue}11464[11464] - Fixed Beat ID being reported by GET / API. {pull}12180[12180] - Fixed setting bulk max size in kafka output. {pull}12254[12254] - Add host.os.codename to fields.yml. {pull}12261[12261] - Fix `@timestamp` being duplicated in events if `@timestamp` is set in a processor (or by any code utilizing `PutValue()` on a `beat.Event`). - Fix leak in script processor when using Javascript functions in a processor chain. {pull}12600[12600] - Add additional nil pointer checks to Docker client code to deal with vSphere Integrated Containers {pull}12628[12628] - Fixed `json.add_error_key` property setting for delivering error messages from beat events {pull}11298[11298] - Fix Central Management enroll under Windows {issue}12797[12797] {pull}12799[12799] - ILM: Use GET instead of HEAD when checking for alias to expose detailed error message. {pull}12886[12886] - Fix seccomp policy preventing some features to function properly on 32bit Linux systems. {issue}12990[12990] {pull}13008[13008] - Fix unexpected stops on docker autodiscover when a container is restarted before `cleanup_timeout`. {issue}12962[12962] {pull}13127[13127] - Fix install-service.ps1's ability to set Windows service's delay start configuration. {pull}13173[13173] - Fix some incorrect types and formats in field.yml files. {pull}13188[13188] - Load DLLs only from Windows system directory. {pull}13234[13234] {pull}13384[13384] - Fix mapping for kubernetes.labels and kubernetes.annotations in add_kubernetes_metadata. {issue}12638[12638] {pull}13226[13226] - Fix case insensitive regular expressions not working correctly. {pull}13250[13250] - Disable `add_kubernetes_metadata` if no matchers found. {pull}13709[13709] - Better wording for xpack beats when the _xpack endpoint is not reachable. {pull}13771[13771] - Recover from panics in the javascript process and log details about the failure to aid in future debugging. {pull}13690[13690] - Make the script processor concurrency-safe. {issue}13690[13690] {pull}13857[13857] - Kubernetes watcher at `add_kubernetes_metadata` fails with StatefulSets {pull}13905[13905] - Fix panics that could result from invalid TLS certificates. This can affect Beats that connect over TLS or Beats that accept connections over TLS and validate client certificates. {pull}14146[14146] - Support usage of custom builders without hints and mappers {pull}13839[13839] - Fix memory leak in kubernetes autodiscover provider and add_kubernetes_metadata processor happening when pods are terminated without sending a delete event. {pull}14259[14259] - Fix kubernetes `metaGenerator.ResourceMetadata` when parent reference controller is nil {issue}14320[14320] {pull}14329[14329] - Allow users to configure only `cluster_uuid` setting under `monitoring` namespace. {pull}14338[14338] - Fix bug with potential concurrent reads and writes from event.Meta map by Kafka output. {issue}14542[14542] {pull}14568[14568] *Auditbeat* - Process dataset: Fixed a memory leak under Windows. {pull}12100[12100] - Login dataset: Fix re-read of utmp files. {pull}12028[12028] - Package dataset: Fixed a crash inside librpm after Auditbeat has been running for a while. {issue}12147[12147] {pull}12168[12168] - Fix formatting of config files on macOS and Windows. {pull}12148[12148] - Fix direction of incoming IPv6 sockets. {pull}12248[12248] - Package dataset: Close librpm handle. {pull}12215[12215] - Package dataset: Auto-detect package directories. {pull}12289[12289] - Package dataset: Improve dpkg parsing. {pull}12325[12325] - System module: Start system module without host ID. {pull}12373[12373] - Host dataset: Fix reboot detection logic. {pull}12591[12591] - Add syscalls used by librpm for the system/package dataset to the default Auditbeat seccomp policy. {issue}12578[12578] {pull}12617[12617] - Process dataset: Do not show non-root warning on Windows. {pull}12740[12740] - Host dataset: Export Host fields to gob encoder. {pull}12940[12940] - Socket dataset: Fix start errors when IPv6 is disabled on the kernel. {issue}13953[13953] {pull}13966[13966] *Filebeat* - Add support for Cisco syslog format used by their switch. {pull}10760[10760] - Cover empty request data, url and version in Apache2 module{pull}10730[10730] - Fix registry entries not being cleaned due to race conditions. {pull}10747[10747] - Improve detection of file deletion on Windows. {pull}10747[10747] - Add missing Kubernetes metadata fields to Filebeat CoreDNS module, and fix a documentation error. {pull}11591[11591] - Reduce memory usage if long lines are truncated to fit `max_bytes` limit. The line buffer is copied into a smaller buffer now. This allows the runtime to release unused memory earlier. {pull}11524[11524] - Fix memory leak in Filebeat pipeline acker. {pull}12063[12063] - Fix goroutine leak caused on initialization failures of log input. {pull}12125[12125] - Fix goroutine leak on non-explicit finalization of log input. {pull}12164[12164] - Skipping unparsable log entries from docker json reader {pull}12268[12268] - Parse timezone in PostgreSQL logs as part of the timestamp {pull}12338[12338] - Load correct pipelines when system module is configured in modules.d. {pull}12340[12340] - Fix timezone offset parsing in system/syslog. {pull}12529[12529] - When TLS is configured for the TCP input and a `certificate_authorities` is configured we now default to `required` for the `client_authentication`. {pull}12584[12584] - Apply `max_message_size` to incoming message buffer. {pull}11966[11966] - Syslog input will now omit the `process` object from events if it is empty. {pull}12700[12700] - Fix multiline pattern in Postgres which was too permissive {issue}12078[12078] {pull}13069[13069] - Allow path variables to be used in files loaded from modules.d. {issue}13184[13184] - Fix filebeat autodiscover fileset hint for container input. {pull}13296[13296] - Fix incorrect references to index patterns in AWS and CoreDNS dashboards. {pull}13303[13303] - Fix timezone parsing of system module ingest pipelines. {pull}13308[13308] - Fix timezone parsing of elasticsearch module ingest pipelines. {pull}13367[13367] - Change iis url path grok pattern from URIPATH to NOTSPACE. {issue}12710[12710] {pull}13225[13225] {issue}7951[7951] {pull}13378[13378] {pull}14754[14754] - Fix timezone parsing of nginx module ingest pipelines. {pull}13369[13369] - Fix incorrect field references in envoyproxy dashboard {issue}13420[13420] {pull}13421[13421] - Fixed early expiration of templates (Netflow v9 and IPFIX). {pull}13821[13821] - Fixed bad handling of sequence numbers when multiple observation domains were exported by a single device (Netflow V9 and IPFIX). {pull}13821[13821] - Fix timezone parsing of rabbitmq module ingest pipelines. {pull}13879[13879] - Fix conditions and error checking of date processors in ingest pipelines that use `event.timezone` to parse dates. {pull}13883[13883] - Fix timezone parsing of Cisco module ingest pipelines. {pull}13893[13893] - Fix timezone parsing of logstash module ingest pipelines. {pull}13890[13890] - cisco asa and ftd filesets: Fix parsing of message 106001. {issue}13891[13891] {pull}13903[13903] - Fix timezone parsing of iptables, mssql and panw module ingest pipelines. {pull}13926[13926] - Fix merging of fields specified in global scope with fields specified under an input's scope. {issue}3628[3628] {pull}13909[13909] - Fix delay in enforcing close_renamed and close_removed options. {issue}13488[13488] {pull}13907[13907] - Fix missing netflow fields in index template. {issue}13768[13768] {pull}13914[13914] - Fix cisco module's asa and ftd filesets parsing of domain names where an IP address is expected. {issue}14034[14034] - Fixed increased memory usage with large files when multiline pattern does not match. {issue}14068[14068] - panw module: Use geo.name instead of geo.country_iso_code for free-form location. {issue}13272[13272] - Fix azure fields names. {pull}14098[14098] - Fix calculation of `network.bytes` and `network.packets` for bi-directional netflow events. {pull}14111[14111] - Accept '-' as http.response.body.bytes in apache module. {pull}14137[14137] - Fix timezone parsing of MySQL module ingest pipelines. {pull}14130[14130] - Improve error message in s3 input when handleSQSMessage failed. {pull}14113[14113] - Close chan of Closer first before calling callback {pull}14231[14231] - Fix race condition in S3 input plugin. {pull}14359[14359] - Decode hex values in auditd module. {pull}14471[14471] - Fix parse of remote addresses that are not IPs in nginx logs. {pull}14505[14505] - Fix handling multiline log entries in nginx module. {issue}14349[14349] {pull}14499[14499] - Fix parsing of Elasticsearch node name by `elasticsearch/slowlog` fileset. {pull}14547[14547] - cisco/asa fileset: Fix parsing of 302021 message code. {pull}14519[14519] - Fix filebeat azure dashboards, event category should be `Alert`. {pull}14668[14668] - Update Logstash module's Grok patterns to support Logstash 7.4 logs. {pull}14743[14743] - Fix a problem in Filebeat input httpjson where interval is not used as time.Duration. {issue}14752[14752] {pull}14753[14753] *Heartbeat* - Fix NPEs / resource leaks when executing config checks. {pull}11165[11165] - Fix duplicated IPs on `mode: all` monitors. {pull}12458[12458] - Fix integer comparison on JSON responses. {pull}13348[13348] - Fix storage of HTTP bodies to work when JSON/Regex body checks are enabled. {pull}14223[14223] - Fix recording of SSL cert metadata for Expired/Unvalidated x509 certs. {pull}13687[13687] - The heartbeat scheduler no longer drops scheduled items when under very high load causing missed deadlines. {pull}14890[14890] *Journalbeat* - Use backoff when no new events are found. {pull}11861[11861] - Iterate over journal correctly, so no duplicate entries are sent. {pull}12716[12716] - Preserve host name when reading from remote journal. {pull}12714[12714] *Metricbeat* - Change diskio metrics retrieval method (only for Windows) from wmi query to DeviceIOControl function using the IOCTL_DISK_PERFORMANCE control code {pull}11635[11635] - Call GetMetricData api per region instead of per instance. {issue}11820[11820] {pull}11882[11882] - Update documentation with cloudwatch:ListMetrics permission. {pull}11987[11987] - Check permissions in system socket metricset based on capabilities. {pull}12039[12039] - Get process information from sockets owned by current user when system socket metricset is run without privileges. {pull}12039[12039] - Avoid generating hints-based configuration with empty hosts when no exposed port is suitable for the hosts hint. {issue}8264[8264] {pull}12086[12086] - Fixed a socket leak in the postgresql module under Windows when SSL is disabled on the server. {pull}11393[11393] - Change some field type from scaled_float to long in aws module. {pull}11982[11982] - Fixed RabbitMQ `queue` metricset gathering when `consumer_utilisation` is set empty at the metrics source {pull}12089[12089] - Fix direction of incoming IPv6 sockets. {pull}12248[12248] - Refactored Windows perfmon metricset: replaced method to retrieve counter paths with PdhExpandWildCardPathW, separated code by responsibility, removed unused functions {pull}12212[12212] - Validate that kibana/status metricset cannot be used when xpack is enabled. {pull}12264[12264] - Ignore prometheus metrics when their values are NaN or Inf. {pull}12084[12084] {issue}10849[10849] - In the kibana/stats metricset, only log error (don't also index it) if xpack is enabled. {pull}12265[12265] - Fix an issue listing all processes when run under Windows as a non-privileged user. {issue}12301[12301] {pull}12475[12475] - The `elasticsearch/index_summary` metricset gracefully handles an empty Elasticsearch cluster when `xpack.enabled: true` is set. {pull}12489[12489] {issue}12487[12487] - When TLS is configured for the http metricset and a `certificate_authorities` is configured we now default to `required` for the `client_authentication`. {pull}12584[12584] - Reuse connections in PostgreSQL metricsets. {issue}12504[12504] {pull}12603[12603] - PdhExpandWildCardPathW will not expand counter paths in 32 bit windows systems, workaround will use a different function. {issue}12590[12590] {pull}12622[12622] - In the elasticsearch/node_stats metricset, if xpack is enabled, make parsing of ES node load average optional as ES on Windows doesn't report load average. {pull}12866[12866] - Ramdisk is not filtered out when collecting disk performance counters in diskio metricset {issue}12814[12814] {pull}12829[12829] - Fix incoherent behaviour in redis key metricset when keyspace is specified both in host URL and key pattern {pull}12913[12913] - Fix connections leak in redis module {pull}12914[12914] {pull}12950[12950] - Fix wrong uptime reporting by system/uptime metricset under Windows. {pull}12915[12915] - Print errors that were being omitted in vSphere metricsets. {pull}12816[12816] - Fix redis key metricset dashboard references to index pattern. {pull}13303[13303] - Check if fields in DBInstance is nil in rds metricset. {pull}13294[13294] {issue}13037[13037] - Fix silent failures in kafka and prometheus module. {pull}13353[13353] {issue}13252[13252] - Fix issue with aws cloudwatch module where dimensions and/or namespaces that contain space are not being parsed correctly {pull}13389[13389] - Fix panic in Redis Key metricset when collecting information from a removed key. {pull}13426[13426] - Fix module-level fields in Kubernetes metricsets. {pull}13433[13433] {pull}13544[13544] - Fix reporting empty events in cloudwatch metricset. {pull}13458[13458] - Fix `docker.cpu.system.pct` calculation by using the reported number online cpus instead of the number of metrics per cpu. {pull}13691[13691] - Fix rds metricset dashboard. {pull}13721[13721] - Ignore prometheus untyped metrics with NaN value. {issue}13750[13750] {pull}13790[13790] - Change kubernetes.event.message to text. {pull}13964[13964] - Fix performance counter values for windows/perfmon metricset. {issue}14036[14036] {pull}14039[14039] - Add FailOnRequired when applying schema and fix metric names in mongodb metrics metricset. {pull}14143[14143] - Change `server_status_path` default setting for nginx module {issue}13806[13806] {pull}14099[14099] - Convert increments of 100 nanoseconds/ticks to milliseconds for WriteTime and ReadTime in diskio metricset (Windows) for consistency. {issue}14233[14233] - Limit some of the error messages to the logs only {issue}14317[14317] {pull}14327[14327] - Convert indexed ms-since-epoch timestamp fields in `elasticsearch/ml_job` metricset to ints from float64s. {issue}14220[14220] {pull}14222[14222] - Fix ARN parsing function to work for ELB ARNs. {pull}14316[14316] - Update azure configuration example. {issue}14224[14224] - Fix cloudwatch metricset with names and dimensions in config. {issue}14376[14376] {pull}14391[14391] - Fix marshaling of ms-since-epoch values in `elasticsearch/cluster_stats` metricset. {pull}14378[14378] - Fix checking tagsFilter using length in cloudwatch metricset. {pull}14525[14525] - Log bulk failures from bulk API requests to monitoring cluster. {issue}14303[14303] {pull}14356[14356] - Fixed bug with `elasticsearch/cluster_stats` metricset not recording license expiration date correctly. {issue}14541[14541] {pull}14591[14591] - Fix regular expression to detect instance name in perfmon metricset. {issue}14273[14273] {pull}14666[14666] - Vshpere module splits `virtualmachine.host` into `virtualmachine.host.id` and `virtualmachine.host.hostname`. {issue}7187[7187] {pull}7213[7213] - Fixed bug with `elasticsearch/cluster_stats` metricset not recording license ID in the correct field. {pull}14592[14592] - Fix perfmon expanding counter path/adding counter to query when OS language is not english. {issue}14684[14684] {pull}14800[14800] - Add extra check on `ignore_non_existent_counters` flag if the PdhExpandWildCardPathW returns no errors but does not expand the counter path successfully in windows/perfmon metricset. {pull}14797[14797] - Fix rds metricset from reporting same values for different instances. {pull}14702[14702] - Closing handler after verifying the registry key in diskio metricset. {issue}14683[14683] {pull}14759[14759] - Fix docker network stats when multiple interfaces are configured. {issue}14586[14586] {pull}14825[14825] - Fix ListMetrics pagination in aws module. {issue}14926[14926] {pull}14942[14942] *Packetbeat* - Prevent duplicate packet loss error messages in HTTP events. {pull}10709[10709] - Fixed a memory leak when using process monitoring under Windows. {pull}12100[12100] - Improved debug logging efficiency in PGQSL module. {issue}12150[12150] - Limit memory usage of Redis replication sessions. {issue}12657[12657] - Fix parsing the extended RCODE in the DNS parser. {pull}12805[12805] - Fix parsing of the HTTP host header when it contains a port or an IPv6 address. {pull}14215[14215] *Winlogbeat* - Fix data race affecting config validation at startup. {issue}13005[13005] - Set host.name to computername in Windows event logs & sysmon. Requires {pull}14407[14407] in libbeat to work {issue}13706[13706] *Functionbeat* - Fix function name reference for Kinesis streams in CloudFormation templates {pull}11646[11646] - Fix Cloudwatch logs timestamp to use timestamp of the log record instead of when the record was processed {pull}13291[13291] - Look for the keystore under the correct path. {pull}13332[13332] ==== Added *Affecting all Beats* - Decouple Debug logging from fail_on_error logic for rename, copy, truncate processors {pull}12451[12451] - Add an option to append to existing logs rather than always rotate on start. {pull}11953[11953] - Add `network` condition to processors for matching IP addresses against CIDRs. {pull}10743[10743] - Add if/then/else support to processors. {pull}10744[10744] - Add `community_id` processor for computing network flow hashes. {pull}10745[10745] - Add output test to kafka output {pull}10834[10834] - Gracefully shut down on SIGHUP {pull}10704[10704] - New processor: `copy_fields`. {pull}11303[11303] - Add `error.message` to events when `fail_on_error` is set in `rename` and `copy_fields` processors. {pull}11303[11303] - New processor: `truncate_fields`. {pull}11297[11297] - Allow a beat to ship monitoring data directly to an Elasticsearch monitoring cluster. {pull}9260[9260] - Updated go-seccomp-bpf library to v1.1.0 which updates syscall lists for Linux v5.0. {pull}11394[11394] - Add `add_observer_metadata` processor. {pull}11394[11394] - Add `decode_csv_fields` processor. {pull}11753[11753] - Add `convert` processor for converting data types of fields. {issue}8124[8124] {pull}11686[11686] - New `extract_array` processor. {pull}11761[11761] - Add number of goroutines to reported metrics. {pull}12135[12135] - Add `proxy_disable` output flag to explicitly ignore proxy environment variables. {issue}11713[11713] {pull}12243[12243] - Processor `add_cloud_metadata` adds fields `cloud.account.id` and `cloud.image.id` for AWS EC2. {pull}12307[12307] - Add configurable bulk_flush_frequency in kafka output. {pull}12254[12254] - Add `decode_base64_field` processor for decoding base64 field. {pull}11914[11914] - Add support for reading the `network.iana_number` field by default to the community_id processor. {pull}12701[12701] - Add aws overview dashboard. {issue}11007[11007] {pull}12175[12175] - Add `decompress_gzip_field` processor. {pull}12733[12733] - Add `timestamp` processor for parsing time fields. {pull}12699[12699] - Fail with error when autodiscover providers have no defined configs. {pull}13078[13078] - Add a check so alias creation explicitely fails if there is an index with the same name. {pull}13070[13070] - Update kubernetes watcher to use official client-go libraries. {pull}13051[13051] - Add support for unix epoch time values in the `timestamp` processor. {pull}13319[13319] - add_host_metadata is now GA. {pull}13148[13148] - Add an `ignore_missing` configuration option the `drop_fields` processor. {pull}13318[13318] - add_host_metadata is no GA. {pull}13148[13148] - Add `registered_domain` processor for deriving the registered domain from a given FQDN. {pull}13326[13326] - Add support for RFC3339 time zone offsets in JSON output. {pull}13227[13227] - Add autodetection mode for add_docker_metadata and enable it by default in included configuration files{pull}13374[13374] - Added `monitoring.cluster_uuid` setting to associate Beat data with specified ES cluster in Stack Monitoring UI. {pull}13182[13182] - Add autodetection mode for add_kubernetes_metadata and enable it by default in included configuration files. {pull}13473[13473] - Add `providers` setting to `add_cloud_metadata` processor. {pull}13812[13812] - Use less restrictive API to check if template exists. {pull}13847[13847] - Do not check for alias when setup.ilm.check_exists is false. {pull}13848[13848] - Add support for numeric time zone offsets in timestamp processor. {pull}13902[13902] - Add condition to the config file template for add_kubernetes_metadata {pull}14056[14056] - Marking Central Management deprecated. {pull}14018[14018] - Add `keep_null` setting to allow Beats to publish null values in events. {issue}5522[5522] {pull}13928[13928] - Add shared_credential_file option in aws related config for specifying credential file directory. {issue}14157[14157] {pull}14178[14178] - GA the `script` processor. {pull}14325[14325] - Add `fingerprint` processor. {issue}11173[11173] {pull}14205[14205] - Add support for API keys in Elasticsearch outputs. {pull}14324[14324] - Ensure that init containers are no longer tailed after they stop {pull}14394[14394] - Add consumer_lag in Kafka consumergroup metricset {pull}14822[14822] - Make use of consumer_lag in Kafka dashboard {pull}14863[14863] - Refactor kubernetes autodiscover to enable different resource based discovery {pull}14738[14738] *Auditbeat* - Auditd module: Add `event.outcome` and `event.type` for ECS. {pull}11432[11432] - Process: Add file hash of process executable. {pull}11722[11722] - Socket: Add network.transport and network.community_id. {pull}12231[12231] - Host: Fill top-level host fields. {pull}12259[12259] - Socket: Add DNS enrichment. {pull}14004[14004] *Filebeat* - Add more info to message logged when a duplicated symlink file is found {pull}10845[10845] - Add option to configure docker input with paths {pull}10687[10687] - Add Netflow module to enrich flow events with geoip data. {pull}10877[10877] - Set `event.category: network_traffic` for Suricata. {pull}10882[10882] - Allow custom default settings with autodiscover (for example, use of CRI paths for logs). {pull}12193[12193] - Allow to disable hints based autodiscover default behavior (fetching all logs). {pull}12193[12193] - Change Suricata module pipeline to handle `destination.domain` being set if a reverse DNS processor is used. {issue}10510[10510] - Add the `network.community_id` flow identifier to field to the IPTables, Suricata, and Zeek modules. {pull}11005[11005] - New Filebeat coredns module to ingest coredns logs. It supports both native coredns deployment and coredns deployment in kubernetes. {pull}11200[11200] - New module for Cisco ASA logs. {issue}9200[9200] {pull}11171[11171] - Added support for Cisco ASA fields to the netflow input. {pull}11201[11201] - Configurable line terminator. {pull}11015[11015] - Add Filebeat envoyproxy module. {pull}11700[11700] - Add apache2(httpd) log path (`/var/log/httpd`) to make apache2 module work out of the box on Redhat-family OSes. {issue}11887[11887] {pull}11888[11888] - Add support to new MongoDB additional diagnostic information {pull}11952[11952] - New module `panw` for Palo Alto Networks PAN-OS logs. {pull}11999[11999] - Add RabbitMQ module. {pull}12032[12032] - Add new `container` input. {pull}12162[12162] - Add timeouts on communication with docker daemon. {pull}12310[12310] - `container` and `docker` inputs now support reading of labels and env vars written by docker JSON file logging driver. {issue}8358[8358] - Add specific date processor to convert timezones so same pipeline can be used when convert_timezone is enabled or disabled. {pull}12253[12253] - Add MSSQL module {pull}12079[12079] - Add ISO8601 date parsing support for system module. {pull}12568[12568] {pull}12578[12579] - Update Kubernetes deployment manifest to use `container` input. {pull}12632[12632] - Use correct OS path separator in `add_kubernetes_metadata` to support Windows nodes. {pull}9205[9205] - Add support for virtual host in Apache access logs {pull}12778[12778] - Add support for client addresses with port in Apache error logs {pull}12695[12695] - Add `google-pubsub` input type for consuming messages from a Google Cloud Pub/Sub topic subscription. {pull}12746[12746] - Add module for ingesting Cisco IOS logs over syslog. {pull}12748[12748] - Add module for ingesting Google Cloud VPC flow logs. {pull}12747[12747] - Report host metadata for Filebeat logs in Kubernetes. {pull}12790[12790] - Add netflow dashboards based on Logstash netflow. {pull}12857[12857] - Parse more fields from Elasticsearch slowlogs. {pull}11939[11939] - Update module pipelines to enrich events with autonomous system fields. {pull}13036[13036] - Add module for ingesting IBM MQ logs. {pull}8782[8782] - Add S3 input to retrieve logs from AWS S3 buckets. {pull}12640[12640] {issue}12582[12582] - Add aws module s3access metricset. {pull}13170[13170] {issue}12880[12880] - Update Suricata module to populate ECS DNS fields and handle EVE DNS version 2. {issue}13320[13320] {pull}13329[13329] - Update PAN-OS fileset to use the ECS NAT fields. {issue}13320[13320] {pull}13330[13330] - Add fields to the Zeek DNS fileset for ECS DNS. {issue}13320[13320] {pull}13324[13324] - Add container image in Kubernetes metadata {pull}13356[13356] {issue}12688[12688] - Add timezone information to apache error fileset. {issue}12772[12772] {pull}13304[13304] - Add module for ingesting Cisco FTD logs over syslog. {pull}13286[13286] - Update CoreDNS module to populate ECS DNS fields. {issue}13320[13320] {pull}13505[13505] - Parse query steps in PostgreSQL slowlogs. {issue}13496[13496] {pull}13701[13701] - Add filebeat azure module with activitylogs, auditlogs, signinlogs filesets. {pull}13776[13776] {pull}14033[14033] - Add support to set the document id in the json reader. {pull}5844[5844] - Add input httpjson. {issue}13545[13545] {pull}13546[13546] - Filebeat Netflow input: Remove beta label. {pull}13858[13858] - Remove `event.timezone` from events that don't need it in some modules that support log formats with and without timezones. {pull}13918[13918] - Add ExpandEventListFromField config option in the kafka input. {pull}13965[13965] - Add ELB fileset to AWS module. {pull}14020[14020] - Add module for MISP (Malware Information Sharing Platform). {pull}13805[13805] - Add `source.bytes` and `source.packets` for uni-directional netflow events. {pull}14111[14111] - Add support for gzipped files in S3 input. {pull}13980[13980] - Add support for all the ObjectCreated events in S3 input. {pull}14077[14077] - Add Kibana Dashboard for MISP module. {pull}14147[14147] - Add JSON options to autodiscover hints {pull}14208[14208] - Add more filesets to Zeek module. {pull}14150[14150] - Add `index` option to all inputs to directly set a per-input index value. {pull}14010[14010] - Remove beta flag for some filebeat modules. {pull}14374[14374] - Add support for http hostname in nginx filebeat module. {pull}14505[14505] - Add attack_pattern_kql field to MISP threat indicators. {pull}14470[14470] - Add fileset to the Zeek module for the intel.log. {pull}14404[14404] - Add vpc flow log fileset to AWS module. {issue}13880[13880] {pull}14345[14345] - New fileset googlecloud/firewall for ingesting Google Cloud Firewall logs. {pull}14553[14553] - Add document for Filebeat input httpjson. {pull}14602[14602] - Add more configuration options to the Netflow module. {pull}14628{14628} - Add dashboards to the CEF module (ported from the Logstash ArcSight module). - Add dashboards to the CEF module (ported from the Logstash ArcSight module). {pull}14342[14342] - Fix timezone parsing in haproxy pipeline. {pull}14755[14755] - Add module for ActiveMQ. {pull}14840[14840] - Add dashboards for the ActiveMQ Filebeat module. {pull}14880[14880] *Heartbeat* - Add non-privileged icmp on linux and darwin(mac). {pull}13795[13795] {issue}11498[11498] - Enable `add_observer_metadata` processor in default config. {pull}11394[11394] - Record HTTP body metadata and optionally contents in `http.response.body.*` fields. {pull}13022[13022] - Allow `hosts` to be used to configure http monitors {pull}13703[13703] - google-pubsub input: ACK pub/sub message when acknowledged by publisher. {issue}13346[13346] {pull}14715[14715] - Remove Beta label from google-pubsub input. {issue}13346[13346] {pull}14715[14715] *Journalbeat* *Metricbeat* - Add AWS SQS metricset. {pull}10684[10684] {issue}10053[10053] - Add AWS s3_request metricset. {pull}10949[10949] {issue}10055[10055] - Add s3_daily_storage metricset. {pull}10940[10940] {issue}10055[10055] - Add `coredns` metricbeat module. {pull}10585[10585] - Add SSL support for Metricbeat HTTP server. {pull}11482[11482] {issue}11457[11457] - The `elasticsearch.index` metricset (with `xpack.enabled: true`) now collects `refresh.external_total_time_in_millis` fields from Elasticsearch. {pull}11616[11616] - Allow module configurations to have variants {pull}9118[9118] - Add `timeseries.instance` field calculation. {pull}10293[10293] - Added new disk states and raid level to the system/raid metricset. {pull}11613[11613] - Added `path_name` and `start_name` to service metricset on windows module {issue}8364[8364] {pull}11877[11877] - Add check on object name in the counter path if the instance name is missing {issue}6528[6528] {pull}11878[11878] - Add AWS cloudwatch metricset. {pull}11798[11798] {issue}11734[11734] - Add `regions` in aws module config to specify target regions for querying cloudwatch metrics. {issue}11932[11932] {pull}11956[11956] - Keep `etcd` followers members from reporting `leader` metricset events {pull}12004[12004] - Add overview dashboard to Consul module {pull}10665[10665] - New fields were added in the mysql/status metricset. {pull}12227[12227] - Add Kubernetes metricset `proxy`. {pull}12312[12312] - Add Kubernetes proxy dashboard to Kubernetes module {pull}12734[12734] - Always report Pod UID in the `pod` metricset. {pull}12345[12345] - Add Vsphere Virtual Machine operating system to `os` field in Vsphere virtualmachine module. {pull}12391[12391] - Add validation for elasticsearch and kibana modules' metricsets when xpack.enabled is set to true. {pull}12386[12386] - Add CockroachDB module. {pull}12467[12467] - Add support for metricbeat modules based on existing modules (a.k.a. light modules) {issue}12270[12270] {pull}12465[12465] - Add a system/entropy metricset {pull}12450[12450] - Add kubernetes metricset `controllermanager` {pull}12409[12409] - Add Kubernetes controller manager dashboard to Kubernetes module {pull}12744[12744] - Allow redis URL format in redis hosts config. {pull}12408[12408] - Add tags into ec2 metricset. {issue}[12263]12263 {pull}12372[12372] - Add metrics to kubernetes apiserver metricset. {pull}12922[12922] - Add kubernetes metricset `scheduler` {pull}12521[12521] - Add Kubernetes scheduler dashboard to Kubernetes module {pull}12749[12749] - Add `beat` module. {pull}12181[12181] {pull}12615[12615] - Collect tags for cloudwatch metricset in aws module. {issue}[12263]12263 {pull}12480[12480] - Add AWS RDS metricset. {pull}11620[11620] {issue}10054[10054] - Add Oracle Module {pull}11890[11890] - Add Oracle Tablespaces Dashboard {pull}12736[12736] - Collect client provided name for rabbitmq connection. {issue}12851[12851] {pull}12852[12852] - Add support to load default aws config file to get credentials. {pull}12727[12727] {issue}12708[12708] - Add statistic option into cloudwatch metricset. {issue}12370[12370] {pull}12840[12840] - Add support for kubernetes cronjobs {pull}13001[13001] - Add cgroup memory stats to docker/memory metricset {pull}12916[12916] - Add AWS elb metricset. {pull}12952[12952] {issue}11701[11701] - Add AWS ebs metricset. {pull}13167[13167] {issue}11699[11699] - Add `metricset.period` field with the configured fetching period. {pull}13242[13242] {issue}12616[12616] - Add rate metrics for ec2 metricset. {pull}13203[13203] - Add refresh list of perf counters at every fetch {issue}13091[13091] - Add Performance metricset to Oracle module {pull}12547[12547] - Add proc/vmstat data to the system/memory metricset on linux {pull}13322[13322] - Use DefaultMetaGeneratorConfig in MetadataEnrichers to initialize configurations {pull}13414[13414] - Add module for statsd. {pull}13109[13109] - Add support for NATS version 2. {pull}13601[13601] - Add `docker.cpu.*.norm.pct` metrics for `cpu` metricset of Docker Metricbeat module. {pull}13695[13695] - Add `instance` label by default when using Prometheus collector. {pull}13737[13737] - Add azure module. {pull}13196[13196] {pull}13859[13859] {pull}13988[13988] - Add Apache Tomcat module {pull}13491[13491] - Add ECS `container.id` and `container.runtime` to kubernetes `state_container` metricset. {pull}13884[13884] - Add `job` label by default when using Prometheus collector. {pull}13878[13878] - Add `state_resourcequota` metricset for Kubernetes module. {pull}13693[13693] - Add tags filter in ec2 metricset. {pull}13872[13872] {issue}13145[13145] - Add cloud.account.id and cloud.account.name into events from aws module. {issue}13551[13551] {pull}13558[13558] - Add `metrics_path` as known hint for autodiscovery {pull}13996[13996] - Leverage KUBECONFIG when creating k8s client. {pull}13916[13916] - Add ability to filter by tags for cloudwatch metricset. {pull}13758[13758] {issue}13145[13145] - Release cloudwatch, s3_daily_storage, s3_request, sqs and rds metricset as GA. {pull}14114[14114] {issue}14059[14059] - Add Oracle overview dashboard {pull}14021[14021] - Release CoreDNS module as GA. {pull}14308[14308] - Release CouchDB module as GA. {pull}14300[14300] - Add `elasticsearch/enrich` metricset. {pull}14243[14243] {issue}14221[14221] - Add support for Application ELB and Network ELB. {pull}14123[14123] {issue}13538[13538] {issue}13539[13539] - Release aws ebs metricset as GA. {pull}14312[14312] {issue}14060[14060] - Add `connection.state` field for RabbitMQ module. {pull}13981[13981] - Add more TCP states to Metricbeat system socket_summary. {pull}14347[14347] - Add Kafka JMX metricsets. {pull}14330[14330] - Add metrics to envoyproxy server metricset and support for envoy proxy 1.12. {pull}14416[14416] {issue}13642[13642] - Release kubernetes modules `controllermanager`, `scheduler`, `proxy`, `state_cronjob` and `state_resourcequota` as GA. {pull}14584[14584] - Add module for ActiveMQ. {pull}14580[14580] - Enable script processor. {pull}14711[14711] - Add usage metricset in aws modules. {pull}14925[14925] {issue}14935[14935] - Add billing metricset in aws modules. {pull}14801[14801] {issue}14934[14934] - Add AWS SNS metricset. {pull}14946[14946] *Packetbeat* - Update DNS protocol plugin to produce events with ECS fields for DNS. {issue}13320[13320] {pull}13354[13354] *Functionbeat* - New options to configure roles and VPC. {pull}11779[11779] - Export automation templates used to create functions. {pull}11923[11923] - Configurable Amazon endpoint. {pull}12369[12369] - Add timeout option to reference configuration. {pull}13351[13351] - Configurable tags for Lambda functions. {pull}13352[13352] - Add input for Cloudwatch logs through Kinesis. {pull}13317[13317] - Enable Logstash output. {pull}13345[13345] - Make `bulk_max_size` configurable in outputs. {pull}13493[13493] *Winlogbeat* - Add support for reading from .evtx files. {issue}4450[4450] - Add support for event ID 4634 and 4647 to the Security module. {pull}12906[12906] - Add `network.community_id` to Sysmon network events (event ID 3). {pull}13034[13034] - Add `event.module` to Winlogbeat modules. {pull}13047[13047] - Add `event.category: process` and `event.type: process_start/process_end` to Sysmon process events (event ID 1 and 5). {pull}13047[13047] - Add support for event ID 4672 to the Security module. {pull}12975[12975] - Add support for event ID 22 (DNS query) to the Sysmon module. {pull}12960[12960] - Add certain winlog.event_data.* fields to the index template. {issue}13700[13700] {pull}13704[13704] - Fill `event.provider`. {pull}13937[13937] - Add support for user management events to the Security module. {pull}13530[13530] - GA the Winlogbeat `sysmon` module. {pull}14326[14326] - Add support for event ID 4688 & 4689 (Process create & exit) to the Security module. {issue}14038[14038] ==== Deprecated *Affecting all Beats* *Filebeat* - `docker` input is deprecated in favour `container`. {pull}12162[12162] - `postgresql.log.timestamp` field is deprecated in favour of `@timestamp`. {pull}12338[12338] *Heartbeat* *Journalbeat* *Metricbeat* - `kubernetes.container.id` field for `state_container` is deprecated in favour of ECS `container.id` and `container.runtime`. {pull}13884[13884] *Packetbeat* *Winlogbeat* *Functionbeat* ==== Known Issue *Journalbeat* ",16231,True,3710.577771589124,median ":author: hhaim :email: ifndef::backend-docbook[] ++++++++++++++










++++++++++++++ include::trex_ga.asciidoc[] :github_stl_path: https://github.com/cisco-system-traffic-generator/trex-core/tree/master/scripts/stl :github_stl_examples_path: https://github.com/cisco-system-traffic-generator/trex-core/tree/master/scripts/automation/trex_control_plane/interactive/trex/examples/stl == TRex release notes == endif::backend-docbook[] ifdef::backend-docbook[] == TRex release notes == :numbered: endif::backend-docbook[] == Release 2.47 == * ASTF: supports interactive framework like STL. common features are: ** L2 emulation (arp/ipv6/l3/ping/vlan/scan6 etc) ** Port management (e.g. link attribute) ** Network namespace ** Capture/service mode ** Plugin services ** Console/TUI/API ** Not supported yet: cluster mode * The ASTF batch mode is planned to be deprecated .Start ASTF in interactive mode [source,bash] ------------------- sudo ./t-rex-64 -i --astf ------------------- .Console [source,bash] ------------------- ./trex-console -s [server-ip] ----------------- .From Console [source,bash] ------------------- trex>start -f astf/http_simple.py -m 1000 -d 1000 -l 1000 trex>tui trex>[press] t/l for astf statistics and latency trex>stop ------------------ * An updated manual with the new features link:trex_astf.html[astf] * ASTF API docomentation is here link:cp_astf_docs/api/client_code.html[python_astf_api] link:trex_astf.html#_tutorial_python_automation_v2_47_and_up[automation] * ASTF RPC spec for developers is here link:trex_rpc_server_spec.html#_rpc_commands_astf[rpc] * STL: add stream pinning to core see link:trex_stateless.html#_tutorial_core_pinning[core_pinning] * ASTF/STL Linux network namespace emulation stacks see link:trex_manual.html#_emulation_stacks[emulation] === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-540[trex-540] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-538[trex-538] == Release 2.46 == * ASTF: add per_core_distribution field see link:cp_astf_docs/_modules/trex/astf/trex_astf_profile.html#ASTFIPGenDist[per_core_distribution] * Extend astf-sim to replay pcap file for STF mode link:https://github.com/cisco-system-traffic-generator/trex-core/issues/156[github-256] * Amazon DPDK ENA driver fix * Stateless GUI can build trex_cfg.yaml file * Support Python ZMQ 32bit binding for x86-32bit platforms * fix scapy igmp3 for python-3 * eWLC plugin for AP scale tests === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-536[trex-536] * link:https://github.com/cisco-system-traffic-generator/trex-core/issues/150[github-150] * link:https://github.com/cisco-system-traffic-generator/trex-core/issues/123[github-123] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-192[trex-192] == Release 2.45 == * Upgrade to DPDK 18.08 * Latency dummy stream does not consume pgid * Server/Python client use the same C-ZMQ share object. * Simplified Python ZMQ binding * Speedup service mode using server side ZMQ IPC == Release 2.44 == * Upgrade to DPDK 18.05 * Stateless: allow ""start"" when port is unresolved and all streams have explicit dest MAC. * mlx5 can compile with Ubuntu distro === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-533[trex-533] == Release 2.43 == * Client Python library consolidation STL/ASTF ** New code should use: + ---- from trex.stl.api import * ---- ** For backward compatability old code still works: + ---- from trex_stl_lib.api import * ---- ** Interactive ASTF connects to the console, sending traffic/collecting stats via new lib is WIP. * Mellanox with OFED 4.3.1 offers newer FW with significantly better RX speed (due to faster dropping). + Bidirectional 64B packets RX is \\~132MPPS from 2 ports (compared to ~38MPPS with older OFED/FW) * TODO: describe FE instruction ""list"" === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-531[trex-531] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-532[trex-532] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-510[trex-510] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-528[trex-528] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-529[trex-529] == Release 2.41 == * ASTF ** Add support for non-blocking `send`, for better eflow performance (30Gb/sec per one flow) see http_eflow2.py profile ** Fix TCP fast recovery. dupack counter wasn't cleard * minor bug fixes == Release 2.41 == * ASTF ** Add support for non-blocking `send`, for better eflow performance (30Gb/sec per one flow) see http_eflow2.py profile ** Fix TCP fast recovery. dupack counter wasn't cleard * minor bug fixes == Release 2.40 == * Search for Python2/3 in start-up scripts * Add Amazon ENA DPDK driver - there are reports that the performance is not that good. * Fix STL Console history issue * ARM compilation issue fix (BPF) * Add ASTF example profiles (e.g elephant flow) === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-526[trex-526] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-525[trex-525] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-524[trex-524] == Release 2.39 == * ASTF multi-core support see link:trex_astf.html#_multi_core_support[astf] can reach 200gb/sec with TCP/UDP stack === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-428[trex-428] == Release 2.38 == * Dummy port support. (more info in link:trex_manual.html#_dummy_ports[manual]) + They can solve 2 issues: ** Odd number of interfaces (e.g. single port) ** Performance degradation when adjacent interfaces belong to different NUMAs. * Advance Stateful (ASTF) ** Support L7 emulation on top of UDP (e.g. DNS/RTP Video) ** Faster script to convert to JSON (Scapy->dpkt) * Napatech benchmark on UCS240 link:trex_appendix_napatech.html#_performance_benchmark[napatech_benchmark] === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-500[trex-500] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-521[trex-521] == Release 2.37 == * Low footprint support. Resource require with this mode 1 thread and ~500MB RAM. More info in link:trex_manual.html#_low_end_machines[manual] * Option to work with Linux interfaces (raw socket mode,--vdev/af_packet). More info in link:trex_manual.html#_linux_interfaces[manual] Example [source,bash] ---- - port_limit : 2 version : 2 low_end : true #<1> interfaces : [""veth0"", ""veth1""] #<2> port_info : # set eh mac addr - ip : 1.1.1.1 default_gw : 2.2.2.2 - ip : 2.2.2.2 default_gw : 1.1.1.1 ---- <1> low footprint <2> Linux interfaces * Above options introduced for supporting Cisco VIRL and Cisco IOx. * Docker hub image for simple tutorials using veth/low footprint link:trex_vm_manual.html[Docker] * ARM build support (works with virio for now) * ASTF, simulator can have `-e` option to debug the emulation layer == Release 2.36 == * ASTF ** Remove ASTFTCPInfo object from the profile (*NOT* backward compatible) ** Add support for scheduler.rampup_sec tunable ** Add support for scheduler.accurate tunable - accurate traffic generation for low rates(<20gbps) important for ASA ** Add --lro-disable CLI ** Add profiles that are Spirent compatible * ASTF/STF - add promiscuous mode using ""--prom"" CLI * Support CX-3 Mellanox cards * Update Napatech driver * STL ** HLTAPI bug fixes ** fix XL710 VF counters crash ** Add IPV6 ND service === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-278[trex-278] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-514[trex-514] == Release 2.35 == * ASTF L7 emulation enhancements. ** Ability to control the L7 application with more commands (e.g. random delay in the server,elephant flow, syn-ack-rst flow) see link:trex_astf.html#_tutorial_l7_emulation_fin_ack_fin_ack[l7-emulation-example] and link:cp_astf_docs/api/profile_code.html#astfprogram-class[l7-program] ** Ability to limit the total number of generated flows using `limit` directive. For example, to create a limited number of elephant flows. ** profile-tunable: ability to tune the profile using key-val input see link: trex_astf.html#_tutorial_profile_cli_tunable[l7-cli-tunable] ** Refactor the code for ASTF interactive support ** Fix TCP crash in case of corrupted packet * Napatech support for DPDK 17.11 * Stateless, Fix ipv6.scan6 crash in case of ""ff02::1"" addr (VPP use case) == Release 2.34 == * Mellanox Cx-4/5 ** Fix stability issue link:https://trex-tgn.cisco.com/youtrack/issue/trex-507[trex-507] ** Workaround to link:https://trex-tgn.cisco.com/youtrack/issue/trex-481[trex-481] * Stateless ** Add support for update/pause/resume per stream-id see link:trex_stateless.html#_per_stream_operations[per stream operation] ** Fix core pinning with latency stream. link:https://trex-tgn.cisco.com/youtrack/issue/trex-428[trex-428] * Advance Stateful - add client cluster mode support === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-428[trex-428] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-507[trex-507] thanks to Mellanox DPDK team == Release 2.33 == * Upgrade to DPDK 17.11 ** Better XXV710 support ** Mellanox CX-4/CX-5 big performance improvement (CX-5, Tx=149MPPS/Rx=120MPPS at 64B). ** A small degradation in XL710 Stateless performance WARNING: For Mellanox CX-5/4 there is a need to upgrade the distro to CentOs 7.4 and OFED to 4.2.1. This new OFED version does *not* work with older TRex versions see link:trex_manual.html#ofed_upgrade[ofed upgrade procedure] === Known issues: === * Mellanox CX-4/CX-5 stability issues see link:https://trex-tgn.cisco.com/youtrack/issue/trex-507[trex-507] == Release 2.32 == * Advance Stateful (ASTF) ** Tunables support. Tunables is a mechanism to tune the behavior of ASTF traffic profile see here link:trex_astf.html#tunable_tcp_mss[tunables] ** Cisco VIC support TSO now * Support gcc 7.x/6.x and sanitizer * Stateless ** Improve performance (mbuf-refcnt locality) == Release 2.31 == * Stateless ** Console - added option to save loaded streams as Python profile (stream command from the Console) ** Console - ability to load JSON/YAML from start command (e.g. `start -f stl/gui_example.yaml -m 100kpps --port 0`) * TCP some performance improvements (up to 5MPPS/core) ** Tune TCP timers for traffic generation case (e.g. 2MSL/keepalive is shorter) ** Add support to RFC6928 (add support for initwnd and set it by default to 10). A way to tune all the TCP parameters (including this one) will be given from the traffic profile. ** Protect TRex ASTF resource (e.g. overflow in active flows) ** General hardening ** Support client or server mode see link:trex_astf.html#_client_server_only_mode[client_server_only_mode] * Refactor the code to support ASTF in interactive mode (both STL and STF will work with the same RPC framework) * Increase the TX queue for all drivers by default - less probability for queue_full in high rates === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-495[trex-495] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-491[trex-491] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-486[trex-486] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-492[trex-492] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-485[trex-485] == Release 2.30 == * Advance Stateful (ASTF) with scalable TCP support ** Support all SFR profile with TCP flows ** Mellanox driver issue workaround see here link:https://trex-tgn.cisco.com/youtrack/issue/trex-481[trex-481] ** Hardening ** Add full simulation support using `./astf-sim --full` see here link:trex_astf.html[ASTF mode] * Wireless AP/Station emulation plugin for WLC testing. ** Improve performance considerably ** Update documentation link:trex_stateless_wlc_bench.html[WLC] * Support Napatech NIC (100Gb@64B line-rate) * Stateless ** Full Stream object are return from the client ** Old YAML profile support was removed === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-483[trex-483] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-480[trex-480] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-472[trex-472] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-475[trex-475] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-461[trex-461] == Release 2.29 == * Preliminary version with Advance Stateful (ASTF) with scalable TCP support see here link:trex_astf.html[ASTF mode] * Wireless AP/Station emulation plugin for WLC testing see link:trex_stateless_wlc_bench.html[WLC] * General ** IPv4 software checksum was wrong for 0.01% of the cases - found by link:https://wiki.fd.io/view/CSIT[CSIT group] === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-469[trex-469] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-464[trex-464] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-463[trex-463] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-462[trex-462] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-460[trex-460] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-457[trex-457] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-435[trex-435] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-453[trex-453] == Release 2.28 == * Cisco FirePOWER/ASA Stateful friendly ** Fix TCP/UDP by default in case DPDK driver support it (--checksum-offload is deprecated, new switch to disable this) ** start client source port is random- better distribution to queues ** Stateful performance degradation 5-9% due to checksum offload * Stateless ** Add capture mode information in JSON ** Fix behaviour of clear_flow_stats and clear_latency_stats args in stateless clear_stats API ** BPF-JIT filter support for traffic capture ** services are using BPF filter for better performance ** Report 0 rate immediately after stopping the flow stat stream ** Fix HLTAPI per-stream stats (keys of line utilization in pg_id stats got removed) ** Add openssl share object for DTLS/CAPWAP services * General ** Fix dpdk_setup_ports.py fails with Python 3 ** Fix latency in case cluster configuration === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-451[trex-451] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-447[trex-447] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-439[trex-439] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-446[trex-446] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-445[trex-445] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-443[trex-443] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-440[trex-440] == Release 2.27 == * Support 802.1Q and 802.1AD (QinQ) for Stateless services and port config see link:cp_stl_docs/api/client_code.html#trex_stl_lib.trex_stl_client.STLClient.set_l3_mode[l3 configuration with vlan] and link:{github_stl_examples_path}/stl_multiple_arps.py[stl_ndr_bench_tool.py example] * Remove async RPC flow-stats support. Only new sync RPC API is supported from this version. The implication is that only new GUI version (>v3.2 will work) ** refactor Python client side and fix some multi-user crash/bugs WARNING: Only GUI with version greater than v3. 2 will work with this version === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-432[trex-432] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-431[trex-431] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-427[trex-427] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-376[trex-376] == Release 2.26 == * get_pgid RPC command - change the JSON format. v2.25 client will not work with v2.26 server. Done for better JSON compatibility == Release 2.25 == * Added new stateless Python API, link:cp_stl_docs/api/client_code.html#get-pgid-stats[""get_pgid_stats""]. New API brings flow statistics and latency info for given list of packet group IDs by doing synchronous call to the server. This is opposed to the old API ""get_stats"" which brings information saved in the client, and updated every 0.5 second by asynchronous message from the server. This way, we can scale the number of pgids and the client can consume only the information it really needs, when it needs it, so statistics for more flows can be supported. **Notice** that in some future release, pgid info will not be supported using the old ""get_stats"" any more. Example for using the new API can be found in link:{github_stl_examples_path}/stl_flow_latency_stats.py[stl_flow_latency_stats.py] WARNING: In some future release, per stream statistics will not be reported using the old `get_stats` API due to scale issue, please move to the new API * Fix mlx5 driver crash/corruption (bug exits from version v2.18) * Fix Python client race condition in case of fast connect/disconnect * Remove Enum from Python packages for Python 3.5 backward compatibility * Preliminary RFC 2544 example link:{github_stl_examples_path}/stl_ndr_bench_tool.py[stl_ndr_bench_tool.py] === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-420[trex-420] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-405[trex-405] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-415[trex-415] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-416[trex-416] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-413[trex-413] == Release 2.24 == * Add support for Mellanox CX-3 VF * Better way to map DPDK ports to TRex ports [source,python] ---- * In order interfaces : [""03:00.0"",""03:00.1"",""82:00.0"",""82:00.1""] * Out order interfaces : [""03:00.1"",""03:00.0"",""82:00.1"",""82:00.0""] * Out order interfaces : [""03:00.1"",""82:00.0""] * CX3 example : each PCI has 2 ports /1 is sub interface interfaces : [""03:00.0/1"",""03:00.0/0""] ---- * L2 emulation plugins framework see here link:trex_stateless.html#_services[services framework] example for DHCP/ARP/ICMP * 2K mbuf in Rx side --> less memory is needed * Fix Docker uid issue * Better errors in case of slow RTC network === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-449[trex-449] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-448[trex-448] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-295[trex-295] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-413[trex-413] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-408[trex-408] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-398[trex-398] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-372[trex-372] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-402[trex-402] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-400[trex-400] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-371[trex-371] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-397[trex-397] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-393[trex-393] == Release 2.23 == * Support up to 1023 per stream statistics ids in software mode and with mlx5 driver * Service mode works better with multi-user * i40e - disable LLDP === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-381[trex-381] == Release 2.22 == * hotfix for software mode == Release 2.21 == * New command line arguments. `--no-hw-flow-stat`, and `--software`, for changing behavior of stateless per stream flow statistics and latency features. See detail link:trex_manual.html#_command_line_options[here]. * Support for QinQ packets in stateless per port statistics (if using new `--software` command line arg). * Support for all types of VIC cards (including ones will old firmware), using `--software`. Since we do not have all cards in our lab, we could not test all of them. Will be glad for feedback on this (good or bad). * GUI : packet builder scapy server fix for cases of packets with variable length fields (e.g. DNS) * ConnectX-4/5 support VF mode * Stateless STLVmFlowVarRepeatableRandom instruction - fix typo, add another instruction with the right name * Support vfio-pci in case it exists in the kernel (instead of igb_uio) to support Docker container without the need to compile the kernel module * Capture TRex internal generated packets (e.g. ARP/Ping) * Support older Linux distribution for Python Client code (ZMQ share object can be loaded on older machine) * Performance trend report information is taken from ElasticSearch instead of Google analytics === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-370[trex-370] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-373[trex-373] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-375[trex-375] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-377[trex-377] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-378[trex-378] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-369[trex-369] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-368[trex-368] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-366[trex-366] == Release 2.20 == * hotfix release add mlx-dpdk share objects to the package == Release 2.19 == * mlx5 dpdk driver works only with OFED 4.0 (OFED 3.4 will not be supported) ** ConnectX-5 should work now * VirtualBox with E1000 (Our Tutorial OVA) get latency packets correctly * fix NAT randomization mode * Ability to build without mlx5-dpdk driver using ./configure `--no-mlx` * RX thread CPU% is not 100% all the time from this version * Better handling of latency packets (case of fast start/stop) === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-295[trex-295] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-364[trex-364] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-361[trex-361] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-361[trex-361] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-362[trex-362] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-360[trex-360] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-359[trex-359] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-358[trex-358] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-354[trex-354] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-350[trex-350] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-355[trex-355] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-352[trex-352] WARNING: you must upgrade to OFED 4.0 even with ConnectX-4 cards == Release 2.18 == * DPDK 17.02 ** Should supports ConnectX-5 but has an OFED issue see link:https://trex-tgn.cisco.com/youtrack/issue/trex-353[trex-353] ** ixgbe SR-IOV works * Ability to add VLAN per direction link:trex_manual.html#_vlan_dot1q_support[vlan_dot1q_support] * Stateless packet capture - ability to capture tx side * mlx5 dpdk driver is share object. Reduce image OFED libs dependency === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-344[trex-344] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-269[trex-269] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-339[trex-339] == Release 2.17 == * hotfix release === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-342[trex-342] == Release 2.16 == * IPv6 console basic support (link:trex_stateless.html#_ipv6_nd_client[ipv6]): ** scan6 function to search for IPv6-enabled neighbors ** ping can be used with IPv6 addresses to ping nearby devices * Stateless Rx capturing mode support link:trex_stateless.html#_packet_capturing[capturing] * Stateless support functional testing / send packet /expect RX packet etc link:trex_stateless.html#_functional_tutorials[functional] === Video Tutorials (Beta) : === Our first video tutorial on YouTube: ifdef::backend-xhtml11[] ++++++++++++++++++ ++++++++++++++++++ endif::backend-xhtml11[] The Tutorial shows a little bit of our new packet capture ability which was released on v2.16 === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-258[trex-258] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-337[trex-337] == Release 2.15 == * XL710/X710 VF (SR-IOV) mode works better * 599 VF mode is *not* supported === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-333[trex-333] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-331[trex-331] == Release 2.14 == * Another performance improvement in Stateful case with high active flows. There is less burstiness * Scapy server - warning in case of permissions errors * Maximum supported ports are 16 (instead of 12) * ConnectX-4 DPDK driver is based on 16.11 (from 16.07) - better performance is some cases * Early support for Intel XL710/X710/599 VF support link:trex_manual.html#_configure_linux_to_use_vf_on_intel_x710_and_82599_nics[sr_iov] * Fix Cluster mode breakage (v2.12-v2.13) * Stateless GUI v3.0 works with this version === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-319[trex-319] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-322[trex-322] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-326[trex-326] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-330[trex-330] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-329[trex-329] == Release 2.13 == * Significantly improve performance and scale for stateful case with high active flows (70%-300% better) see here link:trex_manual.html#_more_active_flows[More active flows] * Stateful with low active repeatable flows - an optimization was removed, for example `cap2/imix_fast_1g.yaml`. users that want to get this in high performance are adviced to move to Stateles mode. Removing this support improved the common case. * Support NAT without IPv4.option and UDP flows- for ASA link:https://trex-tgn.cisco.com/youtrack/issue/trex-274[trex-274] * Scapy server is restart automatically - for future Stateless GUI link:https://trex-tgn.cisco.com/youtrack/issue/trex-291[trex-291] * Add minimum ipg for remote pcap link:https://trex-tgn.cisco.com/youtrack/issue/trex-281[trex-281] * Console port commands works on VIC and ConnectX-4 * RPC API version is 3.0 - New stateless GUI is required === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-317[trex-317] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-282[trex-282] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-190[trex-190] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-279[trex-279] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-313[trex-313] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-312[trex-312] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-310[trex-310] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-191[trex-191] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-306[trex-306] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-234[trex-234] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-308[trex-308] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-283[trex-283] == Release 2.12 == * Improve support for Mellanox ConnectX-4 cards (100/50/25GbE) ** Only CentOs/RedHat 7.2 and up is supported due to OFED issues ** Improve 64Byte Stateleess performance * Cisco VIC is fully supported * Stateless L2/L3 configuration mode for ports - link:trex_stateless.html#_port_layer_mode_configuration[Port Layer Mode Configuration] * Stateless neighboring protocols infra and first protocols support/Python API - link:trex_stateless.html#_neighboring_protocols[Neighboring Protocols] * Stateful - ARP support for Client clustering mode (a.k.a APIC-EM) see here link:trex_manual.html#_client_clustering_configuration[Client Clustering] * Added Stateless performance trend document link:trex_analytics.html[trex performance trend] [IMPORTANT] ===================================== Change of behavior - trex config file (/trex/cfg.yaml) should include a distinct MAC address or distinct IP address. Not setting the port information : before v2.12 : src MAC addr == 00:00:00:01:00:00 v2.12 and up : src MAC addr == HW MAC address =========================== === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-257[trex-257] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-265[trex-265] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-280[trex-280] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-277[trex-277] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-278[trex-278] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-199[trex-199] == Release 2.11 == * Early support for Mellanox ConnectX-4 cards (100/50/25GbE) - based on contributions from Mellanox DPDK team see here for more info link:trex_manual.html#_mellanox_connectx_4_support[Mellanox ConnectX-4 Support] * Add support for Cisco VIC 1300 series adapter (40GbE)- based on Cisco VIC DPDK team see link:trex_manual.html#_cisco_vic_support[Cisco VIC Support] === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-268[trex-268] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-267[trex-267] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-195[trex-195] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-271[trex-271] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-255[trex-255] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-249[trex-249] == Release 2.10 == * Added support for IP based configuration files (As opposed to MAC based used until now), with the ability of TRex to send ARP requests for default gateway, and gratitues ARP for its own addresses. See link:trex_manual.html#_configuration_yaml_parameter_of_cfg_option[here] and link:trex_config_guide.html[here] for details. * Added commands/API to Stateless client/console: ** Getting extended counters of port for improved debug purposes. See example: link:trex_stateless.html#_stats[stats] ** Changing of port attributes and getting async feedback on the changed status. See example: link:trex_stateless.html#_portattr[portattr] * For developers - added/updated RPC commands (which can be used for GUI etc.): ** Getting system info added new options, for example description of interface: link:trex_rpc_server_spec.html#_get_system_info[get_system_info] ** Setting port attributes added new options: link:trex_rpc_server_spec.html#_setting_port_attributes[set_port_attr] ** Getting xstats names (can be polled once and then combined with updated values): link:trex_rpc_server_spec.html#_get_xstat_names[get_port_xstats_names] ** Getting xstats values: link:trex_rpc_server_spec.html#_get_xstat_values[get_port_xstats_values] === Fixed issues: === * link:https://trex-tgn.cisco.com/youtrack/issue/trex-253[trex-253] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-212[trex-212] * link:https://trex-tgn.cisco.com/youtrack/issue/trex-251[trex-251] == Release 2.09 == * Stateless, split to core algorithm is more accurate and simple see link:trex_stateless.html#_tutorial_field_engine_split_to_core[split_to_core] * Add repeatable random instruction see an example link:https://github.com/cisco-system-traffic-generator/trex-core/tree/master/scripts/stl/udp_1pkt_repeat_random.py[stl/udp_1pkt_repeat_random.py] link:cp_stl_docs/api/field_engine.html#stlvmflowvarrepetablerandom[repetable_random] and link:trex_rpc_server_spec.html#_repetable_random[repetable_random_spec] * Add TCP/UDP checksum fix instruction see an example link:https://github.com/cisco-system-traffic-generator/trex-core/tree/master/scripts/stl/syn_attack_fix_cs_hw.py[stl/syn_attack_fix_cs_hw.py] link:cp_stl_docs/api/field_engine.html#stlvmfixchecksumhw[fix checksum] and link:trex_rpc_server_spec.html#_fix_checksum_hw[fix_checksum_hw_spec] * Improve Stateless Field Engine (FE) performance * Support dual mode for push pcap/remote Python API. see here link:cp_stl_docs/api/client_code.html#trex_stl_lib.trex_stl_client.STLClient.push_remote[push_remote] and link:cp_stl_docs/api/client_code.html#trex_stl_lib.trex_stl_client.STLClient.push_pcap[push_pcap] Using this feature pcap can be splited to client/server ports * Add infra for L2 emulation support === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/issue/trex-243[trex-243] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-247[trex-247] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-244[trex-244] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-249[trex-249] == Release 2.08 == * Scapy JSON-RPC server for GUI packet crafting, see link:trex_scapy_rpc_server.html[trex_scapy_rpc_server] * Client.start Python API supports Core mask - significantly improve the Stateless performance. link:cp_stl_docs/_modules/trex_stl_lib/trex_stl_client.html#STLClient.start[start API], and link:trex_stateless.html#_core_masking_per_interface[core_masking] * Upgrade the ./dpdk_setup_ports.py script. It simplifies the way to create first time *optimized* config file (/etc/trex_cfg.yaml). More info at the manual: link:trex_manual.html#_script_for_creating_config_file[Script for creating config file] [source,bash] ---- [bash]>sudo ./dpdk_setup_ports.py -t # show the list of ports [bash]>sudo ./dpdk_setup_ports.py -l # return DPDK interfaces to Linux (if there is proper Linux driver) [bash]>sudo ./dpdk_setup_ports.py -i # interactive creation of config file [bash]>sudo ./dpdk_setup_ports.py -c 03:00.0 03:00.1 -o /etc/trex_cfg.yaml # create optimum /etc/trex_cfg.yaml file ---- * Preliminary Cisco VIC support. Advanced Stateless/Stateful functionality is still not supported. * Enforce latest firmware for XL710/X710 (5.04) * Add a way to stop/close NICS at TRex termination (link would be down) `-close-at-end` * IPv6 XL710 ICMP packets are supported now === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/issue/trex-240[trex-240] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-242[trex-242] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-246[trex-246] == Release 2.07 == * DPDK 16.07 * ASYNC ZMQ is compressed by default. It improves response time see link:http://trex-tgn.cisco.com/youtrack/issue/trex-232[trex-232] ** You will need to update the GUI * Support Ubuntu 16.01 - Stateful serverr is Python 3.0 and Python 3.5 for ZMQ library * XL710/X710 low latency was improved - see link:http://trex-tgn.cisco.com/youtrack/issue/trex-214[trex-214] * Support graceful shutdown command * Console - support L1 BPS using `-m 10bpsl1` see link:http://trex-tgn.cisco.com/youtrack/issue/trex-230[trex-230] * Improve TUI refresh time * Support IPV6 latency streams (support is available for all interface types except 82599) see link:trex_stateless.html#_tutorial_per_stream_latency_jitter_packet_errors[IPV6 latency] [IMPORTANT] ===================================== For XL710/X710 there is a need to upgrade the firmware to 5.04 (or later) ===================================== === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/issue/trex-214[trex-214] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-223[trex-223] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-226[trex-226] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-224[trex-224] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-235[trex-235] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-236[trex-236] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-238[trex-238] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-233[trex-233] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-231[trex-231] == Release 2.06 == * Support APIC-EM scale Stateful VLAN/IP/MAC mapping. * TCP SYN Randomization learning support for advanced ASA stateful testing - link:trex_manual.html#_nat_support[here] and link:trex_manual.html#_trex_with_asa_5585[here] * Advanced to latest DPDK 16.07RC3 - fix some XL710 driver performance issues === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/issue/trex-229[trex-229] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-227[trex-227] == Release 2.05 == === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/issue/trex-221[trex-221] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-220[trex-220] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-219[trex-219] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-218[trex-218] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-217[trex-217] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-216[trex-216] == Release 2.04 == * Watchdog support * Ability to export core file * Optimized the case of Latency stream, Field Engine and 9K template packets === Fixed issues: === * XL710/X710 present high latency with 9K packets link:http://trex-tgn.cisco.com/youtrack/issue/trex-214[trex-214] * The latency seq number gets out of sync link:http://trex-tgn.cisco.com/youtrack/issue/trex-215[trex-215] * Port/Latency stats should be with FCS link:http://trex-tgn.cisco.com/youtrack/issue/trex-213[trex-213] * Stateless Unicode is not accepted for multiplier API see link:https://github.com/cisco-system-traffic-generator/trex-core/issues/15[github-issue15] == Release 2.03 == * More accurate stateless latency/more TUI support * Speedup DPDK XL710 fdir driver === Fixed issues: === * Disconnect issue link:http://trex-tgn.cisco.com/youtrack/issue/trex-210[trex-210] == Release 2.02 == * The python latency statistic is compatible to JSON for easy manipulation * Add latency minimum value Python API taken from histogram === Fixed issues: === * Fix corruption of mbuf in case of with high rate latency stream. == Release 2.01 == * First release of latency/jitter per stream see link:trex_stateless.html#_tutorial_per_stream_latency_jitter_packet_errors[here] * Ability to send server side pcap file - unlimited pcap file size see link:/cp_stl_docs/_modules/trex_stl_lib/trex_stl_client.html#STLClient.push_remote[here] and link:trex_stateless.html#_pcap_based_traffic_tutorials[PCAP tutorial] * Significatly improve performance for both Stateful and Stateless - in some cases up to x2 due to Scheduler/CPU utilization rewrite * CPU utilization estimation is done differently * Ability to significatly improve performance for Stateless profile with Field engine (up to x5, 22MPPS) see link:trex_stateless.html#_tutorial_field_engine_significantly_improve_performance[here] * Add documentation index link:index.html[index] * Fix documentation Table of Content javascript * Update Stateless presentation link:http://www.slideshare.net/HanochHaim/trex-realistic-traffic-generator-stateless-support[Statelss presenation] * Stateful Python server API - Add support for iterator of remote file for Stateful GUI === Fixed issues: === * Performance issue, link:http://trex-tgn.cisco.com/youtrack/issue/trex-207[trex-207] * Sporadic timeout on wait_on_traffic() API see link:http://trex-tgn.cisco.com/youtrack/issue/trex-209[trex-209] == Release 2.00 == * Console ** Support partial port acquire using new CLI switch `-a ACQUIRE` (first phase) ** Add tx/rx graphs * Python API: add an API for reading events as warning/errors * HLTAPI support for per stream stats * support VALN mode for per stream stats for 82599 using `--vlan` switch at server invocation * A peek into TRex stateless GUI version for evaluation still without many features like packet builder, advance packet builder, per stream stats link:https://www.dropbox.com/s/vs9gojtdc5ewv05/setupCiscoTrex1.96-SNAPSHOT.exe?dl=0[TRex Stateless GUI Download] ** Only pcap file packet builder is supported in this version image::images/trex_stl_gui.png[title=""TRex Stateless GUI"",align=""left"",width=600, link=""images/trex_stl_gui.png""] === Fixed issues: === * X710/XL710 per stream hardware stats ** link:http://trex-tgn.cisco.com/youtrack/issue/trex-199[trex-199] ** Fix issue of RX bytes ** Fix issue with mbuf leak * Packet Memory shortage fix link:http://trex-tgn.cisco.com/youtrack/issue/trex-197[trex-197] * Python Examples - move all examples to be 16.0.0.x/48.0.0.x for some refactor == Release 1.99 == * The Client package includes Console/examples * Client API verification mechanism. The client should match the server version range === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/issue/trex-193[trex-193] * Python2/Python3 client API hardening * Per stream statistics in software hardening - add support for wait on rx packets == Release 1.98 == * Minor Console issue * [red]*Image is broken* see link:http://trex-tgn.cisco.com/youtrack/issue/trex-193[trex-193] == Release 1.97 == * Support pyATS with Python 3/32bit * Per stream statistic supported by software for I350/82559/VXNET3 * [red]*Image is broken* see link:http://trex-tgn.cisco.com/youtrack/issue/trex-193[trex-193] == Release 1.96 == * Support pyATS/32bit/Python2.x for TCL * Traffic profile direction/port directive works see link:draft_trex_stateless.html#_tutorial_advance_traffic_profile[here] * Documentation ** Add Python API documentation link:cp_stl_docs/index.html[here] ** Add pyATS2.0 support link:cp_stl_docs/index.html[here] ** Update per stream statistic documentation see link:draft_trex_stateless.html#_tutorial_per_stream_statistics[per stream statistic] ** Update HLTAPI arguments link:draft_trex_stateless.html#_hlt_supported_arguments_a_id_altapi_support_a[HLTAPI] === Fixed issues: === * Per stream statistic - Fix High speed of start/stop of giving zero in statistics * Fix E1000 DPDK driver prints with ESXi == Release 1.95 == * TUI support per stream stats (press s to get to this window) * per stream statistic API examples * Add Python API automatic documentation scripts * Fix issue with a packet smaller than 64 bytes === Known issue * High speed of start/stop of per stream stats give zero in statistics == Release 1.94 == * Fix Python API stop/sync issue. Now TX counters are synced in case of stop API * Improve performance of Python API, ~2000 cycles/sec of load/start/stop * Add per stream Tx/Rx statistics for XL710/X710 NICS work in flow-director hardware [source,python] ---- class STLS1(object): def get_streams (self, direction = 0): return [STLStream(packet = STLPktBuilder( pkt =""stl/yaml/udp_64B_no_crc.pcap""), mode = STLTXCont(pps=10), rx_stats = STLRxStats(user_id = 7)) <1> ] ---- <1> Configure this stream to be count on all RX ports as user_id=7 * Add HTLAPI full example (examples `examples/hlt_udp_simple.py`) * Add user manual draft for Stateless functionality link:draft_trex_stateless.html[here] == Release 1.93 == * Support port attribute API and Console command. See `$portattr -a --prom` * Support random seed per Stream attribute - see specification for more info * Add more sample/profiles (stl/hlt) from real use cases * Enhance Field Engine with new instructions * TUI now shows L1 and L2 bandwidth. Console support L1 and L2 and %% * Stream rate can be configured with PPS/bps_L1/bps_L2/port_percentage * Update Stateless JSON-RPC specification * HLT fixes and support split_by variable * First phase of per stream rx/tx statistic - XL710/X710 hardware support === Fixed issues: === * Fix some typo in Python API stl/example folder * Fix Field Engine IPv4 checksum issue with big packet size * Fix Field Engine issue with random variables * Fix `streams -a` crash * Fix X710 issue. Now return speed of 10gb instead of 40gb for Stateless port speed == Release 1.92 == ** Stream can set static Source/Destination MAC-Address as oppose to the default (TRex port from /etc/trex_config.yaml) [source,python] ---- def create_stream (self): base_pkt = Ether(src=""00:00:dd:dd:00:01"")/IP()/UDP() pad = max(0, size - len(base_pkt)) * 'x' ---- ** Stream support action_count. Loop of streams can end after action_count number. The push command uses this new feature to import pcap to streams and stop after x iteration. [source,python] ---- STLStream( self_start = False, name ='S2', packet = STLPktBuilder(pkt = base_pkt2/pad), mode = STLTXSingleBurst( pps = 10, total_pkts = 3 ), action_count = 2, # loop 2 times next = 'S0' ) ---- ** Support new Field-Engine instructions (variable with step and write with mask). See new sample folder and specification for more info [source,python] ---- def create_stream (self): # 2 MPLS label the internal with s=1 (last one) pkt = Ether()/MPLS(label=17,cos=1,s=0,ttl=255)/MPLS(label=0,cos=1,s=1,ttl=12)/IP()/UDP()/('x'*20) vm = CTRexScRaw( [ STLVmFlowVar(name=""mlabel"", min_value=1, max_value=2000, size=2, op=""inc""), STLVmWrMaskFlowVar(fv_name=""mlabel"", pkt_offset= ""MPLS:1.label"",pkt_cast_size=4, mask=0xFFFFF000,shift=12) # write mask ] ) ---- [source,python] ---- vm = CTRexScRaw( [ STLVmFlowVar(name=""mac_src"", min_value=1, max_value=30, size=1, op=""dec"",step=7), # step STLVmWrFlowVar(fv_name=""mac_src"", pkt_offset= 11) ] ) ---- ** More profile samples (native/hlt) == Release 1.91 == * Convert Stateless traffic profile to Scapy see `stl/*.py` sample folder * Add HLTAPI tests and profile `stl/hlt/*.py` * Fix simulator path issue fix * The Stateless python library is not self-contained. in `automation/trex_control_plane/stl/` library is `automation/trex_control_plane/stl/trex_stl_lib/` (import trex_stl_lib) How to run the simulator [source,bash] ---- ./stl-sim -f stl/udp_1pkt_range_clients_split.py -o b.pcap -l 100 -c 2 ---- * Add push command to convert pcap to streams ------------------- TRex > push --help usage: push [-h] -f FILE [--port PORTS [PORTS ...] | -a] [-d TIME] [-i IPG_USEC] [-s SPEEDUP] [--force] optional arguments: -h, --help show this help message and exit -f FILE File path to load --port PORTS [PORTS ...] A list of ports on which to apply the command -a Set this flag to apply the command on all available ports -d TIME Set duration time for job. -i IPG_USEC, --ipg IPG_USEC IPG value in usec between packets. default will be from the pcap -s SPEEDUP, --speedup SPEEDUP Factor to accelerate the injection. effectively means IPG = IPG / SPEEDUP --force Set if you want to stop active ports before appyling command. TRex >push -f cap2/dns.pcap --port 0 -i 10 ------------------- == Release 1.90 == * Missing file in the pkg == Release 1.89 == * Integrate Scapy as a packet builder see `stl/profiles` folder * Improve Python API, samples can be seen link:https://github.com/cisco-system-traffic-generator/trex-core/tree/master/scripts/api/stl/examples[here] * Add Stateless simulator into the package Example how to run [source,bash] ---- ./stl-sim -f stl/profiles/udp_1pkt.py -l 10 -o a.pcap #<1> ./stl-sim -f stl/profiles/udp_1pkt_tuple_gen.py -l 20 -o a.pcap #<2> ./stl-sim -f stl/profiles/imix.py -l 100 -o a.pcap --json #<3> ---- <1> Limit the number of packets to 10 <2> Tuple generator example <3> imix The simulator takes Stateless profile,YAML or Py and output pcap file or json * Console can load the new Python profile [source,bash] ---- TRex > start -f stl/profiles/udp_1pkt.py -a -m 1mbps ---- * Basic Python HLTAPI support === Fixed issues: === * Dependent streams (e.g. `stl/burst_1000_pkt.yaml`) can be loaded == Release 1.88 == * Add the Python API to the package * Remove mock support == Release 1.87 == * Fix some 82599 ierror in case of high rate * First Stateless API examples under api folder (not part of the package) == Release 1.86 == * NAT Cisco ASA support ** Add support for learning using TCP-ACK field see more here link:trex_manual.html#_nat_support[here] and link:trex_manual.html#_trex_with_asa_5585[here] * More stateless support == Release 1.85 == * Upgrade to DPDK 2.2.0 ** Some XL710/X710 NIC phy issues solved ** VMXNET3 driver is optimized ** Cisco VIC should be supported, not tested yet * Jumbo packet size is supported for 1/10/40 Intel NIC up to 9K for both stateless and stateful * youTrack is public now, can be seen here link:http://trex-tgn.cisco.com/youtrack[here] * More stateless support ** Support random packet size trim instruction - see stl/udp_rand_size_9k.yaml for an example ** Move Python Regression to trex-core ** Add Coverity scripts ** Console/Python API can be call from Cisco CEL now (ZMQ Python library is compiled to an old glibc) ** Add simulator for stateless === Fixed issues: === * The infamous DPDK error is not seen in case of a wrong core argument see here link:http://trex-tgn.cisco.com/youtrack/issue/trex-147[trex-147] == Release 1.84 == * more stateless support ** Add splitter range support see ""split_by_var"" in style/imix_1pkt_vm. yaml ** Add more samples see stl/syn_attack_sample.yaml. Improve random performance ** more improvement with TUI window == Release 1.83 == * more stateless support ** Add basic Packet Field engine see stl/imin_1pkt_vm.yaml ** some improvement with TUI window. Can be run in parallel with --tui option == Release 1.82 == * more stateless support ** console stats/tui function works now ** R/W support. only one client has R/W capability * XL710/X710 support ICMP filter === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/trex-110[trex-110] == Release 1.81 == * more stateless support and fixes ** change the JSON-RPC result format * Support for specifying different modes for the packets used for latency measurement. Details link:trex_manual.html#_measure_jitter_latency[here]. === Fixed issues: === * link:http://trex-tgn.cisco.com/youtrack/issue/trex-149[trex-149] == Release 1.80 == * more stateless support ** All type of streams are supported (Continues/Burst/Multi-burst) ** Stream can call to other streams ** start/stop/pause/resume work from the Console ** -m[rate] is supported for example -m10gbps or -m10kpps from console ** update XL710 installation support == Release 1.79 == * Initial support for stateless ** Only continues streams are supported ** more info how to enable the interactive shell link:trex_console.html[here] == Release 1.78 == * some clean up in tuple generator * trex stateles console works with trex-mock === Fixed issues: === Python API fixup see here * link:http://trex-tgn.cisco.com/youtrack/issue/trex-126[trex-126] * link:http://trex-tgn.cisco.com/youtrack/issue/trex-123[trex-122] Check for 64bit Kernel * link:http://trex-tgn.cisco.com/youtrack/issue/trex-123[trex-123] == Release 1.77 == * improve tuple generator capability now it is more flexiable see more link:trex_manual.html#_clients_servers_ip_allocation_scheme[here] == Release 1.76 == === Fixed issues: === * minor pcap loader issues * plugin cleanup == Release 1.75 == === fix issues: === * First version that works from GitHub/Git - init script are in the output package == Release 1.72 == ",16366,True,3796.5802609900707,median "import ""relay/Guide/Support/Item Filter.ash"" void QLevel12Init() { //questL12War //fratboysDefeated, hippiesDefeated //sidequestArenaCompleted, sidequestFarmCompleted, sidequestJunkyardCompleted, sidequestLighthouseCompleted, sidequestNunsCompleted, sidequestOrchardCompleted //warProgress //Sidequests: //state_boolean[""Lighthouse Finished""] //state_boolean[""Orchard Finished""] QuestState state; QuestStateParseMafiaQuestProperty(state, ""questL12War""); if (my_path_id() == PATH_COMMUNITY_SERVICE) QuestStateParseMafiaQuestPropertyValue(state, ""finished""); state.quest_name = ""Island War Quest""; state.image_name = ""island war""; state.council_quest = true; state.state_boolean[""Arena Finished""] = (get_property(""sidequestArenaCompleted"") != ""none""); state.state_boolean[""Farm Finished""] = (get_property(""sidequestFarmCompleted"") != ""none""); state.state_boolean[""Junkyard Finished""] = (get_property(""sidequestJunkyardCompleted"") != ""none""); state.state_boolean[""Lighthouse Finished""] = (get_property(""sidequestLighthouseCompleted"") != ""none""); state.state_boolean[""Nuns Finished""] = (get_property(""sidequestNunsCompleted"") != ""none""); state.state_boolean[""Orchard Finished""] = (get_property(""sidequestOrchardCompleted"") != ""none""); state.state_boolean[""War started""] = (state.mafia_internal_step >= 2); state.state_boolean[""War in progress""] = state.state_boolean[""War started""] && !state.finished; state.state_int[""hippies left on battlefield""] = 1000 - get_property_int(""hippiesDefeated""); state.state_int[""frat boys left on battlefield""] = 1000 - get_property_int(""fratboysDefeated""); if (state.finished) { state.state_boolean[""Arena Finished""] = true; state.state_boolean[""Farm Finished""] = true; state.state_boolean[""Junkyard Finished""] = true; state.state_boolean[""Lighthouse Finished""] = true; state.state_boolean[""Nuns Finished""] = true; state.state_boolean[""Orchard Finished""] = true; } if (my_path_id() == PATH_EXPLOSIONS) state.state_boolean[""Lighthouse Finished""] = true; int quests_completed_hippy = 0; int quests_completed_frat = 0; foreach s in $strings[sidequestArenaCompleted,sidequestFarmCompleted,sidequestJunkyardCompleted,sidequestLighthouseCompleted,sidequestNunsCompleted,sidequestOrchardCompleted] { string property_value = get_property(s); if (property_value == ""hippy"") quests_completed_hippy += 1; else if (property_value == ""fratboy"") quests_completed_frat += 1; } state.state_int[""Quests completed for hippies""] = quests_completed_hippy; state.state_int[""Quests completed for frat boys""] = quests_completed_frat; if (!state.finished) { //define state.state_string[""Side seemingly fighting for""] //""hippy"", ""frat boys"", ""both"", """" if (state.state_int[""Quests completed for hippies""] > 0) state.state_string[""Side seemingly fighting for""] = ""hippy""; if (state.state_int[""Quests completed for frat boys""] > 0) state.state_string[""Side seemingly fighting for""] = ""frat boys""; if (state.state_int[""hippies left on battlefield""] == 1000 && state.state_int[""frat boys left on battlefield""] != 1000) state.state_string[""Side seemingly fighting for""] = ""hippy""; if (state.state_int[""hippies left on battlefield""] != 1000 && state.state_int[""frat boys left on battlefield""] == 1000) state.state_string[""Side seemingly fighting for""] = ""frat boys""; if (state.state_int[""hippies left on battlefield""] != 1000 && state.state_int[""frat boys left on battlefield""] != 1000) state.state_string[""Side seemingly fighting for""] = ""both""; if (state.state_int[""Quests completed for hippies""] > 0 && state.state_int[""Quests completed for frat boys""] > 0) state.state_string[""Side seemingly fighting for""] = ""both""; } if (false) { //Internal debugging: state.state_boolean[""Arena Finished""] = false; state.state_boolean[""Farm Finished""] = false; state.state_boolean[""Junkyard Finished""] = false; state.state_boolean[""Lighthouse Finished""] = false; state.state_boolean[""Nuns Finished""] = false; state.state_boolean[""Orchard Finished""] = false; } if (my_level() >= 12 && my_path_id() != PATH_EXPLOSIONS) state.startable = true; __quest_state[""Level 12""] = state; __quest_state[""Island War""] = state; } void QLevel12GenerateTasksSidequests(ChecklistEntry [int] task_entries, ChecklistEntry [int] optional_task_entries, ChecklistEntry [int] future_task_entries) { QuestState base_quest_state = __quest_state[""Level 12""]; if (!base_quest_state.state_boolean[""Orchard Finished""]) { string [int] details; string [int] modifiers; string url = ""bigisland.php?place=orchard""; modifiers.listAppend(""+1000% item""); if (__misc_state[""yellow ray potentially available""]) modifiers.listAppend(""potential YR""); location next_location; monster pickpocket_monster = $monster[none]; boolean need_gland = false; if ($item[heart of the filthworm queen].available_amount() > 0) { modifiers.listClear(); details.listAppend(""Go talk to the hippies to complete quest.""); } else if ($effect[Filthworm Guard Stench].have_effect() > 0 || $item[Filthworm royal guard scent gland].available_amount() > 0) { if ($effect[Filthworm Guard Stench].have_effect() == 0) { url = ""inventory.php?which=3""; details.listAppend(""Use filthworm royal guard scent gland.""); } modifiers.listClear(); modifiers.listAppend(""+meat""); details.listAppend(""Defeat the filthworm queen in the queen's chamber.""); next_location = $location[the filthworm queen's chamber]; } else if ($effect[Filthworm Drone Stench].have_effect() > 0 || $item[Filthworm drone scent gland].available_amount() > 0) { if ($effect[Filthworm Drone Stench].have_effect() == 0) { url = ""inventory.php?which=3""; details.listAppend(""Use filthworm drone scent gland""); } details.listAppend(""Adventure with +item in the guards' chamber.""); need_gland = true; pickpocket_monster = $monster[filthworm royal guard]; next_location = $location[the royal guard chamber]; } else if ($effect[Filthworm Larva Stench].have_effect() > 0 || $item[filthworm hatchling scent gland].available_amount() > 0) { if ($effect[Filthworm Larva Stench].have_effect() == 0) { url = ""inventory.php?which=3""; details.listAppend(""Use filthworm hatchling scent gland""); } details.listAppend(""Adventure with +item in the feeding chamber.""); need_gland = true; pickpocket_monster = $monster[filthworm drone]; next_location = $location[the feeding chamber]; } else { details.listAppend(""Adventure with +item in the hatching chamber.""); need_gland = true; pickpocket_monster = $monster[larval filthworm]; next_location = $location[the hatching chamber]; } if (__misc_state[""can pickpocket""] && pickpocket_monster != $monster[none]) { int total_initiative_needed = pickpocket_monster.base_initiative; int initiative_needed = total_initiative_needed - initiative_modifier(); if (initiative_needed > 0) details.listAppend(""Need "" + initiative_needed + ""% more initiative to pickpocket every turn.""); } if (need_gland) { float effective_item_drop = next_location.item_drop_modifier_for_location() / 100.0; //FIXME take into account pickpocketing, init, etc. float average_glands_found_per_combat = MIN(1.0, (effective_item_drop + 1.0) * 0.1); float turns_per_gland = -1.0; if (average_glands_found_per_combat != 0.0) turns_per_gland = 1.0 / average_glands_found_per_combat; details.listAppend(""~"" + roundForOutput(turns_per_gland, 1) + "" turns per gland.""); } optional_task_entries.listAppend(ChecklistEntryMake(""Island War Orchard"", url, ChecklistSubentryMake(""Island War Orchard Quest"", modifiers, details), $locations[the hatching chamber, the feeding chamber, the royal guard chamber, the filthworm queen's chamber])); } if (!base_quest_state.state_boolean[""Farm Finished""]) { string [int] details; details.listAppend(""Great flappin' beasts, with webbed feet and bills! dooks!""); string [int] modifiers; modifiers.listAppend(""+meat""); string [int] tasks; int ncs_seen = $location[McMillicancuddy's Barn].noncombatTurnsAttemptedInLocation(); if (ncs_seen < 3) { tasks.listAppend(""make a fence out of the barbed wire""); tasks.listAppend(""knock over the lantern""); tasks.listAppend(""dump out the drum""); details.listAppend(""Remember to use a chaos butterfly in combat before clearing the barn.|Then "" + tasks.listJoinComponents("", "", ""and"") + "".""); if (__misc_state[""free runs available""]) modifiers.listAppend(""free runs in barn""); } optional_task_entries.listAppend(ChecklistEntryMake(""Island War Farm"", ""bigisland.php?place=farm"", ChecklistSubentryMake(""Island War Farm Quest"", modifiers, details), $locations[mcmillicancuddy's farm,mcmillicancuddy's barn,mcmillicancuddy's pond,mcmillicancuddy's back 40,mcmillicancuddy's other back 40,mcmillicancuddy's granary,mcmillicancuddy's bog,mcmillicancuddy's family plot,mcmillicancuddy's shady thicket])); } if (!base_quest_state.state_boolean[""Nuns Finished""]) { string [int] details; int meat_gotten = get_property_int(""currentNunneryMeat""); int meat_remaining = 100000 - meat_gotten; details.listAppend(meat_remaining + "" meat remaining.""); float meat_drop_multiplier = meat_drop_modifier() / 100.0 + 1.0; vec2i brigand_meat_drop_range = vec2iMake(800 * meat_drop_multiplier, 1200 * meat_drop_multiplier); vec2i turn_range; if (brigand_meat_drop_range.x != 0 && brigand_meat_drop_range.y != 0) turn_range = vec2iMake(ceil(to_float(meat_remaining) / to_float(brigand_meat_drop_range.y)), ceil(to_float(meat_remaining) / to_float(brigand_meat_drop_range.x))); if (my_path_id() == PATH_2CRS) turn_range = Vec2iMake(MAX(100, turn_range.x), MAX(100, turn_range.y)); string turns_extra = "".""; string [int] extra_details; if (get_property(""boomBoxSong"") == ""Total Eclipse of Your Meat"") { vec2i brigand_meat_drop_range_sing = vec2iMake(820 * meat_drop_multiplier, 1230 * meat_drop_multiplier); vec2i turn_range_sing; if (brigand_meat_drop_range_sing.x != 0 && brigand_meat_drop_range_sing.y != 0) turn_range_sing = vec2iMake(ceil(to_float(meat_remaining) / to_float(brigand_meat_drop_range_sing.y)), ceil(to_float(meat_remaining) / to_float(brigand_meat_drop_range_sing.x))); turns_extra = "", if you don't sing.""; if (turn_range_sing.x == turn_range.x && turn_range_sing.y == turn_range.y) { turns_extra = "".""; } else if (turn_range_sing.x == turn_range_sing.y) details.listAppend(pluralise(turn_range_sing.x, ""turn"", ""turns"") + "" remaining, if you sing.""); else details.listAppend(""["" + turn_range_sing.x + "" to "" + turn_range_sing.y + ""] turns remaining, if you sing.""); extra_details.listAppend(""Be sure to Sing Along with your boombox every turn.""); /*float without = meat_remaining / (1000.0 * meat_drop_multiplier); float with = meat_remaining / (1025.0 * meat_drop_multiplier); details.listAppend(""Singing saves "" + (without - with) + "" turns."");*/ } //FIXME consider looking into tracking how long until the semi-rare item runs out, for turn calculation if (turn_range.x == turn_range.y) details.listAppend(pluralise(turn_range.x, ""turn"", ""turns"") + "" remaining"" + turns_extra); else details.listAppend(""["" + turn_range.x + "" to "" + turn_range.y + ""] turns remaining"" + turns_extra); if (turn_range.x == 1 && turn_range.y == 2) { float chance = 1.0 - TriangularDistributionCalculateCDF(meat_remaining + 1, brigand_meat_drop_range.x, brigand_meat_drop_range.y); details.listAppend((chance * 100.0).floor() + ""% chance of completing in one turn.""); } if ($item[ice nine].available_amount() == 0 && __misc_state[""can equip just about any weapon""] && $item[ice harvest].available_amount() >= 9 && $item[ice nine].is_unrestricted() && $item[miracle whip].available_amount() == 0) //is this safe? unfinished ice sculpture is really nice, and ice bucket in sneaky pete... details.listAppend(""Possibly make and equip an ice nine. (+30% meat 1h weapon)""); if ($effect[Sinuses For Miles].have_effect() > 0 && !get_property_ascension(""lastTempleAdventures"") && $item[stone wool].available_amount() > 0 && get_property_ascension(""lastTempleUnlock"")) details.listAppend(""Potentially use stone wool and visit the hidden temple to extend Sinuses for Miles for 3 turns.""); if (my_path_id() == PATH_HEAVY_RAINS && $skill[Make it Rain].skill_is_usable() && turn_range.y > 1) details.listAppend(""Cast Make it Rain each fight. (+300%? meat)""); if ($item[Sneaky Pete's leather jacket (collar popped)].equipped_amount() > 0 && turn_range.y > 1) details.listAppend(""Could unpop your collar. (+20% meat)""); if (__misc_state_int[""pulls available""] > 0 && meat_drop_modifier() < 1000.0) { int limit = 100; if (meat_drop_modifier() < 800.0) limit = 50; if (my_path_id() == PATH_G_LOVER) limit = 25; limit = 0; //show them all - we'll go based off of turns saved boolean [item] blacklist = $items[uncle greenspan's bathroom finance guide,black snowcone]; item [int] relevant_potions = ItemFilterGetPotionsCouldPullToAddToNumericModifier(""Meat Drop"", limit, blacklist); string [int] relevant_potions_output; float average_turns_currently = meat_remaining / ((meat_drop_modifier() / 100.0 + 1.0) * 1000.0); foreach key, it in relevant_potions { effect e = it.to_effect(); if (!e.effect_is_usable()) continue; if (!it.item_is_usable()) continue; //average_turns_currently - float meat_dropped_per_turn_with_item = ((meat_drop_modifier() + e.numeric_modifier(""meat drop"")) / 100.0 + 1.0) * 1000.0; float turns_saved = average_turns_currently - meat_remaining / meat_dropped_per_turn_with_item; if (turns_saved < 1.0) continue; relevant_potions_output.listAppend(it + "" ("" + e.numeric_modifier(""meat drop"").roundForOutput(0) + ""%, "" + turns_saved.roundForOutput(1) + "" turns saved)""); } if (relevant_potions_output.count() > 0) details.listAppend(""Could try pulling "" + relevant_potions_output.listJoinComponents("", "", ""or"") + "".""); } details.listAppendList(extra_details); optional_task_entries.listAppend(ChecklistEntryMake(""Island War Nuns"", ""bigisland.php?place=nunnery"", ChecklistSubentryMake(""Island War Nuns Quest"", ""+meat"", details), $locations[the themthar hills])); } if (!base_quest_state.state_boolean[""Junkyard Finished""]) { string [int] details; if ($item[molybdenum magnet].available_amount() == 0) { details.listAppend(""Talk to Yossarian first.""); } else { location [item] items_and_locations; items_and_locations[$item[molybdenum hammer]] = $location[Next to that Barrel with Something Burning in it]; items_and_locations[$item[molybdenum pliers]] = $location[Near an Abandoned Refrigerator]; items_and_locations[$item[molybdenum crescent wrench]] = $location[Over Where the Old Tires Are]; items_and_locations[$item[molybdenum screwdriver]] = $location[Out By that Rusted-Out Car]; boolean have_all = true; string [location][int] location_monsters; location_monsters[$location[Next to that Barrel with Something Burning in it]] = listMake(""tool batwinged"", ""vegetable""); location_monsters[$location[Out By that Rusted-Out Car]] = listMake(""tool vegetable"", ""erudite""); location_monsters[$location[Near an Abandoned Refrigerator]] = listMake(""tool spider"", ""batwinged""); location_monsters[$location[Over Where the Old Tires Are]] = listMake(""tool erudite"", ""spider""); location [int][monster] banishment_locations; //it's time we had a talk... about your hair! it's gone too far! banishment_locations[1][$monster[batwinged gremlin]] = $location[Near an Abandoned Refrigerator]; banishment_locations[1][$monster[erudite gremlin]] = $location[Out By that Rusted-Out Car]; banishment_locations[1][$monster[spider gremlin]] = $location[Over Where the Old Tires Are]; banishment_locations[1][$monster[vegetable gremlin]] = $location[Next to that Barrel with Something Burning in it]; banishment_locations[0][$monster[batwinged gremlin]] = $location[Next to that Barrel with Something Burning in it]; banishment_locations[0][$monster[erudite gremlin]] = $location[Over Where the Old Tires Are]; banishment_locations[0][$monster[spider gremlin]] = $location[Near an Abandoned Refrigerator]; banishment_locations[0][$monster[vegetable gremlin]] = $location[Out By that Rusted-Out Car]; foreach key in banishment_locations { foreach m in banishment_locations[key] { if (!m.is_banished()) continue; location l = banishment_locations[key][m]; if (key == 0 && location_monsters[l][key].contains_text(""tool "")) location_monsters[l][key] = ""tool "" + HTMLGenerateSpanFont(location_monsters[l][key].replace_string(""tool "", """"), ""grey"", """"); else location_monsters[l][key] = HTMLGenerateSpanFont(location_monsters[l][key], ""grey""); } } item [int] item_display_order = listMake($item[molybdenum hammer],$item[molybdenum pliers],$item[molybdenum crescent wrench],$item[molybdenum screwdriver]); //make a path string [int] areas_left_strings; //foreach it in items_and_locations string [location] location_shorthand_name; location_shorthand_name[$location[Next to that Barrel with Something Burning in it]] = ""Barrel""; location_shorthand_name[$location[Out By that Rusted-Out Car]] = ""Car""; location_shorthand_name[$location[Near an Abandoned Refrigerator]] = ""Refrigerator""; location_shorthand_name[$location[Over Where the Old Tires Are]] = ""Tires""; foreach key in item_display_order { item it = item_display_order[key]; location loc = items_and_locations[it]; if (it.available_amount() > 0) { continue; } else have_all = false; string location_display_name; if (location_shorthand_name contains loc) location_display_name = location_shorthand_name[loc]; else location_display_name = loc.to_string().to_lower_case(); areas_left_strings.listAppend("""" + location_display_name + "" - "" + location_monsters[loc].listJoinComponents("", "")); } if (areas_left_strings.count() > 0) details.listAppend(""Areas left:|*"" + areas_left_strings.listJoinComponents(""
|*"")); if (have_all) details.listAppend(""Talk to Yossarian to complete quest.""); else { if ($item[dictionary].available_amount() > 0 && $item[dictionary].item_is_usable()) { details.listAppend(""Read from the dictionary to stasis gremlins.""); } else if ($item[facsimile dictionary].available_amount() > 0 && $item[facsimile dictionary].item_is_usable()) { details.listAppend(""Read from the facsimile dictionary to stasis gremlins.""); } else if ($item[seal tooth].available_amount() > 0 && $item[seal tooth].item_is_usable()) { details.listAppend(""Use your seal tooth to stasis gremlins.""); } else if ($skill[suckerpunch].skill_is_usable()) { details.listAppend(""Cast suckerpunch to stasis gremlins.""); } else if ($item[seal tooth].item_is_usable()) details.listAppend(HTMLGenerateSpanFont(""Acquire a seal tooth"", ""red"") + "" to stasis gremlins. (from hermit)""); else if ($item[beehive].available_amount() > 0) details.listAppend(""Use your beehive to stasis gremlins.""); if (!$monster[A.M.C. gremlin].is_banished()) details.listAppend(""Potentially banish A.M.C. Gremlin.""); } } optional_task_entries.listAppend(ChecklistEntryMake(""Island War Junkyard"", ""bigisland.php?place=junkyard"", ChecklistSubentryMake(""Island War Junkyard Quest"", listMake(""+DR"", ""+DA"", ""+HP"", ""+moxie""), details), $locations[next to that barrel with something burning in it,near an abandoned refrigerator,over where the old tires are,out by that rusted-out car])); } if (!base_quest_state.state_boolean[""Lighthouse Finished""]) { string [int] details; int gunpowder_needed = MAX(0, 5 - $item[barrel of gunpowder].available_amount()); string [int] modifiers; if (gunpowder_needed > 0) { modifiers = listMake(""+combat"", ""copies""); if (gunpowder_needed == 1) details.listAppend(""Need "" + gunpowder_needed + "" more barrel of gunpowder.""); else details.listAppend(""Need "" + gunpowder_needed + "" more barrels of gunpowder.""); //this is an approximation: //off by a little over half a turn on average float effective_combat_rate = (11.0 / 12.0) * clampNormalf(0.1 + combat_rate_modifier() / 100.0) + (1.0 / 12.0) * 1.0; float turns_per_lobster = -1.0; if (effective_combat_rate != 0.0) turns_per_lobster = 1.0 / effective_combat_rate; float turns_to_complete = gunpowder_needed.to_float() * turns_per_lobster; //I had the data lying around, so why not? //misses <-10 and >30, but the estimate above will catch that float [int][int] lfm_simulation_data; lfm_simulation_data[5][-10] = 60.00; lfm_simulation_data[5][-5] = 40.02; lfm_simulation_data[5][0] = 29.92; lfm_simulation_data[5][5] = 23.84; lfm_simulation_data[5][10] = 19.76; lfm_simulation_data[5][15] = 16.84; lfm_simulation_data[5][20] = 14.66; lfm_simulation_data[5][25] = 13.00; lfm_simulation_data[4][-10] = 48.00; lfm_simulation_data[4][-5] = 32.27; lfm_simulation_data[4][0] = 24.20; lfm_simulation_data[4][5] = 19.29; lfm_simulation_data[4][10] = 16.00; lfm_simulation_data[4][15] = 13.68; lfm_simulation_data[4][20] = 11.96; lfm_simulation_data[4][25] = 10.63; lfm_simulation_data[3][-10] = 36.00; lfm_simulation_data[3][-5] = 24.53; lfm_simulation_data[3][0] = 18.47; lfm_simulation_data[3][5] = 14.78; lfm_simulation_data[3][10] = 12.34; lfm_simulation_data[3][15] = 10.59; lfm_simulation_data[3][20] = 9.26; lfm_simulation_data[3][25] = 8.20; lfm_simulation_data[2][-10] = 24.00; lfm_simulation_data[2][-5] = 16.79; lfm_simulation_data[2][0] = 12.84; lfm_simulation_data[2][5] = 10.38; lfm_simulation_data[2][10] = 8.68; lfm_simulation_data[2][15] = 7.40; lfm_simulation_data[2][20] = 6.40; lfm_simulation_data[2][25] = 5.60; lfm_simulation_data[1][-10] = 12.00; lfm_simulation_data[1][-5] = 9.19; lfm_simulation_data[1][0] = 7.17; lfm_simulation_data[1][5] = 5.72; lfm_simulation_data[1][10] = 4.66; lfm_simulation_data[1][15] = 3.87; lfm_simulation_data[1][20] = 3.29; lfm_simulation_data[1][25] = 2.84; lfm_simulation_data[5][26] = 12.71; lfm_simulation_data[5][27] = 12.44; lfm_simulation_data[5][28] = 12.18; lfm_simulation_data[5][29] = 11.93; lfm_simulation_data[5][30] = 11.69; lfm_simulation_data[4][26] = 10.40; lfm_simulation_data[4][27] = 10.17; lfm_simulation_data[4][28] = 9.96; lfm_simulation_data[4][29] = 9.75; lfm_simulation_data[4][30] = 9.56; lfm_simulation_data[3][26] = 8.01; lfm_simulation_data[3][27] = 7.83; lfm_simulation_data[3][28] = 7.65; lfm_simulation_data[3][29] = 7.48; lfm_simulation_data[3][30] = 7.32; lfm_simulation_data[2][26] = 5.46; lfm_simulation_data[2][27] = 5.33; lfm_simulation_data[2][28] = 5.20; lfm_simulation_data[2][29] = 5.07; lfm_simulation_data[2][30] = 4.96; lfm_simulation_data[1][26] = 2.76; lfm_simulation_data[1][27] = 2.69; lfm_simulation_data[1][28] = 2.62; lfm_simulation_data[1][29] = 2.56; lfm_simulation_data[1][30] = 2.50; if (lfm_simulation_data[gunpowder_needed] contains combat_rate_modifier().to_int()) { turns_to_complete = lfm_simulation_data[gunpowder_needed][combat_rate_modifier().to_int()]; if (gunpowder_needed != 0.0) turns_per_lobster = turns_to_complete / gunpowder_needed.to_float(); } details.listAppend(""~"" + roundForOutput(turns_to_complete, 1) + "" turns to complete quest at "" + combat_rate_modifier().floor() + ""% combat.|~"" + roundForOutput(turns_per_lobster, 1) + "" turns per lobster.""); if ($skill[meteor lore].have_skill() && get_property_int(""_macrometeoriteUses"") < 10) { details.listAppend(""Could use macrometeorite on a wandering monster (portscan, voting) to guarantee an LFM.""); if (lookupItem("""I Voted!" sticker"").available_amount() > 0 && get_property_int(""_voteFreeFights"") >= 3) { if (total_turns_played() % 11 == 1 && get_property_int(""lastVoteMonsterTurn"") < total_turns_played()) { details.listAppend(""Voting monster now!""); } else { int turns_to_next_voting_monster = 11 - (((total_turns_played() % 11) - 1 + 11) % 11); details.listAppend(""Voting monster will appear in "" + pluralise(turns_to_next_voting_monster, ""more turn"", ""more turns"") + "".""); } } } } else details.listAppend(""Talk to the lighthouse keeper to finish quest.""); optional_task_entries.listAppend(ChecklistEntryMake(""Island War Lighthouse"", ""bigisland.php?place=lighthouse"", ChecklistSubentryMake(""Island War Lighthouse Quest"", modifiers, details), $locations[sonofa beach])); } if (!base_quest_state.state_boolean[""Arena Finished""] && my_path_id() != PATH_G_LOVER && my_path_id() != PATH_POCKET_FAMILIARS) { string [int] modifiers; modifiers.listAppend(""+ML""); float percent_done = clampf(get_property_int(""flyeredML"") / 10000.0 * 100.0, 0.0, 100.0); int ml_remaining = 10000 - get_property_int(""flyeredML""); string [int] details; if (percent_done >= 100.0) { modifiers.listClear(); details.listAppend(""Turn in quest.""); } else { if ($item[jam band flyers].available_amount() == 0 && $item[rock band flyers].available_amount() == 0) details.listAppend(""Acquire fliers.""); details.listAppend(round(percent_done, 1) + ""% ML completed, "" + ml_remaining + "" ML remains.""); } //Normally, this would be bigisland.php?place=concert //But that could theoretically complete the quest for the wrong side, if they're wearing the wrong uniform and misclick. optional_task_entries.listAppend(ChecklistEntryMake(""Island War Arena"", ""bigisland.php"", ChecklistSubentryMake(""Island War Arena Quest"", modifiers, details))); if (ml_remaining > 0 && ($item[jam band flyers].available_amount() > 0 || $item[rock band flyers].available_amount() > 0)) { item it = $item[jam band flyers]; if ($item[rock band flyers].available_amount() > 0 && $item[jam band flyers].available_amount() == 0) it = $item[rock band flyers]; task_entries.listAppend(ChecklistEntryMake(it, """", ChecklistSubentryMake(""Flyer with "" + it + "" every combat"", ""+ML"", details), -11)); } } } void QLevel12GenerateBattlefieldDescription(ChecklistSubentry subentry, string side, int enemies_remaining, int enemies_defeated_per_combat, string enemy_name, string enemy_name_plural, string boss_name, string [int] sidequest_list, string [int] base_sidequest_list) { if (enemies_defeated_per_combat == 0) return; int enemies_defeated = 1000 - enemies_remaining; string line; if (enemies_remaining > 0) { line = pluralise(enemies_remaining, enemy_name, enemy_name_plural) + "" left.""; } else { line += ""Fight "" + boss_name + ""!""; if (my_path_id() == PATH_DEMIGUISE && $effect[Flared Nostrils].have_effect() > 0) line += ""|"" + HTMLGenerateSpanFont(""Remove Flared Nostrils"", ""red"") + "" or you will die.""; if (my_path_id() == PATH_DEMIGUISE) { int damage_taken = 0; damage_taken += ceil(my_maxhp() * 2.0 * (1.0 - elemental_resistance($element[stench]) / 100.0)); if ($effect[flared nostrils].have_effect() > 0) damage_taken += ceil(my_maxhp() * 2.0 * 2.0); else damage_taken += ceil(my_maxhp() * 2.0 * (1.0 - elemental_resistance($element[sleaze]) / 100.0)); subentry.modifiers.listAppend(HTMLGenerateSpanOfClass(""+stench res"", ""r_element_stench_desaturated"")); subentry.modifiers.listAppend(HTMLGenerateSpanOfClass(""+sleaze res"", ""r_element_sleaze_desaturated"")); line += ""|Will take "" + damage_taken + "" damage at the start of combat""; if (damage_taken >= my_maxhp()) line += "", "" + HTMLGenerateSpanFont(""which you cannot survive"", ""red""); line += "".""; line += ""|Run "" + HTMLGenerateSpanOfClass(""stench"", ""r_element_stench"") + "" and "" + HTMLGenerateSpanOfClass(""sleaze"", ""r_element_sleaze"") + "" resistance.""; if (my_hp() != my_maxhp()) line += ""|"" + HTMLGenerateSpanFont(""Also restore your HP."", ""red""); } } string outfit_name; if (side == ""hippy"") outfit_name = ""War Hippy Fatigues""; if (side == ""frat boy"") outfit_name = ""Frat Warrior Fatigues""; if (outfit_name != """") { item [int] missing_outfit_components = missing_outfit_components(outfit_name); if (missing_outfit_components.count() > 0) line += ""|*Missing outfit piece"" + (missing_outfit_components.count() > 1 ? ""s"" : """") + "" "" + missing_outfit_components.listJoinComponents("", "", ""and"") + "".""; } int turns_remaining = ceiling(enemies_remaining.to_float() / enemies_defeated_per_combat.to_float()); if (turns_remaining > 0) { line += ""|*"" + pluralise(turns_remaining, ""turn"", ""turns"") + "" remaining.""; line += "" "" + pluralise(enemies_defeated_per_combat, enemy_name, enemy_name_plural) + "" defeated per combat.""; } int enemies_to_defeat_for_unlock = -1; string area_to_unlock = """"; string [int] areas_unlocked_but_not_completed; boolean [string] areas_blocked; if (my_path_id() == PATH_G_LOVER || my_path_id() == PATH_POCKET_FAMILIARS) areas_blocked[""Arena""] = true; foreach key, sidequest in base_sidequest_list { if (areas_blocked[sidequest]) continue; if (!__quest_state[""Level 12""].state_boolean[sidequest + "" Finished""]) { areas_unlocked_but_not_completed.listAppend(sidequest); } } if (my_path_id() != PATH_BUGBEAR_INVASION) //FIXME test against trendy bugbear chef being needed { if (side == ""frat boy"" && __misc_state[""free runs usable""]) subentry.modifiers.listAppend(""possibly olfact Green Ops Soldier""); else if (side == ""hippy"") subentry.modifiers.listAppend(""possibly olfact Sorority Operator""); } int [int] unlock_threshold; unlock_threshold[0] = 64; unlock_threshold[1] = 192; unlock_threshold[2] = 458; for i from 2 to 0 by -1 { int threshold = unlock_threshold[i]; if (areas_blocked[sidequest_list[i]]) continue; if (!__quest_state[""Level 12""].state_boolean[sidequest_list[i] + "" Finished""]) { if (enemies_defeated < threshold) { area_to_unlock = sidequest_list[i]; enemies_to_defeat_for_unlock = threshold - enemies_defeated; } else { areas_unlocked_but_not_completed.listAppend(sidequest_list[i]); } } } if (enemies_to_defeat_for_unlock != -1) { int turns_to_reach = ceiling(enemies_to_defeat_for_unlock.to_float() / enemies_defeated_per_combat.to_float()); line += ""|*"" + pluralise(turns_to_reach, ""turn"", ""turns"") + "" ("" + pluralise(enemies_to_defeat_for_unlock, enemy_name, enemy_name_plural) + "") to unlock "" + area_to_unlock + "".""; } if (areas_unlocked_but_not_completed.count() > 0 && enemies_remaining > 0) line += ""|*Quests accessible: "" + areas_unlocked_but_not_completed.listJoinComponents("", "", ""and"") + "".""; subentry.entries.listAppend(line); if (enemies_remaining == 0) { string [int] items_to_turn_in_for; if (__quest_state[""Level 13""].state_boolean[""shadow will need to be defeated""]) { if (side == ""hippy"") items_to_turn_in_for.listAppend(""filthy poultices for shadow""); else items_to_turn_in_for.listAppend(""gauze garters for shadow""); } string line2 = ""Also, turn in gear to your home camp.""; if (items_to_turn_in_for.count() > 0) line2 += "" Acquire "" + items_to_turn_in_for.listJoinComponents("", "", ""and"") + "", etc.""; subentry.entries.listAppend(line2); } } void QLevel12ExplosionsGenerateTasks(ChecklistEntry [int] task_entries, ChecklistEntry [int] optional_task_entries, ChecklistEntry [int] future_task_entries) { if (my_path_id() != PATH_EXPLOSIONS) return; if (QuestState(""questL12HippyFrat"").finished) return; string [int] description; string url = ""place.php?whichplace=exploathing""; int fratboys_defeated = get_property_int(""fratboysDefeated""); int hippies_defeated = get_property_int(""hippiesDefeated""); int fratboys_left = clampi(333 - fratboys_defeated, 0, 333); int hippies_left = clampi(333 - hippies_defeated, 0, 333); if (!have_outfit_components(""War Hippy Fatigues"") && !have_outfit_components(""Frat Warrior Fatigues"")) description.listAppend(""Find a uniform. Either calculate the universe 151st + YR, wish + YR?, pull, or yellow-ray a battlefield enemy with the outfit?""); else if (!is_wearing_outfit(""War Hippy Fatigues"") && !is_wearing_outfit(""Frat Warrior Fatigues"")) { description.listAppend(""Equip a war outfit first.""); url = ""inventory.php?which=2""; } if ($items[jacob's rung,haunted paddle-ball].available_amount() == 0) { description.listAppend((!in_hardcore() ? ""Pull/"" : """") + ""YR a jacob's rung or haunted paddle-ball, from the top floor of spookyraven manor.|Jacob's adder in the Haunted Laboratory or possessed toy chest in the The Haunted Nursery have them.""); } else if ($items[jacob's rung,haunted paddle-ball].equipped_amount() == 0) { if ($item[haunted paddle-ball].have()) { description.listAppend(""Equip haunted paddle-ball first.""); url = ""inventory.php?which=2""; } else if ($item[jacob's rung].have()) { description.listAppend(""Equip jacob's rung first.""); url = ""inventory.php?which=2""; } } boolean likely_fighting_frats = false; if (fratboys_defeated > 0 && fratboys_defeated > hippies_defeated) { likely_fighting_frats = true; if (fratboys_left <= 0) description.listAppend(""Fight the Man!""); else description.listAppend(""Defeat "" + pluralise(fratboys_left, ""more fratboy"", ""more fratboys"") + "".""); } else { if (hippies_left <= 0) description.listAppend(""Fight the Big Wisniewski!""); else description.listAppend(""Defeat "" + pluralise(hippies_left, ""more hippy"", ""more hippies"") + "".""); } int battlefield_turns = lookupLocation(""The Exploaded Battlefield"").turns_spent; int turns_until_next_war_nc = -1; if (battlefield_turns < 7) turns_until_next_war_nc = 7 - battlefield_turns; else { turns_until_next_war_nc = (battlefield_turns + 7) % 7; if (turns_until_next_war_nc != 0) turns_until_next_war_nc = 7 - turns_until_next_war_nc; } if (turns_until_next_war_nc == 0) { description.listAppend(""Non-combat now. Throw high-adventure consumable to speed up war.""); } else description.listAppend(pluraliseWordy(turns_until_next_war_nc, ""More Turn"", ""more turns"").capitaliseFirstLetter() + "" until war NC.""); if (likely_fighting_frats) { if (lookupItems(""space wine"").available_amount() == 0) description.listAppend(""Buy some space wine for the non-combat.""); } else { if (lookupItems(""pie man was not meant to eat,space chowder"").available_amount() == 0) description.listAppend(""Buy some space chowder for the non-combat.""); } task_entries.listAppend(ChecklistEntryMake(""island war"", url, ChecklistSubentryMake(""War!"", """", description), 0)); } void QLevel12GenerateTasks(ChecklistEntry [int] task_entries, ChecklistEntry [int] optional_task_entries, ChecklistEntry [int] future_task_entries) { if (my_path_id() == PATH_EXPLOSIONS) QLevel12ExplosionsGenerateTasks(task_entries, optional_task_entries, future_task_entries); if (!__quest_state[""Level 12""].in_progress) return; QuestState base_quest_state = __quest_state[""Level 12""]; ChecklistSubentry subentry; subentry.header = base_quest_state.quest_name; task_entries.listAppend(ChecklistEntryMake(base_quest_state.image_name, ""island.php"", subentry, $locations[the battlefield (frat uniform), the battlefield (hippy uniform), frat house, hippy camp, wartime frat house, wartime frat house (hippy disguise), wartime hippy camp, wartime hippy camp (frat disguise)])); if (base_quest_state.mafia_internal_step < 2) { subentry.modifiers.listAppend(""-combat""); subentry.entries.listAppend(""Start the war!""); float noncombat_rate = 1.0 - (.85 + combat_rate_modifier() / 100.0); float turns_remaining = -1.0; if (noncombat_rate != 0.0) turns_remaining = 3.0 / noncombat_rate; if (!have_outfit_components(""War Hippy Fatigues"") && !have_outfit_components(""Frat Warrior Fatigues"")) { //FIXME suggest routes to doing both. subentry.entries.listAppend(""Need either the war hippy fatigues or frat warrior fatigues outfit.""); if ($familiar[slimeling].familiar_is_usable()) subentry.modifiers.listAppend(""slimeling?""); } else { string [int] stats_needed; if (my_basestat($stat[moxie]) < 70) stats_needed.listAppend((70 - my_basestat($stat[moxie])) + "" more moxie""); if (my_basestat($stat[mysticality]) < 70) stats_needed.listAppend((70 - my_basestat($stat[mysticality])) + "" more mysticality""); if (stats_needed.count() == 0) subentry.entries.listAppend(""Wear war outfit, run -combat, adventure in other side's camp.""); else { string line = ""Acquire "" + stats_needed.listJoinComponents("", "", ""and"") + "" to wear war outfit.""; if (my_class() == $class[pastamancer] && (is_wearing_outfit(""War Hippy Fatigues"") || is_wearing_outfit(""Frat Warrior Fatigues""))) line += ""|Or... wear it anyways, because you're a pastamancer.""; subentry.entries.listAppend(line); } //need 70 moxie, 70 myst } if (false && $item[talisman o' namsilat].available_amount() == 0 && !__quest_state[""Level 11 Palindome""].finished && my_path_id() != PATH_G_LOVER) { subentry.entries.listAppend(""May want to "" + HTMLGenerateSpanFont(""acquire the Talisman o' Nam"", ""red"") + "" first.""); } subentry.entries.listAppend(generateTurnsToSeeNoncombat(85, 3, ""start war"")); } else { int sides_completed_hippy = base_quest_state.state_int[""Quests completed for hippies""]; int sides_completed_frat = base_quest_state.state_int[""Quests completed for frat boys""]; int frat_boys_left = base_quest_state.state_int[""frat boys left on battlefield""]; int hippies_left = base_quest_state.state_int[""hippies left on battlefield""]; int frat_boys_defeated_per_combat = powi(2, sides_completed_hippy); int hippies_defeated_per_combat = powi(2, sides_completed_frat); if (my_path_id() == PATH_AVATAR_OF_SNEAKY_PETE && get_property(""peteMotorbikeCowling"") == ""Rocket Launcher"") { frat_boys_defeated_per_combat += 3; hippies_defeated_per_combat += 3; } if (my_path_id() == PATH_LICENSE_TO_ADVENTURE && get_property_boolean(""bondWar"")) { frat_boys_defeated_per_combat += 3; hippies_defeated_per_combat += 3; } subentry.modifiers.listAppend(""+item""); if (hippies_left < 1000 || (frat_boys_left == 1000 && hippies_left == 1000) || sides_completed_frat > 0) QLevel12GenerateBattlefieldDescription(subentry, ""frat boy"", hippies_left, hippies_defeated_per_combat, ""hippy"", ""hippies"", ""The Big Wisniewski"", listMake(""Orchard"", ""Nuns"", ""Farm""), listMake(""Lighthouse"", ""Junkyard"", ""Arena"")); //specific exception to deal with 151st cheating: if ((frat_boys_left < 1000 && !(frat_boys_left >= 998 && hippies_left < 1000)) || (frat_boys_left == 1000 && hippies_left == 1000) || sides_completed_hippy > 0) QLevel12GenerateBattlefieldDescription(subentry, ""hippy"", frat_boys_left, frat_boys_defeated_per_combat, ""frat boy"", ""frat boys"", ""The Man"", listMake(""Lighthouse"", ""Junkyard"", ""Arena""), listMake(""Orchard"", ""Nuns"", ""Farm"")); if (frat_boys_left == 1 && hippies_left == 1) { if ($item[flaregun].available_amount() > 0) subentry.entries.listAppend(""Wossname time! Adventure on battlefield, use a flaregun.""); else if (!in_hardcore()) subentry.entries.listAppend(""Pull a flaregun for wossname.""); else if (__misc_state[""fax equivalent accessible""]) subentry.entries.listAppend(""Fax smarmy pirate, run +234% item (or YR) for flaregun for wossname.""); else subentry.entries.listAppend(""That almost was a wossname, but you needed more flare.""); } item [int] items_to_closet_for_desert_hippy; foreach it in $items[reinforced beaded headband,round purple sunglasses,bullet-proof corduroys,beer helmet,distressed denim pants,bejeweled pledge pin] { if (it.available_amount() == 0) continue; items_to_closet_for_desert_hippy.listAppend(it); } if (!have_outfit_components(""War Hippy Fatigues"") && !have_outfit_components(""Frat Warrior Fatigues"")) { string line = ""Visit the Arid, Extra-Dry Desert to find a hippy uniform.""; if (items_to_closet_for_desert_hippy.count() > 0) line += ""|But first closet "" + items_to_closet_for_desert_hippy.listJoinComponents("", "", ""and""); subentry.entries.listAppend(line); } //FIXME Add when spaded: /*else if (!have_outfit_components(""War Hippy Fatigues"")) { string line = ""If you want a hippy uniform without visiting the battlefield, adventure in the Arid, Extra-Dry Desert.""; if (items_to_closet_for_desert_hippy.count() > 0) line += ""|But first closet "" + items_to_closet_for_desert_hippy.listJoinComponents("", "", ""and""); subentry.entries.listAppend(line); }*/ QLevel12GenerateTasksSidequests(task_entries, optional_task_entries, future_task_entries); } } ",12092,False,2099.2939254087737,median "void generateRandomMessageLocation(string [int] random_messages) { if (__last_adventure_location == $location[none]) return; string message = """"; switch (__last_adventure_location) { case $location[the penultimate fantasy airship]: message = ""insert disc 2 to continue""; break; case $location[a-boo peak]: message = ""allons-y!""; break; case $location[twin peak]: message = ""fire walk with me""; break; case $location[The Arrrboretum]: message = ""save the planet""; break; case $location[the red queen's garden]: message = ""curiouser and curiouser""; break; case $location[A Massive Ziggurat]: message = ""1.21 ziggurats""; break; case $location[McMillicancuddy's Barn]: message = ""dooks""; break; case $location[The Roman Forum]: message = ""they go the house""; break; case $location[the battlefield (hippy uniform)]: message = ""love and war""; break; case $location[the middle chamber]: message = ""pyramid laundry machine""; break; case $location[the arid, extra-dry desert]: message = ""can't remember your name""; break; case $location[outside the club]: message = ""around the world around the world around the world around the world""; break; case $location[the hidden temple]: message = ""beware of temple guards""; break; case $location[sonar]: message = ""one ping only""; break; case $location[galley]: message = ""hungry?""; break; case $location[science lab]: message = ""poetry in motion""; break; case $location[fear man's level]: case $location[doubt man's level]: case $location[regret man's level]: case $location[anger man's level]: message = ""this isn't me""; break; case $location[domed city of ronaldus]: case $location[domed city of grimacia]: case $location[hamburglaris shield generator]: message = ""spaaaace!""; break; case $location[The Mansion of Dr. Weirdeaux]: case $location[The Deep Dark Jungle]: case $location[The Secret Government Laboratory]: message = ""they know where you live, "" + get_property(""System.user.name"").to_lower_case(); break; case $location[The castle in the clouds in the sky (ground floor)]: case $location[The castle in the clouds in the sky (basement)]: case $location[The castle in the clouds in the sky (top floor)]: if (my_class() == $class[disco bandit]) message = ""making castles of your disco""; break; case $location[The Prince's Restroom]: case $location[The Prince's Dance Floor]: case $location[The Prince's Kitchen]: case $location[The Prince's Balcony]: case $location[The Prince's Lounge]: case $location[The Prince's Canapes table]: message = ""social sabotage""; break; case $location[anemone mine (mining)]: case $location[itznotyerzitz mine (in disguise)]: case $location[the knob shaft (mining)]: case $location[The Crimbonium Mine]: case $location[The Velvet / Gold Mine (Mining)]: message = ""street sneaky pete don't you call me cause I can't go""; break; case lookupLocation(""Through the Spacegate""): message = ""oh look! rocks!""; case $location[hell]: message = ""that's a clean burning hell, I'll tell you what""; break; } if (message != """") random_messages.listAppend(message); } void generateRandomMessageFamiliar(string [int] random_messages) { string lowercase_player_name = my_name().to_lower_case().HTMLEscapeString(); if (my_familiar() == $familiar[none]) return; string message = """"; switch (my_familiar()) { case $familiar[none]: message = ""even introverts need friends""; break; case $familiar[crimbo shrub]: if (format_today_to_string(""MM"") == ""07"") message = ""crimbo in july""; break; case $familiar[black cat]: message = ""aww, cute kitty!""; break; case $familiar[temporal riftlet]: message = ""master of time and space""; break; case $familiar[Frumious Bandersnatch]: message = ""frabjous""; break; case $familiar[Pair of Stomping Boots]: if (__misc_state[""free runs usable""]) message = ""running away again?""; break; case $familiar[baby sandworm]: message = ""the waters of life""; break; case $familiar[baby bugged bugbear]: message = ""expected }, found }̋̑̀̆͊̑̔͏̱̩̠̰ ̣̻͊ͅf̝͎̰̥̙ͣͦͥ̎,̜̘̖ͭ͋ ̲͉̮̭̪̣͌͋ͤ̉͗ͪ̄̕;̹̼̋̈͛͊ ̧͔̥̤「͙̺̻͖̯͛̀̓̏͑̀l͍̍̍̍͑i̖̖͙͂ͪͮ̍ ̓͑̉̀̆҉̠̜͚̜̹1̶͔̩̬̦̦͍ͥ7͛҉̬̯͇̻͖͉1̆̑̂͒̓」̧̼̜̹̘͕͆̾́͆͐ͯͧ""; //causes severe rendering slowdown; working as intended break; case $familiar[mechanical songbird]: message = ""a little glowing friend""; break; case $familiar[nanorhino]: message = ""write every day""; break; case $familiar[rogue program]: message = ""ascends for the users""; break; case $familiar[O.A.F.]: message = ""helping""; break; case $familiar[Bank Piggy]: case $familiar[Egg Benedict]: case $familiar[Floating Eye]: case $familiar[Money-Making Goblin]: case $familiar[Oyster Bunny]: case $familiar[Plastic Grocery Bag]: case $familiar[Snowhitman]: case $familiar[Vampire Bat]: case $familiar[Worm Doctor]: message = ""hacker""; break; case $familiar[adorable space buddy]: message = ""far beyond the stars""; break; case $familiar[happy medium]: message = ""karma slave""; //what mistakes could I have made? break; case $familiar[wild hare]: message = ""or you wouldn't have come here""; //you must be mad break; case $familiar[artistic goth kid]: message = ""life is pain, "" + lowercase_player_name; break; case $familiar[angry jung man]: message = ""personal trauma""; break; case $familiar[unconscious collective]: message = ""zzz""; break; case $familiar[dataspider]: message = ""spiders are your friends""; break; case $familiar[stocking mimic]: message = ""delicious candy""; break; case $familiar[cocoabo]: message = ""flightless bird""; break; case $familiar[whirling maple leaf]: message = ""canadian pride""; break; case $familiar[Hippo Ballerina]: message = ""spin spin spin""; break; case $familiar[Mutant Cactus Bud]: message = ""always watching""; break; case $familiar[ghuol whelp]: message = ""¯\\\\_(ツ)_/¯""; //¯\\_(ツ)_/¯ break; case $familiar[bulky buddy box]: message = ""♥︎""; //♥︎ break; case $familiar[emo squid]: message = ""sob""; break; case $familiar[fancypants scarecrow]: message = ""the best in terms of pants""; break; case $familiar[jumpsuited hound dog]: message = ""a little less conversation""; break; case $familiar[Gluttonous Green Ghost]: message = ""I think he can hear you, "" + lowercase_player_name; break; case $familiar[hand turkey]: message = ""a rare bird""; break; case $familiar[reanimated reanimator]: message = ""weird science""; break; case $familiar[Twitching Space Critter]: message = ""right right right right down right agh""; break; case $familiar[slimeling]: message = ""lost mother""; break; case $familiar[Puck Man]: case $familiar[Ms. Puck Man]: message = ""ᗧ • • • • • • • • •""; break; case $familiar[Lil' Barrel Mimic]: message = "":D""; break; case $familiar[pet rock]: message = ""what if the rock's eyebrow froze that way. would anyone notice?""; break; case $familiar[space jellyfish]: message = ""deer force""; if (__quest_state[""Level 13""].state_boolean[""king waiting to be freed""]) { int obtained = 0; int obtainable = 0; foreach it in $items[] { if (it.quest) continue; //these disappear if (it.item_amount_almost_everywhere() > 0) obtained += 1; obtainable += 1; } float rate = to_float(obtained) / to_float(obtainable); random_messages.listClear(); message = ""SEE YOU NEXT MISSION
your rate for collecting items is "" + to_int(rate * 100) + ""%""; } else if (my_level() == 1 || my_turncount() <= 2) { random_messages.listClear(); message = ""the last jellyfish is in captivity
the kingdom is at peace""; } break; case $familiar[bad vibe]: message = ""it's all your fault""; break; } if (message != """") random_messages.listAppend(message); } string generateRandomMessage() { string [int] random_messages; int current_hour = now_to_string(""HH"").to_int_silent(); int current_minute = now_to_string(""mm"").to_int_silent(); int minute_of_day = current_hour * 60 + current_minute; if (!playerIsLoggedIn()) return ""the kingdom awaits""; if (__misc_state[""In valhalla""]) return ""rebirth""; if (__misc_state[""in run""]) { if (my_turncount() > 1000 && !in_bad_moon()) random_messages.listAppend(""so many turns""); if (false) random_messages.listAppend(""you are ascending perfectly, excellent work!""); else if (my_daycount() >= 365) random_messages.listAppend(""no king, forever""); else if (my_daycount() >= 11) random_messages.listAppend(""does the king even exist...?""); else if (my_turncount() > 400 && my_daycount() == 1) random_messages.listAppend(""you are ascending too... wait, what?""); else if (gameday_to_int() == 7) random_messages.listAppend(""you are ascending at a reasonable pace, could do better""); else random_messages.listAppend(""you are ascending too slowly, ascend faster!""); string what_does_the_spreadsheet_say = ""saves a turn""; if (my_path_id() == PATH_ONE_CRAZY_RANDOM_SUMMER) what_does_the_spreadsheet_say = ""gives +fun""; if ($item[optimal spreadsheet].equipped_amount() > 0) random_messages.listAppend(""every spreadsheet you wear "" + what_does_the_spreadsheet_say); //sure, why not? else random_messages.listAppend(""every spreadsheet you make "" + what_does_the_spreadsheet_say); } string [string] holiday_messages; holiday_messages[""Groundhog Day""] = ""it's cold out there every day""; holiday_messages[""Crimbo""] = ""merry crimbo""; if ($item[tommy gun].equipped_amount() > 0) //I believe ya, but my tommy gun don't! holiday_messages[""Crimbo""] = ""merry crimbo, ya filthy animal""; holiday_messages[""April Fool's Day""] = ""you are ascending too quickly, ascend slower!""; holiday_messages[""Valentine's Day""] = HTMLGenerateSpanFont(""♥︎"", ""pink"", ""3.0em""); holiday_messages[""Towel Day""] = ""don't panic""; boolean [string] holidays_today = getHolidaysToday(); foreach holiday in holidays_today { if (holiday_messages contains holiday) { random_messages.listAppend(holiday_messages[holiday]); } } if ($item[The One Mood Ring].equipped_amount() > 0 || $item[mood ring].equipped_amount() > 0) { string [int] moods = split_string(""grateful,awake,accomplished,disappointed,enraged,tired,exhausted,amused,crushed,peaceful,energetic,listless,hyper,jubilant,hungry,sad,bewildered,alone,quixotic,recumbent,bored,excited,relaxed,lonely,curious,guilty,jealous,cheerful,depressed,stressed,infuriated,pleased,crappy,aggravated,okay,rejuvenated,apathetic,bittersweet,optimistic,exanimate,complacent,devious,rejected,blissful,discontent,sympathetic,mellow,refreshed,ecstatic,lazy,morose,dark,mischievous,bouncy,thankful,melancholy,content,drained,numb,uncomfortable,indifferent,groggy,calm,irate,determined,giggly,good,confused,anxious,relieved,mad,accepted,happy,angry,lethargic,shocked,indescribable,satisfied,gloomy,irritated,pessimistic,rushed,frustrated,surprised,annoyed,sleepy,touched,enthralled,cynical,envious,hopeful,ashamed,chipper,loved,giddy,restless"", "",""); string mood_today = moods[gameday_to_int()]; if (mood_today != """") random_messages.listAppend(mood_today); } if (__misc_state[""in run""]) { random_messages.listAppend(""optimal power, make up!""); random_messages.listAppend(""the faster your runs, the longer they take""); } generateRandomMessageLocation(random_messages); //random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""if you're feeling stressed, play alice's army"", generateMainLinkMap(""aagame.php""))); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""if you're feeling stressed, play witchess"", generateMainLinkMap(""playwitchess.php?action=another""))); random_messages.listAppend(""consider your mistakes creative spading""); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""Found inaccurate/questionable information?
Have a question/suggestion? Click here!"", string [string] {""href"":""https://github.com/cdrock/TourGuide/discussions"", ""target"":""_blank"", ""class"":""r_a_undecorated""})); if (hippy_stone_broken()) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""it's not easy having yourself a good time"", generateMainLinkMap(""peevpee.php""))); string [item] equipment_messages; equipment_messages[$item[whatsian ionic pliers]] = ""ionic pliers untinker to a screwdriver and a sonar-in-a-biscuit""; equipment_messages[$item[yearbook club camera]] = ""rule of thirds""; equipment_messages[$item[happiness]] = ""bang bang""; equipment_messages[$item[mysterious silver lapel pin]] = ""be seeing you""; equipment_messages[$item[Moonthril Circlet]] = ""moon tiara""; //action! equipment_messages[$item[numberwang]] = ""simply everyone""; equipment_messages[$item[Mark V Steam-Hat]] = ""girl genius""; equipment_messages[$item[mr. accessory]] = ""you can equip mr. accessories?""; equipment_messages[$item[white hat hacker T-shirt]] = ""hack the planet""; equipment_messages[$item[heart necklace]] = ""♥︎""; //♥︎ equipment_messages[$item[fleetwood chain]] = ""running in the shadows""; equipment_messages[$item[liar's pants]] = ""never tell the same lie twice""; equipment_messages[$item[detective skull]] = HTMLGenerateSpanFont(""too slow ascend faster"", ""#ACA200""); //speakeasy password equipment_messages[$item[gasmask]] = ""are you my mummy?""; equipment_messages[$item[spanish fly trap]] = ""around the world around the world around the world around the world""; equipment_messages[$item[wand of nagamar]] = ""levi OH sa""; if (in_bad_moon() && my_primestat() != $stat[moxie]) equipment_messages[$item[sneaky pete's breath spray]] = ""every class a moxie class""; foreach it in $items[twisted-up wet towel,sommelier's towel,time bandit time towel] equipment_messages[it] = ""don't panic""; equipment_messages[$item[pirate fledges]] = "" oh, better far to live and die, under the brave black flag I fly! ""; foreach it in equipment_messages { if (it.equipped_amount() > 0) { random_messages.listAppend(equipment_messages[it]); break; } } if (my_ascensions() == 0) random_messages.listAppend(""welcome to the kingdom!""); else if (my_ascensions() == 1) random_messages.listAppend(""run, while you still have the chance!""); if (__misc_state[""in run""]) random_messages.listAppend(""perfect runs are overrated""); random_messages.listAppend(""math is your helpful friend""); if (get_property_int(""_pantsgivingCount"") >= 5500) { random_messages.listAppend(""Could not connect to secondary database server:2003 - Can't connect to MySQL server on '10.0.0.51' (99)""); } if ((gameday_to_int() & 31) == 0) random_messages.listAppend(""seek the alchemist""); //a young lady's illustrated ascension guide string [effect] effect_messages; effect_messages[$effect[consumed by anger]] = ""don't ascend angry""; effect_messages[$effect[consumed by regret]] = ""wasted potential""; effect_messages[$effect[All Revved Up]] = ""vroom""; if (my_path_id() != PATH_WAY_OF_THE_SURPRISING_FIST) effect_messages[$effect[Expert Timing]] = ""martial arts and crafts""; effect_messages[$effect[apathy]] = """"; // effect_messages[$effect[silent running]] = ""an awful lot of running""; effect_messages[$effect[Neuromancy]] = ""the silver paths""; effect_messages[$effect[Teleportitis]] = ""everywhere and nowhere""; effect_messages[$effect[Form of...Bird!]] = ""fiddle fiddle fiddle""; effect_messages[$effect[superstar]] = ""★""; effect_messages[$effect[hopped up on goofballs]] = ""a massive drug deficiency""; foreach s in $strings[Warlock\\, Warstock\\, and Warbarrel,Barrel of Laughs,Barrel Chested,Pork Barrel,Double-Barreled,Beer Barrel Polka] effect_messages[s.to_effect()] = ""just let me throw a barrel at it""; effect_messages[$effect[Meteor Showered]] = ""すきだ""; foreach e in effect_messages { if (e.have_effect() > 0 && e != $effect[none]) { random_messages.listAppend(effect_messages[e]); break; } } if (__misc_state[""single familiar run""]) random_messages.listAppend(""together forever""); random_messages.listAppend(""click click click""); switch (my_path_id()) { case PATH_OXYGENARIAN: random_messages.listAppend(""the slow path""); break; case PATH_BEES_HATE_YOU: random_messages.listAppend(""bzzzzzz""); break; case PATH_WAY_OF_THE_SURPRISING_FIST: random_messages.listAppend(""martial arts and crafts""); break; case PATH_TRENDY: random_messages.listAppend(""played out""); break; case PATH_AVATAR_OF_BORIS: random_messages.listAppend(""testosterone poisoning""); break; case PATH_BUGBEAR_INVASION: random_messages.listAppend(""bugbears!""); break; case PATH_ZOMBIE_SLAYER: random_messages.listAppend(""consumerism metaphor""); break; case PATH_CLASS_ACT: random_messages.listAppend(""try the sequel""); break; case PATH_AVATAR_OF_JARLSBERG: random_messages.listAppend(""nerd""); break; case PATH_BIG: random_messages.listAppend(""everything's so tiny...""); break; case PATH_KOLHS: random_messages.listAppend(""did you study?""); break; case PATH_CLASS_ACT_2: random_messages.listAppend(""lonely guild trainer""); break; case PATH_AVATAR_OF_SNEAKY_PETE: random_messages.listAppend(""sunglasses at night""); break; case PATH_SLOW_AND_STEADY: if (!in_hardcore()) random_messages.listAppend(""infinite pulls""); else random_messages.listAppend(""skip a day if you like""); break; case PATH_HEAVY_RAINS: random_messages.listAppend(""survive""); break; case PATH_PICKY: if ($skill[cannelloni cannon].skill_is_usable() && !$skill[cannelloni cocoon].skill_is_usable()) //such an easy mistake... random_messages.listAppend(""cannelloni confusion""); else random_messages.listAppend(""combinatorial ascension""); break; case PATH_STANDARD: random_messages.listAppend(""no past no path""); break; case PATH_ACTUALLY_ED_THE_UNDYING: random_messages.listAppend(""UNDYING!""); break; case PATH_ONE_CRAZY_RANDOM_SUMMER: random_messages.listAppend(""dance the mersenne twist""); break; case PATH_COMMUNITY_SERVICE: random_messages.listAppend(""make the world a better place""); break; case PATH_AVATAR_OF_WEST_OF_LOATHING: random_messages.listAppend(""draw""); break; case PATH_THE_SOURCE: if (my_daycount() % 2 == 0) random_messages.listAppend(""don't think you aren't. know you aren't.""); else random_messages.listAppend(""it is not the spoon that ascends, it is only yourself""); break; case PATH_NUCLEAR_AUTUMN: random_messages.listAppend(""I do want to set the world on "" + HTMLGenerateSpanFont(""fire"", ""red"")); break; case PATH_GELATINOUS_NOOB: random_messages.listAppend(""you jelly?""); break; case PATH_LICENSE_TO_ADVENTURE: random_messages.listAppend(""FOR YOUR EYES ONLY""); break; case PATH_LIVE_ASCEND_REPEAT: random_messages.listAppend(""a single perfect day""); break; case PATH_POCKET_FAMILIARS: random_messages.listAppend(""adorable slaves""); break; case PATH_G_LOVER: random_messages.listAppend(""get going, guuuurl""); break; case PATH_DEMIGUISE: random_messages.listAppend(""who are you?""); break; case PATH_VAMPIRE: random_messages.listAppend(""die monster! you don't belong in this world!""); break; case PATH_2CRS: random_messages.listAppend(""what happened to my inventory?""); break; case PATH_EXPLOSIONS: random_messages.listAppend(""kaboooooom""); break; /*case PATH_CLASS_ACT_3: random_messages.listAppend(""buttons for the people""); break; case PATH_AVATAR_OF_THE_NAUGHTY_SORCERESS: random_messages.listAppend(""go forth to your lair! have some tea""); break;*/ } if (in_ronin() && my_adventures() <= 3) random_messages.listAppend(""always tomorrow""); random_messages.listAppend(""I don't know either, sorry""); string lowercase_player_name = my_name().to_lower_case().HTMLEscapeString(); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""check the wiki"", mapMake(""class"", ""r_a_undecorated"", ""href"", ""http://kol.coldfront.net/thekolwiki/index.php/Main_Page"", ""target"", ""_blank""))); random_messages.listAppend(""the RNG is only trying to "" + ((random(100) == 0) ? ""hurt"" : ""help"")); if (__misc_state[""in run""]) { int choice = gameday_to_int() & 3; if (choice == 0) random_messages.listAppend(""speed ascension is all I have left, "" + lowercase_player_name); else if (choice == 1) random_messages.listAppend(""let the turns go""); else if (choice == 2) random_messages.listAppend(""mostly made up""); else if (choice == 3) random_messages.listAppend(""kingdom of self loathing""); if (my_ascensions() >= 1000) random_messages.listAppend(""dedicated""); } if (item_drop_modifier() <= -100.0) random_messages.listAppend(""let go of your material posessions""); if ($item[puppet strings].item_amount() > 0 && my_id() != 1557284) { //full puppet string support: string chosen_message; switch (gameday_to_int() % 13) { case 0: chosen_message = ""%playername% is easily the most great person ever! three cheers for %playername%!""; break; case 1: chosen_message = ""%playername% is my hero! don't you all agree?""; break; case 2: chosen_message = ""%playername% is such a sexy beast!""; break; case 3: chosen_message = ""%playername% is super-attractive and studly! don't you all agree?""; break; case 4: chosen_message = ""%playername% is super-attractive and studly! just saying that name makes me feel all tingly inside!""; break; case 5: chosen_message = ""who do I think is the best KoLer? obviously\\, it's %playername%! how about a round of applause?""; break; case 6: chosen_message = ""I wish I was as good-looking as %playername%. hip hip hooray!""; break; case 7: chosen_message = ""I'm %playername%'s biggest fan! let's hear it for %playername%!""; break; case 8: chosen_message = ""I've never met anyone as attractive as %playername%! how about a round of applause?""; break; case 9: chosen_message = ""I've never met anyone as studly as %playername%! all the rest of us are totally lame in comparison!""; break; case 10: chosen_message = ""is anyone as fabulous as %playername%? I don't think so! just saying that name makes me feel all tingly inside!""; break; case 11: chosen_message = ""is anyone as intelligent as %playername%? I don't think so! hooray for %playername%!""; break; default: chosen_message = ""%playername% is totally awesome! hooray for %playername%!""; break; } chosen_message = chosen_message.replace_string(""%playername%"", lowercase_player_name); random_messages.listAppend(chosen_message); //random_messages.listAppend(lowercase_player_name + "" is totally awesome! hooray for "" + lowercase_player_name + ""!""); } if (__quest_state[""Level 12""].in_progress && __quest_state[""Level 12""].state_int[""hippies left on battlefield""] < 1000 && __quest_state[""Level 12""].state_int[""frat boys left on battlefield""] < 1000) random_messages.listAppend(""playing sides""); if (__iotms_usable[$item[Order of the Green Thumb Order Form]]) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""the forgotten friar cries himself to sleep"", generateMainLinkMap(""place.php?whichplace=forestvillage&action=fv_friar""))); if (!__misc_state[""skills temporarily missing""] && !$skill[Transcendent Olfaction].skill_is_usable()) { random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""visit the bounty hunter hunter sometime"", generateMainLinkMap(""bounty.php""))); } if (__misc_state[""in aftercore""]) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""ascension is waiting for you"", generateMainLinkMap(""place.php?whichplace=nstower""))); if (my_adventures() == 0) random_messages.listAppend(""nowhere left to go""); if (__quest_state[""Level 11""].in_progress) random_messages.listAppend(""try not to lose your sanity""); if (__quest_state[""Level 13""].in_progress) { if (my_daycount() == 1) random_messages.listAppend(""all the world's work in a day""); else random_messages.listAppend(""it'll be all over soon""); } if (!CounterLookup(""Semi-rare"").CounterIsRange() && CounterLookup(""Semi-rare"").CounterExists() && CounterLookup(""Semi-rare"").exact_turns.count() > 1) random_messages.listAppend(""superpositioned semi-rare""); if (hippy_stone_broken() && pvp_attacks_left() > 0) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""aggressive friendship"", generateMainLinkMap(""peevpee.php""))); if (get_property_boolean(""_warbearGyrocopterUsed"")) random_messages.listAppend(""[gyroseaten] => 109""); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""♫"", mapMake(""class"", ""r_a_undecorated"", ""href"", ""http://www.kingdomofloathing.com/radio.php"", ""target"", ""_blank""))); if (__misc_state_int[""free rests remaining""] > 0) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""dream your life away"", generateMainLinkMap(__misc_state_string[""resting url""]))); if (get_property_int(""cinderellaScore"") >= 32) random_messages.listAppend(""mother knows best""); if ($location[the shore\\, inc. travel agency].turnsAttemptedInLocation() >= 11) { if (hippy_stone_broken()) random_messages.listAppend(""beware of shorebots""); else random_messages.listAppend(""under a distant shore you will find your answers""); } if (current_hour >= 2 && current_hour <= 3) random_messages.listAppend(""up late?""); else if (current_hour >= 4 && current_hour <= 5) random_messages.listAppend(""zzz...""); else if (current_hour == 6) random_messages.listAppend(""the dawn is your enemy""); random_messages.listAppend(""take chances, be courageous, go exploring!""); switch (my_class()) { case $class[disco bandit]: random_messages.listAppend(""making discos of your castles""); break; case $class[seal clubber]: random_messages.listAppend(""I ♣︎ seals""); break; case $class[turtle tamer]: random_messages.listAppend(""friends everywhere you go""); break; case $class[sauceror]: random_messages.listAppend(""journey of the sauceror""); break; case $class[Snake Oiler]: random_messages.listAppend(""ten points to slytherin""); break; } if (numeric_modifier(""hot damage"") <= 0.0 && gameday_to_int() % 4 == 0) random_messages.listAppend(""have you tried "" + HTMLGenerateSpanFont(""fire"", ""red"")); if (__misc_state[""Chateau Mantegna available""] && get_property_monster(""chateauMonster"").phylum == $phylum[fish] && !get_property_boolean(""_chateauMonsterFought"")) { random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""personal aquarium"", generateMainLinkMap(""place.php?whichplace=chateau""))); //WhiteWizard42: feeeeesh. feesh in the waaaall } generateRandomMessageFamiliar(random_messages); if (last_monster().phylum == $phylum[penguin]) { random_messages.listClear(); //sufficiently rare random_messages.listAppend(""dood""); } string [monster] monster_messages; string [monster] beaten_up_monster_messages; //TODO add a message for the procrastination giant foreach m in $monsters[The Temporal Bandit,crazy bastard,Knott Slanding,hockey elemental,Hypnotist of Hey Deze,infinite meat bug,QuickBASIC Elemental,The Master of Thieves,Baiowulf,Count Bakula,The Nuge] //Pooltergeist (Ultra-Rare)? monster_messages[m] = ""an ultra rare! congratulations!""; monster_messages[$monster[The Master of Thieves]] = ""don't @ me""; monster_messages[$monster[Dad Sea Monkee]] = ""is always was always"" + HTMLGenerateSpanFont("" is always was always"", ""#444444"") + HTMLGenerateSpanFont("" is always was always"", ""#888888"") + HTMLGenerateSpanFont("" is always was always"", ""#BBBBBB""); foreach m in $monsters[Ed the Undying (1),Ed the Undying (2),Ed the Undying (3),Ed the Undying (4),Ed the Undying (5),Ed the Undying (6),Ed the Undying (7)] monster_messages[m] = ""UNDYING!""; foreach m in $monsters[Naughty Sorceress, Naughty Sorceress (2), Naughty Sorceress (3)] { if (holidays_today[""Valentine's Day""]) monster_messages[m] = ""please be mine, sorceress""; else monster_messages[m] = ""she isn't all that bad""; } foreach m in $monsters[Shub-Jigguwatt\\, Elder God of Violence,Yog-Urt\\, Elder Goddess of Hatred] monster_messages[m] = ""strange aeons""; monster_messages[$monster[daft punk]] = ""can you feel it?""; monster_messages[$monster[ghastly organist]] = ""phantom of the opera""; monster_messages[$monster[The Man]] = ""let the workers unite""; monster_messages[$monster[The Big Wisniewski]] = ""far out""; monster_messages[$monster[Quiet Healer]] = ""...""; monster_messages[$monster[menacing thug]] = ""watch your back""; monster_messages[$monster[sea cowboy]] = ""pardon me""; monster_messages[$monster[topiary golem]] = ""almost ther... wait, golems?""; monster_messages[$monster[The Server]] = ""console cowboy""; monster_messages[$monster[Fickle Finger of F8]] = ""f/8 and be there""; monster_messages[$monster[malevolent crop circle]] = ""I want to believe""; monster_messages[$monster[Enraged Cow]] = ""moo""; if ($item[bottle of blank-out].is_unrestricted()) monster_messages[$monster[Claybender Sorcerer Ghost]] = ""accio blank-out""; else monster_messages[$monster[Claybender Sorcerer Ghost]] = ""leaderboardus totalus""; monster_messages[$monster[Whatsian Commando Ghost]] = ""captain jack hotness""; if (my_path_id() == PATH_ACTUALLY_ED_THE_UNDYING) monster_messages[$monster[Whatsian Commando Ghost]] = ""are you my mummy?""; monster_messages[$monster[Space Tourist Explorer Ghost]] = ""oh my""; monster_messages[$monster[Battlie Knight Ghost]] = ""boring conversation anyway""; monster_messages[$monster[oil slick]] = ""run more ML!""; monster_messages[$monster[Space Marine]] = ""as if it were from an old dream""; monster_messages[$monster[Regret Man]] = ""wasted potential""; monster_messages[$monster[Principal Mooney]] = ""life moves pretty fast""; if (my_turncount() < 11) monster_messages[$monster[family of kobolds]] = ""in a hurry?""; monster_messages[$monster[Black Crayon Spiraling Shape]] = ""be what you're like""; monster_messages[$monster[best-selling novelist]] = ""fiction to escape reality""; monster_messages[$monster[7-Foot Dwarf Replicant]] = ""it's too bad she won't live
but then again, who does?""; monster_messages[$monster[The Avatar of Jarlsberg]] = ""smoked cheese""; monster_messages[$monster[giant sandworm]] = ""walk without rhythm""; monster_messages[$monster[bookbat]] = ""tattered scrap of dignity""; monster_messages[$monster[Urge to Stare at Your Hands]] = "".⃝.⃝""; //.⃝.⃝ if (my_path_id() == PATH_HEAVY_RAINS) monster_messages[$monster[pygmy bowler]] = ""right into the gutter""; //come back! monster_messages[$monster[Ron ""The Weasel"" Copperhead]] = ""RONALD WEASLEY! HOW DARE YOU STEAL THAT ZEPPELIN
"" + ChecklistGenerateModifierSpan(""your father's now facing an inquiry at work and it's entirely YOUR FAULT""); monster_messages[$monster[Mr. Loathing]] = HTMLGenerateTagWrap(""a"", ""ruuun! go! get to the towah!"", generateMainLinkMap(""place.php?whichplace=nstower"")); if (my_hp() < my_maxhp()) monster_messages[$monster[Smooth Criminal]] = ""you've been hit by
you've been struck by
a smooth criminal""; monster_messages[$monster[demonic icebox]] = ""zuul""; monster_messages[$monster[angry mushroom guy]] = ""touch fizzy, get dizzy""; beaten_up_monster_messages[$monster[storm cow]] = ""
^__^            
(oo)\\\\_______
(__)\\\\ )\\\\/\\\\
||----w |
|| ||
""; monster_messages[$monster[The Barrelmech of Diogenes]] = ""just let me throw a barrel at it""; //beaten_up_monster_messages[$monster[Lavalos]] = HTMLGenerateTagWrap(""span"", ""but... the future refused to change"", mapMake(""onclick"", ""var l = new Audio('"" + __lavalos_sound_data + ""'); l.play();"", ""class"", ""r_clickable"")); //copyright, etc beaten_up_monster_messages[$monster[Lavalos]] = ""but... the future refused to change""; if ($item[protonic accelerator pack].equipped_amount() > 0 && last_monster().monsterIsGhost()) beaten_up_monster_messages[last_monster()] = ""venkman makes it look easy""; if ($effect[beaten up].have_effect() > 0 && $items[rainbow pearl earring,rainbow pearl necklace,rainbow pearl ring,vampire pearl earring,vampire pearl ring,vampire pearl necklace,freshwater pearl necklace,pearl diver's ring,pearl diver's necklace,pearl necklace].equipped_amount() > 0) beaten_up_monster_messages[last_monster()] = ""WHY WON'T YOU LET ME DO THIS FOR YOU, ROSE?""; if (last_monster().phylum == $phylum[demon]) beaten_up_monster_messages[last_monster()] = ""he made the devil so much stronger than a man!""; if (current_hour >= 5 && current_hour <= 11) monster_messages[$monster[Lavalos]] = ""good morning, "" + lowercase_player_name + ""!""; else monster_messages[$monster[Lavalos]] = ""all life begins with nu and ends with nu""; monster_messages[$monster[sk8 gnome]] = ""he was a sk8 gnome she said see u l8 gnome""; monster_messages[$monster[The Inquisitor]] = ""nothing is up""; monster_messages[$monster[Doc Clock]] = ""your defeat will happen at "" + (current_hour > 12 ? current_hour - 12 : current_hour) + "":"" + current_minute + "" precisely""; // + (current_hour >= 12 ? "" PM"" : "" AM"") monster_messages[lookupMonster(""God Lobster"")] = ""what a grand and intoxicating innocence""; //how can you kill a god? equip the heart of the volcano? monster_messages[lookupMonster(""cockroach"")] = ""are bug exterminators professional assassins?""; string day_cycle; if (current_hour >= 5 && current_hour <= 11) day_cycle = ""morning""; else if (current_hour >= 12 && current_hour <= 16) day_cycle = ""afternoon""; else if (current_hour >= 17 && current_hour <= 20) day_cycle = ""evening""; else day_cycle = ""night""; monster_messages[$monster[Travoltron]] = now_to_string(""EEEE"").to_lower_case() + "" "" + day_cycle + "" fever""; if (my_daycount() == 2 && (my_adventures() == 0 || availableDrunkenness() < 0) && availableFullness() == 0 && availableDrunkenness() <= 0 && my_path_id() != PATH_OXYGENARIAN && __quest_state[""Level 12""].started && !__quest_state[""Level 13""].state_boolean[""king waiting to be freed""] && my_path_id() != PATH_NUCLEAR_AUTUMN && my_path_id() != PATH_SLOW_AND_STEADY && !__quest_state[""Level 13""].finished) { //detect failed two-day runs, and provide psychological support: random_messages.listClear(); if (__quest_state[""Level 13""].started) random_messages.listAppend(""ever so close""); else random_messages.listAppend(""three days is fine""); } boolean already_output_relevant_beaten_up_effect = false; if ((my_hp() == 0 || $effect[beaten up].have_effect() > 0) && beaten_up_monster_messages contains last_monster() && last_monster() != $monster[none]) { random_messages.listClear(); random_messages.listAppend(beaten_up_monster_messages[last_monster()]); already_output_relevant_beaten_up_effect = true; } else if (monster_messages contains last_monster() && last_monster() != $monster[none]) { random_messages.listClear(); random_messages.listAppend(monster_messages[last_monster()]); } if (__quest_state[""Level 13""].state_boolean[""king waiting to be freed""]) { if (my_path_id() == PATH_ONE_CRAZY_RANDOM_SUMMER) { random_messages.listClear(); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""roll the dice"", generateMainLinkMap(""place.php?whichplace=nstower""))); } } if (__misc_state_int[""Basement Floor""] == 500) { random_messages.listClear(); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""open it!"", generateMainLinkMap(""basement.php""))); } string [string] encounter_messages; boolean encounter_override = false; encounter_messages[""It's Always Swordfish""] = ""one two three four five""; encounter_messages[""Meet Frank""] = ""don't trust the skull""; encounter_messages[""The Mirror in the Tower has the View that is True""] = ""shatter the false reality""; encounter_messages[""A Tombstone""] = ""peperony and chease""; encounter_messages[""Witchess Puzzles""] = ""this etch a sketch is hard""; encounter_messages[""Rubbed it the Right Way""] = ""desire incarnate""; if (my_class() == $class[turtle tamer]) { //The Horror... needs disambiguation foreach s in $strings[Nantucket Snapper,Blue Monday,Capital!,Training Day,Boxed In,Duel Nature,Slow Food,A Rolling Turtle Gathers No Moss,Slow Road to Hell,C'mere\\, Little Fella,The Real Victims,Like That Time in Tortuga,Cleansing your Palette,Harem Scarum,Turtle in peril,No Man\\, No Hole,Slow and Steady Wins the Brawl,Stormy Weather,Turtles of the Universe,O Turtle Were Art Thou,Allow 6-8 Weeks For Delivery,Kick the Can,Turtles All The Way Around,More eXtreme Than Usual,Jewel in the Rough,The worst kind of drowning] encounter_messages[s] = ""friend!""; } if (encounter_messages contains get_property(""lastEncounter"")) { random_messages.listClear(); random_messages.listAppend(encounter_messages[get_property(""lastEncounter"")]); encounter_override = true; } if (__quest_state[""Level 12""].in_progress && __quest_state[""Level 12""].state_int[""hippies left on battlefield""] == 1 && __quest_state[""Level 12""].state_int[""frat boys left on battlefield""] == 1) { random_messages.listClear(); random_messages.listAppend(""wossname is waiting""); } if (my_familiar() == $familiar[Helix Fossil]) { buffer generated; string [int] commands; string property_value = get_property(""__voices""); if (property_value.length() > 1) //remove sentinel { if (property_value.char_at(property_value.length() - 1) == ""|"") property_value = property_value.substring(0, property_value.length() - 1); } commands = property_value.split_string_alternate("",""); for i from 0 to 0 { string word; int r = random(100); if (r < 15) word = ""⬆""; //⬆︎ else if (r < 30) word = ""⬇""; //⬇︎ else if (r < 45) word = ""➡""; //➡ else if (r < 60) word = ""⬅""; //⬅︎ else if (r < 75) word = ""A"";// Ⓐ = Ⓐ else if (r < 95) word = ""B""; //Ⓑ = Ⓑ else word = ""start""; commands.listAppend(word); } while (commands.count() > 6) remove commands[commands.listKeyForIndex(0)]; set_property(""__voices"", commands.listJoinComponents("","") + ""|""); //we add an ending sentinel because set_property() will remove "";"" if it's at the end of the string. set_property() is not guaranteed to keep data integrity random_messages.listClear(); string message = commands.listJoinComponents("" ""); message = HTMLGenerateTagWrap(""span"", message, mapMake(""onclick"", ""updatePageAndFireTimer()"", ""class"", ""r_clickable"")); random_messages.listAppend(message); } foreach s in $strings[rainDohMonster,spookyPuttyMonster,cameraMonster,photocopyMonster,envyfishMonster,iceSculptureMonster,crudeMonster,crappyCameraMonster,romanticTarget,chateauMonster] { if (get_property_monster(s) == $monster[Quiet Healer]) { random_messages.listClear(); random_messages.listAppend(""you can't bring her back""); break; } } if (false)//mmg_my_bets().count() > 0) { random_messages.listClear(); random_messages.listAppend(""win some, lose some""); } if ($effect[beaten up].have_effect() > 0 && limit_mode().length() == 0 && !already_output_relevant_beaten_up_effect) { random_messages.listClear(); switch (my_path_id()) { case PATH_BEES_HATE_YOU: random_messages.listAppend(""BZZZZZZ""); break; case PATH_ONE_CRAZY_RANDOM_SUMMER: random_messages.listAppend(""tick, tock""); break; case PATH_ACTUALLY_ED_THE_UNDYING: random_messages.listAppend(""DYING!""); break; case PATH_COMMUNITY_SERVICE: random_messages.listAppend(""no good deed goes unpunished""); break; case PATH_AVATAR_OF_WEST_OF_LOATHING: random_messages.listAppend(""shucks""); break; case PATH_LIVE_ASCEND_REPEAT: random_messages.listAppend(""I got you babe""); break; case PATH_LICENSE_TO_ADVENTURE: random_messages.listAppend(""you only live twice""); break; case PATH_THE_SOURCE: random_messages.listAppend(""not like this""); break; case PATH_POCKET_FAMILIARS: random_messages.listAppend(lowercase_player_name + ""! now is not the time to use that!""); break; case PATH_G_LOVER: random_messages.listAppend(""the Gs will continue until morale improves""); break; default: random_messages.listAppend(""ow""); break; } } if (my_turncount() <= 0) { random_messages.listClear(); if (my_path_id() == PATH_LIVE_ASCEND_REPEAT) random_messages.listAppend(""I got you babe""); else if (my_path_id() == PATH_POCKET_FAMILIARS) random_messages.listAppend(""pika pika!""); else random_messages.listAppend(""find yourself
starting back""); } if (limit_mode() == ""Spelunky"" && !encounter_override) { random_messages.listClear(); if (get_property(""lastEncounter"") == ""Spelunkrifice"" && get_property(""spelunkyStatus"").contains_text(""Buddy: "")) { if (get_property(""spelunkingStatus"").contains_text(""Resourceful Kid"")) random_messages.listAppend(""he's only a child!""); else random_messages.listAppend(""et tu, "" + lowercase_player_name + ""?""); } else random_messages.listAppend(""ascend? yes! play? no!""); } if (limit_mode() == ""batman"" && !encounter_override) { random_messages.listClear(); random_messages.listAppend(""a superstitious, cowardly lot""); } if (format_today_to_string(""yyyyMMdd"") == ""20151021"") //october 21st, 2015 { //kept active for any time travelers random_messages.listClear(); if (get_property(""System.user.country.format"") == ""US"") random_messages.listAppend(""88 MPH
hey, you did it!""); else random_messages.listAppend(""142 km/h
hey, you did it!""); } //Choose: if (random_messages.count() == 0) return ""lack of cleverness""; string chosen_message = """"; //Base message off of the minute, so it doesn't cycle when the page reloads often: chosen_message = random_messages[minute_of_day % random_messages.count()]; return chosen_message; } ",12449,True,2563.0212467257033,median "script ""auto_mr2016.ash"" # This is meant for items that have a date of 2016. # Handling: Witchess Set, Snojo, Source Terminal, Protonic Accelerator Pack # Time-Spinner boolean snojoFightAvailable(); boolean auto_advWitchess(string target); boolean auto_advWitchess(string target, string option); boolean auto_haveWitchess(); boolean auto_haveSourceTerminal(); boolean auto_sourceTerminalRequest(string request); boolean auto_sourceTerminalEnhance(string request); int auto_sourceTerminalEnhanceLeft(); boolean auto_sourceTerminalExtrude(string request); int auto_sourceTerminalExtrudeLeft(); int[string] auto_sourceTerminalStatus(); boolean auto_doPrecinct(); item auto_bestBadge(); boolean auto_sourceTerminalEducate(skill first); boolean auto_sourceTerminalEducate(skill first, skill second); boolean LX_ghostBusting(); boolean expectGhostReport(); boolean haveGhostReport(); boolean timeSpinnerGet(string goal); boolean timeSpinnerConsume(item goal); boolean timeSpinnerCombat(monster goal); boolean timeSpinnerCombat(monster goal, string option); boolean timeSpinnerAdventure(string option); boolean timeSpinnerAdventure(); boolean rethinkingCandy(effect acquire); boolean rethinkingCandy(effect acquire, boolean simulate); boolean rethinkingCandyList(); //Supplemental int auto_advWitchessTargets(string target); boolean snojoFightAvailable() { if(!is_unrestricted($item[X-32-F Snowman Crate])) { return false; } if(!get_property(""snojoAvailable"").to_boolean()) { return false; } if(my_inebriety() > inebriety_limit()) { return false; } if(!get_property(""kingLiberated"").to_boolean()) { int[string] controls; controls[""MUSCLE""] = 1; controls[""MYSTICALITY""] = 2; controls[""MOXIE""] = 3; controls[""Muscle""] = 1; controls[""Mysticality""] = 2; controls[""Moxie""] = 3; //List the three desired goals and then a ""final"" state that we stay in string[int] standard; standard[0] = ""Moxie""; standard[1] = ""Mysticality""; standard[2] = ""Muscle""; standard[3] = ""Moxie""; if((my_path() == ""Avatar of Boris"") && (possessEquipment($item[Boris\\'s Helm]) || possessEquipment($item[Boris\\'s Helm (Askew)]))) { standard[0] = ""Muscle""; standard[1] = ""Mysticality""; standard[2] = ""Moxie""; standard[3] = ""Mysticality""; } if(my_path() == ""Community Service"") { standard[0] = ""Mysticality""; standard[1] = ""Moxie""; standard[2] = ""Muscle""; standard[3] = ""Mysticality""; } if(my_path() == ""License to Adventure"") { standard[0] = ""Mysticality""; standard[1] = ""Moxie""; standard[2] = ""Muscle""; standard[3] = ""Mysticality""; } if((get_property(""snojo"" + standard[0] + ""Wins"").to_int() < 14) && (get_property(""snojoSetting"") != to_upper_case(standard[0]))) { string temp = visit_url(""place.php?whichplace=snojo&action=snojo_controller""); temp = run_choice(controls[standard[0]]); } if((get_property(""snojoSetting"") == to_upper_case(standard[0])) && (get_property(""snojo"" + standard[0] + ""Wins"").to_int() >= 14) && (get_property(""snojoSetting"") != to_upper_case(standard[1])) && (get_property(""snojo"" + standard[1] + ""Wins"").to_int() < 14)) { string temp = visit_url(""place.php?whichplace=snojo&action=snojo_controller""); temp = run_choice(controls[standard[1]]); } if((get_property(""snojoSetting"") == to_upper_case(standard[1])) && (get_property(""snojo"" + standard[1] + ""Wins"").to_int() >= 14) && (get_property(""snojoSetting"") != to_upper_case(standard[2])) && (get_property(""snojo"" + standard[2] + ""Wins"").to_int() < 14)) { string temp = visit_url(""place.php?whichplace=snojo&action=snojo_controller""); temp = run_choice(controls[standard[2]]); } if((get_property(""snojoSetting"") == to_upper_case(standard[2])) && (get_property(""snojo"" + standard[2] + ""Wins"").to_int() >= 11) && (get_property(""snojoSetting"") != to_upper_case(standard[3]))) { string temp = visit_url(""place.php?whichplace=snojo&action=snojo_controller""); temp = run_choice(controls[standard[3]]); } } if(get_property(""snojoSetting"") == ""NONE"") { print(""Snojo not set, attempting to set to "" + my_primestat(), ""blue""); visit_url(""place.php?whichplace=snojo&action=snojo_controller""); } return (get_property(""_snojoFreeFights"").to_int() < 10); } boolean auto_haveSourceTerminal() { if(!is_unrestricted($item[Source Terminal])) { return false; } static boolean didCheck = false; if((auto_my_path() == ""Nuclear Autumn"") && !didCheck) { didCheck = true; string temp = visit_url(""place.php?whichplace=falloutshelter&action=vault_term""); if(contains_text(temp, ""Source Terminal"")) { set_property(""auto_haveSourceTerminal"", true); } } return (auto_get_campground() contains $item[Source Terminal]); } boolean auto_sourceTerminalRequest(string request) { //enhance .enh [meat|items|init|critical] //enquiry .enq [familiar|monsters] //educate .edu [digitize|extract] //extrude .ext [food|booze|goggles] print(""Source Terminal request: "" + request, ""green""); //""campground.php?action=terminal&hack=enhance items.enh"" if(auto_haveSourceTerminal()) { if(auto_my_path() == ""Nuclear Autumn"") { string temp = visit_url(""place.php?whichplace=falloutshelter&action=vault_term""); } else { string temp = visit_url(""campground.php?action=terminal""); } # temp = visit_url(""choice.php?pwd=&whichchoice=1191&option=1&input=reset""); string temp = visit_url(""choice.php?pwd=&whichchoice=1191&option=1&input="" + request); # temp = visit_url(""choice.php?pwd=&whichchoice=1191&option=1&input=reset""); return true; } return false; } boolean auto_sourceTerminalExtrude(string request) { if(!auto_haveSourceTerminal()) { return false; } if(auto_sourceTerminalExtrudeLeft() == 0) { return false; } string actual = """"; request = to_lower_case(request); switch(request) { case ""food"": case ""food.ext"": case ""browser cookie"": actual = ""food""; break; case ""booze"": case ""booze.ext"": case ""hacked gibson"": actual = ""booze""; break; case ""goggles"": case ""goggles.ext"": case ""source shades"": actual = ""goggles""; break; default: return false; } return auto_sourceTerminalRequest(""extrude -f "" + actual + "".ext""); } int auto_sourceTerminalExtrudeLeft() { if(auto_haveSourceTerminal()) { return 3 - get_property(""_sourceTerminalExtrudes"").to_int(); } return 0; } boolean auto_sourceTerminalEnhance(string request) { if(!auto_haveSourceTerminal()) { return false; } if(auto_sourceTerminalEnhanceLeft() == 0) { return false; } string actual = """"; switch(request) { case ""meat"": case ""meat.enh"": actual = ""meat""; break; case ""item"": case ""items"": case ""item.enh"": case ""items.enh"": actual = ""items""; break; case ""substats"": case ""substats.enh"": case ""stats"": actual = ""substats""; break; case ""damage"": case ""damage.enh"": actual = ""damage""; break; case ""init"": case ""initiative"": actual = ""init""; break; case ""critical"": actual = ""critical""; break; default: return false; } if(contains_text(get_property(""sourceTerminalEnhanceKnown""), actual + "".enh"")) { return auto_sourceTerminalRequest(""enhance "" + actual + "".enh""); } return false; } int auto_sourceTerminalEnhanceLeft() { if(auto_haveSourceTerminal()) { int used = get_property(""_sourceTerminalEnhanceUses"").to_int(); int total = 1; if(get_property(""sourceTerminalChips"") != """") { string[int] chips = split_string(get_property(""sourceTerminalChips""), "",""); foreach index in chips { string chip = trim(chips[index]); if((chip == ""CRAM"") || (chip == ""SCRAM"")) { total += 1; } } } return total - used; } return 0; } int[string] auto_sourceTerminalMissing() { int[string] status; status[""ASHRAM""] = 1; status[""CRAM""] = 1; status[""DIAGRAM""] = 1; status[""DRAM""] = 1; status[""GRAM""] = 10; status[""INGRAM""] = 1; status[""PRAM""] = 10; status[""SCRAM""] = 1; status[""SPAM""] = 10; status[""TRAM""] = 1; status[""TRIGRAM""] = 1; status[""booze.ext""] = 1; status[""compress.edu""] = 1; status[""cram.ext""] = 1; status[""critical.enh""] = 1; status[""damage.enh""] = 1; status[""digitize""] = 3; status[""digitize.edu""] = 1; status[""dram.ext""] = 1; status[""duplicate.edu""] = 1; status[""educate""] = 2; status[""enhance""] = 103; status[""enhanceBuff""] = 100; status[""enhanceUses""] = 3; status[""enquiry""] = 250; status[""extract.edu""] = 1; status[""familiar.enq""] = 1; status[""familiar.ext""] = 1; status[""food.ext""] = 1; status[""goggles.ext""] = 1; status[""gram.ext""] = 1; status[""init.enh""] = 1; status[""items.enh""] = 1; status[""meat.enh""] = 1; status[""monsters.enq""] = 1; status[""mpReduce""] = 15; status[""portscan.edu""] = 1; status[""pram.ext""] = 1; status[""protect.enq""] = 1; status[""spam.ext""] = 1; status[""stats.enq""] = 1; status[""substats.enh""] = 1; status[""tram.ext""] = 1; status[""turbo.edu""] = 1; int[string] have = auto_sourceTerminalStatus(); foreach thing in have { status[thing] -= have[thing]; } return status; } int[string] auto_sourceTerminalStatus() { int[string] status; if(auto_haveSourceTerminal()) { string temp = visit_url(""campground.php?action=terminal""); temp = visit_url(""choice.php?pwd=&whichchoice=1191&option=1&input=reset""); temp = visit_url(""choice.php?pwd=&whichchoice=1191&option=1&input=status""); temp = visit_url(""choice.php?pwd=&whichchoice=1191&option=1&input=ls""); matcher ramMatcher = create_matcher(""
((?:[A-Z]*?)?[RP]AM) (chip(?:s?)) installed([:,]) ((?:\\\\d+)|(?:\\\\w))"", temp); while(ramMatcher.find()) { if(ramMatcher.group(3) == "","") { status[ramMatcher.group(1)] = 1; } else { status[ramMatcher.group(1)] = ramMatcher.group(4).to_int(); } } matcher extrude = create_matcher(""\\\\b((?:\\\\w+?)[.](?:ext|enh|edu|enq))"", temp); while(extrude.find()) { status[extrude.group(1)] = 1; } # temp = visit_url(""choice.php?pwd=&whichchoice=1191&option=1&input=reset""); status[""enhanceBuff""] = 25 + (25 * status[""INGRAM""]) + (5 * status[""PRAM""]); status[""enhanceUses""] = 1 + status[""CRAM""] + status[""SCRAM""]; status[""enhance""] = status[""enhanceBuff""] + status[""enhanceUses""]; status[""enquiry""] = 50 + ((status[""DIAGRAM""] + 1) * status[""GRAM""] * 10); status[""educate""] = 1 + status[""DRAM""]; status[""digitize""] = 1 + status[""TRIGRAM""] + status[""TRAM""]; status[""mpReduce""] = (5 * status[""ASHRAM""]) + status[""SPAM""]; } return status; } boolean auto_sourceTerminalEducate(skill first, skill second) { if(!auto_haveSourceTerminal()) { return false; } if(auto_my_path() == ""Pocket Familiars"") { return false; } if(first == $skill[none]) { first = second; second = $skill[none]; } if(!contains_text(get_property(""sourceTerminalChips""), ""DRAM"")) { second = $skill[none]; set_property(""sourceTerminalEducate2"", """"); } if(first == $skill[none]) { return false; } string firstSkill = to_lower_case(to_string(first)) + "".edu""; string secondSkill = to_lower_case(to_string(second)) + "".edu""; if((get_property(""sourceTerminalEducate1"") == firstSkill) || (get_property(""sourceTerminalEducate2"") == firstSkill)) { if((get_property(""sourceTerminalEducate1"") == secondSkill) || (get_property(""sourceTerminalEducate2"") == secondSkill) || (secondSkill == ""none.edu"")) { return true; } } auto_sourceTerminalRequest(""educate "" + firstSkill); if(secondSkill != ""none.edu"") { auto_sourceTerminalRequest(""educate "" + secondSkill); } return true; } boolean auto_sourceTerminalEducate(skill first) { return auto_sourceTerminalEducate(first, $skill[none]); } boolean auto_haveWitchess() { if(!is_unrestricted($item[Witchess Set])) { return false; } return (auto_get_campground() contains $item[Witchess Set]); } boolean auto_advWitchess(string target) { return auto_advWitchess(target, """"); } boolean auto_advWitchess(string target, string option) { if(!auto_haveWitchess()) { return false; } if(my_adventures() == 0) { return false; } int goal = auto_advWitchessTargets(target); if(goal == 0) { return false; } if(get_property(""_auto_witchessBattles"").to_int() >= 5) { return false; } # if(get_property(""_witchessFights"").to_int() >= 5) # { # return false; # } # if(get_property(""_witchessFights"").to_int() > get_property(""_auto_witchessBattles"").to_int()) # { # print(""_witchessFights is greater than our tracking, it is probably more accurate at this point (assuming manual Witchess combats)."", ""red""); # set_property(""_auto_witchessBattles"", get_property(""_witchessFights"")); # } set_property(""_auto_witchessBattles"", get_property(""_auto_witchessBattles"").to_int() + 1); string temp = visit_url(""campground.php?action=witchess""); if(!contains_text(temp, ""Examine the shrink ray"")) { set_property(""_auto_witchessBattles"", 5); return false; } temp = visit_url(""choice.php?whichchoice=1181&pwd=&option=1""); matcher witchessMatcher = create_matcher(""You can fight (\\\\d) more piece(s?) today"", temp); if(witchessMatcher.find()) { int consider = (5 - witchessMatcher.group(1).to_int()) + 1; if(consider > get_property(""_auto_witchessBattles"").to_int()) { set_property(""_auto_witchessBattles"", consider); } } else { set_property(""_auto_witchessBattles"", 5); return false; } temp = visit_url(""choice.php?pwd=&option=2&whichchoice=1182""); string[int] pages; pages[0] = ""campground.php?action=witchess""; pages[1] = ""choice.php?whichchoice=1181&pwd=&option=1""; pages[2] = ""choice.php?pwd="" + my_hash() + ""&whichchoice=1182&option=1&piece="" + goal; // We use 4 to cause pages[2] to use GET. return autoAdvBypass(4, pages, $location[Noob Cave], option); } int auto_advWitchessTargets(string target) { target = to_lower_case(target); if((target == ""knight"") || (target == ""meat"") || (target == ""food"")) { return 1936; } if((target == ""pawn"") || (target == ""spleen"") || (target == ""init"")) { return 1935; } if((target == ""bishop"") || (target == ""item"") || (target == ""booze"")) { return 1942; } if((target == ""rook"") || (target == ""ml"") || (target == ""stats"")) { return 1938; } if((target == 1942) && (auto_my_path() == ""Teetotaler"")) { return 1936; } if((target == ""ox"") || (target == ""ox-head shield"") || (target == ""shield"") || (target == ""pvp"") || (target == ""hp"") || (target == ""resist"") || (target == ""resistance"")) { return 1937; } if((target == ""king"") || (target == ""dented scepter"") || (target == ""scepter"") || (target == ""club"") || (target == ""muscle"") || (target == ""hpregen"")) { return 1940; } if((target == ""witch"") || (target == ""battle broom"") || (target == ""broom"") || (target == ""myst"") || (target == ""mpregen"") || (target == ""spell"")) { return 1941; } if((target == ""queen"") || (target == ""very pointy crown"") || (target == ""crown"") || (target == ""adv"") || (target == ""moxie"") || (target == ""nc"") || (target == ""noncombat"") || (target == ""non-combat"")) { return 1939; } return 0; } item auto_bestBadge() { item retval = $item[none]; foreach it in $items[Plastic Detective Badge, Bronze Detective Badge, Silver Detective Badge, Gold Detective Badge] { if(possessEquipment(it)) { retval = it; } } return retval; } boolean auto_doPrecinct() { if(!is_unrestricted($item[Detective School Application])) { return false; } if(!get_property(""hasDetectiveSchool"").to_boolean()) { return false; } if(get_property(""_detectiveCasesCompleted"").to_int() >= 3) { return false; } if(svn_info(""Ezandora-Detective-Solver-branches-Release"").last_changed_rev > 0) { //Assume if someone has this installed that they want to use it. cli_execute(""ash import solveAllCases(false);""); return true; } if(get_property(""auto_eggDetective"") != """") { set_property(""auto_eggDetective"", """"); } string page = visit_url(""place.php?whichplace=town_wrong&action=townwrong_precinct""); matcher eggMatcher = create_matcher(""You have been on this case for (\\\\d+) minute(?:s?)"", page); if(!eggMatcher.find()) { if(!contains_text(page, ""The Precinct"")) { return false; } int casesLeft = 0; matcher precinctMatcher = create_matcher(""[(](\\\\d) more case(?:s?) today[)]"", page); if(precinctMatcher.find()) { casesLeft = to_int(precinctMatcher.group(1)); print(""We have "" + casesLeft + "" case(s) leftover!"", ""green""); } if(casesLeft == 0) { page = visit_url(""wham.php"", false); if(!contains_text(page, ""You have been on this case for"")) { return false; } print(""Trying to resume case...."", ""red""); } page = visit_url(""choice.php?pwd=&whichchoice=1193&option=1""); eggMatcher = create_matcher(""You have been on this case for (\\\\d+) minute(?:s?)"", page); if(!contains_text(page, ""murdered with an egg"")) { if(!eggMatcher.find()) { print(""Someone was not murdered with an egg.... that's sad."" + page, ""red""); return false; } } print(""Murdered with an egg! I love Egg!!"", ""green""); page = visit_url(""wham.php"", false); } eggMatcher = create_matcher(""You have been on this case for (\\\\d+) minute(?:s?)"", page); if(!eggMatcher.find()) { print(""I can not resolve my case situation...."", ""red""); return false; } while(!contains_text(get_property(""auto_eggDetective""), ""solved"")) { string[int] eggData = split_string(get_property(""auto_eggDetective""), "",""); int i=1; while(i<=9) { boolean visited = false; foreach index in eggData { //print(""Subegg: "" + eggData[index], ""blue""); string[int] subEgg = split_string(eggData[index], "":""); if(subEgg[0].to_int() == i) { visited = true; break; } } if(!visited) { print(""Going to visit room: "" + i, ""green""); page = visit_url(""wham.php?visit="" + i, false); matcher personMatcher = create_matcher(""(?:\\\\s+)(?:\\\\s+)
(?:\\\\s+)([a-zA-Z ]+?)(?:\\\\s+?)
(?:\\\\s+?)([a-zA-Z -]+)(?:\\\\s+?)

(?:\\\\s+?)[(]([a-zA-Z ']+?)[)]"", page); if(personMatcher.find()) { string person = personMatcher.group(1); string job = personMatcher.group(2); string room = personMatcher.group(3); print(""Found "" + personMatcher.group(1), ""green""); print(""Found "" + personMatcher.group(2), ""green""); print(""Found "" + personMatcher.group(3), ""green""); string generated = """" + i + "":"" + room + "":"" + person + "":"" + job; //Get killer response as well. page = visit_url(""wham.php?ask=killer&visit="" + i, false); matcher killerMatcher = create_matcher(""you (?:ask|say)(?:.*?)

(.*?)(\\\\s*?)"", page); if(killerMatcher.find()) { string killerInfo = killerMatcher.group(1); killerInfo = replace_string(killerInfo, "","", """"); killerInfo = replace_string(killerInfo, "":"", """"); killerInfo = replace_string(killerInfo, ""

"", """"); killerInfo = replace_string(killerInfo, """", """"); killerInfo = replace_string(killerInfo, """", """"); string[int] nameSplit = split_string(person, "" ""); foreach index in nameSplit { killerInfo = replace_string(killerInfo, nameSplit[index], """"); } generated += "":"" + killerInfo; } else { print(""Jerkwad '"" + person + ""' won't say anything!"", ""blue""); generated += "":liar""; } set_property(""auto_eggDetective"", generated + "","" + get_property(""auto_eggDetective"")); } } i += 1; } eggData = split_string(get_property(""auto_eggDetective""), "",""); print(""Generating goals..."", ""blue""); //At this point we\\'ve visited every place and queried everyone. Now we need to determine who is identifying a killer. //Extract names and jobs boolean[string] personGoals; boolean[string] jobGoals; boolean[string] locationGoals; foreach index in eggData { if(eggData[index] == """") { continue; } string[int] subEgg = split_string(eggData[index], "":""); personGoals[subEgg[2]] = true; jobGoals[subEgg[3]] = true; locationGoals[subEgg[1]] = true; } print(""Verifications...."", ""blue""); foreach index in eggData { //print(""Subegg: "" + eggData[index], ""blue""); string[int] subEgg = split_string(eggData[index], "":""); if(count(subEgg) < 4) { continue; } boolean isTruth = true; if(subEgg[4] == ""liar"") { isTruth = false; } if(subEgg[4] != ""liar"") { boolean hasAnyone = false; string oldValue = subEgg[4]; foreach goal in personGoals { matcher goalMatcher = create_matcher(""\\\\b"" + goal + ""\\\\b"",subEgg[4]); if(goalMatcher.find()) { hasAnyone = true; subEgg[4] = goal; } } foreach goal in jobGoals { matcher goalMatcher = create_matcher(""\\\\b"" + goal + ""\\\\b"",subEgg[4]); if(goalMatcher.find()) { hasAnyone = true; subEgg[4] = goal; } } string replaceString = ""liar""; if(hasAnyone) { replaceString = subEgg[4]; } string temp = get_property(""auto_eggDetective""); temp = replace_string(temp, oldValue, replaceString); set_property(""auto_eggDetective"", temp); eggData = split_string(get_property(""auto_eggDetective""), "",""); subEgg[4] = replaceString; } if(subEgg[4] != ""liar"") { print(subEgg[2] + "" is accusing: "" + subEgg[4], ""blue""); //Now we need to determine if they are lying or not. int currentLocation = to_int(subEgg[0]); page = visit_url(""wham.php?visit="" + currentLocation, false); int otherPerson = 1; boolean corrupted = false; string locationName = subEgg[1]; while((otherPerson <= 9) && isTruth) { if(currentLocation == otherPerson) { otherPerson += 1; continue; } string[int] currentEgg; foreach index in eggData { string[int] subEgg = split_string(eggData[index], "":""); if(to_int(subEgg[0]) == otherPerson) { currentEgg = subEgg; } } page = visit_url(""wham.php?ask="" + otherPerson + ""&visit="" + currentLocation, false); matcher killerMatcher = create_matcher(""you (?:ask|say)(?:.*?)

(.*?)(\\\\s*?)"", page); if(killerMatcher.find()) { string killerInfo = killerMatcher.group(1); //We are asking to attach a job to the person. They might not know. //We need to look up the particular person. boolean exact = false; int count = 0; foreach goal in jobGoals { matcher goalMatcher = create_matcher(""\\\\b"" + goal + ""\\\\b"",killerInfo); if(goalMatcher.find()) { if(goal != currentEgg[3]) { print(""Asked about "" + currentEgg[2] + "","" + currentEgg[3] + "" and was told: "" + goal, ""red""); count += 1; } else { exact = true; } } } if(!exact && (count != 0)) { isTruth = false; } exact = false; count = 0; foreach goal in locationGoals { matcher goalMatcher = create_matcher(""\\\\b"" + goal + ""\\\\b"",killerInfo); if(goalMatcher.find()) { if(goal != currentEgg[1]) { print(""Asked about "" + currentEgg[2] + "","" + currentEgg[1] + "" and was told: "" + goal, ""red""); count += 1; } else { exact = true; } } } if(!exact && (count != 0)) { if(killerInfo == locationName) { if(corrupted) { print(""Doubly corrupted possible truth teller. This person is probably correct."", ""blue""); return false; } print(""Corrupted truth teller? Going to retry...."", ""red""); corrupted = true; continue; } isTruth = false; } } //if still isTruth, we can try the relative questions if so desired. //Really, we should check the list of accused and try to uniquify it. otherPerson += 1; corrupted = false; } } if(subEgg[4] == ""liar"") { isTruth = false; } if(isTruth) { print(subEgg[2] + "" is accusing: "" + subEgg[4] + "" and may be telling the truth!"", ""blue""); //Find person they are accusing and do it. string[int] currentEgg; foreach index in eggData { string[int] subsubEgg = split_string(eggData[index], "":""); if((subsubEgg[2] == subEgg[4]) || (subsubEgg[3] == subEgg[4])) { print(""Accusation against: "" + subsubEgg[2], ""blue""); page = visit_url(""wham.php?visit="" + subsubEgg[0], false); eggMatcher = create_matcher(""You have been on this case for (\\\\d+) minute(?:s?)"", page); if(eggMatcher.find()) { print(""On the case for "" + eggMatcher.group(1) + "" minutes..."", ""green""); } page = visit_url(""wham.php?visit="" + subsubEgg[0] + ""&accuse="" + subsubEgg[0], false); matcher pensionMatcher = create_matcher(""been awarded (\\\\d+) cop dollars"", page); if(pensionMatcher.find()) { print(""Received a pension of "" + pensionMatcher.group(1) + "" cop dollars."", ""green""); } set_property(""auto_eggDetective"", """"); return true; } } } } set_property(""auto_eggDetective"", get_property(""auto_eggDetective"") + ""solved""); return false; } return true; } boolean expectGhostReport() { if(total_turns_played() >= get_property(""nextParanormalActivity"").to_int()) { if(total_turns_played() > get_property(""nextParanormalActivity"").to_int()) { string page = visit_url(""charpane.php""); matcher myGhost = create_matcher(""(?:.*?)(.*?)"", page); if(myGhost.find()) { location goal = to_location(myGhost.group(1)); set_property(""ghostLocation"", goal); set_property(""questPAGhost"", ""started""); } } #

Investigate the paranormal activity reported at The Haunted Conservatory.
if(get_property(""questPAGhost"") == ""unstarted"") { return true; } } return false; } boolean haveGhostReport() { if(get_property(""questPAGhost"") == ""unstarted"") { return false; } if((get_property(""questPAGhost"") == ""started"") && (get_property(""ghostLocation"") != """")) { return true; } return false; } boolean LX_ghostBusting() { if(!possessEquipment($item[Protonic Accelerator Pack])) { return false; } if(get_property(""questPAGhost"") == ""unstarted"") { if(!expectGhostReport()) { return false; } if(get_property(""questPAGhost"") == ""unstarted"") { return false; } } location goal = get_property(""ghostLocation"").to_location(); boolean canAttempt = have_equipped($item[Protonic Accelerator Pack]); if(possessEquipment($item[Protonic Accelerator Pack]) && can_equip($item[Protonic Accelerator Pack])) { canAttempt = true; } if((goal != $location[none]) && canAttempt) { if((auto_my_path() == ""Community Service"") && (my_daycount() == 1) && (goal == $location[The Spooky Forest])) { return false; } useCocoon(); print(""Ghost busting time! At: "" + get_property(""ghostLocation""), ""blue""); boolean newbieFail = false; if(goal == $location[The Skeleton Store]) { startMeatsmithSubQuest(); if(internalQuestStatus(""questM23Meatsmith"") == -1) { newbieFail = true; } else if(internalQuestStatus(""questM23Meatsmith"") == 0) { if(item_amount($item[Skeleton Store Office Key]) > 0) { set_property(""choiceAdventure1060"", 4); } else { set_property(""choiceAdventure1060"", 1); } } else { set_property(""choiceAdventure1060"", 2); } } if(item_amount($item[Check to the Meatsmith]) > 0) { string temp = visit_url(""shop.php?whichshop=meatsmith""); temp = visit_url(""choice.php?pwd=&whichchoice=1059&option=2""); return true; } if(goal == $location[Madness Bakery]) { startArmorySubQuest(); if(internalQuestStatus(""questM25Armorer"") == -1) { newbieFail = true; } else if(internalQuestStatus(""questM25Armorer"") <= 1) { set_property(""choiceAdventure1061"", 1); } else { set_property(""choiceAdventure1061"", 5); } } if(item_amount($item[no-handed pie]) > 0) { string temp = visit_url(""shop.php?whichshop=armory""); temp = visit_url(""choice.php?pwd=&whichchoice=1065&option=2""); return true; } if(goal == $location[The Overgrown Lot]) { //Meh. startGalaktikSubQuest(); if(internalQuestStatus(""questM24Doc"") == -1) { newbieFail = true; } else if(get_property(""questM24Doc"") != ""finished"") { set_property(""choiceAdventure1062"", 1); } else { set_property(""choiceAdventure1062"", 4); } } if((item_amount($item[Swindleblossom]) >= 3) && (item_amount($item[Fraudwort]) >= 3) && (item_amount($item[Shysterweed]) >= 3)) { string temp = visit_url(""shop.php?whichshop=doc""); temp = visit_url(""shop.php?whichshop=doc&action=talk""); temp = visit_url(""choice.php?pwd=&whichchoice=1064&option=2""); return true; } if((goal == $location[The Batrat and Ratbat Burrow]) && (internalQuestStatus(""questL04Bat"") < 1)) { return false; } if((goal == $location[Cobb\\'s Knob Laboratory]) && (item_amount($item[Cobb\\'s Knob Lab Key]) == 0)) { return false; } if((goal == $location[Lair of the Ninja Snowmen]) && ((get_property(""auto_trapper"") != ""yeti"") && (get_property(""auto_trapper"") != ""finished""))) { return false; } if((goal == $location[The VERY Unquiet Garves]) && (get_property(""auto_crypt"") != ""finished"")) { return false; } if(goal == $location[The Castle in the Clouds in the Sky (Top Floor)]) { if(get_property(""auto_castleground"") != ""finished"") { return false; } if(L10_topFloor() || L10_holeInTheSkyUnlock()) { return true; } } if(goal == $location[Lair of the Ninja Snowmen]) { if((item_amount($item[Ninja Rope]) == 0) || (item_amount($item[Ninja Carabiner]) == 0) || (item_amount($item[Ninja Crampons]) == 0)) { if(L8_trapperYeti()) { return true; } } } if((goal == $location[The Red Zeppelin]) && (internalQuestStatus(""questL11Ron"") < 3)) { return false; } if((goal == $location[The Hidden Park]) && (get_property(""auto_hiddenunlock"") == ""finished"")) { return false; } item replaceAcc3 = $item[none]; if(goal == $location[Inside The Palindome]) { if(!possessEquipment($item[Talisman O\\' Namsilat])) { return false; } if(equipped_item($slot[acc3]) != $item[Talisman O\\' Namsilat]) { replaceAcc3 = equipped_item($slot[acc3]); autoEquip($slot[acc3], $item[Talisman O\\' Namsilat]); } } if(newbieFail) { print(""Can't bust that ghost, we don't feel good!!"", ""blue""); abort(""Ghost busting failure, this should not happen""); set_property(""questPAGhost"", ""unstarted""); set_property(""ghostLocation"", """"); return false; } if((equipped_item($slot[Back]) != $item[Protonic Accelerator Pack]) && can_equip($item[Protonic Accelerator Pack])) { autoEquip($slot[Back], $item[Protonic Accelerator Pack]); } print(""Time to bust some ghosts!!!"", ""green""); boolean advVal = autoAdv(goal); if(replaceAcc3 != $item[none]) { autoEquip($slot[acc3], replaceAcc3); } if(have_effect($effect[Beaten Up]) == 0) { set_property(""questPAGhost"", ""unstarted""); set_property(""ghostLocation"", """"); } return advVal; } return false; } boolean timeSpinnerGet(string goal) { goal = to_lower_case(goal); if(!($strings[booze, drink, food, memory, history, ears, mall, none] contains goal)) { return false; } if($strings[booze, drink, food, memory, history, ears, mall] contains goal) { if(get_property(""_timeSpinnerReplicatorUsed"").to_boolean()) { return false; } } if((goal == ""booze"") && (get_property(""timeSpinnerMedals"").to_int() < 5)) { return false; } if((goal == ""drink"") && (get_property(""timeSpinnerMedals"").to_int() < 5)) { return false; } if((goal == ""food"") && (get_property(""timeSpinnerMedals"").to_int() < 15)) { return false; } if((goal == ""history"") && (get_property(""timeSpinnerMedals"").to_int() < 10)) { return false; } if((goal == ""memory"") && (get_property(""timeSpinnerMedals"").to_int() < 20)) { return false; } if(is_unrestricted($item[Time-Spinner]) && (item_amount($item[Time-Spinner]) > 0) && (get_property(""_timeSpinnerMinutesUsed"").to_int() <= 8)) { if(svn_info(""Ezandora-Far-Future-branches-Release"").last_changed_rev > 0) { //Required by dependencies cli_execute(""FarFuture "" + goal); return true; } return false; } return false; } boolean timeSpinnerConsume(item goal) { if(is_unrestricted($item[Time-Spinner]) && (item_amount($item[Time-Spinner]) > 0) && (get_property(""_timeSpinnerMinutesUsed"").to_int() <= 7)) { string temp = visit_url(""inv_use.php?pwd=&which=3&whichitem=9104""); if(get_property(""_timeSpinnerMinutesUsed"").to_int() <= 7) { temp = visit_url(""choice.php?pwd=&whichchoice=1195&option=2""); temp = visit_url(""choice.php?pwd=&whichchoice=1197&option=1&foodid="" + to_int(goal)); } } return false; } boolean timeSpinnerAdventure() { return timeSpinnerAdventure(""""); } boolean timeSpinnerAdventure(string option) { if(is_unrestricted($item[Time-Spinner]) && (item_amount($item[Time-Spinner]) > 0) && (get_property(""_timeSpinnerMinutesUsed"").to_int() <= 9)) { string temp = visit_url(""inv_use.php?pwd=&which=3&whichitem=9104""); if(get_property(""_timeSpinnerMinutesUsed"").to_int() <= 9) { string[int] pages; pages[0] = ""inv_use.php?pwd=&which=3&whichitem=9104""; pages[1] = ""choice.php?pwd=&whichchoice=1195&option=3""; if(autoAdvBypass(0, pages, $location[Noob Cave], option)) {} return true; } } return false; } boolean timeSpinnerCombat(monster goal) { return timeSpinnerCombat(goal, """"); } boolean timeSpinnerCombat(monster goal, string option) { if(is_unrestricted($item[Time-Spinner]) && (item_amount($item[Time-Spinner]) > 0) && (get_property(""_timeSpinnerMinutesUsed"").to_int() <= 7)) { string temp = visit_url(""inv_use.php?pwd=&which=3&whichitem=9104""); if(get_property(""_timeSpinnerMinutesUsed"").to_int() <= 7) { string[int] pages; pages[0] = ""inv_use.php?pwd=&which=3&whichitem=9104""; pages[1] = ""choice.php?pwd=&whichchoice=1195&option=1""; pages[2] = ""choice.php?pwd=&whichchoice=1196&option=1&monid="" + goal.id; if(autoAdvBypass(0, pages, $location[Noob Cave], option)) { handleTracker(goal, $item[Time-Spinner], ""auto_copies""); } else { if(get_property(""lastEncounter"") == ""Travel to a Recent Fight"") { string temp = visit_url(""choice.php?pwd&whichchoice=1196&option=2""); } else { abort(""Time-Spinner combat failed and we were unable to leave the Time-Spinner""); } return false; } return true; } } return false; } boolean rethinkingCandyList() { boolean[effect] synthesis = $effects[Synthesis: Hot, Synthesis: Cold, Synthesis: Pungent, Synthesis: Scary, Synthesis: Greasy, Synthesis: Strong, Synthesis: Smart, Synthesis: Cool, Synthesis: Hardy, Synthesis: Energy, Synthesis: Greed, Synthesis: Collection, Synthesis: Movement, Synthesis: Learning, Synthesis: Style]; foreach eff in synthesis { print(""Trying effect: "" + eff + "": "" + string_modifier(eff, ""Modifiers"") , ""orange""); rethinkingCandy(eff, true); } return true; } boolean rethinkingCandy(effect acquire) { return rethinkingCandy(acquire, false); } boolean rethinkingCandy(effect acquire, boolean simulate) { if(!have_skill($skill[Sweet Synthesis]) && !simulate) { return false; } if((spleen_left() == 0) && !simulate) { return false; } boolean[effect] synthesisList = $effects[Synthesis: Hot, Synthesis: Cold, Synthesis: Pungent, Synthesis: Scary, Synthesis: Greasy, Synthesis: Strong, Synthesis: Smart, Synthesis: Cool, Synthesis: Hardy, Synthesis: Energy, Synthesis: Greed, Synthesis: Collection, Synthesis: Movement, Synthesis: Learning, Synthesis: Style]; effect[int] synthesis = List(synthesisList); if(!(synthesisList contains acquire)) { return false; } int maxprice = 2500; if(get_property(""auto_maxCandyPrice"").to_int() != 0) { maxprice = get_property(""auto_maxCandyPrice"").to_int(); } item[int] simpleList; item[int] complexList; foreach it in $items[] { if(it.candy && (item_amount(it) > 0) && (auto_mall_price(it) <= maxprice) && it.tradeable) { if(it.candy_type == ""simple"") { simpleList[count(simpleList)] = it; } else if(it.candy_type == ""complex"") { complexList[count(complexList)] = it; } } } sort simpleList by auto_mall_price(value); sort complexList by auto_mall_price(value); item[int] simple = List(simpleList); item[int] complex = List(complexList); # foreach idx, it in simple # { # print(it + "": "" + item_amount(it) + "" ("" + to_int(it) + ""): "" + it.candy_type + "" Cost: "" + auto_mall_price(it), ""blue""); # } # # foreach idx, it in complex # { # print(it + "": "" + item_amount(it) + "" ("" + to_int(it) + ""): "" + it.candy_type + "" Cost: "" + auto_mall_price(it), ""blue""); # } int bestCost = 2 * maxprice; item bestFirst = $item[none]; item bestSecond = $item[none]; if($effects[Synthesis: Hot, Synthesis: Cold, Synthesis: Pungent, Synthesis: Scary, Synthesis: Greasy] contains acquire) { int goal = ListFind(synthesis, acquire) % 5; for(int i=0; i 1) { startNextIndex = i; } for(int j=startNextIndex; j 1) { startNextIndex = i; } for(int j=startNextIndex; j> that generates these DTOs. [NOTE] ==== Developers wishing to contribute to the component are instructed to look at the https://github.com/apache/camel/tree/main/components/camel-salesforce/camel-salesforce-component/README.md[README.md] file on instructions on how to get started and setup your environment for running integration tests. ==== == Getting Started Follow these steps to get started with the Salesforce component. . *Create a salesforce org*. If you don't already have access to a salesforce org, you can create a https://developer.salesforce.com/signup[free developer org]. . *Create a Connected App*. In salesforce, go to Setup > Apps > App Manager, then click on *New Connected App*. Make sure to check *Enable OAuth Settings* and include relevant OAuth Scopes, including the scope called *Perform requests at any time*. Click *Save*. . *Get the Consumer Key and Consumer Secret*. You'll need these to configure salesforce authentication. View your new connected app, then copy the key and secret and save in a safe place. . *Add Maven depdendency*. + [source,xml] ---- org.apache.camel camel-salesforce ---- Spring Boot users should use the starter instead. + [source,xml] ---- org.apache.camel.springboot camel-salesforce-starter ---- . *Generate DTOs*. Optionally, generate Java DTOs to represent your salesforce objects. This step isn't a hard requirement per se, but most use cases will benefit from the type safety and auto-completion. Use the <> to generate DTOs for the salesforce objects you'll be working with. . *Configure authentication*. Using the OAuth key and secret you generated previously, configure salesforce <>. . *Create routes*. Starting creating routes that interact with salesforce! // component-configure options: START // component-configure options: END // component options: START include::partial$component-configure-options.adoc[] include::partial$component-endpoint-options.adoc[] // component options: END // endpoint options: START // endpoint options: END == Authenticating to Salesforce [[AuthenticatingToSalesforce]] The component supports three OAuth authentication flows: * https://help.salesforce.com/articleView?id=remoteaccess_oauth_username_password_flow.htm[OAuth 2.0 Username-Password Flow] * https://help.salesforce.com/articleView?id=remoteaccess_oauth_refresh_token_flow.htm[OAuth 2.0 Refresh Token Flow] * https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm[OAuth 2.0 JWT Bearer Token Flow] For each of the flows, different sets of properties needs to be set: .Properties to set for each authentication flow |=== | Property | Where to find it on Salesforce | Flow | clientId | Connected App, Consumer Key | All flows | clientSecret | Connected App, Consumer Secret | Username-Password, Refresh Token | userName | Salesforce user username | Username-Password, JWT Bearer Token | password | Salesforce user password | Username-Password | refreshToken | From OAuth flow callback | Refresh Token | keystore | Connected App, Digital Certificate | JWT Bearer Token |=== The component auto determines what flow you're trying to configure. In order to be explicit, set the `authenticationType` property. [NOTE] ==== Using Username-Password Flow in production is not encouraged. ==== [NOTE] ==== The certificate used in JWT Bearer Token Flow can be a self-signed certificate. The KeyStore holding the certificate and the private key must contain only single certificate-private key entry. ==== == General Usage === URI format When used as a consumer, receiving streaming events, the URI scheme is: ---- salesforce:topic?options ---- When used as a producer, invoking the Salesforce REST APIs, the URI scheme is: ---- salesforce:operationName?options ---- As a general example on using the operations in this salesforce component, the following producer endpoint uses the upsertSObject API, with the sObjectIdName parameter specifying 'Name' as the external id field. The request message body should be an SObject DTO generated using the maven plugin. [source,java] ---- ...to(""salesforce:upsertSObject?sObjectIdName=Name"")... ---- === Passing in Salesforce headers and fetching Salesforce response headers There is support to pass https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers.htm[Salesforce headers] via inbound message headers, header names that start with `Sforce` or `x-sfdc` on the Camel message will be passed on in the request, and response headers that start with `Sforce` will be present in the outbound message headers. For example to fetch API limits you can specify: [source,java] ---- // in your Camel route set the header before Salesforce endpoint //... .setHeader(""Sforce-Limit-Info"", constant(""api-usage"")) .to(""salesforce:getGlobalObjects"") .to(myProcessor); // myProcessor will receive `Sforce-Limit-Info` header on the outbound // message class MyProcessor implements Processor { public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); String apiLimits = in.getHeader(""Sforce-Limit-Info"", String.class); } } ---- In addition, HTTP response status code and text are available as headers `Exchange.HTTP_RESPONSE_CODE` and `Exchange.HTTP_RESPONSE_TEXT`. === Sending null values to salesforce By default, SObject fields with null values are not sent to salesforce. In order to send null values to salesforce, use the `fieldsToNull` property, as follows: [source,java] ---- accountSObject.getFieldsToNull().add(""Site""); ---- == Supported Salesforce APIs Camel supports the following Salesforce APIs: * <> * <> * <> * <> * <> * <> [[RESTAPI]] === REST API The following operations are supported: * <> - Gets supported Salesforce REST API versions. * <> - Gets available Salesforce REST Resource endpoints. * <> - Lists information about limits in your org. * <> - Gets the most recently accessed items that were viewed or referenced by the current user. * <> - Gets metadata for all available SObject types. * <> - Gets basic metadata for a specific SObject type. * <> - Gets comprehensive metadata for a specific SObject type. * <> - Gets an SObject. * <> - Gets an SObject using an External Id (user defined) field. * <> - Retrieves the specified blob field from an individual record. * <> - Creates an SObject. * <> - Updates an SObject. * <> - Deletes an SObject. * <> - Inserts or updates an SObject using an External Id. * <> - Deletes an SObject using an External Id. * <> - Runs a Salesforce SOQL query. * <> - Retrieves more results (in case of large number of results) using result link returned from the 'query' API. * <> - Runs a SOQL query. Unlike the query operation, queryAll returns records that are deleted because of a merge or delete. queryAll also returns information about archived task and event records. * <> - Runs a Salesforce SOSL query. * <> - Executes a user defined APEX REST API call. * <> - Submits a record or records (batch) for approval process. * <> - Fetches a list of all approval processes. * <> - Executes up to 25 REST API requests in a single call. You can use the output of one request as the input to a subsequent request. * <> - Creates up to 200 records with parent-child relationships (up to 5 levels) in one go. * <> - Executes up to 25 sub-requests in a single request. * <> - Retrieves one or more records of the same object type. * <> - Creates up to 200 records. * <> - Update up to 200 records. * <> - Creates or updates up to 200 records based on an External Id field. * <> - Deletes up to 200 records. Unless otherwise specified, DTO types for the following options are from `org.apache.camel.component.salesforce.api.dto` or one if its sub-packages. [[getVersions]] ==== Versions `getVersions` Lists summary information about each Salesforce version currently available, including the version, label, and a link to each version's root. *Output* Type: `List` [[getResources]] ==== Resources by Version `getResources` Lists available resources for the current API version, including resource name and URI. *Output* Type: `Map` [[limits]] ==== Limits `limits` Lists information about limits in your org. For each limit, this resource returns the maximum allocation and the remaining allocation based on usage. *Output* Type: `Limits` *Additional Usage Information* With `salesforce:limits` operation you can fetch of API limits from Salesforce and then act upon that data received. The result of `salesforce:limits` operation is mapped to `org.apache.camel.component.salesforce.api.dto.Limits` class and can be used in a custom processors or expressions. For instance, consider that you need to limit the API usage of Salesforce so that 10% of daily API requests is left for other routes. The body of output message contains an instance of `org.apache.camel.component.salesforce.api.dto.Limits` object that can be used in conjunction with Content Based Router and Content Based Router and xref:languages:spel-language.adoc[Spring Expression Language (SpEL)] to choose when to perform queries. Notice how multiplying `1.0` with the integer value held in `body.dailyApiRequests.remaining` makes the expression evaluate as with floating point arithmetic, without it - it would end up making integral division which would result with either `0` (some API limits consumed) or `1` (no API limits consumed). [source,java] ---- from(""direct:querySalesforce"") .to(""salesforce:limits"") .choice() .when(spel(""#{1.0 * body.dailyApiRequests.remaining / body.dailyApiRequests.max < 0.1}"")) .to(""salesforce:query?..."") .otherwise() .setBody(constant(""Used up Salesforce API limits, leaving 10% for critical routes"")) .endChoice() ---- [[recent]] ==== Recently Viewed Items `recent` Gets the most recently accessed items that were viewed or referenced by the current user. Salesforce stores information about record views in the interface and uses it to generate a list of recently viewed and referenced records, such as in the sidebar and for the auto-complete options in search. |=== | Parameter | Type | Description | Default | Required | `limit` | `int` | An optional limit that specifies the maximum number of records to be returned. If this parameter is not specified, the default maximum number of records returned is the maximum number of entries in RecentlyViewed, which is 200 records per object. | | |=== *Output* Type: `List` *Additional Usage Information* To fetch the recent items use `salesforce:recent` operation. This operation returns an `java.util.List` of `org.apache.camel.component.salesforce.api.dto.RecentItem` objects (`List`) that in turn contain the `Id`, `Name` and `Attributes` (with `type` and `url` properties). You can limit the number of returned items by specifying `limit` parameter set to maximum number of records to return. For example: [source,java] ---- from(""direct:fetchRecentItems"") to(""salesforce:recent"") .split().body() .log(""${body.name} at ${body.attributes.url}""); ---- [[getGlobalObjects]] ==== Describe Global `getGlobalObjects` Lists the available objects and their metadata for your organization’s data. In addition, it provides the organization encoding, as well as the maximum batch size permitted in queries. *Output* Type: `GlobalObjects` [[getBasicInfo]] ==== sObject Basic Information `getBasicInfo` Describes the individual metadata for the specified object. |=== | Parameter | Type | Description | Default | Required | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Alternatively, can be supplied in Body. | | x |=== *Output* Type: `SObjectBasicInfo` [[getDescription]] ==== sObject Describe `getDescription` Completely describes the individual metadata at all levels for the specified object. For example, this can be used to retrieve the fields, URLs, and child relationships for the Account object. |=== | Parameter | Type | Description | Default | Required | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Alternatively, can be supplied in Body. | | x |=== *Output* Type: `SObjectDescription` [[getSObject]] ==== Retrieve SObject `getSObject` Accesses record based on the specified object ID. This operation requires the `packages` option to be set. |=== | Parameter | Type | Description | Default | Required | `sObjectName` | `String` | Name of SObject, e.g. `Account` | | x | `sObjectId` | `String` | Id of record to retrieve. | | x | `sObjectFields` | `String` | Comma-separated list of fields to retrieve|| | Body | `AbstractSObjectBase` | Instance of SObject that is used to query salesforce. If supplied, overrides `sObjectName` and `sObjectId` parameters. | | |=== *Output* Type: Subclass of `AbstractSObjectBase` [[getSObjectWithId]] ==== Retrieve SObject by External Id `getSObjectWithId` Accesses record based on an External ID value. This operation requires the `packages` option to be set. |=== | Parameter | Type | Description | Default | Required | `sObjectIdName` | `String` | Name of External ID field | | x | `sObjectIdValue` | `String` | External ID value | | x | `sObjectName` | `String` | Name of SObject, e.g. `Account` | | x | Body | `AbstractSObjectBase` | Instance of SObject that is used to query salesforce. If supplied, overrides `sObjectName` and `sObjectIdValue` parameters. | | |=== *Output* Type: Subclass of `AbstractSObjectBase` [[getBlobField]] ==== sObject Blob Retrieve `getBlobField` Retrieves the specified blob field from an individual record. |=== | Parameter | Type | Description | Default | Required | `sObjectBlobFieldName` | `String` | SOSL query | |x | `sObjectName` | `String` | Name of SObject, e.g. Account | | Required if SObject not supplied in body | `sObjectId` | `String` | Id of SObject | | Required if SObject not supplied in body | Body | `AbstractSObjectBase` | SObject to determine type and Id from. If not supplied, `sObjectId` and `sObjectName` parameters will be used. | | Required if `sObjectId` and `sObjectName` are not supplied |=== *Output* Type: `InputStream` [[createSObject]] ==== Create SObject `createSObject` Creates a record in salesforce. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` or `String` | Instance of SObject to create. | | x | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is a `String` |=== *Output* Type: `CreateSObjectResult` [[updateSObject]] ==== Update SObject `updateSObject` Updates a record in salesforce. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` or `String` | Instance of SObject to update. | | x | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is a `String` | `sObjectId` | `String` | Id of record to update. Only used if Camel cannot determine from Body. | | If Body is a `String` |=== [[upsertSObject]] ==== Upsert SObject `upsertSObject` Upserts a record by External ID. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` or `String` | SObject to update. | | x | `sObjectIdName` | `String` | External ID field name. ||x | `sObjectIdValue` | `String` | External ID value || If Body is a `String` | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is a `String` |=== *Output* Type: `UpsertSObjectResult` [[deleteSObject]] ==== Delete SObject `deleteSObject` Deletes a record in salesforce. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` | Instance of SObject to delete. | | | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is not an `AbstractSObjectBase` instance | `sObjectId` | `String` | Id of record to delete. | | If Body is not an `AbstractSObjectBase` instance |=== [[deleteSObjectWithId]] ==== Delete SObject by External Id `deleteSObjectWithId` Deletes a record in salesforce by External ID. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` | Instance of SObject to delete. | | | `sObjectIdName` | `String` | Name of External ID field | | If Body is not an `AbstractSObjectBase` instance | `sObjectIdValue` | `String` | External ID value | | If Body is not an `AbstractSObjectBase` instance | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is not an `AbstractSObjectBase` instance |=== [[query]] ==== Query `query` Runs a Salesforce SOQL query |=== | Parameter | Type | Description | Default | Required | Body or `sObjectQuery` | `String` | SOQL query | | x | streamQueryResult | `Boolean` | If true, returns a streaming `Iterator` and transparently retrieves all pages as needed. The `sObjectClass` option must reference an `AbstractQueryRecordsBase` subclass. | false | | `sObjectClass` | `String` | Fully qualified name of class to deserialize response to. Usually a subclass of `AbstractQueryRecordsBase`, e.g. `org.my.dto.QueryRecordsAccount`| |x |=== *Output* Type: Instance of class supplied in `sObjectClass`, or `Iterator` if `streamQueryResult` is true. [[queryMore]] ==== Query More `queryMore` Retrieves more results (in case of large number of results) using result link returned from the `query` and `queryAll` operations. |=== | Parameter | Type | Description | Default | Required | Body or `sObjectQuery` | `String` | `nextRecords` value. Can be found in a prior query result in the `AbstractQueryRecordsBase.nextRecordsUrl` property | | X | `sObjectClass` | `String` | Fully qualified name of class to deserialize response to. Usually a subclass of `AbstractQueryRecordsBase`, e.g. `org.my.dto.QueryRecordsAccount`| |x |=== *Output* Type: Instance of class supplied in `sObjectClass` [[queryAll]] ==== Query All `queryAll` Executes the specified SOQL query. Unlike the `query` operation , `queryAll` returns records that are deleted because of a merge or delete. It also returns information about archived task and event records. |=== | Parameter | Type | Description | Default | Required | Body or `sObjectQuery` | `String` | SOQL query | | x | streamQueryResult | `Boolean` | If true, returns a streaming `Iterable` and transparently retrieves all pages as needed. The `sObjectClass` option must reference an `AbstractQueryRecordsBase` subclass. | false | | `sObjectClass` | `String` | Fully qualified name of class to deserialize response to. Usually a subclass of `AbstractQueryRecordsBase`, e.g. `org.my.dto.QueryRecordsAccount`| |x |=== *Output* Type: Instance of class supplied in `sObjectClass`, or `Iterator` if `streamQueryResult` is true. [[sosl_search]] ==== Search `search` Runs a Salesforce SOSL search |=== | Parameter | Type | Description | Default | Required | Body or `sObjectSearch` | `String` | Name of field to retrieve | |x |=== *Output* Type: `SearchResult2` [[approval]] ==== Submit Approval `approval` Submit a record or records (batch) for approval process. |=== | Parameter | Type | Description | Default | Required | Body | `ApprovalRequest` or `List` | `ApprovalRequest`(s) to process | | | `Approval.` | Prefixed headers or endpoint options in lieu of passing an `ApprovalRequest` in the body. | | | |=== *Output* Type: `ApprovalResult` *Additional usage information* All the properties are named exactly the same as in the Salesforce REST API prefixed with `approval.`. You can set approval properties by setting `approval.PropertyName` of the Endpoint these will be used as template -- meaning that any property not present in either body or header will be taken from the Endpoint configuration. Or you can set the approval template on the Endpoint by assigning `approval` property to a reference onto a bean in the Registry. You can also provide header values using the same `approval.PropertyName` in the incoming message headers. And finally body can contain one `AprovalRequest` or an `Iterable` of `ApprovalRequest` objects to process as a batch. The important thing to remember is the priority of the values specified in these three mechanisms: . value in body takes precedence before any other . value in message header takes precedence before template value . value in template is set if no other value in header or body was given For example to send one record for approval using values in headers use: Given a route: [source,java] ---- from(""direct:example1"")// .setHeader(""approval.ContextId"", simple(""${body['contextId']}"")) .setHeader(""approval.NextApproverIds"", simple(""${body['nextApproverIds']}"")) .to(""salesforce:approval?""// + ""approval.actionType=Submit""// + ""&approval.comments=this is a test""// + ""&approval.processDefinitionNameOrId=Test_Account_Process""// + ""&approval.skipEntryCriteria=true""); ---- You could send a record for approval using: [source,java] ---- final Map body = new HashMap<>(); body.put(""contextId"", accountIds.iterator().next()); body.put(""nextApproverIds"", userId); final ApprovalResult result = template.requestBody(""direct:example1"", body, ApprovalResult.class); ---- [[approvals]] ==== Get Approvals `approvals` Returns a list of all approval processes. *Output* Type: `Approvals` [[composite]] ==== Composite `composite` Executes up to 25 REST API requests in a single call. You can use the output of one request as the input to a subsequent request. The response bodies and HTTP statuses of the requests are returned in a single response body. The entire series of requests counts as a single call toward your API limits. Use Salesforce Composite API to submit multiple chained requests. Individual requests and responses are linked with the provided _reference_. |=== | Parameter | Type | Description | Default | Required | Body | `SObjectComposite` | Contains REST API sub-requests to be executed. | | x | `rawPayload` | `Boolean` | Any (un)marshaling of requests and responses are assumed to be handled by the route | false | x | `compositeMethod` | `String` | HTTP method to use for rawPayload requests. | `POST` | |=== *Output* Type: `SObjectCompositeResponse` [NOTE] ==== Composite API supports only JSON payloads. ==== [NOTE] ==== As with the batch API, the results can vary from API to API so the body of each `SObjectCompositeResult` instance is given as a `java.lang.Object`. In most cases the result will be a `java.util.Map` with string keys and values or other `java.util.Map` as value. Requests are made in JSON format hold some type information (i.e. it is known what values are strings and what values are numbers). ==== Lets look at an example: [source,java] ---- SObjectComposite composite = new SObjectComposite(""38.0"", true); // first insert operation via an external id final Account updateAccount = new TestAccount(); updateAccount.setName(""Salesforce""); updateAccount.setBillingStreet(""Landmark @ 1 Market Street""); updateAccount.setBillingCity(""San Francisco""); updateAccount.setBillingState(""California""); updateAccount.setIndustry(Account_IndustryEnum.TECHNOLOGY); composite.addUpdate(""Account"", ""001xx000003DIpcAAG"", updateAccount, ""UpdatedAccount""); final Contact newContact = new TestContact(); newContact.setLastName(""John Doe""); newContact.setPhone(""1234567890""); composite.addCreate(newContact, ""NewContact""); final AccountContactJunction__c junction = new AccountContactJunction__c(); junction.setAccount__c(""001xx000003DIpcAAG""); junction.setContactId__c(""@{NewContact.id}""); composite.addCreate(junction, ""JunctionRecord""); final SObjectCompositeResponse response = template.requestBody(""salesforce:composite"", composite, SObjectCompositeResponse.class); final List results = response.getCompositeResponse(); final SObjectCompositeResult accountUpdateResult = results.stream().filter(r -> ""UpdatedAccount"".equals(r.getReferenceId())).findFirst().get() final int statusCode = accountUpdateResult.getHttpStatusCode(); // should be 200 final Map accountUpdateBody = accountUpdateResult.getBody(); final SObjectCompositeResult contactCreationResult = results.stream().filter(r -> ""JunctionRecord"".equals(r.getReferenceId())).findFirst().get() ---- *Using the `rawPayload` option* It's possible to directly call Salesforce composite by preparing the Salesforce JSON request in the route thanks to the `rawPayload` option. For instance, you can have the following route: ---- from(""timer:fire?period=2000"").setBody(constant(""{\\n"" + "" \\""allOrNone\\"" : true,\\n"" + "" \\""records\\"" : [ { \\n"" + "" \\""attributes\\"" : {\\""type\\"" : \\""FOO\\""},\\n"" + "" \\""Name\\"" : \\""123456789\\"",\\n"" + "" \\""FOO\\"" : \\""XXXX\\"",\\n"" + "" \\""ACCOUNT\\"" : 2100.0\\n"" + "" \\""ExternalID\\"" : \\""EXTERNAL\\""\\n"" "" }]\\n"" + ""}"") .to(""salesforce:composite?rawPayload=true"") .log(""${body}""); ---- The route directly creates the body as JSON and directly submit to salesforce endpoint using `rawPayload=true` option. With this approach, you have the complete control on the Salesforce request. `POST` is the default HTTP method used to send raw Composite requests to salesforce. Use the `compositeMethod` option to override to the other supported value, `GET`, which returns a list of other available composite resources. [[composite-tree]] ==== Composite Tree `composite-tree` Create up to 200 records with parent-child relationships (up to 5 levels) in one go. |=== | Parameter | Type | Description | Default | Required | Body | `SObjectTree` | Contains REST API sub-requests to be executed. | | x |=== *Output* Type: `SObjectTree` To create up to 200 records including parent-child relationships use `salesforce:composite-tree` operation. This requires an instance of `org.apache.camel.component.salesforce.api.dto.composite.SObjectTree` in the input message and returns the same tree of objects in the output message. The `org.apache.camel.component.salesforce.api.dto.AbstractSObjectBase` instances within the tree get updated with the identifier values (`Id` property) or their corresponding `org.apache.camel.component.salesforce.api.dto.composite.SObjectNode` is populated with `errors` on failure. Note that for some records operation can succeed and for some it can fail -- so you need to manually check for errors. Easiest way to use this functionality is to use the DTOs generated by the `camel-salesforce-maven-plugin`, but you also have the option of customizing the references that identify the each object in the tree, for instance primary keys from your database. Lets look at an example: [source,java] ---- Account account = ... Contact president = ... Contact marketing = ... Account anotherAccount = ... Contact sales = ... Asset someAsset = ... // build the tree SObjectTree request = new SObjectTree(); request.addObject(account).addChildren(president, marketing); request.addObject(anotherAccount).addChild(sales).addChild(someAsset); final SObjectTree response = template.requestBody(""salesforce:composite-tree"", tree, SObjectTree.class); final Map> result = response.allNodes() .collect(Collectors.groupingBy(SObjectNode::hasErrors)); final List withErrors = result.get(true); final List succeeded = result.get(false); final String firstId = succeeded.get(0).getId(); ---- [[composite-batch]] ==== Composite Batch `composite-batch` Submit a composition of requests in batch. Executes up to 25 sub-requests in a single request. |=== | Parameter | Type | Description | Default | Required | Body | `SObjectBatch` | Contains sub-requests to be executed. | | x |=== *Output* Type: `SObjectBatchResponse` The Composite API batch operation allows you to accumulate multiple requests in a batch and then submit them in one go, saving the round trip cost of multiple individual requests. Each response is then received in a list of responses with the order preserved, so that the n-th requests response is in the n-th place of the response. [NOTE] ==== The results can vary from API to API so the result of each sub-request (`SObjectBatchResult.result`) is given as a `java.lang.Object`. In most cases the result will be a `java.util.Map` with string keys and values or other `java.util.Map` as value. Requests are made in JSON format and hold some type information (i.e. it is known what values are strings and what values are numbers). ==== Lets look at an example: [source,java] ---- final String acountId = ... final SObjectBatch batch = new SObjectBatch(""53.0""); final Account updates = new Account(); updates.setName(""NewName""); batch.addUpdate(""Account"", accountId, updates); final Account newAccount = new Account(); newAccount.setName(""Account created from Composite batch API""); batch.addCreate(newAccount); batch.addGet(""Account"", accountId, ""Name"", ""BillingPostalCode""); batch.addDelete(""Account"", accountId); final SObjectBatchResponse response = template.requestBody(""salesforce:composite-batch"", batch, SObjectBatchResponse.class); boolean hasErrors = response.hasErrors(); // if any of the requests has resulted in either 4xx or 5xx HTTP status final List results = response.getResults(); // results of three operations sent in batch final SObjectBatchResult updateResult = results.get(0); // update result final int updateStatus = updateResult.getStatusCode(); // probably 204 final Object updateResultData = updateResult.getResult(); // probably null final SObjectBatchResult createResult = results.get(1); // create result @SuppressWarnings(""unchecked"") final Map createData = (Map) createResult.getResult(); final String newAccountId = createData.get(""id""); // id of the new account, this is for JSON, for XML it would be createData.get(""Result"").get(""id"") final SObjectBatchResult retrieveResult = results.get(2); // retrieve result @SuppressWarnings(""unchecked"") final Map retrieveData = (Map) retrieveResult.getResult(); final String accountName = retrieveData.get(""Name""); // Name of the retrieved account, this is for JSON, for XML it would be createData.get(""Account"").get(""Name"") final String accountBillingPostalCode = retrieveData.get(""BillingPostalCode""); // Name of the retrieved account, this is for JSON, for XML it would be createData.get(""Account"").get(""BillingPostalCode"") final SObjectBatchResult deleteResult = results.get(3); // delete result final int updateStatus = deleteResult.getStatusCode(); // probably 204 final Object updateResultData = deleteResult.getResult(); // probably null ---- [[compositeRetrieveSObjectCollections]] ==== Retrieve Multiple Records with Fewer Round-Trips `compositeRetrieveSObjectCollections` Retrieve one or more records of the same object type. |=== | Parameter | Type | Description | Default | Required | ids | List of String or comma-separated string | A list of one or more IDs of the objects to return. All IDs must belong to the same object type. | | x | fields | List of String or comma-separated string | A list of fields to include in the response. The field names you specify must be valid, and you must have read-level permissions to each field. | | x | sObjectName | String | Type of SObject, e.g. `Account` | | x | sObjectClass | String | Fully-qualified class name of DTO class to use for deserializing the response. | | Required if `sObjectName` parameter does not resolve to a class that exists in the package specified by the `package` option. |=== *Output* Type: `List` of class determined by `sObjectName` or `sObjectClass` header [[compositeCreateSObjectCollections]] ==== Create SObject Collections `compositeCreateSObjectCollections` Add up to 200 records. Mixed SObject types is supported. |=== | Parameter | Type | Description| Default| Required | Body | List of `SObject` | A list of SObjects to create | | x | `allOrNone` | boolean | Indicates whether to roll back the entire request when the creation of any object fails (true) or to continue with the independent creation of other objects in the request. | false | |=== *Output* Type: `List` [[compositeUpdateSObjectCollections]] ==== Update SObject Collections `compositeUpdateSObjectCollections` Update up to 200 records. Mixed SObject types is supported. |=== | Parameter | Type | Description | Default | Required | Body | List of `SObject` | A list of SObjects to update | | x | `allOrNone` | `boolean` | Indicates whether to roll back the entire request when the update of any object fails (true) or to continue with the independent update of other objects in the request. | false | |=== *Output* Type: `List` [[compositeUpsertSObjectCollections]] ==== Upsert SObject Collections `compositeUpsertSObjectCollections` Create or update (upsert) up to 200 records based on an external ID field. Mixed SObject types is not supported. |=== | Parameter | Type | Description | Default | Required | Body | List of `SObject` | A list of SObjects to upsert | | x | `allOrNone` | `boolean` | Indicates whether to roll back the entire request when the upsert of any object fails (true) or to continue with the independent upsert of other objects in the request. | false | | `sObjectName` | `String` | Type of SObject, e.g. `Account` | | x | `sObjectIdName` | `String` | Name of External ID field | | x |=== *Output* Type: `List` [[compositeDeleteSObjectCollections]] ==== Delete SObject Collections `compositeDeleteSObjectCollections` Delete up to 200 records. Mixed SObject types is supported. |=== | Parameter | Type | Description | Default | Required | `sObjectIds` or request body | List of String or comma-separated string | A list of up to 200 IDs of objects to be deleted. | | x | `allOrNone` | boolean | Indicates whether to roll back the entire request when the deletion of any object fails (true) or to continue with the independent deletion of other objects in the request. | false | |=== *Output* Type: `List` [[ApexRESTAPI]] === Apex REST API [[apexCall]] ==== Invoke an Apex REST Web Service method `apexCall` You can https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_rest_intro.htm[expose your Apex class and methods] so that external applications can access your code and your application through the REST architecture. The URI format for invoking Apex REST is: ---- salesforce:apexCall[/yourApexRestUrl][?options] ---- You can supply the apexUrl either in the endpoint (see above), or as the `apexUrl` option as listed in the table below. In either case the Apex URL can contain placeholders in the format of `\\{headerName}`. E.g., for the Apex URL `MyApexClass/\\{id}`, the value of the header named `id` will be used to replace the placeholder. |=== | Parameter | Type | Description| Default| Required | Body | `Map` if `GET`, otherwise `String` or `InputStream`| In the case of a `GET`, the body (`Map` instance) is transformed into query parameters. For other HTTP methods, the body is used for the HTTP body. | | | `apexUrl` | `String` | The portion of the endpoint URL after `https://instance.salesforce.com/services/apexrest/`, e.g., 'MyApexClass/' | | Yes, unless supplied in endpoint | `apexMethod` | `String` | The HTTP method (e.g. `GET`, `POST`) to use. | `GET` | | `rawPayload` | `Boolean` | If true, Camel will not serialize the request or response bodies. | false | | Header: `apexQueryParam.[paramName]` | Object | Headers that override apex parameters passed in the endpoint. | | | `sObjectName` | `String` | Name of sObject (e.g. `Merchandise__c`) used to deserialize the response | | If `rawPayload` is false and `sObjectClass` not supplied | `sObjectClass` | `String` | Fully qualified class name used to deserialize the response | | If `rawPayload` is false and `sObjectName` not supplied |=== *Output* Type: Instance of class supplied in `sObjectClass` input header. [[Bulk2API]] === Bulk 2.0 API The Bulk 2.0 API has a simplified model over the original Bulk API. Use it to quickly load a large amount of data into salesforce, or query a large amount of data out of salesforce. Data must be provided in CSV format, usually via an `InputStream` instance. PK chunking is performed automatically. The minimum API version for Bulk 2.0 is v41.0. The minimum API version for Bulk Queries is v47.0. DTO classes mentioned below are from the `org.apache.camel.component.salesforce.api.dto.bulkv2` package. The following operations are supported: * <> - Creates a bulk ingest job. * <> - Adds a batch of data to an ingest job. * <> - Closes an ingest job. * <> - Aborts an ingest job. * <> - Deletes an ingest job. * <> - Gets successful results for an ingest job. * <> - Gets failed results for an ingest job. * <> - Gets unprocessed records for an ingest job. * <> - Gets an ingest Job. * <> - Gets all ingest jobs. * <> - Creates a query job. * <> - Gets query job results. * <> - Aborts a query job. * <> - Deletes a query job. * <> - Gets a query job. * <> - Gets all query jobs. [[bulk2CreateJob]] ==== Create a Job `bulk2CreateJob` Creates a bulk ingest job. |=== | Parameter | Type | Description| Default| Required | Body | `Job` | Job to create | | x |=== *Output* Type: `Job` [[bulk2CreateBatch]] ==== Upload a Batch of Job Data `bulk2CreateBatch` Adds a batch of data to an ingest job. |=== | Parameter | Type | Description| Default| Required | Body | `InputStream` or `String` | CSV data. The first row must contain headers. | | Required if `jobId` not supplied | `jobId` | `String` | Id of Job to create batch under | | x |=== [[bulk2CloseJob]] ==== Close a Job `bulk2CloseJob` Closes an ingest job. You must close the job in order for it to be processed or aborted/deleted. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to close | | x |=== *Output* Type: `Job` [[bulk2AbortJob]] ==== Abort a Job `bulk2AbortJob` Aborts an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to abort | | x |=== *Output* Type: `Job` [[bulk2DeleteJob]] ==== Delete a Job `bulk2DeleteJob` Deletes an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to delete | | x |=== [[bulk2GetSuccessfulResults]] ==== Get Job Successful Record Results `bulk2GetSuccessfulResults` Gets successful results for an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get results for | | x |=== *Output* Type: `InputStream` + Contents: CSV data [[bulk2GetFailedResults]] ==== Get Job Failed Record Results `bulk2GetFailedResults` Gets failed results for an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get results for | | x |=== *Output* Type: `InputStream` + Contents: CSV data [[bulk2GetUnprocessedRecords]] ==== Get Job Unprocessed Record Results `bulk2GetUnprocessedRecords` Gets unprocessed records for an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get records for | | x |=== *Output* Type: `InputStream` Contents: CSV data [[bulk2GetJob]] ==== Get Job Info `bulk2GetJob` Gets an ingest Job. |=== | Parameter | Type | Description| Default| Required | Body | `Job` | Will use Id of supplied Job to retrieve Job | | Required if `jobId` not supplied | `jobId` | `String` | Id of Job to retrieve | | Required if `Job` not supplied in body |=== *Output* Type: `Job` [[bulk2GetAllJobs]] ==== Get All Jobs `bulk2GetAllJobs` Gets all ingest jobs. |=== | Parameter | Type | Description| Default| Required | `queryLocator` | `String` | Used in subsequent calls if results span multiple pages | | |=== *Output* Type: `Jobs` If the `done` property of the `Jobs` instance is false, there are additional pages to fetch, and the `nextRecordsUrl` property contains the value to be set in the `queryLocator` parameter on subsequent calls. [[bulk2CreateQueryJob]] ==== Create a Query Job `bulk2CreateQueryJob` Gets a query job. |=== | Parameter | Type | Description| Default| Required | Body | `QueryJob` | QueryJob to create | | x |=== *Output* Type: `QueryJob` [[bulk2GetQueryJobResults]] ==== Get Results for a Query Job `bulk2GetQueryJobResults` Get bulk query job results. `jobId` parameter is required. Accepts `maxRecords` and `locator` parameters. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get results for | | x | `maxRecords` | `Integer` | Id of Job to get results for | | | `locator` | `locator` | Value to use for subsequent calls | | |=== *Output* Type: `InputStream` Contents: CSV data Response message headers include `Sforce-NumberOfRecords` and `Sforce-Locator` headers. The value of `Sforce-Locator` can be passed into subsequent calls via the `locator` parameter. [[bulk2AbortQueryJob]] ==== Abort a Query Job `bulk2AbortQueryJob` Aborts a query job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to abort | | x |=== *Output* Type: `QueryJob` [[bulk2DeleteQueryJob]] ==== Delete a Query Job `bulk2DeleteQueryJob` Deletes a query job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to delete | | x |=== [[bulk2GetQueryJob]] ==== Get Information About a Query Job `bulk2GetQueryJob` Gets a query job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to retrieve | | x |=== *Output* Type: `QueryJob` [[bulk2GetAllQueryJobs]] ==== Get Information About All Query Jobs `bulk2GetAllQueryJobs` Gets all query jobs. |=== | Parameter | Type | Description| Default| Required | `queryLocator` | `String` | Used in subsequent calls if results span multiple pages | | |=== *Output* Type: `QueryJobs` If the `done` property of the `QueryJobs` instance is false, there are additional pages to fetch, and the `nextRecordsUrl` property contains the value to be set in the `queryLocator` parameter on subsequent calls. [[BulkAPI]] === Bulk (original) API Producer endpoints can use the following APIs. All Job data formats, i.e. xml, csv, zip/xml, and zip/csv are supported. + The request and response have to be marshalled/unmarshalled by the route. Usually the request will be some stream source like a CSV file, and the response may also be saved to a file to be correlated with the request. The following operations are supported: * <> - Creates a Salesforce Bulk Job. * <> - Gets a Job using its Salesforce Id * <> - Closes a Job * <> - Aborts a Job * <> - Submits a Batch within a Bulk Job * <> - Gets a Batch using Id * <> - Gets all Batches for a Bulk Job Id * <> - Gets Request data (XML/CSV) for a Batch * <> - Gets the results of the Batch when its complete * <> - Creates a Batch from an SOQL query * <> - Gets a list of Result Ids for a Batch Query * <> - Gets results for a Result Id [[createJob]] ==== Create a Job `createJob` Creates a Salesforce Bulk Job. PK Chunking is supported via the pkChunking* options. See an explanation https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/async_api_headers_enable_pk_chunking.htm[here]. |=== | Parameter | Type | Description| Default| Required | Body | `JobInfo` | Job to create | | x | `pkChunking` | `Boolean` | Whether to use PK Chunking | false | | `pkChunkingChunkSize` | `Integer` | | | | `pkChunkingStartRow` | `Integer` | | | | `pkChunkingParent` | `String` | | | |=== *Output* Type: `JobInfo` [[getJob]] ==== Get Job Details `getJob` Gets a Job |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get | | Required if body not supplied | Body | `JobInfo` | `JobInfo` instance from which Id will be used | | Required if `jobId` not supplied |=== *Output* Type: `JobInfo` [[closeJob]] ==== Close a Job `closeJob` Closes a Job |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | Body | `JobInfo` | `JobInfo` instance from which Id will be used | | Required if `jobId` not supplied |=== *Output* Type: `JobInfo` [[abortJob]] ==== Abort a Job `abortJob` Aborts a Job |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | Body | `JobInfo` | `JobInfo` instance from which Id will be used | | Required if `jobId` not supplied |=== *Output* Type: `JobInfo` [[createBatch]] ==== Add a Batch to a Job `createBatch` Submits a Batch within a Bulk Job |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | x | `contentType` | `String` | Content type of body. Can be XML, CSV, ZIP_XML or ZIP_CSV | | x | `Body` | `InputStream` or `String` | Batch data | | x |=== *Output* Type: `BatchInfo` [[getBatch]] ==== Get Information for a Batch `getBatch` Get a Batch |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | Body | `BatchInfo` | `JobInfo` instance from which `jobId` and `batchId` will be used | | Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `BatchInfo` [[getAllBatches]] ==== Get Information for All Batches in a Job `getAllBatches` Gets all Batches for a Bulk Job Id |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | Body | `JobInfo` | `JobInfo` instance from which Id will be used | | Required if `jobId` not supplied |=== *Output* Type: `List` [[getRequest]] ==== Get a Batch Request `getRequest` Gets Request data (XML/CSV) for a Batch |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | Body | `BatchInfo` | `JobInfo` instance from which `jobId` and `batchId` will be used | | Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `InputStream` [[getResults]] ==== Get Batch Results `getResults` Gets the results of the Batch when it's complete |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | Body | `BatchInfo` | `JobInfo` instance from which `jobId` and `batchId` will be used | | Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `InputStream` [[createBatchQuery]] ==== Create Bulk Query Batch `createBatchQuery` Creates a Batch from an SOQL query |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `contentType` | `String` | Content type of body. Can be XML, CSV, ZIP_XML or ZIP_CSV | | Required if `JobInfo` instance not supplied in body | `sObjectQuery` | `String` | SOQL query to be used for this batch | | Required if not supplied in body | Body | `JobInfo` or `String` | Either `JobInfo` instance from which `jobId` and `contentType` will be used, or `String` to be used as the Batch query | | Required `JobInfo` if `jobId` and `contentType` not supplied. |=== *Output* Type: `BatchInfo` [[getQueryResultIds]] ==== Get Batch Results `getQueryResultIds` Gets a list of Result Ids for a Batch Query |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | Body | `BatchInfo` | `JobInfo` instance from which `jobId` and `batchId` will be used | | Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `List` [[getQueryResult]] ==== Get Bulk Query Results `getQueryResult` Gets results for a Result Id |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | `resultId` | `String` | Id of Result | | If not passed in body | Body | `BatchInfo` or `String` | `JobInfo` instance from which `jobId` and `batchId` will be used. Otherwise can be a `String` containing the `resultId` | | `BatchInfo` Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `InputStream` For example, the following producer endpoint uses the createBatch API to create a Job Batch. The in message must contain a body that can be converted into an `InputStream` (usually UTF-8 CSV or XML content from a file, etc.) and header fields 'jobId' for the Job and 'contentType' for the Job content type, which can be XML, CSV, ZIP_XML or ZIP_CSV. The put message body will contain `BatchInfo` on success, or throw a `SalesforceException` on error. [source,java] ---- ...to(""salesforce:createBatch"").. ---- [[StreamingAPI]] === Streaming API The Streaming API enables streaming of events using push technology and provides a subscription mechanism for receiving events in near real time. The Streaming API subscription mechanism supports multiple types of events, including PushTopic events, generic events, platform events, and Change Data Capture events. ==== Push Topics The URI format for consuming Push Topics is: ---- salesforce:[?options] ---- To create and subscribe to a topic [source,java] ---- from(""salesforce:CamelTestTopic?notifyForFields=ALL¬ifyForOperations=ALL&sObjectName=Merchandise__c&updateTopic=true&sObjectQuery=SELECT Id, Name FROM Merchandise__c"")... ---- To subscribe to an existing topic [source,java] ---- from(""salesforce:CamelTestTopic&sObjectName=Merchandise__c"")... ---- |=== | Parameter | Type | Description| Default| Required | `sObjectName` | `String` | SObject to monitor | | x | `sObjectQuery` | `String` | SOQL query used to create Push Topic | | Required for creating new topics | `updateTopic` | `Boolean` | Whether to update an existing Push Topic if exists | false | | `notifyForFields` | `NotifyForFieldsEnum` | Specifies how the record is evaluated against the PushTopic query. | Referenced | | `notifyForOperationCreate` | `Boolean` | Whether a create operation should generate a notification. | false | | `notifyForOperationDelete` | `Boolean` | Whether a delete operation should generate a notification. | false | | `notifyForOperationUndelete` | `Boolean` | Whether an undelete operation should generate a notification. | false | | `notifyForOperationUpdate` | `Boolean` | Whether an update operation should generate a notification. | false | | `notifyForOperations` | `NotifyForOperationsEnum` | Whether an update operation should generate a notification. Only for use in API version < 29.0 | All | | `replayId` | `int` | The replayId value to use when subscribing.| | | `defaultReplayId` | `int` | Default replayId setting if no value is found in initialReplayIdMap. | -1 | | `fallBackReplayId` | `int` | ReplayId to fall back to after an Invalid Replay Id response. | -1 | |=== *Output* Type: Class passed via `sObjectName` parameter ==== Platform Events To emit a platform event use the <> operation, passing an instance of a platform event, e.g. `Order_Event__e`. The URI format for consuming platform events is: ---- salesforce:event/ ---- For example, to receive platform events use for the event type `Order_Event__e`: [source,java] ---- from(""salesforce:event/Order_Event__e"") ---- |=== | Parameter | Type | Description| Default| Required | `rawPayload` | `Boolean` | If false, operation returns a `PlatformEvent`, otherwise returns the raw Bayeux Message | false | | `replayId` | `int` | The replayId value to use when subscribing.| | | `defaultReplayId` | `int` | Default replayId setting if no value is found in initialReplayIdMap. | -1 | | `fallBackReplayId` | `int` | ReplayId to fall back to after an Invalid Replay Id response. | -1 | |=== *Output* Type: `PlatformEvent` or `org.cometd.bayeux.Message` ==== Change Data Capture Events Change Data Capture (CDC) allows you to receive near-real-time changes of Salesforce records, and synchronize corresponding records in an external data store. Change Data Capture publishes change events, which represent changes to Salesforce records. Changes include creation of a new record, updates to an existing record, deletion of a record, and undeletion of a record. The URI format to consume CDC events is as follows: All Selected Entities ---- salesforce:data/ChangeEvents ---- Standard Objects ---- salesforce:data/ChangeEvent ---- Custom Objects ---- salesforce:data/__ChangeEvent ---- Here are a few examples [source,java] ---- from(""salesforce:data/ChangeEvents?replayId=-1"").log(""being notified of all change events"") from(""salesforce:data/AccountChangeEvent?replayId=-1"").log(""being notified of change events for Account records"") from(""salesforce:data/Employee__ChangeEvent?replayId=-1"").log(""being notified of change events for Employee__c custom object"") ---- More details about how to use the Camel Salesforce component change data capture capabilities could be found in the https://github.com/apache/camel/tree/main/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/ChangeEventsConsumerIntegrationTest.java[ChangeEventsConsumerIntegrationTest]. The https://developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/cdc_intro.htm[Salesforce developer guide] is a good fit to better know the subtleties of implementing a change data capture integration application. The dynamic nature of change event body fields, high level replication steps as well as security considerations could be of interest. |=== | Parameter | Type | Description| Default| Required | `rawPayload` | `Boolean` | If false, operation returns a `Map`, otherwise returns the raw Bayeux `Message` | false | | `replayId` | `int` | The replayId value to use when subscribing.| | | `defaultReplayId` | `int` | Default replayId setting if no value is found in initialReplayIdMap. | -1 | | `fallBackReplayId` | `int` | ReplayId to fall back to after an Invalid Replay Id response. | -1 | |=== *Output* Type: `Map` or `org.cometd.bayeux.Message` Headers |=== | Name | Description | `CamelSalesforceChangeType` | `CREATE`, `UPDATE`, `DELETE` or `UNDELETE` |=== [[ReportsAPI]] === Reports API * <> - Gets up to 200 of the reports you most recently viewed. * <> - Retrieves report description. * <> - Runs a report synchronously. * <> - Runs a report asynchronously. * <> - Returns a list of instances for a report that you requested to be run asynchronously. * <> - Retrieves results for an instance of a report run asynchronously. [[getRecentReports]] ==== Report List `getRecentReports` Gets up to 200 of the reports you most recently viewed. *Output* Type: `List` [[getReportDescription]] ==== Describe Report `getReportDescription` Retrieves the report, report type, and related metadata for a report, either in a tabular or summary or matrix format. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | Body | `String` | Id of Report | | Required if not supplied in `reportId` parameter |=== *Output* Type: `ReportDescription` [[executeSyncReport]] ==== Execute Sync `executeSyncReport` Runs a report synchronously with or without changing filters and returns the latest summary data. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | `includeDetails` | `Boolean` | Whether to include details | false| | `reportMetadata` | `ReportMetadata` | Optionally, pass ReportMetadata here instead of body | | | Body | `ReportMetadata` | If supplied, will use instead of `reportId` | | Required if not supplied in `reportId` parameter |=== *Output* Type: `AbstractReportResultsBase` [[executeAsyncReport]] ==== Execute Async `executeAsyncReport` Runs an instance of a report asynchronously with or without filters and returns the summary data with or without details. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | `includeDetails` | `Boolean` | Whether to include details | false| | `reportMetadata` | `ReportMetadata` | Optionally, pass ReportMetadata here instead of body | | | Body | `ReportMetadata` | If supplied, will use instead of `reportId` parameter | | Required if not supplied in `reportId` parameter |=== *Output* Type: `ReportInstance` [[getReportInstances]] ==== Instances List `getReportInstances` Returns a list of instances for a report that you requested to be run asynchronously. Each item in the list is treated as a separate instance of the report. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | Body | `String` | If supplied, will use instead of `reportId` parameter | | Required if not supplied in `reportId` parameter |=== *Output* Type: `List` [[getReportResults]] ==== Instance Results `getReportResults` Contains the results of running a report. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | `instanceId` | `String` | Id of Report instance | | x | Body | `String` | If supplied, will use instead of `reportId` parameter | | Required if not supplied in `reportId` parameter |=== *Output* Type: `AbstractReportResultsBase` == Miscellaneous Operations * <> - Send requests to salesforce and have full, raw control over endpoint, parameters, body, etc. [[raw]] === Raw `raw` Sends HTTP requests to salesforce with full, raw control of all aspects of the call. Any serialization or deserialization of request and response bodies must be performed in the route. The `Content-Type` HTTP header will be automatically set based on the `format` option, but this can be overridden with the `rawHttpHeaders` option. |=== | Parameter | Type | Description| Default| Required | Body | `String` or `InputStream` | Body of the HTTP request | | | `rawPath` | `String` | The portion of the endpoint URL after the domain name, e.g., '/services/data/v51.0/sobjects/Account/' | | x | `rawMethod` | `String` | The HTTP method | | x | `rawQueryParameters` | `String` | Comma separated list of message headers to include as query parameters. Do not url-encode values as this will be done automatically. | | | `rawHttpHeaders` | `String` | Comma separated list of message headers to include as HTTP headers | | |=== *Output* Type: `InputStream` ==== Query example In this example we'll send a query to the REST API. The query must be passed in a URL parameter called ""q"", so we'll create a message header called q and tell the raw operation to include that message header as a URL parameter: ---- from(""direct:queryExample"") .setHeader(""q"", ""SELECT Id, LastName FROM Contact"") .to(""salesforce:raw?format=JSON&rawMethod=GET&rawQueryParameters=q&rawPath=/services/data/v51.0/query"") // deserialize JSON results or handle in some other way ---- ==== SObject example In this example, we'll pass a Contact the REST API in a `create` operation. Since the `raw` operation does not perform any serialization, we make sure to pass XML in the message body ---- from(""direct:createAContact"") .setBody(constant(""TestLast"")) .to(""salesforce:raw?format=XML&rawMethod=POST&rawPath=/services/data/v51.0/sobjects/Contact"") ---- The response is: ---- 0034x00000RnV6zAAF true ---- == Uploading a document to a ContentWorkspace Create the ContentVersion in Java, using a Processor instance: [source,java] ---- public class ContentProcessor implements Processor { public void process(Exchange exchange) throws Exception { Message message = exchange.getIn(); ContentVersion cv = new ContentVersion(); ContentWorkspace cw = getWorkspace(exchange); cv.setFirstPublishLocationId(cw.getId()); cv.setTitle(""test document""); cv.setPathOnClient(""test_doc.html""); byte[] document = message.getBody(byte[].class); ObjectMapper mapper = new ObjectMapper(); String enc = mapper.convertValue(document, String.class); cv.setVersionDataUrl(enc); message.setBody(cv); } protected ContentWorkspace getWorkSpace(Exchange exchange) { // Look up the content workspace somehow, maybe use enrich() to add it to a // header that can be extracted here .... } } ---- Give the output from the processor to the Salesforce component: [source,java] ---- from(""file:///home/camel/library"") .to(new ContentProcessor()) // convert bytes from the file into a ContentVersion SObject // for the salesforce component .to(""salesforce:createSObject""); ---- == Generating SOQL query strings `org.apache.camel.component.salesforce.api.utils.QueryHelper` contains helper methods to generate SOQL queries. For instance to fetch all custom fields from _Account_ SObject you can simply generate the SOQL SELECT by invoking: [source,java] ---- String allCustomFieldsQuery = QueryHelper.queryToFetchFilteredFieldsOf(new Account(), SObjectField::isCustom); ---- [[MavenPlugin]] == Camel Salesforce Maven Plugin The Maven plugin generates Java DTOs to represent salesforce objects. Please refer to https://github.com/apache/camel/tree/main/components/camel-salesforce/camel-salesforce-maven-plugin[README.md] for details on how to use the plugin. include::spring-boot:partial$starter.adoc[] ",16134,True,3099.7181854313326,median "= Main Component :doctitle: Main :shortname: main :artifactid: camel-main :description: Camel Main :since: 3.0 :supportlevel: Stable *Since Camel {since}* This module is used for running Camel standalone via a main class extended from `camel-main`. == Configuration options When running Camel via `camel-main` you can configure Camel in the `application.properties` file. The following tables lists all the options: // main options: START === Camel Main configurations The camel.main supports 112 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.main.allowUseOriginal{zwsp}Message* | Sets whether to allow access to the original message from Camel's error handler, or from org.apache.camel.spi.UnitOfWork.getOriginalInMessage(). Turning this off can optimize performance, as defensive copy of the original message is not needed. Default is false. | false | boolean | *camel.main.autoConfiguration{zwsp}Enabled* | Whether auto configuration of components, dataformats, languages is enabled or not. When enabled the configuration parameters are loaded from the properties component. You can prefix the parameters in the properties file with: - camel.component.name.option1=value1 - camel.component.name.option2=value2 - camel.dataformat.name.option1=value1 - camel.dataformat.name.option2=value2 - camel.language.name.option1=value1 - camel.language.name.option2=value2 Where name is the name of the component, dataformat or language such as seda,direct,jaxb. The auto configuration also works for any options on components that is a complex type (not standard Java type) and there has been an explicit single bean instance registered to the Camel registry via the org.apache.camel.spi.Registry#bind(String,Object) method or by using the org.apache.camel.BindToRegistry annotation style. This option is default enabled. | true | boolean | *camel.main.autoConfiguration{zwsp}EnvironmentVariablesEnabled* | Whether auto configuration should include OS environment variables as well. When enabled this allows to overrule any configuration using an OS environment variable. For example to set a shutdown timeout of 5 seconds: CAMEL_MAIN_SHUTDOWNTIMEOUT=5. This option is default enabled. | true | boolean | *camel.main.autoConfiguration{zwsp}FailFast* | Whether auto configuration should fail fast when configuring one ore more properties fails for whatever reason such as a invalid property name, etc. This option is default enabled. | true | boolean | *camel.main.autoConfiguration{zwsp}LogSummary* | Whether auto configuration should log a summary with the configured properties. This option is default enabled. | true | boolean | *camel.main.autoConfiguration{zwsp}SystemPropertiesEnabled* | Whether auto configuration should include JVM system properties as well. When enabled this allows to overrule any configuration using a JVM system property. For example to set a shutdown timeout of 5 seconds: -D camel.main.shutdown-timeout=5. Note that JVM system properties take precedence over OS environment variables. This option is default enabled. | true | boolean | *camel.main.autoStartup* | Sets whether the object should automatically start when Camel starts. Important: Currently only routes can be disabled, as CamelContext's are always started. Note: When setting auto startup false on CamelContext then that takes precedence and no routes are started. You would need to start CamelContext explicit using the org.apache.camel.CamelContext.start() method, to start the context, and then you would need to start the routes manually using CamelContext.getRouteController().startRoute(String). Default is true to always start up. | true | boolean | *camel.main.autowiredEnabled* | Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. Default is true. | true | boolean | *camel.main.backlogTracing* | Sets whether backlog tracing is enabled or not. Default is false. | false | boolean | *camel.main.basePackageScan* | Package name to use as base (offset) for classpath scanning of RouteBuilder , and org.apache.camel.TypeConverter classes. If you are using Spring Boot then it is instead recommended to use Spring Boots component scanning and annotate your route builder classes with Component. In other words only use this for Camel Main in standalone mode. | | String | *camel.main.basePackageScan{zwsp}Enabled* | Whether base package scan is enabled. | true | boolean | *camel.main.beanIntrospection{zwsp}ExtendedStatistics* | Sets whether bean introspection uses extended statistics. The default is false. | false | boolean | *camel.main.beanIntrospection{zwsp}LoggingLevel* | Sets the logging level used by bean introspection, logging activity of its usage. The default is TRACE. | | LoggingLevel | *camel.main.beanPostProcessor{zwsp}Enabled* | Can be used to turn off bean post processing. Be careful to turn this off, as this means that beans that use Camel annotations such as org.apache.camel.EndpointInject , org.apache.camel.ProducerTemplate , org.apache.camel.Produce , org.apache.camel.Consume etc will not be injected and in use. Turning this off should only be done if you are sure you do not use any of these Camel features. Not all runtimes allow turning this off (such as camel-blueprint or camel-cdi with XML). The default value is true (enabled). | true | boolean | *camel.main.caseInsensitive{zwsp}Headers* | Whether to use case sensitive or insensitive headers. Important: When using case sensitive (this is set to false). Then the map is case sensitive which means headers such as content-type and Content-Type are two different keys which can be a problem for some protocols such as HTTP based, which rely on case insensitive headers. However case sensitive implementations can yield faster performance. Therefore use case sensitive implementation with care. Default is true. | true | boolean | *camel.main.configuration{zwsp}Classes* | Sets classes names that will be used to configure the camel context as example by providing custom beans through org.apache.camel.BindToRegistry annotation. | | String | *camel.main.configurations* | Sets the configuration objects used to configure the camel context. | | List | *camel.main.consumerTemplate{zwsp}CacheSize* | Consumer template endpoints cache size. | 1000 | int | *camel.main.debugging* | Sets whether debugging is enabled or not. Default is false. | false | boolean | *camel.main.devConsoleEnabled* | Whether to enable developer console (requires camel-console on classpath). The developer console is only for assisting during development. This is NOT for production usage. | false | boolean | *camel.main.dumpRoutes* | If dumping is enabled then Camel will during startup dump all loaded routes (incl rests and route templates) represented as XML DSL into the log. This is intended for trouble shooting or to assist during development. Sensitive information that may be configured in the route endpoints could potentially be included in the dump output and is therefore not recommended being used for production usage. This requires to have camel-xml-jaxb on the classpath to be able to dump the routes as XML. | false | boolean | *camel.main.durationHitExitCode* | Sets the exit code for the application if duration was hit | | int | *camel.main.durationMaxAction* | Controls whether the Camel application should shutdown the JVM, or stop all routes, when duration max is triggered. | shutdown | String | *camel.main.durationMaxIdle{zwsp}Seconds* | To specify for how long time in seconds Camel can be idle before automatic terminating the JVM. You can use this to run Camel for a short while. | | int | *camel.main.durationMaxMessages* | To specify how many messages to process by Camel before automatic terminating the JVM. You can use this to run Camel for a short while. | | int | *camel.main.durationMaxSeconds* | To specify for how long time in seconds to keep running the JVM before automatic terminating the JVM. You can use this to run Camel for a short while. | | int | *camel.main.eagerClassloading* | Whether to eager load a common set of Camel classes that would otherwise first be loaded on processing the first message. By eager loading these classes then the JVM has already loaded the classes during build phase, which allows Camel to process the first message faster. | false | boolean | *camel.main.endpointBridgeError{zwsp}Handler* | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN/ERROR level and ignored. The default value is false. | false | boolean | *camel.main.endpointLazyStart{zwsp}Producer* | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. The default value is false. | false | boolean | *camel.main.endpointRuntime{zwsp}StatisticsEnabled* | Sets whether endpoint runtime statistics is enabled (gathers runtime usage of each incoming and outgoing endpoints). The default value is false. | false | boolean | *camel.main.exchangeFactory* | Controls whether to pool (reuse) exchanges or create new exchanges (prototype). Using pooled will reduce JVM garbage collection overhead by avoiding to re-create Exchange instances per message each consumer receives. The default is prototype mode. | default | String | *camel.main.exchangeFactory{zwsp}Capacity* | The capacity the pool (for each consumer) uses for storing exchanges. The default capacity is 100. | 100 | int | *camel.main.exchangeFactory{zwsp}StatisticsEnabled* | Configures whether statistics is enabled on exchange factory. | false | boolean | *camel.main.extraShutdown{zwsp}Timeout* | Extra timeout in seconds to graceful shutdown Camel. When Camel is shutting down then Camel first shutdown all the routes (shutdownTimeout). Then additional services is shutdown (extraShutdownTimeout). | 15 | int | *camel.main.fileConfigurations* | Directory to load additional configuration files that contains configuration values that takes precedence over any other configuration. This can be used to refer to files that may have secret configuration that has been mounted on the file system for containers. You can specify a pattern to load from sub directories and a name pattern such as /var/app/secret/.properties, multiple directories can be separated by comma. | | String | *camel.main.globalOptions* | Sets global options that can be referenced in the camel context Important: This has nothing to do with property placeholders, and is just a plain set of key/value pairs which are used to configure global options on CamelContext, such as a maximum debug logging length etc. | | Map | *camel.main.inflightRepository{zwsp}BrowseEnabled* | Sets whether the inflight repository should allow browsing each inflight exchange. This is by default disabled as there is a very slight performance overhead when enabled. | false | boolean | *camel.main.javaRoutesExclude{zwsp}Pattern* | Used for exclusive filtering RouteBuilder classes which are collected from the registry or via classpath scanning. The exclusive filtering takes precedence over inclusive filtering. The pattern is using Ant-path style pattern. Multiple patterns can be specified separated by comma. For example to exclude all classes starting with Bar use: **/Bar* To exclude all routes form a specific package use: com/mycompany/bar/* To exclude all routes form a specific package and its sub-packages use double wildcards: com/mycompany/bar/** And to exclude all routes from two specific packages use: com/mycompany/bar/*,com/mycompany/stuff/* | | String | *camel.main.javaRoutesInclude{zwsp}Pattern* | Used for inclusive filtering RouteBuilder classes which are collected from the registry or via classpath scanning. The exclusive filtering takes precedence over inclusive filtering. The pattern is using Ant-path style pattern. Multiple patterns can be specified separated by comma. Multiple patterns can be specified separated by comma. For example to include all classes starting with Foo use: **/Foo To include all routes form a specific package use: com/mycompany/foo/* To include all routes form a specific package and its sub-packages use double wildcards: com/mycompany/foo/** And to include all routes from two specific packages use: com/mycompany/foo/*,com/mycompany/stuff/* | | String | *camel.main.jmxEnabled* | Enable JMX in your Camel application. | true | boolean | *camel.main.jmxManagementName{zwsp}Pattern* | The naming pattern for creating the CamelContext JMX management name. The default pattern is #name# | #name# | String | *camel.main.jmxManagement{zwsp}StatisticsLevel* | Sets the JMX statistics level, the level can be set to Extended to gather additional information The default value is Default. | Default | ManagementStatisticsLevel | *camel.main.lightweight* | Configure the context to be lightweight. This will trigger some optimizations and memory reduction options. Lightweight context have some limitations. At this moment, dynamic endpoint destinations are not supported. | false | boolean | *camel.main.loadHealthChecks* | Whether to load custom health checks by scanning classpath. | false | boolean | *camel.main.loadTypeConverters* | Whether to load custom type converters by scanning classpath. This is used for backwards compatibility with Camel 2.x. Its recommended to migrate to use fast type converter loading by setting Converter(loader = true) on your custom type converter classes. | false | boolean | *camel.main.logDebugMaxChars* | Is used to limit the maximum length of the logging Camel message bodies. If the message body is longer than the limit, the log message is clipped. Use -1 to have unlimited length. Use for example 1000 to log at most 1000 characters. | | int | *camel.main.logExhaustedMessage{zwsp}Body* | Sets whether to log exhausted message body with message history. Default is false. | false | boolean | *camel.main.logMask* | Sets whether log mask is enabled or not. Default is false. | false | boolean | *camel.main.mdcLoggingKeys{zwsp}Pattern* | Sets the pattern used for determine which custom MDC keys to propagate during message routing when the routing engine continues routing asynchronously for the given message. Setting this pattern to will propagate all custom keys. Or setting the pattern to foo,bar will propagate any keys starting with either foo or bar. Notice that a set of standard Camel MDC keys are always propagated which starts with camel. as key name. The match rules are applied in this order (case insensitive): 1. exact match, returns true 2. wildcard match (pattern ends with a and the name starts with the pattern), returns true 3. regular expression match, returns true 4. otherwise returns false | | String | *camel.main.messageHistory* | Sets whether message history is enabled or not. Default is false. | false | boolean | *camel.main.modeline* | Whether camel-k style modeline is also enabled when not using camel-k. Enabling this allows to use a camel-k like experience by being able to configure various settings using modeline directly in your route source code. | false | boolean | *camel.main.name* | Sets the name of the CamelContext. | | String | *camel.main.producerTemplate{zwsp}CacheSize* | Producer template endpoints cache size. | 1000 | int | *camel.main.routeControllerBack{zwsp}OffDelay* | Backoff delay in millis when restarting a route that failed to startup. | | long | *camel.main.routeControllerBack{zwsp}OffMaxAttempts* | Backoff maximum number of attempts to restart a route that failed to startup. When this threshold has been exceeded then the controller will give up attempting to restart the route, and the route will remain as stopped. | | long | *camel.main.routeControllerBack{zwsp}OffMaxDelay* | Backoff maximum delay in millis when restarting a route that failed to startup. | | long | *camel.main.routeControllerBack{zwsp}OffMaxElapsedTime* | Backoff maximum elapsed time in millis, after which the backoff should be considered exhausted and no more attempts should be made. | | long | *camel.main.routeControllerBack{zwsp}OffMultiplier* | Backoff multiplier to use for exponential backoff. This is used to extend the delay between restart attempts. | | double | *camel.main.routeController{zwsp}ExcludeRoutes* | Pattern for filtering routes to be excluded as supervised. The pattern is matching on route id, and endpoint uri for the route. Multiple patterns can be separated by comma. For example to exclude all JMS routes, you can say jms:. And to exclude routes with specific route ids mySpecialRoute,myOtherSpecialRoute. The pattern supports wildcards and uses the matcher from org.apache.camel.support.PatternHelper#matchPattern. | | String | *camel.main.routeController{zwsp}IncludeRoutes* | Pattern for filtering routes to be included as supervised. The pattern is matching on route id, and endpoint uri for the route. Multiple patterns can be separated by comma. For example to include all kafka routes, you can say kafka:. And to include routes with specific route ids myRoute,myOtherRoute. The pattern supports wildcards and uses the matcher from org.apache.camel.support.PatternHelper#matchPattern. | | String | *camel.main.routeController{zwsp}InitialDelay* | Initial delay in milli seconds before the route controller starts, after CamelContext has been started. | | long | *camel.main.routeController{zwsp}LoggingLevel* | Sets the logging level used for logging route activity (such as starting and stopping routes). The default logging level is DEBUG. | DEBUG | LoggingLevel | *camel.main.routeController{zwsp}SuperviseEnabled* | To enable using supervising route controller which allows Camel to startup and then the controller takes care of starting the routes in a safe manner. This can be used when you want to startup Camel despite a route may otherwise fail fast during startup and cause Camel to fail to startup as well. By delegating the route startup to the supervising route controller then its manages the startup using a background thread. The controller allows to be configured with various settings to attempt to restart failing routes. | false | boolean | *camel.main.routeController{zwsp}ThreadPoolSize* | The number of threads used by the route controller scheduled thread pool that are used for restarting routes. The pool uses 1 thread by default, but you can increase this to allow the controller to concurrently attempt to restart multiple routes in case more than one route has problems starting. | | int | *camel.main.routeController{zwsp}UnhealthyOnExhausted* | Whether to mark the route as unhealthy (down) when all restarting attempts (backoff) have failed and the route is not successfully started and the route manager is giving up. Setting this to true allows health checks to know about this and can report the Camel application as DOWN. The default is false. | false | boolean | *camel.main.routeFilterExclude{zwsp}Pattern* | Used for filtering routes routes matching the given pattern, which follows the following rules: - Match by route id - Match by route input endpoint uri The matching is using exact match, by wildcard and regular expression as documented by PatternHelper#matchPattern(String,String) . For example to only include routes which starts with foo in their route id's, use: include=foo* And to exclude routes which starts from JMS endpoints, use: exclude=jms:* Multiple patterns can be separated by comma, for example to exclude both foo and bar routes, use: exclude=foo*,bar* Exclude takes precedence over include. | | String | *camel.main.routeFilterInclude{zwsp}Pattern* | Used for filtering routes matching the given pattern, which follows the following rules: - Match by route id - Match by route input endpoint uri The matching is using exact match, by wildcard and regular expression as documented by PatternHelper#matchPattern(String,String) . For example to only include routes which starts with foo in their route id's, use: include=foo* And to exclude routes which starts from JMS endpoints, use: exclude=jms:* Multiple patterns can be separated by comma, for example to exclude both foo and bar routes, use: exclude=foo*,bar* Exclude takes precedence over include. | | String | *camel.main.routesBuilder{zwsp}Classes* | Sets classes names that implement RoutesBuilder . | | String | *camel.main.routesBuilders* | Sets the RoutesBuilder instances. | | List | *camel.main.routesCollector{zwsp}Enabled* | Whether the routes collector is enabled or not. When enabled Camel will auto-discover routes (RouteBuilder instances from the registry and also load additional routes from the file system). The routes collector is default enabled. | true | boolean | *camel.main.routesCompile{zwsp}Directory* | Directory to use for saving runtime compiled Camel routes to class files, when using camel-java-joor-dsl as Java DSL (such as when using Camel K with Java source routes). Camel will compile to in-memory only by default. Specifying this option, allows Camel to persist the compiled class to disk. And when starting the application again the routes are loaded from the pre-compiled class files instead of re-compiling again. | | String | *camel.main.routesCompileLoad{zwsp}First* | Whether to load preexisting compiled Camel routes class files, when using camel-java-joor-dsl as Java DSL (such as when using Camel K with Java source routes). If enabled then Camel will look in the routes compile directory if a compiled Java route already exists and load its bytecode instead of runtime compiling from its java source file. | false | boolean | *camel.main.routesExclude{zwsp}Pattern* | Used for exclusive filtering of routes from directories. The exclusive filtering takes precedence over inclusive filtering. The pattern is using Ant-path style pattern. Multiple patterns can be specified separated by comma, as example, to exclude all the routes from a directory whose name contains foo use: **/foo. | | String | *camel.main.routesInclude{zwsp}Pattern* | Used for inclusive filtering of routes from directories. The exclusive filtering takes precedence over inclusive filtering. The pattern is using Ant-path style pattern. Multiple patterns can be specified separated by comma, as example, to include all the routes from a directory whose name contains foo use: **/foo. | classpath:camel/*,classpath:camel-template/*,classpath:camel-rest/* | String | *camel.main.routesReload{zwsp}Directory* | Directory to scan for route changes. Camel cannot scan the classpath, so this must be configured to a file directory. Development with Maven as build tool, you can configure the directory to be src/main/resources to scan for Camel routes in XML or YAML files. | src/main/resources/camel | String | *camel.main.routesReload{zwsp}DirectoryRecursive* | Whether the directory to scan should include sub directories. Depending on the number of sub directories, then this can cause the JVM to startup slower as Camel uses the JDK file-watch service to scan for file changes. | false | boolean | *camel.main.routesReloadEnabled* | Used for enabling automatic routes reloading. If enabled then Camel will watch for file changes in the given reload directory, and trigger reloading routes if files are changed. | false | boolean | *camel.main.routesReloadPattern* | Used for inclusive filtering of routes from directories. Typical used for specifying to accept routes in XML or YAML files, such as .yaml,.xml. Multiple patterns can be specified separated by comma. | | String | *camel.main.routesReloadRemove{zwsp}AllRoutes* | When reloading routes should all existing routes be stopped and removed. By default, Camel will stop and remove all existing routes before reloading routes. This ensures that only the reloaded routes will be active. If disabled then only routes with the same route id is updated, and any existing routes are continued to run. | true | boolean | *camel.main.routesReloadRestart{zwsp}Duration* | Whether to restart max duration when routes are reloaded. For example if max duration is 60 seconds, and a route is reloaded after 25 seconds, then this will restart the count and wait 60 seconds again. | true | boolean | *camel.main.shutdownLogInflight{zwsp}ExchangesOnTimeout* | Sets whether to log information about the inflight Exchanges which are still running during a shutdown which didn't complete without the given timeout. This requires to enable the option inflightRepositoryBrowseEnabled. | true | boolean | *camel.main.shutdownNowOn{zwsp}Timeout* | Sets whether to force shutdown of all consumers when a timeout occurred and thus not all consumers was shutdown within that period. You should have good reasons to set this option to false as it means that the routes keep running and is halted abruptly when CamelContext has been shutdown. | true | boolean | *camel.main.shutdownRoutesIn{zwsp}ReverseOrder* | Sets whether routes should be shutdown in reverse or the same order as they were started. | true | boolean | *camel.main.shutdownSuppress{zwsp}LoggingOnTimeout* | Whether Camel should try to suppress logging during shutdown and timeout was triggered, meaning forced shutdown is happening. And during forced shutdown we want to avoid logging errors/warnings et all in the logs as a side-effect of the forced timeout. Notice the suppress is a best effort as there may still be some logs coming from 3rd party libraries and whatnot, which Camel cannot control. This option is default false. | false | boolean | *camel.main.shutdownTimeout* | Timeout in seconds to graceful shutdown all the Camel routes. | 45 | int | *camel.main.sourceLocation{zwsp}Enabled* | Whether to capture precise source location:line-number for all EIPs in Camel routes. Enabling this will impact parsing Java based routes (also Groovy, Kotlin, etc.) on startup as this uses JDK StackTraceElement to calculate the location from the Camel route, which comes with a performance cost. This only impact startup, not the performance of the routes at runtime. | false | boolean | *camel.main.startupRecorder* | To use startup recorder for capturing execution time during starting Camel. The recorder can be one of: false (or off), logging, java-flight-recorder (or jfr). | | String | *camel.main.startupRecorderDir* | Directory to store the recording. By default the current directory will be used. Use false to turn off saving recording to disk. | | String | *camel.main.startupRecorder{zwsp}Duration* | How long time to run the startup recorder. Use 0 (default) to keep the recorder running until the JVM is exited. Use -1 to stop the recorder right after Camel has been started (to only focus on potential Camel startup performance bottlenecks) Use a positive value to keep recording for N seconds. When the recorder is stopped then the recording is auto saved to disk (note: save to disk can be disabled by setting startupRecorderDir to false) | | long | *camel.main.startupRecorderMax{zwsp}Depth* | To filter our sub steps at a maximum depth. Use -1 for no maximum. Use 0 for no sub steps. Use 1 for max 1 sub step, and so forth. The default is -1. | -1 | int | *camel.main.startupRecorder{zwsp}Profile* | To use a specific Java Flight Recorder profile configuration, such as default or profile. The default is default. | default | String | *camel.main.startupRecorder{zwsp}Recording* | To enable Java Flight Recorder to start a recording and automatic dump the recording to disk after startup is complete. This requires that camel-jfr is on the classpath, and to enable this option. | false | boolean | *camel.main.startupSummaryLevel* | Controls the level of information logged during startup (and shutdown) of CamelContext. | Default | StartupSummaryLevel | *camel.main.streamCachingAny{zwsp}SpoolRules* | Sets whether if just any of the org.apache.camel.spi.StreamCachingStrategy.SpoolRule rules returns true then shouldSpoolCache(long) returns true, to allow spooling to disk. If this option is false, then all the org.apache.camel.spi.StreamCachingStrategy.SpoolRule must return true. The default value is false which means that all the rules must return true. | false | boolean | *camel.main.streamCachingBuffer{zwsp}Size* | Sets the stream caching buffer size to use when allocating in-memory buffers used for in-memory stream caches. The default size is 4096. | | int | *camel.main.streamCaching{zwsp}Enabled* | Sets whether stream caching is enabled or not. Default is false. | false | boolean | *camel.main.streamCachingRemove{zwsp}SpoolDirectoryWhenStopping* | Whether to remove stream caching temporary directory when stopping. This option is default true. | true | boolean | *camel.main.streamCachingSpool{zwsp}Cipher* | Sets a stream caching cipher name to use when spooling to disk to write with encryption. By default the data is not encrypted. | | String | *camel.main.streamCachingSpool{zwsp}Directory* | Sets the stream caching spool (temporary) directory to use for overflow and spooling to disk. If no spool directory has been explicit configured, then a temporary directory is created in the java.io.tmpdir directory. | | String | *camel.main.streamCachingSpool{zwsp}Threshold* | Stream caching threshold in bytes when overflow to disk is activated. The default threshold is 128kb. Use -1 to disable overflow to disk. | | long | *camel.main.streamCachingSpool{zwsp}UsedHeapMemoryLimit* | Sets what the upper bounds should be when streamCachingSpoolUsedHeapMemoryThreshold is in use. | | String | *camel.main.streamCachingSpool{zwsp}UsedHeapMemoryThreshold* | Sets a percentage (1-99) of used heap memory threshold to activate stream caching spooling to disk. | | int | *camel.main.streamCaching{zwsp}StatisticsEnabled* | Sets whether stream caching statistics is enabled. | false | boolean | *camel.main.threadNamePattern* | Sets the thread name pattern used for creating the full thread name. The default pattern is: Camel (#camelId#) thread ##counter# - #name# Where #camelId# is the name of the CamelContext. and #counter# is a unique incrementing counter. and #name# is the regular thread name. You can also use #longName# which is the long thread name which can includes endpoint parameters etc. | | String | *camel.main.tracing* | Sets whether tracing is enabled or not. Default is false. | false | boolean | *camel.main.tracingLogging{zwsp}Format* | To use a custom tracing logging format. The default format (arrow, routeId, label) is: %-4.4s %-12.12s %-33.33s | %-4.4s [%-12.12s] [%-33.33s] | String | *camel.main.tracingPattern* | Tracing pattern to match which node EIPs to trace. For example to match all To EIP nodes, use to. The pattern matches by node and route id's Multiple patterns can be separated by comma. | | String | *camel.main.tracingStandby* | Whether to set tracing on standby. If on standby then the tracer is installed and made available. Then the tracer can be enabled later at runtime via JMX or via Tracer#setEnabled(boolean) . | false | boolean | *camel.main.useBreadcrumb* | Set whether breadcrumb is enabled. The default value is false. | false | boolean | *camel.main.useDataType* | Whether to enable using data type on Camel messages. Data type are automatic turned on if one ore more routes has been explicit configured with input and output types. Otherwise data type is default off. | false | boolean | *camel.main.useMdcLogging* | To turn on MDC logging | false | boolean | *camel.main.uuidGenerator* | UUID generator to use. default (32 bytes), short (16 bytes), classic (32 bytes or longer), simple (long incrementing counter), off (turned off for exchanges - only intended for performance profiling) | default | String |=== === Camel Thread Pool configurations The camel.threadpool supports 8 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.threadpool.allowCore{zwsp}ThreadTimeOut* | Sets default whether to allow core threads to timeout | false | Boolean | *camel.threadpool.config* | Adds a configuration for a specific thread pool profile (inherits default values) | | Map | *camel.threadpool.keepAliveTime* | Sets the default keep alive time for inactive threads | | Long | *camel.threadpool.maxPoolSize* | Sets the default maximum pool size | | Integer | *camel.threadpool.maxQueueSize* | Sets the default maximum number of tasks in the work queue. Use -1 or an unbounded queue | | Integer | *camel.threadpool.poolSize* | Sets the default core pool size (threads to keep minimum in pool) | | Integer | *camel.threadpool.rejected{zwsp}Policy* | Sets the default handler for tasks which cannot be executed by the thread pool. | | ThreadPoolRejectedPolicy | *camel.threadpool.timeUnit* | Sets the default time unit used for keep alive time | | TimeUnit |=== === Camel Health Check configurations The camel.health supports 7 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.health.consumersEnabled* | Whether consumers health check is enabled | true | Boolean | *camel.health.enabled* | Whether health check is enabled globally | true | Boolean | *camel.health.excludePattern* | Pattern to exclude health checks from being invoked by Camel when checking healths. Multiple patterns can be separated by comma. | | String | *camel.health.exposureLevel* | Sets the level of details to exposure as result of invoking health checks. There are the following levels: full, default, oneline The full level will include all details and status from all the invoked health checks. The default level will report UP if everything is okay, and only include detailed information for health checks that was DOWN. The oneline level will only report either UP or DOWN. | default | String | *camel.health.initialState* | The initial state of health-checks (readiness). There are the following states: UP, DOWN, UNKNOWN. By default, the state is DOWN, is regarded as being pessimistic/careful. This means that the overall health checks may report as DOWN during startup and then only if everything is up and running flip to being UP. Setting the initial state to UP, is regarded as being optimistic. This means that the overall health checks may report as UP during startup and then if a consumer or other service is in fact un-healthy, then the health-checks can flip being DOWN. Setting the state to UNKNOWN means that some health-check would be reported in unknown state, especially during early bootstrap where a consumer may not be fully initialized or validated a connection to a remote system. This option allows to pre-configure the state for different modes. | down | String | *camel.health.registryEnabled* | Whether registry health check is enabled | true | Boolean | *camel.health.routesEnabled* | Whether routes health check is enabled | true | Boolean |=== === Camel Rest-DSL configurations The camel.rest supports 25 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.rest.apiComponent* | Sets the name of the Camel component to use as the REST API (such as swagger or openapi) | | String | *camel.rest.apiContextPath* | Sets a leading API context-path the REST API services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. | | String | *camel.rest.apiHost* | To use a specific hostname for the API documentation (such as swagger or openapi) This can be used to override the generated host with this configured hostname | | String | *camel.rest.apiProperties* | Sets additional options on api level | | Map | *camel.rest.apiVendorExtension* | Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information as vendor extension (eg keys starting with x-) such as route ids, class names etc. Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. | false | boolean | *camel.rest.bindingMode* | Sets the binding mode to be used by the REST consumer | RestBindingMode.off | RestBindingMode | *camel.rest.clientRequest{zwsp}Validation* | Whether to enable validation of the client request to check: 1) Content-Type header matches what the Rest DSL consumes; returns HTTP Status 415 if validation error. 2) Accept header matches what the Rest DSL produces; returns HTTP Status 406 if validation error. 3) Missing required data (query parameters, HTTP headers, body); returns HTTP Status 400 if validation error. 4) Parsing error of the message body (JSon, XML or Auto binding mode must be enabled); returns HTTP Status 400 if validation error. | false | boolean | *camel.rest.component* | Sets the name of the Camel component to use as the REST consumer | | String | *camel.rest.componentProperties* | Sets additional options on component level | | Map | *camel.rest.consumerProperties* | Sets additional options on consumer level | | Map | *camel.rest.contextPath* | Sets a leading context-path the REST services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. Or for components such as camel-jetty or camel-netty-http that includes a HTTP server. | | String | *camel.rest.corsHeaders* | Sets the CORS headers to use if CORS has been enabled. | | Map | *camel.rest.dataFormat{zwsp}Properties* | Sets additional options on data format level | | Map | *camel.rest.enableCORS* | To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. This option is default false | false | boolean | *camel.rest.endpointProperties* | Sets additional options on endpoint level | | Map | *camel.rest.host* | Sets the hostname to use by the REST consumer | | String | *camel.rest.hostNameResolver* | Sets the resolver to use for resolving hostname | RestHostNameResolver.allLocalIp | RestHostNameResolver | *camel.rest.jsonDataFormat* | Sets a custom json data format to be used Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. | | String | *camel.rest.port* | Sets the port to use by the REST consumer | | int | *camel.rest.producerApiDoc* | Sets the location of the api document (swagger api) the REST producer will use to validate the REST uri and query parameters are valid accordingly to the api document. This requires adding camel-swagger-java to the classpath, and any miss configuration will let Camel fail on startup and report the error(s). The location of the api document is loaded from classpath by default, but you can use file: or http: to refer to resources to load from file or http url. | | String | *camel.rest.producerComponent* | Sets the name of the Camel component to use as the REST producer | | String | *camel.rest.scheme* | Sets the scheme to use by the REST consumer | | String | *camel.rest.skipBindingOnError{zwsp}Code* | Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. This option is default true. | true | boolean | *camel.rest.useXForwardHeaders* | Whether to use X-Forward headers to set host etc. for Swagger. This option is default true. | true | boolean | *camel.rest.xmlDataFormat* | Sets a custom xml data format to be used. Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. | | String |=== === Camel AWS Vault configurations The camel.vault.aws supports 4 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.vault.aws.accessKey* | The AWS access key | | String | *camel.vault.aws.default{zwsp}CredentialsProvider* | Define if we want to use the AWS Default Credentials Provider or not | false | boolean | *camel.vault.aws.region* | The AWS region | | String | *camel.vault.aws.secretKey* | The AWS secret key | | String |=== === Camel GCP Vault configurations The camel.vault.gcp supports 3 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.vault.gcp.projectId* | The GCP Project ID | | String | *camel.vault.gcp.serviceAccount{zwsp}Key* | The Service Account Key location | | String | *camel.vault.gcp.useDefault{zwsp}Instance* | Define if we want to use the GCP Client Default Instance or not | false | boolean |=== === Camel Azure Key Vault configurations The camel.vault.azure supports 4 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.vault.azure.clientId* | The client Id for accessing Azure Key Vault | | String | *camel.vault.azure.clientSecret* | The client Secret for accessing Azure Key Vault | | String | *camel.vault.azure.tenantId* | The Tenant Id for accessing Azure Key Vault | | String | *camel.vault.azure.vaultName* | The vault Name in Azure Key Vault | | String |=== === Fault Tolerance EIP Circuit Breaker configurations The camel.faulttolerance supports 13 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.faulttolerance.bulkhead{zwsp}Enabled* | Whether bulkhead is enabled or not on the circuit breaker. Default is false. | false | Boolean | *camel.faulttolerance.bulkhead{zwsp}ExecutorService* | References to a custom thread pool to use when bulkhead is enabled. | | String | *camel.faulttolerance.bulkhead{zwsp}MaxConcurrentCalls* | Configures the max amount of concurrent calls the bulkhead will support. Default value is 10. | 10 | Integer | *camel.faulttolerance.bulkhead{zwsp}WaitingTaskQueue* | Configures the task queue size for holding waiting tasks to be processed by the bulkhead. Default value is 10. | 10 | Integer | *camel.faulttolerance.circuit{zwsp}Breaker* | Refers to an existing io.smallrye.faulttolerance.core.circuit.breaker.CircuitBreaker instance to lookup and use from the registry. When using this, then any other circuit breaker options are not in use. | | String | *camel.faulttolerance.delay* | Control how long the circuit breaker stays open. The value are in seconds and the default is 5 seconds. | 5 | Long | *camel.faulttolerance.failure{zwsp}Ratio* | Configures the failure rate threshold in percentage. If the failure rate is equal or greater than the threshold the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 50 percentage. | 50 | Integer | *camel.faulttolerance.request{zwsp}VolumeThreshold* | Controls the size of the rolling window used when the circuit breaker is closed Default value is 20. | 20 | Integer | *camel.faulttolerance.success{zwsp}Threshold* | Controls the number of trial calls which are allowed when the circuit breaker is half-open Default value is 1. | 1 | Integer | *camel.faulttolerance.timeout{zwsp}Duration* | Configures the thread execution timeout. Default value is 1000 milliseconds. | 1000 | Long | *camel.faulttolerance.timeout{zwsp}Enabled* | Whether timeout is enabled or not on the circuit breaker. Default is false. | false | Boolean | *camel.faulttolerance.timeout{zwsp}PoolSize* | Configures the pool size of the thread pool when timeout is enabled. Default value is 10. | 10 | Integer | *camel.faulttolerance.timeout{zwsp}ScheduledExecutorService* | References to a custom thread pool to use when timeout is enabled | | String |=== === Resilience4j EIP Circuit Breaker configurations The camel.resilience4j supports 19 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.resilience4j.automatic{zwsp}TransitionFromOpenToHalfOpen{zwsp}Enabled* | Enables automatic transition from OPEN to HALF_OPEN state once the waitDurationInOpenState has passed. | false | Boolean | *camel.resilience4j.bulkhead{zwsp}Enabled* | Whether bulkhead is enabled or not on the circuit breaker. | false | Boolean | *camel.resilience4j.bulkheadMax{zwsp}ConcurrentCalls* | Configures the max amount of concurrent calls the bulkhead will support. | | Integer | *camel.resilience4j.bulkheadMax{zwsp}WaitDuration* | Configures a maximum amount of time which the calling thread will wait to enter the bulkhead. If bulkhead has space available, entry is guaranteed and immediate. If bulkhead is full, calling threads will contest for space, if it becomes available. maxWaitDuration can be set to 0. Note: for threads running on an event-loop or equivalent (rx computation pool, etc), setting maxWaitDuration to 0 is highly recommended. Blocking an event-loop thread will most likely have a negative effect on application throughput. | | Integer | *camel.resilience4j.circuit{zwsp}Breaker* | Refers to an existing io.github.resilience4j.circuitbreaker.CircuitBreaker instance to lookup and use from the registry. When using this, then any other circuit breaker options are not in use. | | String | *camel.resilience4j.config* | Refers to an existing io.github.resilience4j.circuitbreaker.CircuitBreakerConfig instance to lookup and use from the registry. | | String | *camel.resilience4j.failureRate{zwsp}Threshold* | Configures the failure rate threshold in percentage. If the failure rate is equal or greater than the threshold the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 50 percentage. | 50 | Float | *camel.resilience4j.minimum{zwsp}NumberOfCalls* | Configures configures the minimum number of calls which are required (per sliding window period) before the CircuitBreaker can calculate the error rate. For example, if minimumNumberOfCalls is 10, then at least 10 calls must be recorded, before the failure rate can be calculated. If only 9 calls have been recorded the CircuitBreaker will not transition to open even if all 9 calls have failed. Default minimumNumberOfCalls is 100 | 100 | Integer | *camel.resilience4j.permitted{zwsp}NumberOfCallsInHalfOpenState* | Configures the number of permitted calls when the CircuitBreaker is half open. The size must be greater than 0. Default size is 10. | 10 | Integer | *camel.resilience4j.sliding{zwsp}WindowSize* | Configures the size of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed. slidingWindowSize configures the size of the sliding window. Sliding window can either be count-based or time-based. If slidingWindowType is COUNT_BASED, the last slidingWindowSize calls are recorded and aggregated. If slidingWindowType is TIME_BASED, the calls of the last slidingWindowSize seconds are recorded and aggregated. The slidingWindowSize must be greater than 0. The minimumNumberOfCalls must be greater than 0. If the slidingWindowType is COUNT_BASED, the minimumNumberOfCalls cannot be greater than slidingWindowSize . If the slidingWindowType is TIME_BASED, you can pick whatever you want. Default slidingWindowSize is 100. | 100 | Integer | *camel.resilience4j.sliding{zwsp}WindowType* | Configures the type of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed. Sliding window can either be count-based or time-based. If slidingWindowType is COUNT_BASED, the last slidingWindowSize calls are recorded and aggregated. If slidingWindowType is TIME_BASED, the calls of the last slidingWindowSize seconds are recorded and aggregated. Default slidingWindowType is COUNT_BASED. | COUNT_BASED | String | *camel.resilience4j.slowCall{zwsp}DurationThreshold* | Configures the duration threshold (seconds) above which calls are considered as slow and increase the slow calls percentage. Default value is 60 seconds. | 60 | Integer | *camel.resilience4j.slowCall{zwsp}RateThreshold* | Configures a threshold in percentage. The CircuitBreaker considers a call as slow when the call duration is greater than slowCallDurationThreshold(Duration. When the percentage of slow calls is equal or greater the threshold, the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 100 percentage which means that all recorded calls must be slower than slowCallDurationThreshold. | 100 | Float | *camel.resilience4j.timeout{zwsp}CancelRunningFuture* | Configures whether cancel is called on the running future. Defaults to true. | true | Boolean | *camel.resilience4j.timeout{zwsp}Duration* | Configures the thread execution timeout (millis). Default value is 1000 millis (1 second). | 1000 | Integer | *camel.resilience4j.timeout{zwsp}Enabled* | Whether timeout is enabled or not on the circuit breaker. Default is false. | false | Boolean | *camel.resilience4j.timeout{zwsp}ExecutorService* | References to a custom thread pool to use when timeout is enabled (uses ForkJoinPool#commonPool() by default) | | String | *camel.resilience4j.wait{zwsp}DurationInOpenState* | Configures the wait duration (in seconds) which specifies how long the CircuitBreaker should stay open, before it switches to half open. Default value is 60 seconds. | 60 | Integer | *camel.resilience4j.writable{zwsp}StackTraceEnabled* | Enables writable stack traces. When set to false, Exception.getStackTrace returns a zero length array. This may be used to reduce log spam when the circuit breaker is open as the cause of the exceptions is already known (the circuit breaker is short-circuiting calls). | false | Boolean |=== === Hystrix (deprecated) EIP Circuit Breaker configurations The camel.hystrix supports 31 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.hystrix.allowMaximumSize{zwsp}ToDivergeFromCoreSize* | Allows the configuration for maximumSize to take effect. That value can then be equal to, or higher, than coreSize | false | Boolean | *camel.hystrix.circuitBreaker{zwsp}Enabled* | Whether to use a HystrixCircuitBreaker or not. If false no circuit-breaker logic will be used and all requests permitted. This is similar in effect to circuitBreakerForceClosed() except that continues tracking metrics and knowing whether it should be open/closed, this property results in not even instantiating a circuit-breaker. | false | Boolean | *camel.hystrix.circuitBreaker{zwsp}ErrorThresholdPercentage* | Error percentage threshold (as whole number such as 50) at which point the circuit breaker will trip open and reject requests. It will stay tripped for the duration defined in circuitBreakerSleepWindowInMilliseconds; The error percentage this is compared against comes from HystrixCommandMetrics.getHealthCounts(). | | Integer | *camel.hystrix.circuitBreaker{zwsp}ForceClosed* | If true the HystrixCircuitBreaker#allowRequest() will always return true to allow requests regardless of the error percentage from HystrixCommandMetrics.getHealthCounts(). The circuitBreakerForceOpen() property takes precedence so if it set to true this property does nothing. | false | Boolean | *camel.hystrix.circuitBreaker{zwsp}ForceOpen* | If true the HystrixCircuitBreaker.allowRequest() will always return false, causing the circuit to be open (tripped) and reject all requests. This property takes precedence over circuitBreakerForceClosed(); | false | Boolean | *camel.hystrix.circuitBreaker{zwsp}RequestVolumeThreshold* | Minimum number of requests in the metricsRollingStatisticalWindowInMilliseconds() that must exist before the HystrixCircuitBreaker will trip. If below this number the circuit will not trip regardless of error percentage. | | Integer | *camel.hystrix.circuitBreaker{zwsp}SleepWindowInMilliseconds* | The time in milliseconds after a HystrixCircuitBreaker trips open that it should wait before trying requests again. | | Integer | *camel.hystrix.corePoolSize* | Core thread-pool size that gets passed to java.util.concurrent.ThreadPoolExecutor#setCorePoolSize(int) | | Integer | *camel.hystrix.execution{zwsp}IsolationSemaphoreMax{zwsp}ConcurrentRequests* | Number of concurrent requests permitted to HystrixCommand.run(). Requests beyond the concurrent limit will be rejected. Applicable only when executionIsolationStrategy == SEMAPHORE. | | Integer | *camel.hystrix.execution{zwsp}IsolationStrategy* | What isolation strategy HystrixCommand.run() will be executed with. If THREAD then it will be executed on a separate thread and concurrent requests limited by the number of threads in the thread-pool. If SEMAPHORE then it will be executed on the calling thread and concurrent requests limited by the semaphore count. | | String | *camel.hystrix.execution{zwsp}IsolationThreadInterruptOn{zwsp}Timeout* | Whether the execution thread should attempt an interrupt (using Future#cancel ) when a thread times out. Applicable only when executionIsolationStrategy() == THREAD. | false | Boolean | *camel.hystrix.executionTimeout{zwsp}Enabled* | Whether the timeout mechanism is enabled for this command | false | Boolean | *camel.hystrix.executionTimeout{zwsp}InMilliseconds* | Time in milliseconds at which point the command will timeout and halt execution. If executionIsolationThreadInterruptOnTimeout == true and the command is thread-isolated, the executing thread will be interrupted. If the command is semaphore-isolated and a HystrixObservableCommand, that command will get unsubscribed. | | Integer | *camel.hystrix.fallbackEnabled* | Whether HystrixCommand.getFallback() should be attempted when failure occurs. | false | Boolean | *camel.hystrix.fallback{zwsp}IsolationSemaphoreMax{zwsp}ConcurrentRequests* | Number of concurrent requests permitted to HystrixCommand.getFallback(). Requests beyond the concurrent limit will fail-fast and not attempt retrieving a fallback. | | Integer | *camel.hystrix.groupKey* | Sets the group key to use. The default value is CamelHystrix. | | String | *camel.hystrix.keepAliveTime* | Keep-alive time in minutes that gets passed to ThreadPoolExecutor#setKeepAliveTime(long,TimeUnit) | | Integer | *camel.hystrix.maximumSize* | Maximum thread-pool size that gets passed to ThreadPoolExecutor#setMaximumPoolSize(int) . This is the maximum amount of concurrency that can be supported without starting to reject HystrixCommands. Please note that this setting only takes effect if you also set allowMaximumSizeToDivergeFromCoreSize | | Integer | *camel.hystrix.maxQueueSize* | Max queue size that gets passed to BlockingQueue in HystrixConcurrencyStrategy.getBlockingQueue(int) This should only affect the instantiation of a threadpool - it is not eliglible to change a queue size on the fly. For that, use queueSizeRejectionThreshold(). | | Integer | *camel.hystrix.metricsHealth{zwsp}SnapshotIntervalInMilliseconds* | Time in milliseconds to wait between allowing health snapshots to be taken that calculate success and error percentages and affect HystrixCircuitBreaker.isOpen() status. On high-volume circuits the continual calculation of error percentage can become CPU intensive thus this controls how often it is calculated. | | Integer | *camel.hystrix.metricsRolling{zwsp}PercentileBucketSize* | Maximum number of values stored in each bucket of the rolling percentile. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}PercentileEnabled* | Whether percentile metrics should be captured using HystrixRollingPercentile inside HystrixCommandMetrics. | false | Boolean | *camel.hystrix.metricsRolling{zwsp}PercentileWindowBuckets* | Number of buckets the rolling percentile window is broken into. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}PercentileWindowInMilliseconds* | Duration of percentile rolling window in milliseconds. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}StatisticalWindowBuckets* | Number of buckets the rolling statistical window is broken into. This is passed into HystrixRollingNumber inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}StatisticalWindowIn{zwsp}Milliseconds* | This property sets the duration of the statistical rolling window, in milliseconds. This is how long metrics are kept for the thread pool. The window is divided into buckets and rolls by those increments. | | Integer | *camel.hystrix.queueSize{zwsp}RejectionThreshold* | Queue size rejection threshold is an artificial max size at which rejections will occur even if maxQueueSize has not been reached. This is done because the maxQueueSize of a BlockingQueue can not be dynamically changed and we want to support dynamically changing the queue size that affects rejections. This is used by HystrixCommand when queuing a thread for execution. | | Integer | *camel.hystrix.requestLog{zwsp}Enabled* | Whether HystrixCommand execution and events should be logged to HystrixRequestLog. | false | Boolean | *camel.hystrix.threadPoolKey* | Sets the thread pool key to use. Will by default use the same value as groupKey has been configured to use. | | String | *camel.hystrix.threadPool{zwsp}RollingNumberStatisticalWindow{zwsp}Buckets* | Number of buckets the rolling statistical window is broken into. This is passed into HystrixRollingNumber inside each HystrixThreadPoolMetrics instance. | | Integer | *camel.hystrix.threadPool{zwsp}RollingNumberStatisticalWindow{zwsp}InMilliseconds* | Duration of statistical rolling window in milliseconds. This is passed into HystrixRollingNumber inside each HystrixThreadPoolMetrics instance. | | Integer |=== === Camel Saga EIP (Long Running Actions) configurations The camel.lra supports 4 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.lra.coordinatorContext{zwsp}Path* | The context-path for the LRA coordinator. Is default /lra-coordinator | /lra-coordinator | String | *camel.lra.coordinatorUrl* | The URL for the LRA coordinator service that orchestrates the transactions | | String | *camel.lra.localParticipant{zwsp}ContextPath* | The context-path for the local participant. Is default /lra-participant | /lra-participant | String | *camel.lra.localParticipantUrl* | The URL for the local participant | | String |=== // main options: END == Package Scanning *Available since Camel 3.16* When running Camel standalone via `camel-main` JAR, then Camel will use package scanning to discover: - Camel routes by discovering `RouteBuilder` classes - Camel configuration classes by discovering `CamelConfiguration` classes or classes annotated with `@Configuration`. - Camel type converters by discovering classes annotated with `@Converter` To use package scanning then Camel needs to know the base package to use as _offset_. This can be specified either with the `camel.main.basePackage` option or via `Main` class as shown below: [source,java] ---- package com.foo.acme; public class MyCoolApplication { public static void main(String[] args) { Main main = new Main(MyCoolApplication.class); main.run(); } } ---- In the example above, then we use `com.foo.acme` as the base package, which is done by passing in the class in the `Main` constructor. This is similar with how Spring Boot does this. Camel will then scan from the base package and the sub packages. === Disabling Package Scanning Package scanning can be turned off by setting `camel.main.basePackageScanEnabled=false`. There is a little overhead when using package scanning as Camel performs this scan during startup. == Configuring Camel Main applications You can use _configuration_ classes to configure Camel Main applications from Java. IMPORTANT: In *Camel 3.16* onwards the configuration classes must either implement the interface `org.apache.camel.CamelConfiguration`, or be annotated with `@Configuration` (or both). In previous versions this was not required. For example to configure a Camel application by creating custom beans you can do: [source,java] ---- public class MyConfiguration implements CamelConfiguration { @BindToRegistry public MyBean myAwesomeBean() { MyBean bean = new MyBean(); // do something on bean return bean; } public void configure(CamelContext camelContext) throws Exception { // this method is optional and can be omitted // do any kind of configuration here if needed } } ---- In the configuration class you can also have custom methods that creates beans, such as the `myAwesomeBean` method that creates the `MyBean` and registers it with the name `myAwesomeBean` (defaults to method name). This is similar to Spring Boot where you can also do this with the Spring Boot `@Bean` annotations, or in Quarkus/CDI with the `@Produces` annotation. === Using annotation based configuration classes Instead of configuration classes that implements `CamelConfiguration`, you can annotate the class with `org.apache.camel.@Configuration` as shown: [source,java] ---- @Configuration public class MyConfiguration { @BindToRegistry public MyBean myAwesomeBean() { MyBean bean = new MyBean(); // do something on bean return bean; } } ---- == Specifying custom beans Custom beans can be configured in `camel-main` via properties (such as in the `application.properties` file). For example to create a `DataSource` for a Postgress database, you can create a new bean instance via `#class:` with the class name (fully qualified). Properties on the data source can then additional configured such as the server and database name, etc. [source,properties] ---- camel.beans.myDS = #class:org.postgresql.jdbc3.Jdbc3PoolingDataSource camel.beans.myDS.dataSourceName = myDS camel.beans.myDS.serverName = mypostrgress camel.beans.myDS.databaseName = test camel.beans.myDS.user = testuser camel.beans.myDS.password = testpassword camel.beans.myDS.maxConnections = 10 ---- The bean is registered in the Camel Registry with the name `myDS`. If you use the SQL component then the datasource can be configured on the SQL component: [source,properties] ---- camel.component.sql.dataSource = #myDS ---- To refer to a custom bean you may want to favour using `#bean:` style, as this states the intention more clearly that its referring to a bean, and not just a text value that happens to start with a `+#+` sign: [source,properties] ---- camel.component.sql.dataSource = #bean:myDS ---- === Creating a custom map bean When creating a bean as a `java.util.Map` type, then you can use the `[]` syntax as shown below: [source,properties] ---- camel.beans.myApp[id] = 123 camel.beans.myApp[name] = Demo App camel.beans.myApp[version] = 1.0.1 camel.beans.myApp[username] = goofy ---- Camel will then create this as a `LinkedHashMap` type with the name `myApp` which is bound to the Camel xref:manual:ROOT:registry.adoc[Registry], with the data defined in the properties. If you desire a different `java.util.Map` implementation, then you can use `#class` style as shown: [source,properties] ---- camel.beans.myApp = #class:com.foo.MyMapImplementation camel.beans.myApp[id] = 123 camel.beans.myApp[name] = Demo App camel.beans.myApp[version] = 1.0.1 camel.beans.myApp[username] = goofy ---- === Creating a custom bean with constructor parameters When creating a bean then parameters to the constructor can be provided. Suppose we have a class `MyFoo` with a constructor: [source,java] ---- public class MyFoo { private String name; private boolean important; private int id; public MyFoo(String name, boolean important, int id) { this.name = name; this.important = important; this.id = id; } } ---- Then we can create a bean instance with name `foo` and provide parameters to the constructor as shown: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean(""Hello World"", true, 123) ---- === Creating custom beans with factory method When creating a bean then parameters to a factorty method can be provided. Suppose we have a class `MyFoo` with a static factory method: [source,java] ---- public class MyFoo { private String name; private boolean important; private int id; private MyFoo() { // use factory method } public static MyFoo buildFoo(String name, boolean important, int id) { MyFoo foo = new MyFoo(); foo.name = name; foo.important = important; foo.id = id; return foo; } } ---- Then we can create a bean instance with name `foo` and provide parameters to the static factory method as shown: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean#buildFoo(""Hello World"", true, 123) ---- IMPORTANT: The syntax must use `#factoryMethodName` to tell Camel that the bean should be created from a factory method. === Optional parameters on beans If a parameter on a bean is not mandatory then the parameter can be marked as optional using `?` syntax, as shown: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean(""Hello World"", true, 123) camel.beans.foo.?company = Acme ---- Then the company parameter is only set if `MyBean` has this option (silent ignore if no option present). Otherwise, if a parameter is set, and the bean does not have such a parameter, then an exception is thrown by Camel. === Optional parameter values on beans If a parameter value on a bean is configured using xref:manual:ROOT:using-propertyplaceholder.adoc[Property Placeholder] and the placeholder is optional, then the placeholder can be marked as optional using `?` syntax, as shown: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean(""Hello World"", true, 123) camel.beans.foo.company = {{?companyName}} ---- Then the company parameter is only set if there is a property placeholder with the key _companyName_ (silent ignore if no option present). ==== Default parameter values on beans It is possible to supply a default value (using `:defaultValue`) if the placeholder does not exist as shown: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean(""Hello World"", true, 123) camel.beans.foo.company = {{?companyName:Acme}} ---- Here the default value is _Acme_ that will be used if there is no property placeholder with the key _companyName_. === Nested parameters on beans You can configure nested parameters separating them via `.` (dot). For example given this `Country` class: [source,java] ---- public class Country { private String iso; private String name; public void setIso(String iso) { this.iso = iso; } public void setName(String name) { this.name = name; } } ---- Which is an option on the `MyBean` class. Then we can then configure its iso and name parameter as shown below: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean(""Hello World"", true, 123) camel.beans.foo.country.iso = USA camel.beans.foo.country.name = United States of America ---- Camel will automatically create an instance of `Country` if `MyBean` has a getter/setter for this option, and that the `Country` bean has a default no-arg constructor. === Configuring singleton beans by their type In the example above the SQL component was configured with the name of the `DataSource`. There can be situations where you know there is only a single instance of a data source in the Camel registry. In such a situation you can instead refer to the class or interface type via the `#type:` prefix as shown below: [source,properties] ---- camel.component.sql.dataSource = #type:javax.sql.DataSource ---- If there is no bean in the registry with the type `javax.sql.DataSource` then the option isn't configured. === Autowiring beans The example above can be taken one step further by letting `camel-main` try to autowire the beans. [source,properties] ---- camel.component.sql.dataSource = #autowired ---- In this situation then `#autowrired` will make Camel detect the type of the `dataSource` option on the `SQL` component. Because type is a `javax.sql.DataSource` instance, then Camel will lookup in the registry if there is a single instance of the same type. If there is no such bean then the option isn't configured. == Defining a Map bean You can specify `java.util.Map` beans in `camel-main` via properties (such as in the `application.properties` file). Maps have a special syntax with brackets as shown below: [source,properties] ---- camel.beans.mymap[table] = 12 camel.beans.mymap[food] = Big Burger camel.beans.mymap[cheese] = yes camel.beans.mymap[quantity] = 1 ---- The Map is registered in the Camel Registry with the name `mymap`. == Defining a List bean This is similar to Map bean where the key is the index, eg 0, 1, 2, etc: [source,properties] ---- camel.beans.myprojects[0] = Camel camel.beans.myprojects[1] = Kafka camel.beans.myprojects[2] = Quarkus ---- The List is registered in the Camel Registry with the name `myprojects`. == Examples You can find a set of examples using `camel-main` in https://github.com/apache/camel-examples[Camel Examples] which demonstrate running Camel in standalone with `camel-main`. ",16230,False,2441.146648351092,median "= bpftrace(8) :doctype: manpage :toc: true //// Style guide: - one sentence per line //// == Name bpftrace - a high-level tracing language == Synopsis *bpftrace* [_OPTIONS_] _FILENAME_ + *bpftrace* [_OPTIONS_] -e 'program code' == Description bpftrace is a high-level tracing language and runtime for Linux based on BPF. It supports static and dynamic tracing for both the kernel and user-space. When _FILENAME_ is ""_-_"", read from stdin. == Examples List all probes with ""sleep"" in their name:: ---- # bpftrace -l '*sleep*' ---- Trace processes calling sleep:: ---- # bpftrace -e 'kprobe:do_nanosleep { printf(""%d sleeping\\n"", pid); }' ---- Trace processes calling sleep while spawning `sleep 5` as a child process:: ---- # bpftrace -e 'kprobe:do_nanosleep { printf(""%d sleeping\\n"", pid); }' -c 'sleep 5' ---- == Supported architectures x86_64, arm64 and s390x == Options //// Custom prefix to easily link section //// :idprefix: flags_ === Output format *-B* _MODE_:: Set the buffer mode for stdout. Valid values are:: *none* No buffering. Each I/O is written as soon as possible + *line* Data is written on the first newline or when the buffer is full. This is the default mode. + *full* Data is written once the buffer is full. *-f* _FORMAT_:: Set the output format. Valid values are:: *json* + *text* *-o* _FILENAME_:: Write bpftrace tracing output to _FILENAME_ instead of stdout. This doesn't include child process (*-c* option) output. Errors are still written to stderr. *--no-warnings*:: Suppress all warning messages created by bpftrace. === Tracing *-e* _PROGRAM_:: Execute _PROGRAM_ instead of reading the program from a file *-I* _DIR_:: Add the directory _DIR_ to the search path for C headers. This option can be used multiple times. *--include* _FILENAME_:: Add _FILENAME_ as an include for the pre-processor. This is equal to adding '#include _FILENAME_' to the start bpftrace program. This option can be used multiple times. *-l* [_SEARCH_]:: List all probes that match the _SEARCH_ pattern. If the pattern is omitted all probes will be listed. This pattern supports wildcards in the same way that probes do. E.g. '-l kprobe:*file*' to list all 'kprobes' with 'file' in the name. For more details see the <> section. *--unsafe*:: Some calls, like 'system', are marked as unsafe as they can have dangerous side effects ('system(""rm -rf"")') and are disabled by default. This flag allows their use. *-k*:: Errors from bpf-helpers(7) are silently ignored by default which can lead to strange results. This flag enables the detection of errors (except for errors from 'probe_read_*'). When errors occurs bpftrace will log an error containing the source location and the error code: ---- stdin:48-57: WARNING: Failed to probe_read_user_str: Bad address (-14) u:lib.so:""fn(char const*)"" { printf(""arg0:%s\\n"", str(arg0));} ~~~~~~~~~ ---- *-kk*:: Same as '-k' but also includes the errors from 'probe_read_*' helpers. === Process management *-p* _PID_:: Attach to the process with _PID_. If the process terminates, bpftrace will also terminate. When using USDT probes they will be attached to only this process. *-c* _COMMAND_:: Run _COMMAND_ as a child process. When the child terminates bpftrace stops as well, as if 'exit()' has been called. If bpftrace terminates before the child process does the child process will be terminated with a SIGTERM. If used, 'USDT' probes these will only be attached to the child process. To avoid a race condition when using 'USDTs' the child is stopped after 'execve' using 'ptrace(2)' and continued when all 'USDT' probes are attached. + The child PID is available to programs as the 'cpid' builtin. + The child process runs with the same privileges as bpftrace itself (usually root). *--usdt-file-activation*:: activate usdt semaphores based on file path === Miscellaneous *--info*:: Print detailed information about features supported by the kernel and the bpftrace build. *-h, --help*:: Print the help summary *-V, --version*:: Print bpftrace version information *-v*:: verbose messages *-d*:: debug mode *-dd*:: verbose debug mode //// ! ! ! This prefix reset must be at the end of the section, else cross references break ! ! //// == Environment Variables Some behavior can only be controlled through environment variables. This section lists all those variables. //// Custom prefix to easily link section //// :idprefix: envvar_ === BPFTRACE_STRLEN Default: 64 Number of bytes allocated on the BPF stack for the string returned by `str()`. Make this larger if you wish to read bigger strings with str(). Beware that the BPF stack is small (512 bytes). Support for even larger strings is [being discussed](https://github.com/iovisor/bpftrace/issues/305). === BPFTRACE_NO_CPP_DEMANGLE Default: 0 C++ symbol demangling in user space stack traces is enabled by default. This feature can be turned off by setting the value of this environment variable to `1`. === BPFTRACE_MAP_KEYS_MAX Default: 4096 This is the maximum number of keys that can be stored in a map. Increasing the value will consume more memory and increase startup times. There are some cases where you will want to: for example, sampling stack traces, recording timestamps for each page, etc. === BPFTRACE_MAX_PROBES Default: 512 This is the maximum number of probes that bpftrace can attach to. Increasing the value will consume more memory, increase startup times and can incur high performance overhead or even freeze or crash the system. === BPFTRACE_CACHE_USER_SYMBOLS Default: 0 if ASLR is enabled on system and `-c` option is not given; otherwise 1 By default, bpftrace caches the results of symbols resolutions only when ASLR (Address Space Layout Randomization) is disabled. This is because the symbol addresses change with each execution with ASLR. However, disabling caching may incur some performance penalty. Set this env variable to 1 to force bpftrace to cache. === BPFTRACE_VMLINUX Default: None This specifies the vmlinux path used for kernel symbol resolution when attaching kprobe to offset. If this value is not given, bpftrace searches vmlinux from pre defined locations. See src/attached_probe.cpp:find_vmlinux() for details. === BPFTRACE_BTF Default: None The path to a BTF file. By default, bpftrace searches several locations to find a BTF file. See src/btf.cpp for the details. === BPFTRACE_PERF_RB_PAGES Default: 64 Number of pages to allocate per CPU for perf ring buffer. The value must be a power of 2. If you're getting a lot of dropped events bpftrace may not be processing events in the ring buffer fast enough. It may be useful to bump the value higher so more events can be queued up. The tradeoff is that bpftrace will use more memory. === BPFTRACE_MAX_BPF_PROGS Default: 512 This is the maximum number of BPF programs (functions) that bpftrace can generate. The main purpose of this limit is to prevent bpftrace from hanging since generating a lot of probes takes a lot of resources (and it should not happen often). //// ! ! ! This prefix reset must be at the end of the section, else cross references break ! ! //// :idprefix: _ //// Custom prefix to easily link to a section //// :idprefix: language_ == bpftrace Language === Overview The `bpftrace` (`bt`) language is inspired by the D language used by `dtrace` and uses the same program structure. Each script consists of an preamble and one or more action blocks. ---- preamble actionblock1 actionblock2 ---- Preprocessor and type definitions take place in the preamble: ---- #include #define RED ""\\033[31m"" struct S { int x; } ---- Each action block consists of three parts: ---- probe[,probe] /predicate/ { action } ---- Probes:: A probe specifies the event and event type to attach too. Predicate:: The predicate is optional condition that must be met for the action to be executed. Action:: Actions are the programs that run when an event fires (and the predicate is met). An action is a semicolon (`;`) separated list of statements and always enclosed by brackets `{}` A basic script that traces the `open(2)` and `openat(2)` system calls can be written as follows: ---- BEGIN { printf(""Tracing open syscalls... Hit Ctrl-C to end.\\n""); } tracepoint:syscalls:sys_enter_open, tracepoint:syscalls:sys_enter_openat { printf(""%-6d %-16s %s\\n"", pid, comm, str(args->filename)); } ---- This script has two action blocks and a total of 3 probes. The first action block uses the special `BEGIN` probe, which fires once during `bpftrace` startup. This probe is used to print a header, indicating that the tracing has started. The second action block uses two probes, one for `open` and one for `openat`, and defines an action that prints the file being `open` ed as well as the `pid` and `comm` of the process that execute the syscall. See the <> section for details on the available probe types. === Identifiers Identifiers must match the following regular expression: `[_a-zA-Z][_a-zA-Z0-9]*` === Comments Both single line and multi line comments are supported. ---- // A single line comment i:s:1 { // can also be used to comment inline /* a multi line comment */ print(/* inline comment block */ 1); } ---- === Data Types The following fundamental integer types are provided by the language. [cols=""~,~""] |=== |*Type* |*Description* |uint8 |Unsigned 8 bit integer |int8 |Signed 8 bit integer |uint16 |Unsigned 16 bit integer |int16 |Signed 16 bit integer |uint32 |Unsigned 32 bit integer |int32 |Signed 32 bit integer |uint64 |Unsigned 64 bit integer |int64 |Signed 64 bit integer |=== ==== Floating-point Floating-point numbers are not supported by BPF and therefore not by bpftrace. === Constants Integers constants can be defined in the following formats: - decimal (base 10) - octal (base 8) - hexadecimal (base 16) - scientific (base 10) Octal constants have to be prefixed with a `0`, e.g. `0123`. Hexadecimal constants start with either `0x` or `0X`, e.g. `0x10`. Scientific are written in the `e` format which is a shorthand for `m*10^n`, e.g. `$i = 2e3;`. Note that scientific literals are integer only due to the lack of floating point support, `1e-3` is not valid. To improve the readability of big literals a underscore `_` can be used as field separator, e.g. 1_000_123_000. Integer suffixes as found in the C language are parsed by bpftrace to ensure compatibility with C headers/definitions but they're not used as size specifiers. `123UL`, `123U` and `123LL` all result in the same integer type with a value of `123`. Character constants can be defined by enclosing the character in single quotes, e.g. `$c = 'c';`. String constants can be defined by enclosing the character string in double quotes, e.g. `$str = ""Hello world"";`. Characters and strings support the following escape sequences: [cols=""~,~""] |=== | \\n |Newline | \\t |Tab | \\0nn |Octal value nn | \\xnn |Hexadecimal value nn |=== === Type conversion Integer and pointer types can be converted using explicit type conversion with an expression like: ---- $y = (uint32) $z; $py = (int16 *) $pz; ---- Integer casts to a higher rank are sign extended. Conversion to a lower rank is done by zeroing leading bits. === Operators and Expressions ==== Arithmetic Operators The following operators are available for integer arithmetic: [cols=""~,~""] |=== | + |integer addition | - |integer subtraction | * |integer multiplication | / |integer division | % |integer modulo |=== // TODO: Words about integer conversion when types mismatch ==== Logical Operators [cols=""~,~""] |=== | && | Logical AND | \\|\\| | Logical OR | ! | Logical NOT |=== ==== Bitwise Operators [cols=""~,~""] |=== | & | AND | \\| | OR | ^ | XOR | << | Left shift the left-hand operand by the number of bits specified by the right-hand expression value | >> | Right shift the left-hand operand by the number of bits specified by the right-hand expression value |=== ==== Relational Operators The following relational operators are defined for integers and pointers. [cols=""~,~""] |=== | < | left-hand expression is less than right-hand | \\<= | left-hand expression is less than or equal to right-hand | > | left-hand expression is bigger than right-hand | >= | left-hand expression is bigger or equal to than right-hand | == | left-hand expression equal to right-hand | != | left-hand expression not equal to right-hand |=== The following relation operators are available for comparing strings. [cols=""~,~""] |=== | == | left-hand string equal to right-hand | != | left-hand string not equal to right-hand |=== ==== Assignment Operators The following assignment operators can be used on both `map` and `scratch` variables: [cols=""~,~""] |=== | = | Assignment, assign the right-hand expression to the left-hand variable | <\\<= | Update the variable with its value left shifted by the number of bits specified by the right-hand expression value | >>= | Update the variable with its value right shifted by the number of bits specified by the right-hand expression value | += | Increment the variable by the right-hand expression value | -= | Decrement the variable by the right-hand expression value | *= | Multiple the variable by the right-hand expression value | /= | Divide the variable by the right-hand expression value | %= | Modulo the variable by the right-hand expression value | &= | Bitwise AND the variable by the right-hand expression value | \\|= | Bitwise OR the variable by the right-hand expression value | ^= | Bitwise XOR the variable by the right-hand expression value |=== All these operators are syntactic sugar for combining assignment with the specified operator. `@ -= 5` is equal to `@ = @ - 5`. ==== Increment and Decrement Operators The increment (`\\++`) and decrement (`--`) operators can be used on integer and pointer variables to increment their value by one. They can only be used on variables and can either be applied as prefix or suffix. The difference is that the expression `x++` returns the original value of `x`, before it got incremented while `++x` returns the value of `x` post increment. E.g. ---- $x = 10; $y = $x--; // y = 10; x = 9 $a = 10; $b = --$a; // a = 9; b = 9 ---- Note that maps will be implicitly declared and initialized to 0 if not already declared or defined. Scratch variables must be initialized before using these operators. === Variables and Maps bpftrace knows two types of variables, `scratch` and `map`. 'scratch' variables are kept on the BPF stack and only exists during the execution of the action block and cannot be accessed outside of the program. Scratch variable names always start with a `$`, e.g. `$myvar`. 'map' variables use BPF 'maps'. These exist for the lifetime of `bpftrace` itself and can be accessed from all action blocks and user-space. Map names always start with a `@`, e.g. `@mymap`. All valid identifiers can be used as `name`. The data type of a variable is automatically determined during first assignment and cannot be changed afterwards. ==== Associative Arrays Associative arrays are a collection of elements indexed by a key, similar to the hash tables found in languages like C++ (`std::map`) and Python (`dict`). They're a variant of 'map' variables. ---- @name[key] = expression @name[key1,key2] = expression ---- Just like with any variable the type is determined on first use and cannot be modified afterwards. This applies to both the key(s) and the value type. The following snippet creates a map with key signature `[int64, string[16]]` and a value type of `int64`: ---- @[pid, comm]++ ---- === Variable scoping // TODO === Pointers Pointers in bpftrace are similar to those found in `C`. // TODO, not true yet === Tuples bpftrace has support for immutable N-tuples (`n > 1`). A tuple is a sequence type (like an array) where, unlike an array, every element can have a different type. Tuples are a comma separated list of expressions, enclosed in brackets, `(1,2)` Individual fields can be accessed with the `.` operator. Tuples are zero indexed like arrays are. ---- i:s:1 { $a = (1,2); $b = (3,4, $a); print($a); print($b); print($b.0); } ---- Prints: ---- (1, 2) (3, 4, (1, 2)) 3 ---- ==== Arrays bpftrace supports accessing one-dimensional arrays like those found in `C`. Constructing arrays from scratch, like `int a[] = {1,2,3}` in `C`, is not supported. They can only be read into a variable from a pointer. The `[]` operator is used to access elements. ---- struct MyStruct { int y[4]; } kprobe:dummy { $s = (struct MyStruct *) arg0; print($s->y[0]); } ---- === Structs `C` like structs are supported by bpftrace. Fields are accessed with the `.` operator. Fields of a pointer to a struct can be accessed with the `\\->` operator. Custom struct can be defined in the preamble Constructing structs from scratch, like `struct X var = {.f1 = 1}` in `C`, is not supported. They can only be read into a variable from a pointer. ---- struct MyStruct { int a; } kprobe:dummy { $ptr = (struct MyStruct *) arg0; $st = *$ptr; print($st.a); print($ptr->a); } ---- === Conditionals Conditional expressions are supported in the form of if/else statements and the ternary operator. The ternary operator consists of three operands: a condition followed by a `?`, the expression to execute when the condition is true followed by a `:` and the expression to execute if the condition is false. ---- condition ? ifTrue : ifFalse ---- Both the `ifTrue` and `ifFalse` expressions must be of the same type, mixing types is not allowed. The ternary operator can be used as part of an assignment. ---- $a == 1 ? print(""true"") : print(""false""); $b = $a > 0 ? $a : -1; ---- If/else statements, like the one in `C`, are supported. ---- if (condition) { ifblock } else if (condition) { if2block } else { elseblock } ---- === Loops Since kernel 5.3 BPF supports loops as long as the verifier can prove they're bounded and fit within the instruction limit. In bpftrace loops are available through the `while` statement. ---- while (condition) { block; } ---- Within a while-loop the following control flow statements can be used: [cols=""~,~""] |=== | continue | skip processing of the rest of the block and jump back to the evaluation of the conditional | break | Terminate the loop |=== ---- i:s:1 { $i = 0; while ($i <= 100) { printf(""%d "", $i); if ($i > 5) { break; } $i++ } printf(""\\n""); } ---- Loop unrolling is also supported with the `unroll` statement. ---- unroll(n) { block; } ---- The compiler will evaluate the block `n` times and generate the BPF code for the block `n` times. As this happens at compile time `n` must be a constant greater than 0 (`n > 0`). The following two probes compile into the same code: ---- i:s:1 { unroll(3) { print(""Unrolled"") } } i:s:1 { print(""Unrolled"") print(""Unrolled"") print(""Unrolled"") } ---- //// ! ! ! This prefix reset must be at the end of the section, else cross references break ! ! //// :idprefix: _ == Sync and Async While BPF in the kernel can do a lot there are still things that can only be done from user space, like the outputting (printing) of data. The way bpftrace handles this is by sending events from the BPF program which user-space will pick up some time in the future (usually in milliseconds). Operations that happen in the kernel are 'synchronous' ('sync') and those that are handled in user space are 'asynchronous' ('async') The async behaviour can lead to some unexpected behavior as updates can happen before user space had time to process the event. One example is updating a map value in a tight loop: ---- BEGIN { @=0; unroll(10) { print(@); @++; } exit() } ---- Maps are printed by reference not by value and as the value gets updated right after the print user-space will likely only see the final value once it processes the event: ---- @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 ---- == Address-spaces Kernel and user pointers live in different address spaces which, depending on the CPU architecture, might overlap. Trying to read a pointer that is in the wrong address space results in a runtime error. This error is hidden by default but can be enabled with the `-kk` flag: ---- stdin:1:9-12: WARNING: Failed to probe_read_user: Bad address (-14) BEGIN { @=*uptr(kaddr(""do_poweroff"")) } ~~~ ---- bpftrace tries to automatically set the correct address space for a pointer based on the probe type, but might fail in cases where it is unclear. The address space can be changed with the `kptr()` and `uptr()` functions. == Builtins Builtins are special variables built into the language. Unlike the scratch and map variable they don't need a `$` or `@` as prefix (except for the positional parameters). [%header,cols=""~,~,~,~,~""] |=== | Variable | Type | Kernel | BPF Helper | Description | `$1`, `$2`, `...$n` | int64 | n/a | n/a | The nth positional parameter passed to the bpftrace program. If less than n parameters are passed this evaluates to `0`. For string arguments use the `str()` call to retrieve the value. | `$#` | int64 | n/a | n/a | Total amount of positional parameters passed. | `arg0`, `arg1`, `...argn` | int64 | n/a | n/a | nth argument passed to the function being traced. These are extracted from the CPU registers. The amount of args passed in registers depends on the CPU architecture. (kprobes, uprobes, usdt). | cgroup | uint64 | 4.18 | get_current_cgroup_id | ID of the cgroup the current task is in. Only works with cgroupv2. | comm | string[16] | 4.2 | get_current_com | `comm` of the current task. Equal to the value in `/proc//comm` | cpid | uint32 | n/a | n/a | PID of the child process | numaid | uint32 | 5.8 | numa_node_id | ID of the NUMA node executing the BPF program | cpu | uint32 | 4.1 | raw_smp_processor_id | ID of the processor executing the BPF program | curtask | uint64 | 4.8 | get_current_task | Pointer to `struct task_struct` of the current task | elapsed | uint64 | (see nsec) | ktime_get_ns / ktime_get_boot_ns | Nanoseconds elapsed since bpftrace initialization, based on `nsecs` | func | string | n/a | n/a | Name of the current function being traced (kprobes,uprobes) | gid | uint64 | 4.2 | get_current_uid_gid | GID of current task | kstack | kstack | | get_stackid | Kernel stack trace | nsecs | uint64 | 4.1 / 5.7 | ktime_get_ns / ktime_get_boot_ns | nanoseconds since kernel boot. On kernels that support `ktime_get_boot_ns` this includes the time spent suspended, on older kernels it does not. | pid | uint64 | 4.2 | get_current_pid_tgid | Process ID (or thread group ID) of the current task. | probe | string | n/na | n/a | Name of the current probe | rand | uint32 | 4.1 | get_prandom_u32 | Random number | retval | int64 | n/a | n/a | Value returned by the function being traced (kretprobe, uretprobe, kretfunc) | `sarg0`, `sarg1`, `...sargn` | int64 | n/a | n/a | nth stack value of the function being traced. (kprobes, uprobes). | tid | uint64 | 4.2 | get_current_pid_tgid | Thread ID of the current task. | uid | uint64 | 4.2 | get_current_uid_gid | UID of current task | ustack | ustack | 4.6 | get_stackid | Userspace stack trace |=== //// Custom prefix to easily link to a function //// :idprefix: functions_ == Map Functions Map functions are built-in functions who's return value can only be assigned to maps. The data type associated with these functions are only for internal use and are not compatible with the (integer) operators. Functions that are marked *async* are asynchronous which can lead to unexpected behavior, see the <> section for more information. === avg .variants * `avg(int64 n)` Calculate the running average of `n` between consecutive calls. ---- i:s:1 { @x++; @y = avg(@x); print(@x); print(@y); } ---- Internally this keeps two values in the map: value count and running total. The average is computed in user-space when printing by dividing the total by the count. === clear .variants * `clear(map m)` *async* Clear all keys/values from map `m`. ---- i:ms:100 { @[rand % 10] = count(); } i:s:10 { print(@); clear(@); } ---- === count .variants * `count()` Count how often this function is called. Using `@=count()` is conceptually similar to `@++`. The difference is that the `count()` function uses a map type optimized for this (PER_CPU), increasing performance. Due to this the map cannot be accessed as a regular integer. ---- i:ms:100 { @ = count(); } i:s:10 { print(@); clear(@); } ---- === delete .variants * `delete(mapkey k)` Delete a single key from a map. For a single value map this deletes the only element. For an associative-array the key to delete has to be specified. ``` k:dummy { @scalar = 1; @associative[1,2] = 1; delete(@scalar); delete(@associative[1,2]); delete(@associative); // error } ``` === hist .variants * `hist(int64 n)` Create a log2 histogram of `n`. ---- kretprobe:vfs_read { @bytes = hist(retval); } ---- Results in: ---- @: [1M, 2M) 3 | | [2M, 4M) 2 | | [4M, 8M) 2 | | [8M, 16M) 6 | | [16M, 32M) 16 | | [32M, 64M) 27 | | [64M, 128M) 48 |@ | [128M, 256M) 98 |@@@ | [256M, 512M) 191 |@@@@@@ | [512M, 1G) 394 |@@@@@@@@@@@@@ | [1G, 2G) 820 |@@@@@@@@@@@@@@@@@@@@@@@@@@@ | ---- === lhist .variants * `lhist(int64 n, int64 min, int64 max, int64 step)` Create a linear histogram of `n`. `lhist` creates `M` (`(max - min) / step`) buckets in the range `[min,max)` where each bucket is `step` in size. Values in the range `(-inf, min)` and `(max, inf)` get their get their own bucket too, bringing the total amount of buckets created to `M+2`. ---- i:ms:1 { @ = lhist(rand %10, 0, 10, 1); } i:s:5 { exit(); } ---- Prints: ---- @: [0, 1) 306 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [1, 2) 284 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [2, 3) 294 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [3, 4) 318 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [4, 5) 311 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [5, 6) 362 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@| [6, 7) 336 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [7, 8) 326 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [8, 9) 328 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [9, 10) 318 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | ---- === max .variants * `max(int64 n)` Update the map with `n` if `n` is bigger than the current value held. === min .variants * `min(int64 n)` Update the map with `n` if `n` is smaller than the current value held. === stats .variants * `stats(int64 n)` `stats` combines the `count`, `avg` and `sum` calls into one. ---- kprobe:vfs_read { @bytes[comm] = stats(arg2); } ---- ---- @bytes[bash]: count 7, average 1, total 7 @bytes[sleep]: count 5, average 832, total 4160 @bytes[ls]: count 7, average 886, total 6208 @ ---- === sum .variants * `sum(int64 n)` Calculate the sum of all `n` passed. === zero .variants * `zero(map m)` *async* Set all values for all keys to zero. == Functions Functions that are marked *async* are asynchronous which can lead to unexpected behaviour, see the <> section for more information. *compile time* functions are evaluated at compile time, a static value will be compiled into the program. *unsafe* functions can have dangerous side effects and should be used with care, the `--unsafe` flag is required for use. === bswap .variants * `uint8 bswap(uint8 n)` * `uint16 bswap(uint16 n)` * `uint32 bswap(uint32 n)` * `uint64 bswap(uint64 n)` `bswap` reverses the order of the bytes in integer `n`. In case of 8 bit integers, `n` is returned without being modified. The return type is an unsigned integer of the same width as `n`. === buf .variants * `buf_t buf(void * data, [int64 length])` `buf` reads `length` amount of bytes from address `data`. The maximum value of `length` is limited to the `BPFTRACE_STRLEN` variable. For arrays the `length` is optional, it is automatically inferred from the signature. `buf` is address space aware and will call the correct helper based on the address space associated with `data`. The `buf_t` object returned by `buf` can safely be printed as a hex encoded string with the `%r` format specifier. Bytes with values >=32 and \\<=126 are printed using their ASCII character, other bytes are printed in hex form (e.g. `\\x00`). The `%rx` format specifier can be used to print everything in hex form, including ASCII characters. ---- i:s:1 { printf(""%r\\n"", buf(kaddr(""avenrun""), 8)); } ---- ---- \\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00 \\xc2\\x02\\x00\\x00\\x00\\x00\\x00\\x00 ---- === cat .variants * `void cat(string namefmt, [...args])` *async* Dump the contents of the named file to stdout. `cat` supports the same format string and arguments that `printf` does. If the file cannot be opened or read an error is printed to stderr. ---- t:syscalls:sys_enter_execve { cat(""/proc/%d/maps"", pid); } ---- ---- 55f683ebd000-55f683ec1000 r--p 00000000 08:01 1843399 /usr/bin/ls 55f683ec1000-55f683ed6000 r-xp 00004000 08:01 1843399 /usr/bin/ls 55f683ed6000-55f683edf000 r--p 00019000 08:01 1843399 /usr/bin/ls 55f683edf000-55f683ee2000 rw-p 00021000 08:01 1843399 /usr/bin/ls 55f683ee2000-55f683ee3000 rw-p 00000000 00:00 0 ---- === cgroup_path .variants * `cgroup_path cgroup_path(int cgroupid, string filter)` Convert cgroup id to cgroup path. This is done asynchronously in userspace when the cgroup_path value is printed, therefore it can resolve to a different value if the cgroup id gets reassigned. This also means that the returned value can only be used for printing. A string literal may be passed as an optional second argument to filter cgroup hierarchies in which the cgroup id is looked up by a wildcard expression (cgroup2 is always represented by ""unified"", regardless of where it is mounted). The currently mounted hierarchy at /sys/fs/cgroup is used to do the lookup. If the cgroup with the given id isn't present here (e.g. when running in a Docker container), the cgroup path won't be found (unlike when looking up the cgroup path of a process via /proc/.../cgroup). ---- BEGIN { $cgroup_path = cgroup_path(3436); print($cgroup_path); print($cgroup_path); /* This may print a different path */ printf(""%s %s"", $cgroup_path, $cgroup_path); /* This may print two different paths */ } ---- === cgroupid .variants * `uint64 cgroupid(const string path)` *compile time* `cgroupid` retrieves the cgroupv2 ID of the cgroup available at `path`. ---- BEGIN { print(cgroupid(""/sys/fs/cgroup/system.slice"")); } ---- === exit .variants * `void exit()` *async* Terminate bpftrace, as if a `SIGTERM` was received. The `END` probe will still trigger (if specified) and maps will be printed. === join .variants * `void join(char *arr[], [char * sep = ' '])` *async* `join` joins all the string array `arr` with `sep` as separator into one string. This string will be printed to stdout directly, it cannot be used as string value. The concatenation of the array members is done in BPF and the printing happens in userspace. ---- tracepoint:syscalls:sys_enter_execve { join(args->argv); } ---- === kaddr .variants * `uint64 kaddr(const string name)` *compile time* Get the address of the kernel symbol `name`. The following script: === kptr .variants * `T * kptr(T * ptr)` Marks `ptr` as a kernel address space pointer. See the address-spaces section for more information on address-spaces. The pointer type is left unchanged. === ksym .variants * `ksym_t ksym(uint64 addr)` *async* Retrieve the name of the function that contains address `addr`. The address to name mapping happens in user-space. The `ksym_t` type can be printed with the `%s` format specifier. ---- kprobe:do_nanosleep { printf(""%s\\n"", ksym(reg(""ip""))); } ---- Prints: ---- do_nanosleep ---- === macaddr .variants * `macaddr_t macaddr(char [6] mac)` Create a buffer that holds a macaddress as read from `mac` This buffer can be printed in the canonical string format using the `%s` format specifier. ---- kprobe:arp_create { printf(""SRC %s, DST %s\\n"", macaddr(sarg0), macaddr(sarg1)); } ---- Prints: ---- SRC 18:C0:4D:08:2E:BB, DST 74:83:C2:7F:8C:FF ---- === ntop .variants * `inet_t ntop([int64 af, ] int addr)` * `inet_t ntop([int64 af, ] char addr[4])` * `inet_t ntop([int64 af, ] char addr[16])` `ntop` returns the string representation of an IPv4 or IPv6 address. `ntop` will infer the address type (IPv4 or IPv6) based on the `addr` type and size. If an integer or `char[4]` is given, ntop assumes IPv4, if a `char[16]` is given, ntop assumes IPv6. You can also pass the address type (e.g. AF_INET) explicitly as the first parameter. === override .variants * `override(uint64 rc)` *unsafe* *Kernel* 4.16 *Helper* `bpf_override` .Supported probes * kprobe When using `override` the probed function will not be executed and instead `rc` will be returned. ---- k:__x64_sys_getuid /comm == ""id""/ { override(2<<21); } ---- ---- uid=4194304 gid=0(root) euid=0(root) groups=0(root) ---- This feature only works on kernels compiled with `CONFIG_BPF_KPROBE_OVERRIDE` and only works on functions tagged `ALLOW_ERROR_INJECTION`. bpftrace does not test whether error injection is allowed for the probed function, instead if will fail to load the program into the kernel: ---- ioctl(PERF_EVENT_IOC_SET_BPF): Invalid argument Error attaching probe: 'kprobe:vfs_read' ---- === reg .variants * `reg(const string name)` .Supported probes * kprobe * uprobe Get the contents of the register identified by `name`. Valid names depend on the CPU architecture. === signal .variants * `signal(const string sig)` * `signal(uint32 signum)` *unsafe* *Kernel* 5.3 *Helper* `bpf_send_signal` Probe types: k(ret)probe, u(ret)probe, USDT, profile Send a signal to the process being traced. The signal can either be identified by name, e.g. `SIGSTOP` or by ID, e.g. `19` as found in `kill -l`. ---- kprobe:__x64_sys_execve /comm == ""bash""/ { signal(5); } ---- ---- $ ls Trace/breakpoint trap (core dumped) ---- === sizeof .variants * `sizeof(TYPE)` * `sizeof(EXPRESSION)` *compile time* Returns size of the argument in bytes. Similar to C/C++ `sizeof` operator. Note that the expression does not get evaluated. === str .variants * `str(char * data [, uint32 length)` *Helper* `probe_read_str, probe_read_{kernel,user}_str` `str` reads a NULL terminated (`\\0`) string from `data`. The maximum string length is limited by the `BPFTRACE_STR_LEN` env variable, unless `length` is specified and shorter than the maximum. In case the string is longer than the specified length only `length - 1` bytes are copied and a NULL byte is appended at the end. When available (starting from kernel 5.5, see the `--info` flag) bpftrace will automatically use the `kernel` or `user` variant of `probe_read_{kernel,user}_str` based on the address space of `data`, see <> for more information. === strftime .variants * `strtime_t strftime(const string fmt, int64 timestamp_ns)` *async* Format the nanoseconds since boot timestamp `timestamp_ns` according to the format specified by `fmt`. The time conversion and formatting happens in user space, therefore the `timestr_t` value returned can only be used for printing using the `%s` format specifier. bpftrace uses the `strftime(3)` function for formatting time and supports the same format specifiers. ---- i:s:1 { printf(""%s\\n"", strftime(""%H:%M:%S"", nsecs)); } ---- bpftrace also supports the following format string extensions: [%header,cols=""~,~""] |=== | Specifier | Description | `%f` | Microsecond as a decimal number, zero-padded on the left |=== === strncmp .variants * `int64 strncmp(char * s1, char * s2, int64 n)` `strncmp` compares up to `n` characters string `s1` and string `s2`. If they're equal `0` is returned, else a non-zero value is returned. bpftrace doesn't read past the length of the shortest string. The use of the `==` and `!=` operators is recommended over calling `strncmp` directly. === system .variants * `void system(string namefmt [, ...args])` *unsafe* *async* `system` lets bpftrace run the specified command (`fork` and `exec`) until it completes and print its stdout. The `command` is run with the same privileges as bpftrace and it blocks execution of the processing threads which can lead to missed events and delays processing of async events. ---- i:s:1 { time(""%H:%M:%S: ""); printf(""%d\\n"", @++); } i:s:10 { system(""/bin/sleep 10""); } i:s:30 { exit(); } ---- Note how the async `time` and `printf` first print every second until the `i:s:10` probe hits, then they print every 10 seconds due to bpftrace blocking on `sleep`. ---- Attaching 3 probes... 08:50:37: 0 08:50:38: 1 08:50:39: 2 08:50:40: 3 08:50:41: 4 08:50:42: 5 08:50:43: 6 08:50:44: 7 08:50:45: 8 08:50:46: 9 08:50:56: 10 08:50:56: 11 08:50:56: 12 08:50:56: 13 08:50:56: 14 08:50:56: 15 08:50:56: 16 08:50:56: 17 08:50:56: 18 08:50:56: 19 ---- `system` supports the same format string and arguments that `printf` does. ---- t:syscalls:sys_enter_execve { system(""/bin/grep %s /proc/%d/status"", ""vmswap"", pid); } ---- === time .variants * `void time(const string fmt)` *async* Format the current wall time according to the format specifier `fmt` and print it to stdout. Unlike `strftime()` `time()` doesn't send a timestamp from the probe, instead it is the time at which user-space processes the event. bpftrace uses the `strftime(3)` function for formatting time and supports the same format specifiers. === uaddr .variants * `T * uaddr(const string sym)` .Supported probes * uprobes * uretprobes * USDT **Does not work with ASLR, see issue link:https://github.com/iovisor/bpftrace/issues/75[#75]** The `uaddr` function returns the address of the specified symbol. This lookup happens during program compilation and cannot be used dynamically. The default return type is `uint64*`. If the ELF object size matches a known integer size (1, 2, 4 or 8 bytes) the return type is modified to match the width (`uint8*`, `uint16*`, `uint32*` or `uint64*` resp.). As ELF does not contain type info the type is always assumed to be unsigned. ---- uprobe:/bin/bash:readline { printf(""PS1: %s\\n"", str(*uaddr(""ps1_prompt""))); } ---- === uptr .variants * `T * uptr(T * ptr)` Marks `ptr` as a user address space pointer. See the address-spaces section for more information on address-spaces. The pointer type is left unchanged. === usym .variants * `usym_t usym(uint64 * addr)` *async* .Supported probes * uprobes * uretprobes Equal to <> but resolves user space symbols ---- uprobe:/bin/bash:readline { printf(""%s\\n"", usym(reg(""ip""))); } ---- Prints: ---- readline ---- === path .variants * `char * path(struct path * path)` *Kernel* 5.10 *Helper* bpf_d_path Return full path referenced by struct path pointer in argument. This function can only be used by functions that are allowed to, these functions are contained in the `btf_allowlist_d_path` set in the kernel. === unwatch .variants * `void unwatch(void * addr)` *async* Removes a watchpoint == Output formatting === print .variants * `void print(T val)` *async* .variants * `void print(T val)` * `void print(@map)` * `void print(@map, uint64 top)` * `void print(@map, uint64 top, uint64 div)` `print` prints a the value, which can be a map or a scalar value, with the default formatting for the type. ---- i:ms:10 { @=hist(rand); } i:s:1 { print(@); print(123); print(""abc""); exit(); } ---- Prints: ---- @: [16M, 32M) 3 |@@@ | [32M, 64M) 2 |@@ | [64M, 128M) 1 |@ | [128M, 256M) 4 |@@@@ | [256M, 512M) 3 |@@@ | [512M, 1G) 14 |@@@@@@@@@@@@@@ | [1G, 2G) 22 |@@@@@@@@@@@@@@@@@@@@@@ | [2G, 4G) 51 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@| 123 abc ---- Note that maps are printed by reference while scalar values are copied. This means that updating and printing maps in a fast loop will likely result in bogus map values as the map will be updated before userspace gets the time to dump and print it. The printing of maps supports the optional `top` and `div` arguments. `top` limits the printing to the top N entries with the highest integer values ---- BEGIN { $i = 11; while($i) { @[$i] = --$i; } print(@, 2); clear(@); exit() } ---- ---- @[9]: 9 @[10]: 10 ---- The `div` argument scales the values prior to printing them. Scaling values before storing them can result in rounding errors. Consider the following program: ---- k:f { @[func] += arg0/10; } ---- With the following sequence as numbers for arg0: `134, 377, 111, 99`. The total is `721` which rounds to `72` when scaled by 10 but the program would print `70` due to the rounding of individual values. Changing the print call to `print(@, 5, 2)` will take the top 5 values and scale them by 2: ---- @[6]: 3 @[7]: 3 @[8]: 4 @[9]: 4 @[10]: 5 ---- === printf .variants * `void printf(const string fmt, args...)` *async* `printf()` formats and prints data. It behaves similar to `printf()` found in `C` and many other languages. The format string has to be a constant, it cannot be modified at runtime. The formatting of the string happens in user space. Values are copied and passed by value. bpftrace supports all the typical format specifiers like `%llx` and `%hhu`. The non-standard ones can be found in the table below: [%header,cols=""~,~,~""] |=== | Specifier | Type | Description | r | buffer | Hex-formatted string to print arbitrary binary content returned by the buf (<>) function. |=== Supported escape sequences Colors are supported too, using standard terminal escape sequences: ---- print(""\\033[31mRed\\t\\033[33mYellow\\033[0m\\n"") ---- //// ! ! ! This prefix reset must be at the end of the section, else cross references break ! ! //// :idprefix: _ == Probes bpftrace supports various probe types which allow the user to attach BPF programs to different types of events. Each probe starts with a provider (e.g. `kprobe`) followed by a colon (`:`) separated list of options. The amount of options and their meaning depend on the provider and are detailed below. The valid values for options can depend on the system or binary being traced, e.g. for uprobes it depends on the binary. Also see <> It is possible to associate multiple probes with a single action as long as the action is valid for all specified probes. Multiple probes can be specified as a comma (`,`) separated list: ---- kprobe:tcp_reset,kprobe:tcp_v4_rcv { printf(""Entered: %s\\n"", probe); } ---- Wildcards are supported too: ---- kprobe:tcp_* { printf(""Entered: %s\\n"", probe); } ---- Both can be combined: ---- kprobe:tcp_reset,kprobe:*socket* { printf(""Entered: %s\\n"", probe); } ---- Most providers also support a short name which can be used instead of the full name, e.g. `kprobe:f` and `k:f` are identical. [#probes-begin-end] === BEGIN and END These are special built-in events provided by the bpftrace runtime. `BEGIN` is triggered before all other probes are attached. `END` is triggered after all other probes are detached. Note that specifying an `END` probe doesn't override the printing of 'non-empty' maps at exit. To prevent the printing all used maps need be cleared, which can be done in the `END` probe: ---- END { clear(@map1); clear(@map2); } ---- [#probes-hardware] === hardware .variants * `hardware:event_name:` * `hardware:event_name:count` .shortname * `h` The `hardware` probe attaches to pre-defined hardware events provided by the kernel. They are implemented using performance monitoring counters (PMCs): hardware resources on the processor. There are about ten of these, and they are documented in the `perf_event_open(2)` man page. The event names are: - `cpu-cycles` or `cycles` - `instructions` - `cache-references` - `cache-misses` - `branch-instructions` or `branches` - `branch-misses` - `bus-cycles` - `frontend-stalls` - `backend-stalls` - `ref-cycles` The `count` option specifies how many events must happen before the probe fires. If `count` is left unspecified a default value is used. ---- hardware:cache-misses:1e6 { @[pid] = count(); } ---- [#probes-interval] === interval .variants * `interval:us:count` * `interval:ms:count` * `interval:s:count` * `interval:hz:rate` .shortnames * `i` The interval probe fires at a fixed interval as specified by its time spec. Interval fire on one CPU at the time, unlike <> probes. [#probes-iterator] === iterator .variants * `iter:task` * `iter:task:pin` * `iter:task_file` * `iter:task_file:pin` .shortnames * `it` These are eBPF iterator probes, that allow iteration over kernel objects. Iterator probe can't be mixed with any other probe, not even other iterator. Each iterator probe provides set of fields that could be accessed with ctx pointer. User can display set of available fields for iterator via -lv options as described below. Examples: ``` # bpftrace -e 'iter:task { printf(""%s:%d\\n"", ctx->task->comm, ctx->task->pid); }' Attaching 1 probe... systemd:1 kthreadd:2 rcu_gp:3 rcu_par_gp:4 kworker/0:0H:6 mm_percpu_wq:8 ... # bpftrace -e 'iter:task_file { printf(""%s:%d %d:%s\\n"", ctx->task->comm, ctx->task->pid, ctx->fd, path(ctx->file->f_path)); }' Attaching 1 probe... systemd:1 1:/dev/null systemd:1 2:/dev/null systemd:1 3:/dev/kmsg ... su:1622 1:/dev/pts/1 su:1622 2:/dev/pts/1 su:1622 3:/var/lib/sss/mc/passwd ... bpftrace:1892 1:pipe:[35124] bpftrace:1892 2:/dev/pts/1 bpftrace:1892 3:anon_inode:bpf-map bpftrace:1892 4:anon_inode:bpf-map bpftrace:1892 5:anon_inode:bpf_link bpftrace:1892 6:anon_inode:bpf-prog bpftrace:1892 7:anon_inode:bpf_iter ``` It's possible to pin iterator with specifying optional probe ':pin' part, that defines the pin file. It can be specified as absolute path or relative to /sys/fs/bpf. .relative pin ---- # bpftrace -e 'iter:task:list { printf(""%s:%d\\n"", ctx->task->comm, ctx->task->pid); }' Program pinned to /sys/fs/bpf/list ---- ---- # cat /sys/fs/bpf/list systemd:1 kthreadd:2 rcu_gp:3 rcu_par_gp:4 kworker/0:0H:6 mm_percpu_wq:8 rcu_tasks_kthre:9 ... ---- Examples with absolute pin file: .absolute pin ---- # bpftrace -e ' iter:task_file:/sys/fs/bpf/files { printf(""%s:%d %s\\n"", ctx->task->comm, ctx->task->pid, path(ctx->file->f_path)); }' Program pinned to /sys/fs/bpf/files ---- ---- # cat /sys/fs/bpf/files systemd:1 anon_inode:inotify systemd:1 anon_inode:[timerfd] ... systemd-journal:849 /dev/kmsg systemd-journal:849 anon_inode:[eventpoll] ... sssd:1146 /var/log/sssd/sssd.log sssd:1146 anon_inode:[eventpoll] ... NetworkManager:1155 anon_inode:[eventfd] NetworkManager:1155 /var/lib/sss/mc/passwd (deleted) ---- [#probes-kfunc] === kfunc and kretfunc .variants * `kfunc:fn` * `kretfunc:fn` .shortnames * `f` (`kfunc`) * `fr` (`kretfunc`) .requires (`--info`) * Kernel features:BTF * Probe types:kfunc ``kfunc``s attach to kernel function similar to <>. They make use of eBPF trampolines which allows kernel code to call into BPF programs with near zero overhead. `kfunc` s make use of BTF type information to derive the type of function arguments at compile time. This removes the need for manual type casting and makes the code more resilient against small signature changes in the kernel. The function arguments are available in the `args` struct which can be inspected by doing verbose listing (see <>). These arguments are also available in the return probe (`kretfunc`). ---- # bpftrace -lv 'kfunc:tcp_reset' kfunc:tcp_reset struct sock * sk struct sk_buff * skb ---- ---- kfunc:x86_pmu_stop { printf(""pmu %s stop\\n"", str(args->event->pmu->name)); } ---- ---- kretfunc:fget { printf(""fd %d name %s\\n"", args->fd, str(retval->f_path.dentry->d_name.name)); } ---- ---- fd 3 name ld.so.cache fd 3 name libselinux.so.1 fd 3 name libselinux.so.1 ... ---- [#probes-kprobe] === kprobe and kretprobe .variants * `kprobe:fn` * `kprobe:fn+offset` * `kretprobe:fn` .shortnames * `k` * `kr` `kprobe` s allow for dynamic instrumentation of kernel functions. Each time the specified kernel function is executed the attached BPF programs are ran. ---- kprobe:tcp_reset { @tcp_resets = count() } ---- Function arguments are available through the `argX` and `sargX` builtins, for register args and stack args respectively. Whether arguments passed on stack or in a register depends on the architecture and the number or arguments in used, e.g. on x86_64 the first non-floating point 6 arguments are passed in registers, all following arguments are passed on the stack. Note that floating point arguments are typically passed in special registers which don't count as `argX` arguments which can cause confusion. Consider a function with the following signature: ---- void func(int a, double d, int x) ---- Due to `d` being a floating point `x` is accessed through `arg1` where one might expect `arg2`. bpftrace does not detect the function signature so it is not aware of the argument count or their type. It is up to the user to perform <> when needed, e.g. ---- kprobe:tcp_connect { $sk = ((struct sock *) arg0); ... } ---- `kprobe` s are not limited to function entry, they can be attached to any instruction in a function by specifying an offset from the start of the function. `kretprobe` s trigger on the return from a kernel function. Return probes do not have access to the function (input) arguments, only to the return value (through `retval`). A common pattern to work around this is by storing the arguments in a map on function entry and retrieving in the return probe: ---- kprobe:d_lookup { $name = (struct qstr *)arg1; @fname[tid] = $name->name; } kretprobe:d_lookup /@fname[tid]/ { printf(""%-8d %-6d %-16s M %s\\n"", elapsed / 1e6, pid, comm, str(@fname[tid])); } ---- [#probes-profile] === profile .variants * `profile:us:count` * `profile:ms:count` * `profile:s:count` * `profile:hz:rate` .shortnames * `p` Profile probes fire on each CPU on the specified interval. [#probes-software] === software .variants * `software:event:` * `software:event:count` .shortnames * `s` The `software` probe attaches to pre-defined software events provided by the kernel. Event details can be found in the `perf_event_open(2)` man page. The event names are: - `cpu-clock` or `cpu` - `task-clock` - `page-faults` or `faults` - `context-switches` or `cs` - `cpu-migrations` - `minor-faults` - `major-faults` - `alignment-faults` - `emulation-faults` - `dummy` - `bpf-output` [#probes-tracepoint] === tracepoint .variants * `tracepoint:subsys:event` .shortnames * `t` Tracepoints are hooks into events in the kernel. Tracepoints are defined in the kernel source and compiled into the kernel binary which makes them a form of static tracing. Which means that unlike `kprobe` s new tracepoints cannot be added without modifying the kernel. The advantage of tracepoints is that they generally provide a more stable interface than `kprobe` s do, they do not depend on the existence of a kernel function. Tracepoint arguments are available in the `args` struct which can be inspected with verbose listing, see the <> section for more details. ---- tracepoint:syscalls:sys_enter_openat { printf(""%s %s\\n"", comm, str(args->filename)); } ---- ---- irqbalance /proc/interrupts irqbalance /proc/stat snmpd /proc/diskstats snmpd /proc/stat snmpd /proc/vmstat snmpd /proc/net/dev [...] ---- .Additional information * https://www.kernel.org/doc/html/latest/trace/tracepoints.html [#probes-uprobe] === uprobe, uretprobe .variants * `uprobe:binary:func` * `uprobe:binary:func+offset` * `uretprobe:binary:func` .shortnames * `u` * `ur` `uprobe` s or user-space probes are the user-space equivalent of `kprobe` s. The same limitations that apply <> also apply to `uprobe` s and `uretprobe` s. When tracing libraries, it is sufficient to specify the library name instead of a full path. The path will be then automatically resolved using `/etc/ld.so.cache`: ---- # bpftrace -e 'uprobe:libc:malloc { printf(""Allocated %d bytes\\n"", arg0); }' Allocated 4 bytes ... ---- If the traced binary has DWARF included, function arguments are available in the `args` struct which can be inspected with verbose listing, see the <> section for more details. It is important to note that for `uretprobe` s to work the kernel runs a special helper on user-space function entry which overrides the return address on the stack. This can cause issues with languages that have their own runtime like Golang: .example.go ---- func myprint(s string) { fmt.Printf(""Input: %s\\n"", s) } func main() { ss := []string{""a"", ""b"", ""c""} for _, s := range ss { go myprint(s) } time.Sleep(1*time.Second) } ---- .bpftrace ---- # bpftrace -e 'uretprobe:./test:main.myprint { @=count(); }' -c ./test runtime: unexpected return pc for main.myprint called from 0x7fffffffe000 stack: frame={sp:0xc00008cf60, fp:0xc00008cfd0} stack=[0xc00008c000,0xc00008d000) fatal error: unknown caller pc ---- [#probes-usdt] === usdt .variants * `usdt:binary:name` .shortnames * `U` [#probes-watchpoint] === watchpoint and asyncwatchpoint .variants * `watchpoint:absolute_address:length:mode` * `watchpoint:function+argN:length:mode` .shortnames * `w` * `aw` These are memory watchpoints provided by the kernel. Whenever a memory address is written to (`w`), read from (`r`), or executed (`x`), the kernel can generate an event. In the first form, an absolute address is monitored. If a pid (`-p`) or a command (`-c`) is provided, bpftrace takes the address as a userspace address and monitors the appropriate process. If not, bpftrace takes the address as a kernel space address. In the second form, the address present in `argN` when `function` is entered is monitored. A pid or command must be provided for this form. If synchronous (`watchpoint`), a `SIGSTOP` is sent to the tracee upon function entry. The tracee will be ``SIGCONT``ed after the watchpoint is attached. This is to ensure events are not missed. If you want to avoid the `SIGSTOP` + `SIGCONT` use `asyncwatchpoint`. Note that on most architectures you may not monitor for execution while monitoring read or write. Examples Print `hit` when a read from or write to `0x10000000` happens: ``` # bpftrace -e 'watchpoint:0x10000000:8:rw { printf(""hit!\\n""); exit(); }' -c ./testprogs/watchpoint ``` Print the call stack every time the `jiffies` variable is updated: ``` # bpftrace -e ""watchpoint:0x$(awk '$3 == ""jiffies"" {print $1}' /proc/kallsyms):8:w { @[kstack] = count(); } i:s:1 { exit(); }"" ...... @[ do_timer+12 tick_do_update_jiffies64.part.22+89 tick_sched_do_timer+103 tick_sched_timer+39 __hrtimer_run_queues+256 hrtimer_interrupt+256 smp_apic_timer_interrupt+106 apic_timer_interrupt+15 cpuidle_enter_state+188 cpuidle_enter+41 do_idle+536 cpu_startup_entry+25 start_secondary+355 secondary_startup_64+164 ]: 319 ``` ""hit"" and exit when the memory pointed to by `arg1` of `increment` is written to. ``` # cat wpfunc.c #include #include #include __attribute__((noinline)) void increment(__attribute__((unused)) int _, int *i) { (*i)++; } int main() { int *i = malloc(sizeof(int)); while (1) { increment(0, i); (*i)++; usleep(1000); } } # bpftrace -e 'watchpoint:increment+arg1:4:w { printf(""hit!\\n""); exit() }' -c ./wpfunc ``` == Listing Probes Probe listing is the method to discover which probes are supported by the current system. Listing supports the same syntax as normal attachment does: ---- # bpftrace -l 'kprobe:*' # bpftrace -l 't:syscalls:*openat* # bpftrace -l 'kprobe:tcp*,trace # bpftrace -l 'k:*socket*,tracepoint:syscalls:*tcp*' ---- The verbose flag (`-v`) can be specified to inspect arguments (`args`) for providers that support it: ---- # bpftrace -l 'fr:tcp_reset,t:syscalls:sys_enter_openat' -v kretfunc:tcp_reset struct sock * sk struct sk_buff * skb tracepoint:syscalls:sys_enter_openat int __syscall_nr int dfd const char * filename int flags umode_t mode # bpftrace -l 'uprobe:/bin/bash:rl_set_prompt' -v # works only if /bin/bash has DWARF uprobe:/bin/bash:rl_set_prompt const char *prompt ---- ",16269,True,2909.3772707591193,median "// // 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. // = Введение в JavaServer Faces 2.x :jbake-type: tutorial :jbake-tags: tutorials :jbake-status: published :icons: font :syntax: true :source-highlighter: pygments :toc: left :toc-title: :description: Введение в JavaServer Faces 2.x - Apache NetBeans :keywords: Apache NetBeans, Tutorials, Введение в JavaServer Faces 2.x JavaServer Faces (JSF) - это платформа разработки интерфейса пользователя для веб-приложений Java. Она призвана значительно упростить процесс создания и поддержки приложений, работающих на сервере приложений Java и визуализирующих свои пользовательские интерфейсы на целевом клиенте. JSF обеспечивает простоту использования благодаря целому ряду факторов: * упрощает формирование пользовательского интерфейса из набора повторно используемых компонентов пользовательского интерфейса; * упрощает перенос данных приложения в пользовательский интерфейс и из него; * помогает управлять состоянием пользовательского интерфейса при запросах к серверу; * предоставляет простую модель установления связи между созданными клиентом событиями и кодом приложения на стороне сервера; * упрощает сборку и повторное использование компонентов пользовательского интерфейса. Подробное описание платформы JSF приведено в link:http://docs.oracle.com/javaee/7/tutorial/doc/jsf-develop.htm[+учебном курсе по Java EE 7, Глава 12. Разработка по технологии JavaServer Faces+]. В этом учебном курсе описывается применение поддержки JSF 2.x к веб-приложениям с помощью IDE NetBeans. Сначала необходимо добавить поддержку платформы JSF 2.x к базовому веб-приложению, а затем приступить к выполнения следующих задач: * создать управляемый компонент JSF для обработки данных запроса, * подключить управляемый компонент к веб-страницам приложения и * преобразовать веб-страницы в файлы шаблонов Facelets. IDE NetBeans обеспечивает долгосрочную поддержку для JavaServer Faces. Начиная с редакции JSF 2.0 и Java EE 6, IDE NetBeans обеспечивает поддержку для JSF 2.0 и JSF 2.1. Подробнее см. в разделе link:jsf20-support.html[+Поддержка JSF 2.x в IDE NetBeans+]. image::images/netbeans-stamp-80-74-73.png[title=""Содержимое этой страницы применимо к IDE NetBeans 7.2, 7.3, 7.4 и 8.0""] Для работы с этим учебным курсом требуются программное обеспечение и материалы, перечисленные ниже. |=== |Программное обеспечение или материал |Требуемая версия |link:https://netbeans.org/downloads/index.html[+IDE NetBeans+] |7.2, 7.3, 7.4, 8.0, пакет Java EE |link:http://www.oracle.com/technetwork/java/javase/downloads/index.html[+Комплект для разработчика на языке Java (JDK)+] |7 или 8 |link:http://glassfish.dev.java.net/[+Сервер GlassFish+] |Open Source Edition 3.x или 4 |link:https://netbeans.org/projects/samples/downloads/download/Samples%252FJavaEE%252FjsfDemo.zip[+Проект веб-приложения `jsfDemo`+] |неприменимо |=== *Примечания* * В комплект Java в среде IDE NetBeans также входит сервер GlassFish - сервер, совместимый с Java EE, который требуется для этого учебного курса. * Для сравнения проекта с рабочим решением загрузите link:https://netbeans.org/projects/samples/downloads/download/Samples%252FJavaEE%252FjsfDemoCompleted.zip[+выполненный демонстрационный проект+]. [[support]] == Добавление поддержки JSF 2.x к веб-приложениям Начните работу с открытия <> в среде IDE. После открытия проекта в среде IDE в него можно добавить поддержку платформы с помощью окна ""Свойства"" в проекте. IDE также позволяет создавать новые проекты с поддержкой JSF 2.x. Подробнее см. раздел link:jsf20-support.html#creatingSupport[+Создание нового проекта с поддержкой JSF 2.x+]. 1. Нажмите кнопку 'Открыть проект' ( image::images/open-project-btn.png[] ) на главной панели инструментов IDE или нажмите Ctrl-Shift-O (⌘-Shift-O в Mac). 2. В диалоговом окне ""Открытие проекта"" перейдите к папке на компьютере, в которой хранится разархивированный файл учебного проекта. Выберите его, а затем для открытия проекта в среде IDE нажмите кнопку ""Открыть проект"". *Примечание.* При открытии проекта NetBeans может быть отображен запрос на разрешение ссылки на библиотеки JUnit, если при установке IDE не был установлен подключаемый модуль JUnit. 3. Выполните проект и посмотрите, как он выглядит в браузере. Либо щелкните правой кнопкой мыши узел проекта `jsfDemo` в окне 'Проекты' и выберите 'Запустить' или нажмите кнопку 'Запустить проект' ( image::images/run-project-btn.png[] ) на главной панели инструментов. Проект запакован и разворачивается на сервере GlassFish, а в браузере открывается страница приветствия(`index.xhtml`). image::images/run-project.png[title=""Запустите проект, чтобы просмотреть его в браузере.""] 4. Нажмите кнопку ""Отправить"". Страница ответа (`response.xhtml`) отображается следующим образом: image::images/response.png[title=""Страницы приветствия и отклика в настоящее время являются статическими страницами""] В настоящее время страницы приветствия и отклика являются статическими, и совместно с файлом `stylesheet.css` и изображением `duke.png` они являются единственными файлами приложений, доступными из браузера. 5. В окне 'Проекты' (Ctrl-1; ⌘ -1 в Mac) щелкните правой кнопкой мыши узел проекта и выберите 'Свойства', чтобы открыть окно 'Свойства проекта'. 6. Выберите категорию 'Платформы', а затем нажмите кнопку 'Добавить'. 7. Выберите 'JavaServer Faces' в диалоговом окне 'Добавление платформы'. Нажмите кнопку 'ОК'. image::images/add-framework.png[title=""Добавление поддержки JSF к существующему проекту""] После выбора ""JavaServer Faces"" станут доступными различные параметры настройки. На вкладке 'Библиотеки' вы можете указать, как проект обращается к библиотекам JSF 2.x. Доступная версия JSF будет зависеть от версии IDE и сервера GlassFish. По умолчанию используются библиотеки, поставляемые с сервером (сервером GlassFish). Тем не менее, в IDE также входят библиотеки JSF 2.x. (Можно выбрать параметр ""Зарегистрированные библиотеки"", если их необходимо использовать в проекте). image::images/libraries-tab.png[title=""Укажите доступ к библиотекам JSF 2.x""] 8. Выберите вкладку ""Настройка"". Можно указать способ регистрации сервлета Faces в дескрипторе развертывания проекта. Также можно указать, нужно ли в проекте использовать страницы Facelets или JSP. image::images/jsf-configuration.png[title=""Укажите параметры сервлета Faces и предпочитаемый язык""] Вы также можете легко настроить проект для использования различных наборов компонентов JSF на вкладке 'Компоненты'. Чтобы использовать набор компонентов, нужно загрузить необходимые библиотеки и использовать диспетчер Ant Library для создания новой библиотеки с библиотеками наборов компонентов. image::images/jsf-components.png[title=""Укажите параметры сервлета Faces и предпочитаемый язык""] 9. Нажмите кнопку ""ОК"" для подтверждения изменений и закройте окно ""Свойства проекта"". После добавления поддержки JSF к проекту дескриптор развертывания `web.xml` изменяется и выглядит следующим образом. (Изменения *выделены полужирным шрифтом*.) [source,xml] ---- * javax.faces.PROJECT_STAGE Development Faces Servlet javax.faces.webapp.FacesServlet 1 Faces Servlet /faces/* * *faces/*index.xhtml ---- *Важно!* Убедитесь, что файл `web.xml` содержит только одну запись `` с компонентом '`faces/`', как показано в примере. Это обеспечивает передачу страницы приветствия проекта (`index.xhtml`) через сервлет Faces перед ее отображением в браузере. Это необходимо для верного отображения компонентов библиотек тегов Facelets. Сервлет Faces регистрируется в проекте, и теперь страница приветствия `index.xhtml` при запросе передается через сервлет Faces. Кроме того, обратите внимание, что добавлена запись для параметра контекста `PROJECT_STAGE`. При установке значения этого параметра на ""`Development`"" предоставляется полезная информация во время отладки приложения. См. link:http://blogs.oracle.com/rlubke/entry/jsf_2_0_new_feature2[+http://blogs.oracle.com/rlubke/entry/jsf_2_0_new_feature2+] для получения дополнительной информации. Для просмотра библиотек JSF разверните узел ""Библиотеки"" проекта в окне ""Проекты"". Если используются библиотеки по умолчанию, включенные в GlassFish Server 3.1.2 или GlassFish Server 4, под узлом сервера GlassFish отображается `javax.faces.jar`. (Если вы используете старую версию GlassFish, вы увидите библиотеки `jsf-api.jar` и `jsf-impl.jar`, а не `javax.faces.jar`.) Поддержка JSF в среде IDE 2.x включает в себя в первую очередь большое количество мастеров для JSF, а также специальные функциональные возможности, предоставляемые редактором Facelets. Эти функциональные возможности описаны ниже. Подробнее см. в разделе link:jsf20-support.html[+Поддержка JSF 2.x в IDE NetBeans+]. [[managedBean]] == Создание управляемого компонента Управляемые компоненты JSF для обработки данных пользователя и сохранения их между запросами. Управляемый компонент – это link:http://en.wikipedia.org/wiki/Plain_Old_Java_Object[+POJO+] (простой объект Java), который используется для сохранения данных и управляется контейнером (например, сервером GlassFish) с помощью платформы JSF. Компонент POJO по существу является классом Java, который содержит публичный безаргументный конструктор и соответствует правилам присвоения имен link:http://download.oracle.com/javase/tutorial/javabeans/[+JavaBeans+] для свойств. При просмотре <>, полученной в результате выполнения проекта, пользователю необходим механизм, который проверяет введенное пользователем число на соответствие текущему выбранному числу и возвращает представление, соответствующее полученному результату. Чтобы создать управляемый компонент для этих целей, используйте link:jsf20-support.html#managedBean[+Мастер создания управляемого компонента+] среды IDE. Страницы Facelets, создаваемые в следующем разделе, должны иметь доступ к числу, вводимому пользователем, и к сгенерированному ответу. Для упрощения добавьте свойства `userNumber` и `response` к управляемому компоненту. * <> * <> * <> [[usingManagedBean]] === Использование мастера создания управляемого компонента 1. В окне 'Проекты' щелкните правой кнопкой мыши узел проекта `jsfDemo` и выберите 'Создать' > 'Управляемый компонент JSF'. (Если ""Управляемый компонент"" отсутствует, выберите ""Другие"". Затем выберите параметр ""Управляемый компонент JSF"" в категории ""JavaServer Faces"". Нажмите кнопку ""Далее"". 2. В мастере введите следующее: * *Имя класса:* UserNumberBean; * *Пакет:* guessNumber; * *Имя:* UserNumberBean * *Контекст:* сеанс image::images/managed-bean.png[title=""Используйте мастер управляемых компонентов JSF для создания нового управляемого компонента""] 3. Нажмите кнопку ""Завершить"". Класс `UserNumberBean` будет создан и открыт в редакторе. Обратите внимание на следующие аннотации (*выделено полужирным шрифтом*): [source,java] ---- package guessNumber; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; /** * * @author nbuser */ *@ManagedBean(name=""UserNumberBean"") @SessionScoped* public class UserNumberBean { /** Creates a new instance of UserNumberBean */ public UserNumberBean() { } } ---- Поскольку вы используете JSF 2.x, можно объявить все относящиеся к JSF компоненты с помощью аннотаций. В предыдущих версиях их необходимо было объявлять в файле настройки Faces (`faces-config.xml`). [tips]#Для просмотра документации Javadoc по всем аннотациям JSF 2.1 обратитесь к link:http://javaserverfaces.java.net/nonav/docs/2.1/managed-bean-javadocs/index.html[+Спецификации аннотации управляемого компонента Faces+].# [[creatingConstructor]] === Создание конструктора Конструктор `UserNumberBean` должен создавать случайное число от 0 до 10 и сохранять его в переменной экземпляра. Таким образом частично формируется бизнес-логика для приложения. 1. Определите конструктор для класса `UserNumberBean`. Введите следующий код (изменения выделены *полужирным шрифтом*). [source,java] ---- public class UserNumberBean { *Integer randomInt;* /** Creates a new instance of UserNumberBean */ public UserNumberBean() { *link:http://docs.oracle.com/javase/7/docs/api/java/util/Random.html[+Random+] randomGR = new Random(); randomInt = new Integer(randomGR.link:http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt%28int%29[+nextInt+](10)); System.out.println(""Duke's number: "" + randomInt);* } } ---- Вышеуказанный код создает случайное число от 0 до 10 и записывает это число в протокол сервера. 2. Исправьте операторы импорта. Для этого щелкните метку4 подсказки ( image::images/hint-icon.png[] ), которая отображается на левой границе редактора, затем выберите параметр для импорта `java.util.Random` в класс. 3. Повторно запустите проект (нажмите кнопку 'Запустить проект' ( image::images/run-project-btn.png[] ) или нажмите F6; fn-F6 в Mac). При выполнении проекта файл протокола сервера автоматически открывается в окне вывода. image::images/output1.png[title=""Файл журнала сервера автоматически открывается в окне вывода.""] Обратите внимание на то, что в окне вывода не отображается ""`Номер Дюка: `"" (как указывалось в конструкторе). Объект `UserNumberBean` не создан, так как по умолчанию в JSF используется _""ленивое"" создание экземпляра_. Таким образом, компоненты в определенных контекстах создаются и инициализируются, только если они необходимы в приложении. Состояния link:http://javaserverfaces.java.net/nonav/docs/2.1/managed-bean-javadocs/index.html[+Документации Javadoc по аннотации `@ManagedBean`+]: _Если атрибут `eager()` имеет значение `true`, а значением `managed-bean-scope` является ""application"", то в среде выполнения при запуске приложения должен быть создан экземпляр этого класса. Создание и сохранение экземпляра должно осуществляться до обслуживания запросов. Если атрибут _eager_ не указан либо имеет значение `false` или элементу `managed-bean-scope` не присвоено значение ""приложение"", по умолчанию происходит ""ленивое"" создание экземпляра и контекстное сохранение управляемого компонента._ 4. Поскольку класс `UserNumberBean` входит в контекст сеанса, реализуется интерфейс `Serializable`. [source,java] ---- @ManagedBean(name=""UserNumberBean"") @SessionScoped public class UserNumberBean *implements Serializable* { ---- Используйте метку подсказки ( image::images/hint-icon.png[] ) для импорта `java.io.Serializable` в класс. [[addingProperties]] === Добавление свойств Страницы Facelets, создаваемые в следующем разделе, должны иметь доступ к числу, вводимому пользователем, и к сгенерированному ответу. Для упрощения этого добавьте свойства `userNumber` и `response` к классу. 1. Начните с объявления `Integer` с именем `userNumber`. [source,java] ---- @ManagedBean(name=""UserNumberBean"") @SessionScoped public class UserNumberBean implements Serializable { Integer randomInt; *Integer userNumber;* ---- 2. Щелкните правой кнопкой мыши в редакторе и выберите команду ""Вставить код"" (ALT+INS; CTRL+I на компьютере Mac). Выберите методы получения и установки. image::images/getter-setter.png[title=""Используйте IDE для создания методов доступа для свойств""] 3. Выберите параметр `userNumber`: `Integer`. Нажмите кнопку ""Создать"". image::images/generate-getters-setters.png[title=""Используйте IDE для создания методов доступа для свойств""] Обратите внимание на то, что методы `getUserNumber()` и `setUserNumber(Integer userNumber)` добавлены в класс. 4. Создайте свойство `response`. Объявите `String` с именем `response`. [source,java] ---- @ManagedBean(name=""UserNumberBean"") @SessionScoped public class UserNumberBean implements Serializable { Integer randomInt; Integer userNumber; *String response;* ---- 5. Создайте метод получения для `response`. (Для этого приложения не требуется метод установки). Для создания кода шаблона в среде IDE можно использовать всплывающее окно ""Создание кода"", упомянутое выше в действии 2. Однако в целях изучения данного руководства просто вставьте нижеуказанный метод в класс. [source,html] ---- public String getResponse() { if ((userNumber != null) && (userNumber.link:http://download.oracle.com/javase/6/docs/api/java/lang/Integer.html#compareTo(java.lang.Integer)[+compareTo+](randomInt) == 0)) { //invalidate user session FacesContext context = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) context.getExternalContext().getSession(false); session.invalidate(); return ""Yay! You got it!""; } else { return ""

Sorry, "" + userNumber + "" isn't it.

"" + ""

Guess again...

""; } } ---- Вышеуказанный метод выполняет две функции. 1. Тестирует введенное пользователем число (`userNumber`) на равенство случайному числу, сгенерированному для сеанса (`randomInt`), и возвращает соответствующий ответ `String`. 2. Определяет пользовательский сеанс как недействительный, если пользователь ввел правильное число (т.е., если `userNumber` равно `randomInt`). Это необходимо для того, чтобы новое сгенерированное число побудило пользователя сыграть еще раз. 6. Щелкните правой кнопкой мыши в области редактора и выберите команду ""Исправить операторы импорта"" (ALT+SHIFT+I; &#8984+SHIFT+I на компьютере Mac). Параметры импорта автоматически создаются для: * `javax.servlet.http.HttpSession` * `javax.faces.context.FacesContext` Можно нажать сочетание клавиш CTRL+ПРОБЕЛ на элементах в редакторе для вызова предложений автозавершения кода и поддержки документации. Нажмите сочетание клавиш CTRL+ПРОБЕЛ, установив курсор на `FacesContext`, для просмотра описания класса из документации Javadoc. image::images/documentation-support.png[title=""Для вызова поддержки автозавершения кода и документации нажмите сочетание клавиш CTRL+ПРОБЕЛ.""] Щелкните значок веб-браузера ( image::images/web-browser-icon.png[] ) в окне документации, чтобы открыть Javadoc во внешнем веб-браузере. [[wire]] == Установление связи между управляемым компонентом и страницами Одной из первичных целей JSF является отмена необходимости записывать шаблонный код для управления объектами <> и их взаимодействием с видами приложений. Пример этого был приведен в предыдущем разделе, в котором JSF создал объект `UserNumberBean` при выполнении приложения. Это представление называется link:http://martinfowler.com/articles/injection.html[+Инверсия управления+] (IoC). Оно позволяет контейнеру принимать на себя ответственность за управление частями приложения, иначе разработчику потребовалось бы написать код с повторениями. В предыдущем разделе был создан управляемый компонент, генерирующий случайное число от 0 до 10. Также было создано два свойства `userNumber` и `response`, представляющие соответственно пользовательский ввод числа и ответ на вопрос пользователя. В этом разделе показаны способы использования `UserNumberBean` и его свойств на веб-страницах. JSF позволяет это сделать с помощью языка выражения. Язык выражения используется для привязки значений свойств к компонентам пользовательского интерфейса JSF, содержащихся на веб-страницах приложений. В этом разделе также показано, как можно воспользоваться внутренними функциями навигации JSF 2.x для перемещения между индексом и страницами ответов. Эта поддержка в среде IDE обеспечивается с помощью функции автозавершения кода и средств документации, которые вызываются нажатием сочетания клавиш CTRL+ПРОБЕЛ, когда курсор установлен на каком-либо элементе в редакторе. Начните с внесения изменений в `index.xhtml`, затем измените `response.xhtml`. На обеих страницах замените элементы формы HTML их эквивалентами JSF, поскольку они определены в link:http://javaserverfaces.java.net/nonav/docs/2.1/vdldocs/facelets/index.html[+библиотеке тегов HTML для JSF+]. Затем используйте язык выражений JSF для привязки значений свойств к выбранным компонентам пользовательского интерфейса. * <> * <> [[index]] === index.xhtml 1. Откройте страницу `index.xhtml` в редакторе. Дважды щелкните узел `index.xhtml` в окне ""Проекты"" или нажмите сочетание клавиш ALT+SHIFT+O для открытия диалогового окна ""Переход к файлу"". Как индекс, так и страницы ответов уже содержат компоненты пользовательского интерфейса JSF, необходимые для этого упражнения. Просто раскомментируйте их и закомментируйте элементы HTML, используемые в настоящий момент. 2. Закомментируйте элемент формы HTML. Для этого выделите элемент формы HTML, как показано на изображении ниже, затем нажмите CTRL+/ (&#8984+/ на компьютере Mac). *Примечание. *Для выделения воспользуйтесь функцией перетаскивания в редакторе с помощью мыши или с помощью клавиатуры удерживайте клавишу Shift и используйте клавиши со стрелками. image::images/comment-out.png[title=""Выделите код, затем нажмите Ctrl-/ для закомментирования кода""] Для переключения комментариев нажмите сочетание клавиш CTRL+/ (&#8984+/ на компьютере Mac). Эту комбинацию клавиш также можно использовать для других типов файлов, например, Java и CSS. 3. Раскомментируйте компонент формы HTML для JSF. Выделите этот компонент, как показано на рисунке ниже, затем нажмите CTRL+/ (&#8984+/ на компьютере Mac). *Примечание.* Возможно, вам придется нажать Ctrl-/ дважды, чтобы раскомментировать код. image::images/comment.png[title=""Выделите закомментированный код, затем нажмите Ctrl-/ для удаления комментария""] После того как компонент формы HTML для JSF раскомментирован, в редакторе будет указано, что теги ``, `` и `` не объявлены. image::images/undeclared-component.png[title=""Редактор обеспечивает сообщения об ошибках для необъявленных компонентов""] 4. Для объявления этих компонентов используйте автозавершение кода IDE, чтобы добавить пространство имен библиотеки тегов в тег `` страницы. Наведите курсор на любой из необъявленных тегов, нажмите Alt-Enter и нажмите Enter, чтобы добавить предложенные библиотеки тегов. (При наличии нескольких параметров перед нажатием клавиши ВВОД убедитесь, что выбран тег, отображаемый в редакторе.) Пространство имен библиотеки тегов HTML для JSF добавляется к тегу `` (*выделено ниже полужирным шрифтом*), и указания на ошибки исчезают. *Примечание.* Если в IDE нет возможности добавить библиотеку тегов, потребуется вручную изменить элемент ```` . [source,java] ---- ---- 5. Используйте язык выражения JSF для привязки свойства `userNumber` для `UserNumberBean` к компоненту `inputText`. Атрибут `value` используется для указания текущего значения визуализируемого компонента. Введите в код, отображаемый ниже *полужирным шрифтом*. [source,java] ---- ---- В языке выражения JSF используется синтаксис `#{}`. Внутри этих парных символов указывается имя требуемого управляемого компонента и его свойство, разделенные точкой (`.`). Теперь при отправке данных формы на сервер значение автоматически сохраняется в свойстве `userNumber` с помощью метода установки свойств (`setUserNumber()`). Кроме того, если страница запрошена и значение для `userNumber` уже установлено, значение автоматически отображается в визуализированном компоненте `inputText`. Дополнительные сведения приведены в link:http://docs.oracle.com/javaee/7/tutorial/doc/jsf-develop001.htm#BNAQP[+Руководстве по Java EE 7. Глава 12.1.2 Использование языка выражений для создания ссылок на управляемые сеансные объекты+]. 6. Укажите адресата для запроса, который вызывается при нажатии кнопки формы. В HTML-версии формы это возможно выполнить с помощью атрибута `action` тега `
`. С помощью JSF можно использовать атрибут `action` для `commandButton`. Кроме того, благодаря внутренней функции навигации JSF 2.x вам нужно только указать имя конечного файла без расширения. Введите код, отображаемый ниже *полужирным шрифтом*. [source,xml] ---- ---- В среде выполнения JSF осуществляется поиск файла с именем `response`. Предполагается, что расширение файла такое же, как у файла, из которого произошел запрос (`index*.xhtml*`), и поиск файла `response.xhtml` выполняется в папке исходного файла (т.е. в корневом веб-узле). *Примечание. *JSF 2.x позволяет упростить разработку. При использовании JSF 1.2 для этого проекта необходимо объявить правило перехода в файле настройки Faces. Объявление правила может выглядеть следующим образом: [source,xml] ---- /index.xhtml response /response.xhtml ---- Нижеприведенные действия с 7 по 12 являются дополнительными. Если необходимо выполнить быструю сборку проекта, сразу перейдите к <>. 7. Протестируйте, выполняется ли вызов метода `setUserNumber()` вышеуказанным выражением на языке выражения при обработке запроса. Для выполнения этого используйте отладчик Java среды IDE. Переключите на класс `UserNumberBean` (нажмите сочетание клавиш CTRL+TAB и выберите из списка файл). Установите точку останова в сигнатуре метода `setUserNumber()`. Это можно сделать, щелкнув мышкой в области левого поля. Появится красный значок, указывающий, что точка останова метода установлена. image::images/set-breakpoint.png[title=""Щелкните левую границу редактора для задания точек останова""] 8. Нажмите кнопку 'Отладка проекта' (image::images/breakpoint-btn.png[]) на главной панели инструментов IDE. Начинается сеанс отладки, и в браузере открывается страница приветствия проекта. *Примечания.* * Вам может быть предложено подтвердить порт сервера для отладки приложений. * Если появится диалоговое окно 'Отладить проект', выберите опцию по умолчанию 'Java на стороне сервера' и нажмите кнопку 'Отладка'. 9. В браузере введите номер в форму и нажмите кнопку ""Отправить"". 10. Вернитесь в среду IDE и проверьте класс `UserNumberBean`. Отладчик приостановлен в методе `setUserNumber()`. image::images/debugger-suspended.png[title=""Выполняется приостановка отладчика в соответствии с точками останова""] 11. Откройте окно ""Переменные отладчика"" (выберите ""Окно"" > ""Отладка > ""Переменные"" или нажмите сочетание клавиш CTRL+SHIFT+1). На экран будут выведены значения переменных для точки, в которой приостановлен отладчик. image::images/variables-window.png[title=""Отслеживание значений переменных с помощью окна 'Переменные отладчика'""] На приведенном выше изображении значение ""`4`"" предоставлено для переменной `userNumber` в сигнатуре `setUserNumber()`. (Число 4 введено в форму.) ""`this`"" относится к объекту `UserNumberBean`, созданному для пользовательского сеанса. Далее можно отметить, что значение свойства `userNumber` в настоящий момент равно `null`. 12. На панели отладчика нажмите кнопку 'Вход в' ( image::images/step-into-btn.png[] ). Отладчик выполняет обработку строки, на которой он в настоящий момент приостановлен. Происходит обновление окна ""Переменные"" с указанием выполненных изменений. image::images/variables-window2.png[title=""Окно переменных обновляется при переходе по коду""] Теперь свойству `userNumber` присвоено значение, введенное в форме. 13. Выберите Отладка> Завершить сеанс отладки (Shift-F5; Shift-Fn-F5 на Mac) из главного меню, чтобы остановить отладчик. [[response]] === response.xhtml 1. Откройте страницу `response.xhtml` в редакторе. В окне ""Проекты"" дважды щелкните узел `response.xhtml` или нажмите сочетание клавиш ALT+SHIFT+O для открытия диалогового окна ""Переход к файлу"". 2. Закомментируйте элемент формы HTML. Выделите открывающий и закрывающий теги HTML `` и код между ними, затем нажмите CTRL+/ (&#8984+/ на компьютере Mac). *Примечание: * Для выделения воспользуйтесь функцией перетаскивания в редакторе с помощью мыши или с помощью клавиатуры удерживайте клавишу Shift и используйте клавиши со стрелками. 3. Раскомментируйте компонент формы HTML для JSF. Выделите открывающий и закрывающий теги `` и код между ними, затем нажмите CTRL+/ (&#8984+/ на компьютере Mac). На данном этапе, код между тегами `` выглядит следующим образом: [source,html] ----

[ response here ]

---- После того как компонент формы HTML для JSF раскомментирован, в редакторе будет указано, что теги `` и `` не объявлены. 4. Для объявления этих компонентов используйте автозавершение кода IDE, чтобы добавить пространство имен библиотеки тегов в тег `` страницы. Используйте поддержку автозавершения кода в редакторе для добавления необходимых пространств имен JSF к файлу. При выборе тега JSF или Facelets через автозавершение кода происходит автоматическое добавление требуемого пространства имен к корневому элементу документа. Подробнее см. в разделе link:jsf20-support.html#facelets[+Поддержка JSF 2.x в IDE NetBeans+]. Установите курсор на один из необъявленных тегов и нажмите сочетание клавиш CTRL+ПРОБЕЛ. Предложения автозавершения кода и отображения поддержки документации. image::images/code-completion2.png[title=""Для вызова рекомендаций по автозавершению кода и всплывающего окна документации""] Нажмите ENTER. (При наличии нескольких параметров перед нажатием клавиши ВВОД убедитесь, что выбран тег, отображаемый в редакторе.) Пространство имен библиотеки тегов HTML для JSF добавляется к тегу `` (*выделено ниже полужирным шрифтом*), и указания на ошибки исчезают. [source,java] ---- ---- 5. Укажите адресата для запроса, который вызывается при нажатии пользователем кнопки формы. Кнопку необходимо установить так, чтобы при ее нажатии пользователь возвращался на страницу-указатель. Для этого следует использовать атрибут `action` для `commandButton`. Введите в код, отображаемый *полужирным шрифтом*. [source,xml] ---- ---- *Примечание. * При вводе `action=""index""` пользователи в работе зависят от функции явной навигации в JSF. При нажатии кнопки формы в среде выполнения JSF осуществляется поиск файла с именем `index`. Предполагается, что расширение файла такое же, как у файла, от которого был направлен запрос (`response*.xhtml*`), и поиск файла `index.xhtml` выполняется в папке исходного файла (т.е. в корневом веб-узле). 6. Замените статический текст ""[здесь ответ]"" значением свойства `response` для `UserNumberBean`. Для этого используйте язык выражения JSF. Введите следующее (*выделено полужирным шрифтом*). [source,html] ----

**

---- 7. Запустите проект (нажмите кнопку 'Запустить проект' ( image::images/run-project-btn.png[] ) или нажмите F6; fn-F6 в Mac). При появлении в браузере страницы приветствия введите номер и нажмите `submit`. Страница ответа будет отображаться следующим образом (выводится на экран, если введен неправильный номер). image::images/response2.png[title=""Просмотрит текущее состояния проекта в браузере""] Две ошибки в текущем состоянии страницы ответа: 1. Теги HTML `

` отображаются в ответном сообщении. 2. Кнопка ""Назад"" не отображается в правильном местоположении. (Сравните с <>.) При выполнении следующих двух шагов эти ошибки устраняются. 8. Установите атрибут `escape` тега `` на `false`. Установите курсор между `outputText` и `value`, вставьте пробел и нажмите сочетание клавиш CTRL+ПРОБЕЛ для вызова автозавершения кода. Прокрутите вниз для выбора атрибута `escape` и проверки документации. image::images/escape-false.png[title=""Нажмите Ctrl-Пробел для просмотра возможных значений атрибутов и документации""] Как указано в документации, значение `escape` установлено по умолчанию на `true`. Это означает, что символы, которые стандартно анализируются как html, включены в строку, как указано выше. Установка значения на `false` означает, что символы, анализируемые как HTML, можно визуализировать как HTML. Нажмите ENTER, затем в качестве значения введите `false`. [source,xml] ----

---- 9. Установите атрибут `prependId` тега `` на `false`. Установите курсор сразу после ""`m`"" в `` и вставьте пробел, затем нажмите сочетание клавиш CTRL+ПРОБЕЛ для вызова автозавершения кода. Прокрутите вниз для выбора атрибута `prependId` и проверки документации. Затем нажмите ENTER и в качестве значения введите `false`. [source,java] ---- ---- В JSF применяются внутренние идентификаторы для отслеживания компонентов пользовательского интерфейса. В текущем примере при проверке исходного кода визуализируемой страницы отображается следующее: [source,xml] ---- ---- Идентификатором элемента формы является `j_idt5`, и этот идентификатор _предшествует_ идентификатору кнопки ""Назад"", включенной в форму (*выделено полужирным шрифтом* в приведенном выше примере). Поскольку кнопка ""Назад"" зависит от правила стиля `#backButton` (определенного в `stylesheet.css`), это правило становится блокированным, если идентификатор JSF предшествует идентификатору кнопки. Этого можно избежать, если для `prependId` установить значение `false`. 10. Повторно запустите проект (нажмите кнопку 'Запустить проект' ( image::images/run-project-btn.png[] ) или нажмите F6; fn-F6 в Mac). Введите число на странице приветствия, затем нажмите кнопку ""Отправить"". Теперь на странице ответа отображается ответное сообщение без тегов `

`, и кнопка ""Назад"" размещена правильно. image::images/response3.png[title=""Просмотрит текущее состояния проекта в браузере""] 11. Нажмите кнопку ""Назад"". Поскольку текущее значение свойства `userNumber` для `UserNumberBean` привязано к компоненту `inputText` JSF, ранее введенное число теперь отображается в текстовом поле. 12. Проверьте протокол сервера в окне вывода среды IDE (CTRL+4; &#8984+4 на компьютере Mac) для определения правильного загаданного числа. Если по каким-то причинам просмотреть протокол сервера невозможно, откройте его посредством переключения на окно ""Службы"" (CTRL+5; &#8984+5 на компьютере Mac) и развертывания узла ""Серверы"". Затем щелкните правой кнопкой мыши сервер GlassFish, на котором развернут проект и выберите 'Просмотреть журнал сервера'. Если номер не отображается в журнале сервера, попробуйте повторно выполнить сборку приложения, щелкнув правой кнопкой мыши узел проекта и выбрав 'Очистка и сборка'. 13. Введите правильное число и нажмите кнопку ""Отправить"". В приложении происходит сравнение введенного числа с текущим сохраненным числом и выводится соответствующее сообщение. image::images/yay.png[title=""При вводе соответствующего числа отображается правильный отклик""] 14. Нажмите еще раз кнопку ""Назад"". Обратите внимание на то, что ранее введенное число более не отображается в текстовом поле. Следует помнить о том, что метод `getResponse()` для `UserNumberBean` <> при угадывании правильного числа. [[template]] == Применение шаблона Facelets Facelets сегодня является стандартной технологией отображения для JSF 2.x. Facelets - это облегченная платформа шаблонов, которая поддерживает все компоненты JSF пользовательского интерфейса и используется для построения и визуализации дерева компонентов JSF для просмотра приложений. Кроме того, эта технология обеспечивает поддержку разработки при возникновении ошибок языка выражений за счет возможности проверять трассировку стека, дерево компонентов и контекстные переменные. Хотя, возможно, вы об этом не задумывались, файлы `index.xhtml` и `response.xhtml`, с которыми вы работаете в этом руководстве, являются страницами Facelets. Страницы Facelets имеют расширение `.xhtml` и, поскольку вы работаете в проекте JSF 2.x (библиотеки JSF 2.x включают в себя файлы JAR Facelets), эти представления способны надлежащим образом визуализировать дерево компонентов JSF. Целью этого раздела является знакомство с созданием шаблона Facelets. Для проектов с несколькими представлениями зачастую полезно применять файл шаблона, определяющего структуру и внешний вид для нескольких представлений. При обслуживании запросов приложение вставляет динамически подготовленное содержимое во временный файл и отправляет результат обратно клиенту. Хотя данный проект имеет только два представления (страницу приветствия и страницу ответа), можно легко отметить, что большая часть содержимого в них дублируется. Это дублированное содержимое можно перенести в шаблон Facelets и создать файлы клиента шаблона для обработки содержимого, которое является специфичным для страницы приветствия и страницы ответа. В среде IDE существует link:jsf20-support.html#faceletsTemplate[+мастер создания шаблона Facelets+] для создания шаблонов Facelets и мастер создания клиента шаблона Facelets для создания файлов, зависящих от шаблона. В этом разделе описано использование этих мастеров. *Примечание.* IDE также предоставляет мастер страниц JSF, что позволяет создавать индивидуальные страницы Facelets для проекта. Подробнее см. в разделе link:jsf20-support.html#jsfPage[+Поддержка JSF 2.x в IDE NetBeans+]. * <> * <> [[templateFile]] === Создание файла шаблона Facelets 1. Создайте файл шаблона Facelets. Нажмите сочетание клавиш CTRL+N (&#8984+N на компьютере Mac) для открытия мастера создания файлов. Выберите категорию ""JavaServer Faces"", затем ""Шаблон Facelets"". Нажмите кнопку ""Далее"". 2. В поле ""Имя файла"" введите `template`. 3. Выберите один из восьми стилей размещения и нажмите кнопку ""Готово"". (Вы будете использовать существующую таблицу стилей, так что не имеет значения, какой стиль вы выберете.) image::images/layout-style.png[title=""Мастер шаблонов Facelets позволяет сделать выбор из распространенных стилей компоновки""] Мастером будут созданы файл `template.xhtml` и сопутствующие таблицы стилей на основе выбора, которые будут помещены в папку `resources` > `css` в корневом веб-узле проекта. После завершения выполнения мастера в редакторе открывается файл шаблона. Для просмотра шаблона в браузере, щелкните правой кнопкой мыши в редакторе и выберите 'Просмотр'. 4. Проверьте разметку файла шаблона. Обратите внимание на следующие моменты. * Библиотека тегов `facelets` объявлена в теге `` страницы. Библиотека тегов имеет префикс `ui`. [source,java] ---- ---- * На странице Facelets используются теги `` и `` вместо тегов HTML `` и ``. При использовании этих тегов у Facelets появляется возможность создания дерева компонентов, которое включает в себя всю страницу. * Страница ссылается на таблицы стилей, которые также создаются при завершении выполнения мастера. [source,xml] ---- ** ** Facelets Template ---- * Теги `` используются в теле страницы для каждого раздела, связанного с выбранным стилем размещения. Каждый тег `` имеет атрибут `name`, определяющий раздел. Например: [source,html] ----

*Top*
---- 5. Повторно проверьте страницу <> и страницу <>. Содержимым, которое изменяется на этих страницах, является только заголовок и текст в сером квадрате. Следовательно, шаблон может включать в себя все остальное содержимое. 6. Замените все содержимое файла шаблона содержимым, приведенным ниже. [source,html] ---- <ui:insert name=""title"">Facelets Template</ui:insert>
Box Content Here
---- Приведенный выше код реализует следующие изменения. * Файл `stylesheet.css` проекта заменяет ссылки на таблицу стилей шаблона, созданные в мастере. * Все теги `` (вместе с тегами `
`) удаляются за исключением одного с именем `box`. * В теги `` вставляется заголовок страницы с именем `title`. 7. Скопируйте в шаблон соответствующий код из файла `index.xhtml` или файла `response.xhtml`. Добавьте содержимое, отображаемое ниже *полужирным шрифтом*, в теги `` файла шаблона. [source,html] ---- *
*
Box Content Here
*
*
---- 8. Выполните проект. При открытии страницы приветствия в браузере измените URL-адрес на следующий: [source,java] ---- http://localhost:8080/jsfDemo/faces/template.xhtml ---- Файл шаблона отображается следующим образом: image::images/facelets-template.png[title=""Просмотрите шаблон Facelets в браузере""] Теперь проект включает в себя файл шаблона, предоставляющий внешний вид и структуру всех представлений. Теперь можно создавать файлы клиента для вызова шаблона. [[templateClient]] === Создание файлов клиента шаблона Создайте файлы клиента шаблона для страниц приветствия и ответа. Укажите имя файла клиента шаблона для страницы приветствия `greeting.xhtml`. Для страницы ответа – файл `response.xhtml`. ==== greeting.xhtml 1. Нажмите сочетание клавиш CTRL+N (⌘-N на компьютере Mac) для открытия мастера создания файлов. Выберите категорию ""JavaServer Faces"", затем ""Клиент шаблона Facelets"". Нажмите кнопку ""Далее"". 2. В поле ""Имя файла"" введите `greeting`. 3. Нажмите кнопку ""Обзор"" рядом с полем ""Шаблон"", затем в открывшемся диалоговом окне перейдите к файлу `template.xhtml`, созданному в предыдущем разделе. image::images/template-client.png[title=""Мастер создания клиентов шаблона Facelets""] 4. Нажмите кнопку ""Завершить"". Будет создан новый файл клиента шаблона `greeting.xhtml`, который откроется в редакторе. 5. Проверьте разметку. Обратите внимание на содержимое, выделенное *полужирным шрифтом*. [source,xml] ---- title box ---- Файл клиента шаблона ссылается на шаблон с помощью атрибута `template` тега ``. Поскольку шаблон содержит теги `` для `title` и `box`, клиент шаблона содержит теги `` для этих двух имен. Содержимое, указываемое в тегах ``, - это содержимое, вставляемое в шаблон в тегах `` соответствующего имени. 6. Укажите `greeting` в качестве заголовка файла. Внесите следующее изменение, выделенное *полужирным шрифтом*. [source,xml] ---- *Greeting* ---- 7. Перейдите к файлу `index.xhtml` (нажмите CTRL+TAB) и скопируйте содержимое, которое обычно появляется в сером квадрате, выведенном на визуализируемой странице. Затем обратно переключитесь на файл `greeting.xhtml` и вставьте его в файл клиента шаблона. (Изменения *выделены полужирным шрифтом*.) [source,xml] ---- *

Hi, my name is Duke!

I'm thinking of a number
between 0 and 10.
Can you guess it?
*
---- 8. Объявите библиотеку тегов HTML JSF для файла. Установите курсор на один из тегов, помеченных флагом ошибки (любой тег с префиксом ""`h`""), и нажмите сочетание клавиш CTRL+ПРОБЕЛ. Затем выберите тег из списка предложений автозавершения кодов. Пространство имен библиотеки тегов добавляется к тегу `` файла (выделено ниже *полужирным шрифтом*), и указания на ошибки исчезают. [source,java] ---- ---- При установке курсора после ""`m`"" в `` и нажатии сочетания клавиш CTRL+ПРОБЕЛ к файлу автоматически добавляется пространство имен. Если при нажатии сочетания клавиш CTRL+ПРОБЕЛ доступен только один логический параметр, он немедленно применяется к файлу. Библиотека тегов JSF автоматически объявляется при вызове автозавершения кода в тегах. ==== response.xhtml Поскольку проект уже содержит файл с именем `response.xhtml` и известно, как теперь должен выглядеть файл клиента шаблона, измените существующий файл `response.xhtml`, чтобы получить соответствующий файл клиента шаблона. (В целях данного руководства просто скопируйте и вставьте предоставленный код.) 1. Откройте файл `response.xhtml` в редакторе. (Если он уже открыт, нажмите CTRL+TAB и выберите его). Замените содержимое всего файла нижеприведенным кодом. [source,xml] ---- Response

---- Обратите внимание на то, что файл идентичен файлу `greeting.xhtml`, за исключением содержимого, указанного в тегах `` для `title` и `box`. 2. В дескрипторе развертывания `web.xml` проекта измените запись файла приветствия таким образом, чтобы при запуске приложения открывалась страница, представленная файлом `greeting.xhtml`. В окне 'Проекты' дважды щелкните 'Файлы конфигурации' > `web.xml`, чтобы открыть его в редакторе. На вкладке ""Страницы"" измените поле ""Файлы приветствия"" на `faces/greeting.xhtml`. image::images/welcome-files.png[title=""Измените запись 'Файлы приветствия' в дескрипторе развертывания""] 3. Выполните проект и посмотрите, как он выглядит в браузере. Нажмите F6 (fn-F6 в Mac) или нажмите кнопку 'Запустить проект'( image::images/run-project-btn.png[] ) на главной панели инструментов. Проект будет развернут на сервере GlassFish и открыт в браузере. При использовании шаблона Facelets и файлов клиента шаблона поведение приложения не меняется. Выделив повторяющийся код на страницах приветствия и ответа приложения, можно уменьшить размер приложения и устранить возможность написания повторяющегося кода, если впоследствии будут добавляться другие страницы. Это позволяет сделать разработку более эффективной и упростить управление при работе с большими проектами. link:/about/contact_form.html?to=3&subject=Feedback:%20Introduction%20to%20JSF%202.0[+Отправить отзыв по этому учебному курсу+] [[seealso]] == Дополнительные сведения Подробнее о JSF 2.x см. в следующих ресурсах. === Статьи и учебные курсы по NetBeans * link:jsf20-support.html[+Поддержка JSF 2.x в IDE NetBeans+] * link:jsf20-crud.html[+Создание приложения JavaServer Faces 2.x CRUD на основе базы данных+] * link:../../samples/scrum-toys.html[+Scrum Toys – полный пример приложения JSF 2.0+] * link:../javaee/javaee-gettingstarted.html[+Начало работы с приложениями Java EE+] * link:../../trails/java-ee.html[+Учебная карта по Java EE и Java Web+] === Внешние ресурсы * link:http://www.oracle.com/technetwork/java/javaee/javaserverfaces-139869.html[+Технология JavaServer Faces+] (официальная домашняя страница) * link:http://jcp.org/aboutJava/communityprocess/final/jsr314/index.html[+Спецификация JSR 314 для JavaServer Faces 2.0+] * link:http://docs.oracle.com/javaee/7/tutorial/doc/jsf-develop.htm[+Учебный курс по Java EE 7. Глава 12. Разработка по технологии JavaServer Faces+] * link:http://javaserverfaces.dev.java.net/[+GlassFish Project Mojarra+] (официальный пример реализации JSF 2.х) * link:http://forums.oracle.com/forums/forum.jspa?forumID=982[+Интернет-форум OTN: JavaServer Faces+] * link:http://www.jsfcentral.com/[+JSF Central+] === Блоги * link:http://www.java.net/blogs/edburns/[+Эд Бернс (Ed Burns)+] * link:http://www.java.net/blogs/driscoll/[+Джим Дрисколл (Jim Driscoll)+] ",16231,True,3226.777797422072,median "== Mappings As already mentioned in the <> section, the entity view module builds up on the core module. Some of the basics like link:{core_doc}#implicit-joins[implicit joins] and the basic link:{core_doc}#expressions[expression structure] should be known to understand all of the following mapping examples. Entity views are to entities in ORM, what table views are to tables in an RDBMS. They represent projections on the entity model. In a sense you can say that entity views are DTOs 2.0 or DTOs done right. One of the unique features of entity views is that it *only* imposes a structure and the projections, but the base query defines the data source. {projectname} tried to reduce as much of the boilerplate as possible for defining the structure and the projections by employing a convention over configuration approach. The result of these efforts is that entity views are defined as interfaces or abstract classes mostly containing just getter definitions that serve as attribute definitions. To declare that an interface or an abstract class as entity view, you have to annotate it and specify the entity class for which this entity view provides projections. [source,java] ---- @EntityView(Cat.class) interface CatView { ... } ---- So an entity view can be seen as a named wrapper for a bunch of attributes, where every attribute has some kind of mapping that is based on the attributes the entity type offers. An attribute is declared by defining a public abstract method in an entity view i.e. every abstract method is considered to be an attribute. [source,java] ---- @EntityView(Cat.class) interface CatView { String getName(); } ---- Since every method of an interface is abstract and public, you can omit the `abstract` and `public` keywords. In this simple example you can see that the `CatView` has an attribute named `name`. The implicit mapping for the attribute is the attribute name itself, so `name`. This means that the entity view attribute `name` declared by the abstract method `getName()` is mapped to the entity attribute `name`. NOTE: Since entity views and their mappings are validated during startup against the entity model, you should see any mapping related runtime errors and can be sure it works if it doesn't fail to start One of the nice things about using interfaces is that you can have multiple inheritance. If you separate concerns in separate _feature interfaces_, you can effectively make use of multiple inheritance. [source,java] ---- interface NameView { String getName(); } interface AgeView { Long getAge(); } @EntityView(Cat.class) interface CatView extends NameView, AgeView { } ---- In this example `CatView` has two attributes, `name` and `age`. Even though the interfaces are not entity views, they could have custom mappings. === Mapping types So far, you have mostly seen basic attribute mappings in entity views, but there is actually support for far many mapping types. * Basic mappings - maps basic attributes from entities into entity views * Subview mappings - maps a *ToOne relation of an entity to an entity view * Flat view mappings - maps an embeddable or association of an entity to a flat entity view * Subquery mappings - maps the result of a subquery to a basic attribute into entity views * Parameter mappings - maps named query parameters into an entity view * Entity mappings - maps *ToOne or *ToMany relations of an entity as is into an entity view * Collection mappings - maps *ToMany relations of an entity into an entity view with support for basic, subview and embeddable types * Correlated mappings - correlates an entity type by some key and maps it or an attribute of it into an entity view as subview or basic type respectively WARNING: In general we do not recommend to make extensive use of entity mappings as it defeats the purpose of entity views and can lead to lazy loading issues Apart from mapping attributes, it is also possible have a constructor and map parameters when using an abstract class. One of the biggest use cases for this is for doing further transformations on the data that can't be pushed to the DBMS like e.g. money formatting. === Mapping defaults As mentioned before, the entity view module implements a convention over configuration approach and thus has some smart defaults for mappings. Whenever an attribute(getter method) without a mapping annotation is encountered, a default mapping to the same named entity attribute will be created. If there is none, it will obviously report an error. [[anchor-id-mappings]] === Id mappings Id mappings declare that an attribute represents the identifier i.e. can be used to uniquely identify an entity view object. The id mapping is declared by annotating the desired attribute with `@IdMapping` and optionally specifying the mapping path. Having an id attribute allows an entity view to map collections, be mapped in collections and gives an entity view object a meaningful identity. If an entity view has no id mapping, it is considered to be a flat view which probably only makes sense for scalar results or embedded objects. TIP: It is generally recommended to always declare an id mapping if possible. When an id mapping is present, the generated entity view implementation's equals-hashCode implementation will be based on it. Otherwise it will consider *all* attributes in the equals-hashCode implementation. [source,java] ---- @EntityView(Cat.class) interface CatView { @IdMapping Long getId(); } ---- [[anchor-flat-view-id-mappings]] === Flat view id mappings A flat view id mapping is given when the type of the id attribute is a flat view type. This is the case when the view type has no id declared. It's very similar to subview mappings and is mostly used when working with JPA embeddable types. Imagine the following model for illustration purposes. [source,java] ---- @EntityView(Cat.class) interface CatIdView { String getName(); } @EntityView(Cat.class) interface CatView { @IdMapping(""this"") CatIdView getId(); } ---- This example already makes use of many concepts. It declares the `CatIdView` as flat view with a basic mapping and the `CatView` with a flat view id. The mapping for the flat view id in `CatView` uses to the <> expression extension to allow the flat view to be based on the same entity that is backing the `CatView`. NOTE: Since flat view types will consider *all* attributes in the equals-hashCode implementation, the type shouldn't contain unnecessary attributes if possible. === Basic mappings A basic mapping is declared by annotating the desired attribute with `@Mapping` and specifying the mapping expression. An attribute that has no mapping annotations is only considered to have a basic mapping if it is of a basic type like e.g. Integer. Without a mapping annotation, the default mapping rules apply. In general, every non-collection and non-managed type is considered to be basic. Managed types are JPA managed types and entity view types. Although most example only use path expressions for the mapping, it is actually allowed to use any link:{core_doc}#expressions[scalar expression] that JPQL or {projectname} allows. [source,java] ---- @EntityView(Cat.class) interface CatView { @IdMapping Long getId(); @Mapping(""UPPER(name)"") String getUpperName(); } ---- As you might expect, the expression `UPPER(name)` will upper-case the name, so `getUpperName()` will return the upper-cased name. Applying such an entity view on a simple query builder will show what happens behind the scenes. [source,java] ---- List result = evm.applySetting( EntityViewSetting.create(CatView.class), cbf.create(em, Cat.class) ).getResultList(); ---- [source,sql] ---- SELECT cat.id, UPPER(cat.name) FROM Cat cat ---- The expression in the mapping ends up as select item in the query just as expected. === Subview mappings Subview and embeddable view mappings are similar to basic mappings in the sense that the same rules apply, except for the allowed mappings. Since these mappings get their data from objects of managed types, only path expressions are allowed for their mappings. Path expressions can have arbitrary depth i.e. multiple de-references like `relation.subRelation.otherRelation` and path elements can be of the following types: * Simple path elements that refer to entity type attributes * `TREAT` expression like `TREAT(..).subRelation` * Qualified expression like `KEY(..).subRelation` * Array expression like `relation[:param].subRelation` A subview mapping is given when the type of the attribute is a entity view type. Since a entity view is always declared for a specific entity type, the target type of the subview mapping and the entity view's entity type must be compatible. This means that you could apply a `AnimalView` to a `Cat` if it extends `Animal` but can't apply a `PersonView` since it's not compatible i.e. `Cat` is not a subtype of `Person`. [source,java] ---- @EntityView(Person.class) interface PersonView { @IdMapping Long getId(); String getName(); } @EntityView(Animal.class) interface AnimalView { @IdMapping Long getId(); String getName(); } @EntityView(Cat.class) interface CatView { @IdMapping Long getId(); AnimalView getFather(); } ---- As you might imagine, the `CatView` will additionally select attributes of the father relation since they are requested by the `AnimalView`. In order to understand the following generated query, you should know what an link:{core_doc}#implicit-joins[implicit join] does and how entity views make use of such implicit joins. Behind the scenes, the entity views runtime will apply a select on the criteria builder for the expressions `cat.id`, `father.id` and `father.name`. The expression `father.name` accesses an entity attribute is only accessible when actually joining the relation. This is why an implicit/default join is generated for the father relation. [source,sql] ---- SELECT cat.id, father_1.id, father_1.name FROM Cat cat LEFT JOIN cat.father father_1 ---- Since the `father` relation is optional or nullable, a (default) left join is created due to the rules of link:{core_doc}#model-awareness[model awareness] in implicit joins. This is a perfect fit for entity views as the subview object will be simply `null` if a cat has no father. If the implicit join worked like JPQL defines it, an inner join would have to be created. An inner join would mean that cats without a father would get filtered out which is an undesirable effect since we only want a projection on top of a base query. NOTE: Subviews can in turn have subviews again, so there is no limitation regarding the depth. The only requirement is that there is no cycle. ==== Flat view mappings A flat view mapping is given when the type of the attribute is a flat view type. This is the case when the entity view has no id declared. It's very similar to subview mappings and is mostly used when working with JPA embeddable types. Note that a flat view can be used like a normal view except when * it is used as view root i.e. the flat view is the entity view type used in `EntityViewSetting`, * it is embedded in a flat view which in turn is the view root i.e. the parent is a flat view that is used in `EntityViewSetting` * or it is used as subview for a non-indexed collection then the flat view can't have collection attributes with fetch strategy `JOIN`. The reason is that the elements of the collection can't be matched with the flat view as it has no identity it can use for matching. Imagine the following model for illustration purposes. [source,java] ---- @Embeddable class Name { String firstName; String lastName; } @Entity class Person { @Id @GeneratedValue Long id; @Embedded Name name; } @EntityView(Name.class) interface SimpleNameView { String getFirstName(); } @EntityView(Person.class) interface PersonView { @IdMapping Long getId(); SimpleNameView getName(); } ---- Applying a `PersonView` would produce a query like [source,sql] ---- SELECT person.id, person.name.firstName FROM Person person ---- Such a flat view can also be used with the <> which is similar to JPAs `@Embedded`. NOTE: A limitation in Hibernate actually requires the use of flat entity views for mapping of element collections i.e. you can map the element collection 1:1 to the entity view. Flat views for singular attributes are by default always created, even if all attributes of a flat view are `null` i.e. the flat view is empty. This can be overridden by annotating the attribute with `@EmptyFlatViewCreation(false)` or globally by specifying the configuration option <>. When empty flat view creation is disabled, the attribute value will be set to `null` instead of an empty flat view. [[anchor-subquery-mappings]] === Subquery mappings Subquery mappings allow to map scalar subqueries into entity views and are declared by annotating the desired attribute with `@MappingSubquery` and specifying a link:{entity_view_jdoc}/persistence/view/SubqueryProvider.html[`SubqueryProvider`]. The following example should illustrate the usage: [source,java] ---- @EntityView(Cat.class) interface CatView { @IdMapping Long getId(); @MappingSubquery(KittenCountSubqueryProvider.class) Long getKittenCount(); class KittenCountSubqueryProvider implements SubqueryProvider { @Override public T createSubquery(SubqueryInitiator subqueryBuilder) { return subqueryBuilder.from(Cat.class, ""subCat"") .select(""COUNT(*)"") .whereOr() .where(""subCat.father.id"").eqExpression(""EMBEDDING_VIEW(id)"") .where(""subCat.mother.id"").eqExpression(""EMBEDDING_VIEW(id)"") .endOr() .end(); } } } ---- This entity view already comes into contact with the link:{core_doc}[core] API for creating subqueries. It produces just what it defines, a subquery in the select clause. [source,sql] ---- SELECT cat.id, ( SELECT COUNT(*) FROM Cat subCat WHERE subCat.father.id = cat.id OR subCat.mother.id = cat.id ) FROM Cat cat ---- In the subquery provider before you saw the usage of `EMBEDDING_VIEW` which is gone in the final query. This is because `EMBEDDING_VIEW` is a way to refer to attributes of the relation of the entity view into which the subquery is embedded without having to refer to the concrete the query alias. For more information on this check out the documentation of the <> TIP: The subquery was just used for illustration purposes and could be replaced with a basic mapping `SIZE(kittens)` which would also generate a more efficient query. [[anchor-parameter-mappings]] === Parameter mappings A parameter mapping is a convenient way to _inject_ the values of query parameters or optional parameters into instances of an entity view. Introducing a parameter mapping with `@MappingParameter` will introduce a _fake_ select item. If a parameter is not used in a query, `NULL` will be injected into the entity view. [source,java] ---- @EntityView(Cat.class) interface CatView { @IdMapping Long getId(); @MappingParameter(""myParam"") String getMyParam(); } ---- [source,sql] ---- SELECT cat.id, NULLIF(1,1) FROM Cat cat ---- Parameter mappings are probably most useful in <> where they can be used for some transformation logic. Optional parameters can be configured globally through link:{entity_view_jdoc}/persistence/view/spi/EntityViewConfiguration.html#setOptionalParameter(java.lang.String,%20java.lang.Object)[`setOptionalParameter()`] or for a specific use case through link:{entity_view_jdoc}/persistence/view/EntityViewSetting.html#addOptionalParameter(java.lang.String,%20java.lang.Object)[`addOptionalParameter()`]. === Entity mappings Apart from having custom projections for entity or embeddable types through subviews, you can also map the JPA managed types directly. You can use the `@Mapping` annotation if desired and map any path expression as singular or plural attribute(i.e. collection) with managed types. [source,java] ---- @EntityView(Cat.class) interface CatView { @IdMapping Long getId(); Cat getFather(); } ---- [source,sql] ---- SELECT cat.id, father_1 FROM Cat cat LEFT JOIN cat.father father_1 ---- Beware that when using managed types directly, you might run into _lazy loading_ issues when accessing uninitialized/un-fetched properties of the entity. You can however specify what properties should be fetched for such entity mappings by using the `fetches` configuration. [source,java] ---- @EntityView(Cat.class) interface CatView { @IdMapping Long getId(); @Mapping(fetches = ""kittens"") Cat getFather(); } ---- This will fetch the kittens of the father. [source,sql] ---- SELECT cat.id, father_1 FROM Cat cat LEFT JOIN cat.father father_1 LEFT JOIN FETCH father_1.kittens kittens_1 ---- === Collection mappings One of the most important features of the {projectname} entity view module is the possibility to map collections. You can map collections defined in the entity model to collections in the entity view model in multiple ways. ==== Simple 1:1 collection mapping The simplest possible mapping is a 1:1 mapping of e.g. a *ToMany collection. [source,java] ---- @EntityView(Cat.class) interface CatView { @IdMapping Long getId(); Set getKittens(); } ---- This will simply join the `kittens` collection. During entity view construction the elements are collected and the result is flattened as expected. [source,sql] ---- SELECT cat.id, kittens_1 FROM Cat cat LEFT JOIN cat.kittens kittens_1 ---- ==== Subset basic collection mapping Most of the time, only a subset of the properties of a relation is needed. In case only a single property is required, the use of `@Mapping` to refer to the property within a collection can be used. [source,java] ---- @EntityView(Cat.class) interface CatView { @IdMapping Long getId(); @Mapping(""kittens.name"") Set getKittenNames(); } ---- This will join the `kittens` collection and only select their `name`. [source,sql] ---- SELECT cat.id, kittens_1.name FROM Cat cat LEFT JOIN cat.kittens kittens_1 ---- ==== Subview collection mapping For the cases when multiple properties of a relation are needed, you can also use subviews. [source,java] ---- @EntityView(Cat.class) interface SimpleCatView { @IdMapping Long getId(); String getName(); } @EntityView(Cat.class) interface CatView extends SimpleCatView { Set getKittens(); } ---- Applying the `CatView` entity view will again join the `kittens` collection but this time select some more properties. [source,sql] ---- SELECT cat.id, kittens_1.id, kittens_1.name FROM Cat cat LEFT JOIN cat.kittens kittens_1 ---- A subview within a collection can have subviews and collections of subviews again i.e. there is no limit to nesting. ==== Collection type re-mapping Another nice feature of {projectname} entity views is the ability to re-map a collection to a different collection type. In the entity model one might for example choose to always use a `java.util.Set` for mapping collections, but to be able to make use of the elements in a UI, you might require e.g. a `java.util.List`. Although the `kittens` relation in the `Cat` entity uses a `Set`, you can map the `kittens` as `List` in the `CatView`. As you might expect, the order of the elements will then depend on the order of the query result. [source,java] ---- @EntityView(Cat.class) interface SimpleCatView { @IdMapping Long getId(); String getName(); } @EntityView(Cat.class) interface CatView extends SimpleCatView { List getKittens(); } ---- By executing the query with a custom link:{core_doc}#anchor-order-by-clause[`ORDER BY` clause], the result order can be made deterministic. [source,java] ---- List result = entityViewManager.applySetting( EntityViewSetting.create(CatView.class), cb.create(Cat.class) .orderByAsc(""name"") .orderByAsc(""kittens.name"") ).getResultList(); ---- [source,sql] ---- SELECT cat.id, kittens_1.id, kittens_1.name FROM Cat cat LEFT JOIN cat.kittens kittens_1 ORDER BY cat.name ASC NULLS LAST, kittens_1.name ASC NULLS LAST ---- NOTE: We do not recommend to rely on this behavior but instead make use of sorted collection mappings. ==== Ordered collection mapping Apart from changing the collection type to e.g. `List` it is also possible to get _ordered_ results with sets. By specifying `ordered = true` for the collection via the annotation `@CollectionMapping` you can force a set implementation that retains the insertion order like a `LinkedHashSet`. [source,java] ---- @EntityView(Cat.class) interface SimpleCatView { @IdMapping Long getId(); String getName(); } @EntityView(Cat.class) interface CatView extends SimpleCatView { @CollectionMapping(ordered = true) Set getKittens(); } ---- The query doesn't change, the only thing that does, is the implementation for the collection. [source,sql] ---- SELECT cat.id, kittens_1.id, kittens_1.name FROM Cat cat LEFT JOIN cat.kittens kittens_1 ---- This oviously only makes sense when used along with an _ORDER BY_ clause that orders the result set deterministically. ==== Sorted collection mapping In addition to ordering, the following sorted collection types are supported * `SortedSet` and `NavigableSet` * `SortedMap` and `NavigableMap` You can specify the comparator for the collection via the annotation `@CollectionMapping` [source,java] ---- @EntityView(Cat.class) interface SimpleCatView { @IdMapping Long getId(); String getName(); static class DefaultComparator implements Comparator { @Override public int compare(SimpleCatView o1, SimpleCatView o2) { return String.CASE_INSENSITIVE_ORDER.compare(o1.getName(), o2.getName()); } } } @EntityView(Cat.class) interface CatView extends SimpleCatView { @CollectionMapping(comparator = SimpleCatView.DefaultComparator.class) SortedSet getKittens(); } ---- This will ensure the correct ordering of the collection elements regardless of the query ordering. The query stays the same. [source,sql] ---- SELECT cat.id, kittens_1.id, kittens_1.name FROM Cat cat LEFT JOIN cat.kittens kittens_1 ---- ==== Indexed collection re-mapping Mapping an indexed collection like a `java.util.Map` or `java.util.List` with an `@OrderColumn` can happen in multiple ways. Let's consider the following model. [source,java] ---- @Entity class Cat { @Id Long id; @OneToMany @OrderColumn List indexedKittens; @ManyToMany Map kittensBestFriends; } @EntityView(Cat.class) interface SimpleCatView { @IdMapping Long getId(); String getName(); } ---- Indexed mapping:: One way is to map the collections indexed again, i.e. a `Map` in the entity is mapped as `Map` in the entity view. [source,java] ---- @EntityView(Cat.class) interface CatView extends SimpleCatView { List getIndexedKittens(); Map getKittensBestFriends(); # <1> } ---- <1> Careful when mapping the key to a subview. This is only supported in the latest JPA provider versions [source,sql] ---- SELECT cat.id, cat.name, INDEX(indexedKittens_1), indexedKittens_1.id, indexedKittens_1.name KEY(kittensBestFriends_1).id, KEY(kittensBestFriends_1).name, kittensBestFriends_1.id, kittensBestFriends_1.name FROM Cat cat LEFT JOIN cat.indexedKittens indexedKittens_1 LEFT JOIN cat.kittensBestFriends kittensBestFriends_1 ---- Map-Key only mapping:: By using the qualified expression `KEY()` you can map the keys of a map to a collection by using `@Mapping` [source,java] ---- @EntityView(Cat.class) interface CatView extends SimpleCatView { @Mapping(""KEY(kittensBestFriends)"") List getKittens(); } ---- [source,sql] ---- SELECT cat.id, cat.name, KEY(kittensBestFriends_1).id, KEY(kittensBestFriends_1).name FROM Cat cat LEFT JOIN cat.kittensBestFriends kittensBestFriends_1 ---- Map-Value only mapping:: Simply mapping a path expression for a `Map` to a normal collection, will result in only fetching the map values. [source,java] ---- @EntityView(Cat.class) interface CatView extends SimpleCatView { @Mapping(""kittensBestFriends"") List getBestFriends(); } ---- [source,sql] ---- SELECT cat.id, cat.name, kittensBestFriends_1.id, kittensBestFriends_1.name FROM Cat cat LEFT JOIN cat.kittensBestFriends kittensBestFriends_1 ---- List-Value only mapping:: Sometimes it might be required to ignore the index of an indexed `List` when mapping it to a `List` again. To do so use `ignoreIndex` on `@CollectionMapping` [source,java] ---- @EntityView(Cat.class) interface CatView extends SimpleCatView { @Mapping(""indexedKittens"") @CollectionMapping(ignoreIndex = true) List getKittens(); } ---- [source,sql] ---- SELECT cat.id, cat.name, indexedKittens_1.id, indexedKittens_1.name FROM Cat cat LEFT JOIN cat.indexedKittens indexedKittens_1 ---- ==== Custom indexed collection mapping Mapping an indexed collection like a `java.util.Map` or `java.util.List` in entity views does not necessarily require that the source collection must be of the same type. A custom index mapping can be specified by annotating the attribute with `@MappingIndex`. The index mapping is relative to the target mapping. Let's consider the following model. [source,java] ---- @Entity class Cat { @Id Long id; int age; @OneToMany Set kittens; } @EntityView(Cat.class) interface SimpleCatView { @IdMapping Long getId(); String getName(); } ---- Indexed-List mapping:: An indexed `List` can be mapped by specifying a `@MappingIndex` that resolves to a 0-based integer of the target mapping. [source,java] ---- @EntityView(Cat.class) interface CatView extends SimpleCatView { @MappingIndex(""age"") @Mapping(""kittens"") List getKittensByAge(); } ---- [source,sql] ---- SELECT cat.id, cat.name, kittens_1.age, kittens_1.id, kittens_1.name FROM Cat cat LEFT JOIN cat.kittens kittens_1 ---- Note that depending on the age values, there can be many `null` entries in the list. An indexed `List` is filled up with `null` entries for missing indexes. Map mapping:: An `Map` indexed by some value can be mapped by specifying a `@MappingIndex` relative to the target mapping. [source,java] ---- @EntityView(Cat.class) interface CatView extends SimpleCatView { @MappingIndex(""age"") @Mapping(""kittens"") Map getKittensByAge(); } ---- [source,sql] ---- SELECT cat.id, cat.name, kittens_1.age, kittens_1.id, kittens_1.name FROM Cat cat LEFT JOIN cat.kittens kittens_1 ---- Since the age might not be unique for the kittens in a collection, some cats could be overwritten, which is prevented by throwing an exception. To avoid the exception and instead collect all kittens grouped by the index value, multi-collections can be used. Multi-collection mapping:: An indexed `List` or `Map` can specify a collection value to collect all values grouped by their index value. Valid types for the collections are `Collection`, `Set`, `SortedSet` and `List`. [source,java] ---- @EntityView(Cat.class) interface CatView extends SimpleCatView { @MappingIndex(""age"") @Mapping(""kittens"") Map> getKittensByAge(); } ---- [source,sql] ---- SELECT cat.id, cat.name, kittens_1.age, kittens_1.id, kittens_1.name FROM Cat cat LEFT JOIN cat.kittens kittens_1 ---- Subview key mapping:: An indexed `Map` can specify a subview as key as well. Note how the `this` mapping is used for the index mapping which allows the key view to be based on the target mapping `kittens`. [source,java] ---- @EntityView(Cat.class) interface CatAgeView { int getAge(); } @EntityView(Cat.class) interface CatView extends SimpleCatView { @MappingIndex(""this"") @Mapping(""kittens"") Map> getKittensByAge(); } ---- [source,sql] ---- SELECT cat.id, cat.name, kittens_1.age, kittens_1.id, kittens_1.name FROM Cat cat LEFT JOIN cat.kittens kittens_1 ---- Ordered element collection mapping:: By specifying `ordered = true` for the element collection via the annotation `@MultiCollectionMapping` you can force a set implementation that retains the insertion order like a `LinkedHashSet`. [source,java] ---- @EntityView(Cat.class) interface CatAgeView { int getAge(); } @EntityView(Cat.class) interface CatView extends SimpleCatView { @MappingIndex(""this"") @Mapping(""kittens"") @MultiCollectionMapping(ordered = true) Map> getKittensByAge(); } ---- The query doesn't change, the only thing that does, is the implementation for the collection. [source,sql] ---- SELECT cat.id, cat.name, kittens_1.age, kittens_1.id, kittens_1.name FROM Cat cat LEFT JOIN cat.kittens kittens_1 ---- This oviously only makes sense when used along with an _ORDER BY_ clause that orders the result set deterministically. Sorted element collection mapping:: You can specify the comparator for the collection via the annotation `@MultiCollectionMapping` [source,java] ---- @EntityView(Cat.class) interface CatAgeView { int getAge(); } @EntityView(Cat.class) interface CatView extends SimpleCatView { @MappingIndex(""this"") @Mapping(""kittens"") @MultiCollectionMapping(comparator = SimpleCatView.DefaultComparator.class) Map> getKittensByAge(); } ---- This will ensure the correct ordering of the element collection elements regardless of the query ordering. The query stays the same. [source,sql] ---- SELECT cat.id, cat.name, kittens_1.age, kittens_1.id, kittens_1.name FROM Cat cat LEFT JOIN cat.kittens kittens_1 ---- === Singular collection type mappings There are cases when the entity model defines a collection that is actually a singular entity attribute. This can happen when you use custom type implementations or JPA 2.1 attribute converters that produce collections. A custom type or converter could map a DBMS array, json, xml or any other type to a collection. Since such an entity attribute is not a relation, it can only be a singular attribute. By default {projectname} entity views assume that an entity view attribute with a collection type is a plural attribute and the mapping refers to a plural entity attribute. In order to be able to map such special singular attribute collections, you have to specifically use `@MappingSingular`. [source,java] ---- @Entity class Cat { @Id Long id; @Basic @Convert(converter = StringSetConverter.class) Set tags; } class StringSetConverter implements AttributeConverter> { ... } @EntityView(Cat.class) interface CatView { @IdMapping Long getId(); @MappingSingular Set getTags(); } ---- Beware that you can't re-map the collection type in this case although this might soon be possible. The query will not generate a join but simply select the `tags` since it's a singular attribute. [source,sql] ---- SELECT cat.id, cat.tags FROM Cat cat ---- === Limit mapping Oftentimes it is not necessary to fetch all elements of a collection or correlation but only the top N values. To achieve that, the `@Limit` annotation can be used like in the following example: [source,java] ---- @EntityView(Cat.class) interface CatView extends SimpleCatView { @Mapping(""kittens"") @Limit(limit = ""5"", order = {""age DESC"", ""id DESC""}) List getKittens(); } ---- This will fetch only the 5 oldest kittens per cat, regardless of the used fetch strategy. A possible query for this view could look like this: [source,sql] ---- SELECT cat.id, cat.name, kittens.id, kittens.name FROM Cat cat LEFT JOIN LATERAL Cat( SELECT kitten.age, kitten.father.id, kitten.id, kitten.mother.id, kitten.name FROM Cat kitten WHERE kitten MEMBER OF cat.kittens ORDER BY kitten.age DESC, kitten.id DESC LIMIT 5 ) kittens(age, father.id, id, mother.id, name) ON 1=1 ---- [[anchor-correlation-mappings]] === Correlated mappings In some entity models, not every relation between entities might be explicitly mapped. There are multiple possible reasons for that like e.g. not wanting to have explicit dependencies, to keep it simple etc. Apart from unmapped relations, there is sometimes the need to _correlate_ entities based on some criteria with other entities which are more of an ad-hoc nature than explicit relations. For these cases {projectname} entity views introduces the concept of _correlated mappings_. These mappings can be used to connect entities through a custom criteria instead of through mapped entity relations. Correlated mappings can be used for any attribute type(basic, entity, subview, collection) although singular basic attributes can also be implemented as <>. A correlation mapping is declared by annotating the desired attribute with `@MappingCorrelated` or `@MappingCorrelatedSimple`. ==== General correlated mappings In order to map the correlation you need to specify some values * `correlationBasis` - An expression that maps to the so called _correlation key_ * `correlator` - The `CorrelationProvider` to use for the correlation that introduces a so called _correlated entity_ By default, the correlated entity type is _projected into_ the view. To map a specific property of the entity type, use the `correlationResult` attribute. There is also the possibility to specify a <> that should be used for the correlation. By default, the `SELECT` strategy is used. [source,java] ---- @EntityView(Cat.class) public interface CatView { @IdMapping Long getId(); @MappingCorrelated( correlationBasis = ""age"", correlator = PersonAgeCorrelationProvider.class, fetch = FetchStrategy.JOIN ) Set getSameAgedPersons(); static class PersonAgeCorrelationProvider implements CorrelationProvider { @Override public void applyCorrelation(CorrelationBuilder builder, String correlationExpression) { final String alias = builder.getCorrelationAlias(); # <1> builder.correlate(Person.class) .on(alias + "".age"").inExpressions(correlationExpression) # <2> .end(); } } } ---- <1> `getCorrelationAlias()` defines the alias for the correlated entity <2> `correlationExpression` represents the `correlationBasis`. We generally recommend to use the `IN` predicate through `inExpressions()` to be able to easily switch the fetch strategy Depending on the fetch strategy multiple other queries might be executed. Check out the different <> for further information. In this case, the `JOIN` strategy was used, so the following query is generated. [source,sql] ---- SELECT cat.id, pers FROM Cat cat LEFT JOIN Person correlated_SameAgedPersons # <1> ON cat.age = correlated_SameAgedPersons.age # <2> ---- <1> This makes use of the so called link:{core_doc}#anchor-entity-joins[`entity join` feature] which is only available in newer JPA provider versions <2> Note that the `IN` predicate which was used in the correlation provider was rewritten to a equality predicate Since entity joins are required for using the `JOIN` fetch strategy with correlation mappings you have to make sure your JPA provider supports them. If your JPA provider does not support entity joins, you have to use a different fetch strategy instead. NOTE: Entity joins are only supported in newer versions of JPA providers(Hibernate 5.1+, EclipseLink 2.4+, DataNucleus 5+) ==== Simple correlated mappings Since correlation providers are mostly static, {projectname} also offers a way to define simple correlations in a declarative manner. The `@MappingCorrelatedSimple` annotation only requires a few values * `correlationBasis` - An expression that maps to the so called _correlation key_ * `correlated` - The _correlated entity_ type * `correlationExpression` - The expression to use for correlating the _correlated entity_ type to the view [source,java] ---- @EntityView(Person.class) public interface PersonView { @IdMapping Long getId(); String getName(); } @EntityView(Cat.class) public interface CatView { @IdMapping Long getId(); @MappingCorrelatedSimple( correlationBasis = ""age"", correlated = Person.class, correlationExpression = ""age IN correlationKey"" # <1> fetch = FetchStrategy.JOIN ) Set getSameAgedPersons(); # <2> } ---- <1> The expression uses the default name for the correlation key but could use a different name by specifying the attribute `correlationKeyAlias` <2> As you see here, it is obviously also possible to map subviews for correlated entity types Just like the general correlation, by default, the correlated entity type is _projected into_ the view. To map a specific property of the entity type, use the `correlationResult` attribute. There is also the possibility to specify a <> that should be used for the correlation. By default, the `SELECT` strategy is used. [[entity-array-expression-correlation]] === Correlation mappings via entity array syntax The easiest way to correlate an entity is by using the entity array syntax `EntityName[predicate]` which is explained in detail in the link:{core_doc}#entity-array-expressions[core documentation]. Such a mapping can be used anywhere with all fetch strategies. Correlating with the current view is usually done with the `VIEW` macro which allows to refer to the current view. This is important because within the brackets of an entity array expression, the implicit root for path expressions is the joined entity itself. The previous example can be simplified to the following. [source,java] ---- @EntityView(Person.class) public interface PersonView { @IdMapping Long getId(); String getName(); } @EntityView(Cat.class) public interface CatView { @IdMapping Long getId(); @Mapping(""Person[age IN VIEW(age)]"") Set getSameAgedPersons(); } ---- The result is very similar and roughly looks like this [source,sql] ---- SELECT cat.id, Person__age_IN_VIEW_age__.id, Person__age_IN_VIEW_age__.name FROM Cat cat LEFT JOIN Person Person__age_IN_VIEW_age__ ON Person__age_IN_VIEW_age__.age = cat.age ---- === Special method attributes There are some special methods that can be declared abstract in an entity view type which have special runtime support. [[entity-view-special-method-entity-view-manager-getter]] ==== EntityViewManager getter An abstract method that returns `EntityViewManager` will not be considered to be an attribute. Such a method has special runtime support as it will always return the associated `EntityViewManager`. [source,java] ---- @EntityView(Person.class) public abstract class PersonView { @IdMapping public abstract Long getId(); abstract EntityViewManager getEntityViewManager(); public void someMethod() { // ... use getEntityViewManager() } } ---- This is especially useful for <> when a method wants to create a new instance of a subview or get a reference to a subview. === Mapping expression extensions {projectname} entity views generally supports the full set of link:{core_doc}#expressions[expressions] that JPQL and {projectname} core module supports, but in addition to that, also offers some expression extensions. ==== THIS Similar to the `this` expression in Java, in a mapping expression within entity views the `this` expression can be used to refer to the entity type backing the entity view. The expression can be used to implement embedded objects that are able to refer to the entity type of the entity view. [source,java] ---- @EntityView(Cat.class) interface EmbeddedCatView { @IdMapping Long getId(); String getName(); } @EmbeddableEntityView(Cat.class) interface ExternalInterfaceView { @Mapping(""name"") String getExternalName(); } @EntityView(Cat.class) interface CatView { @IdMapping Long getId(); @Mapping(""this"") EmbeddedCatView getEmbedded(); @Mapping(""this"") ExternalInterfaceView getAdapter(); } ---- Both `EmbeddedCatView` and `ExternalInterfaceView` refer to the same `Cat` as their parent `CatView`. The query looks as if the types were directly embedded into the entity view. [source,sql] ---- SELECT cat.id, cat.id, cat.name, cat.name FROM Cat cat ---- ==== OUTER In {projectname} core the `OUTER` function can be used to refer to the query root of a parent query from within a subquery. This is still the same with {projectname} entity views but might lead to unintuitive behavior when the subquery provider uses `OUTER` and is used in a subview. The following example shows the unintuitive behavior. [source,java] ---- @EntityView(Cat.class) interface CatView { @IdMapping Long getId(); Set getKittens(); } @EntityView(Cat.class) interface KittenCatView { @IdMapping Long getId(); @MappingSubquery(KittenCountSubqueryProvider.class) Long getKittenCount(); class KittenCountSubqueryProvider implements SubqueryProvider { @Override public T createSubquery(SubqueryInitiator subqueryBuilder) { return subqueryBuilder.from(Cat.class, ""subCat"") .select(""COUNT(*)"") .whereOr() .where(""subCat.father.id"").eqExpression(""OUTER(id)"") .where(""subCat.mother.id"").eqExpression(""OUTER(id)"") .endOr() .end(); } } } ---- When applying the `KittenCatView` directly, everything works as expected. [source,sql] ---- SELECT cat.id, ( SELECT COUNT(*) FROM Cat subCat WHERE subCat.father.id = cat.id OR subCat.mother.id = cat.id ) FROM Cat cat ---- But when using `KittenCatView` as subview within `CatView`, it starts to break. [source,sql] ---- SELECT cat.id, kittens_1.id, ( SELECT COUNT(*) FROM Cat subCat WHERE subCat.father.id = cat.id # <1> OR subCat.mother.id = cat.id ) FROM Cat cat LEFT JOIN cat.kittens kittens_1 ---- <1> `OUTER` resolved to `cat` instead of `kittens_1` The `OUTER` function doesn't know about the entity view structure and will remain to refer to the *query root*. It is often best to make use of the `EMBEDDING_VIEW` function instead, which refers to the relation of the _embedding view_. ==== VIEW The `VIEW` function can be used to refer to the relation backed by the _current view_. Usually this is not necessary as the relation of the current view is the implicit root for path expressions, but within the brackets of an <> the implicit root is the joined entity. In such a case it is necessary to use the `VIEW` function to refer to attributes of the relation of the current view in the predicate. For an example usage, go to the <> section. ==== EMBEDDING_VIEW The `EMBEDDING_VIEW` function can be used to refer to the relation backed by the _embedding view_. In case of a subquery provider, this will refer to the relation of the view, using the subquery provider. In case of a normal subview, this will refer to the relation of the view which contains the subview. One of the main use cases for this function is when using <>. [source,java] ---- @EntityView(Cat.class) interface CatView { @IdMapping Long getId(); Set getKittens(); } @EntityView(Cat.class) interface KittenCatView { @IdMapping Long getId(); @MappingSubquery(KittenCountSubqueryProvider.class) Long getKittenCount(); class KittenCountSubqueryProvider implements SubqueryProvider { @Override public T createSubquery(SubqueryInitiator subqueryBuilder) { return subqueryBuilder.from(Cat.class, ""subCat"") .select(""COUNT(*)"") .whereOr() .where(""subCat.father.id"").eqExpression(""EMBEDDING_VIEW(id)"") .where(""subCat.mother.id"").eqExpression(""EMBEDDING_VIEW(id)"") .endOr() .end(); } } } ---- When applying the `KittenCatView` directly, everything works as expected, just like it did before with `OUTER`. [source,sql] ---- SELECT cat.id, ( SELECT COUNT(*) FROM Cat subCat WHERE subCat.father.id = cat.id OR subCat.mother.id = cat.id ) FROM Cat cat ---- But when using `KittenCatView` as subview within `CatView`, `EMBEDDING_VIEW` plays out it's unique properties. [source,sql] ---- SELECT cat.id, kittens_1.id, ( SELECT COUNT(*) FROM Cat subCat WHERE subCat.father.id = kittens_1.id # <1> OR subCat.mother.id = kittens_1.id ) FROM Cat cat LEFT JOIN cat.kittens kittens_1 ---- <1> `EMBEDDING_VIEW` resolved to `kittens_1` whereas `OUTER` would resolve to `cat` TIP: Make sure you understand the < of the `EMBEDDING_VIEW` function when using the batched `SELECT` fetch strategy as this might affect performance. Note that the use of the `EMBEDDING_VIEW` function in a top level view will result in an exception since there is no _embedding view_. ==== VIEW_ROOT The `VIEW_ROOT` function can be used to refer to the relation for which the main entity view is applied. Normally this will resolve to the query root, but beware that the entity view root might not always be the query root. One of the main use cases for this function is when using <>. NOTE: For further information on applying a different entity view root take a look into the <>. The `VIEW_ROOT` function can be used in a correlation provider to additionally refer to a view root. [source,java] ---- @EntityView(Cat.class) public interface CatView { @IdMapping Long getId(); @MappingCorrelated( correlationBasis = ""age"", correlator = CatAgeCorrelationProvider.class ) Set getSameAgedCats(); static class CatAgeCorrelationProvider implements CorrelationProvider { @Override public void applyCorrelation(CorrelationBuilder builder, String correlationExpression) { final String correlatedCat = builder.getCorrelationAlias(); builder.correlate(Cat.class) .on(correlatedCat + "".age"").inExpressions(correlationExpression) .on(correlatedCat + "".id"").notInExpressions(""VIEW_ROOT(id)"") # <1> .end(); } } } ---- <1> We generally recommend to use the `IN` predicate through `inExpressions()` or `notInExpressions()` to be able to easily switch the fetch strategy The `VIEW_ROOT` function is usable with every fetch strategy. In case of the `JOIN` fetch strategy the result is just as expected. [source,sql] ---- SELECT cat.id, correlatedCat FROM Cat cat LEFT JOIN Cat correlatedCat ON correlatedCat.age = cat.age AND correlatedCat.id <> cat.id # <1> ---- <1> Again, the `IN` predicate was rewritten to an equality predicate TIP: Make sure you understand the < of the `VIEW_ROOT` function when using the batched `SELECT` fetch strategy as this might affect performance. [[anchor-constructor-mapping]] === Entity View constructor mapping So far, all mapping examples used interfaces for entity views, but as outlined in the beginning, {projectname} entity views also has support for abstract classes. There are multiple use cases for using abstract classes for entity views, but in general we recommend to use an interface as often as possible. The biggest advantage of using abstract classes is that you can have a custom constructor which can further apply transformations on data. ==== Abstract class Entity View with custom equals-hashCode Abstract classes, contrary to interfaces, can define an implementation for the equals and hashCode methods which is normally generated for the runtime implementations of Entity Views. If you decide to have a custom implementation you have to fulfill the general requirement, that the equals and hashCode methods use * Only the attribute mapped with `@IdMapping` if there is one * Otherwise use all attributes of the Entity View Not following these requirements could lead to unexpected results so it is generally best to rely on the default implementation. For every custom implementation that is detected during the bootstrap a warning message will be logged. ==== Map external data model with view constructor One of those use cases for a view constructor is integrating with an existing external data model. [source,java] ---- class CatRestDTO { private final Long id; private final String name; public MyOldCatDTO(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public String getName() { return name; } } ---- In general we recommend to use the entity view types directly instead of an external data model, because of the additional boilerplate code needed. Note that the creators of {projectname} are not generally against external data models since it is reasonable to have them e.g. in API projects that shouldn't expose a library dependency. [source,java] ---- @EntityView(Cat.class) public abstract class CatView extends CatRestDTO { public CatView( @Mapping(""id"") Long id, @Mapping(""name"") String name ) { super(id, name); } } ---- Now you can use the `CatView` for efficient querying but still have objects that are an instance of `CatRestDTO` and can thus be used like normal `CatRestDTO` instances. To decouple the actual entity view `CatView` from the data access or service one normally uses method signatures like [source,java] ---- interface CatDAO { List findAll(Class entityViewClass); # <1> List findAll(EntityViewSetting> entityViewSetting); # <2> } ---- <1> Create the `EntityViewSetting` within the implementation <2> Supply a custom `EntityViewSetting` which can also have filters, sorts, optional parameters and pagination information By using one of these approaches you can have a projection independent implementation for `CatDAO` and let the consumer i.e. a REST endpoint decide about the representation. ==== Additional data transformation in view constructor Another use case for view constructors is the transformation of data. Sometimes it is just easier to do the transformation in Java code instead of through a JPQL expression, but then there are also times when there is no other way than doing it in Java code. Let's assume you want to have an attribute that contains different text based on the age. [source,java] ---- @EntityView(Cat.class) interface CatView { @IdMapping Long getId(); @Mapping(""CASE WHEN age = 0 THEN 'newborn' WHEN age < 10 THEN 'child' WHEN age < 18 THEN 'teenager' ELSE 'adult' END"") String getText(); } ---- As you can see, the `CASE WHEN` expression can be used to implement that, but if the text is only static, there is no need to use that kind of expression. You can instead just inject the `age` as constructor parameter and do the mapping to the text in Java code. [source,java] ---- @EntityView(Cat.class) public abstract class CatView { private final String text; public CatView(@Mapping(""age"") long age) { if (age == 0) { this.text = ""newborn""; } else if (age < 10) { this.text = ""child""; } else if (age < 18) { this.text = ""teenager""; } else { this.text = ""adult""; } } @IdMapping public abstract Long getId(); public String getText() { return text; } } ---- Since that kind of mapping logic is normally externalized, {projectname} entity views also offers a way to _inject_ external services. You can provide services to entity views via <> like [source,java] ---- EntityViewSetting> setting = EntityViewSetting.create(CatView.class); setting.addOptionalParameter(""ageMapper"", new AgeToTextMapper()); List result = entityViewManager.applySetting(setting, cbf.create(em, Cat.class)) .getResultList(); ---- The services, or optional parameters in general can be consumed either as attributes or as constructor parameters with `@MappingParameter`. If the parameter is not supplied, `null` is injected. [source,java] ---- @EntityView(Cat.class) public abstract class CatView { private final String text; public CatView( @Mapping(""age"") long age, @MappingParameter(""ageMapper"") AgeToTextMapper mapper ) { this.text = ageMapper.map(age); } @IdMapping public abstract Long getId(); public String getText() { return text; } } ---- [[anchor-named-constructor]] ==== Multiple named constructors So far, the example always used no or just a single constructor, but it is actually possible to have multiple constructors. Every constructor in an entity view must have a name defined via `@ViewConstructor`. The default name is `init` and is used for constructors that have no `@ViewConstructor` annotation. [source,java] ---- @EntityView(Cat.class) public abstract class CatView { private final String text; public CatView( @Mapping(""age"") long age, @MappingParameter(""ageMapper"") AgeToTextMapper mapper ) { this.text = ageMapper.map(age); } @ViewConstructor(""special"") public CatView(@Mapping(""age"") long age) { this.text = age > 80 ? ""oldy"" : ""normal""; } @IdMapping public abstract Long getId(); public String getText() { return text; } } ---- The constructor name can be chosen when constructing a `EntityViewSetting` via link:{entity_view_jdoc}/persistence/view/EntityViewSetting.html#create(java.lang.Class,%20java.lang.String)[`create()`]. [source,java] ---- EntityViewSetting.create(CatView.class, ""special""); ---- ==== Using attribute getters in constructor Since mapping constructor parameters can become very cumbersome and oftentimes you need a value not only in the constructor but also accessible directly via a getter, {projectname} came up with a solution that allows you to use the getters of attributes in the constructor. It might not be immediately obvious why this is a special thing. Since entity views are declared as abstract classes you can imagine that the runtime has to actually create concrete classes. These concrete classes _normally_ initialize fields *after* calling the super constructor, thus making it impossible for the super constructor to actually retrieve values by using the attribute getters. The JVM enforces that fields can only be accessed after the super constructor has been called, so normally there is no way that the getter implementations that serve the fields can return non-null values in the super constructor. Fortunately, {projectname} entity views found a way around this limitation of the JVM by making use of the infamous `sun.misc.Unsafe` to define a class that would normally fail bytecode verification. The trick is, that the implementations that are generated will set the fields before calling the super constructor thus making the values available to the super constructor. By default, all abstract classes will be defined through `sun.misc.Unsafe`. If you don't want that behavior and instead want bytecode verifiable implementations to be generated, you can always disable this strategy by using a <>. [source,java] ---- @EntityView(Cat.class) public abstract class CatView { private final String text; public CatView(@MappingParameter(""ageMapper"") AgeToTextMapper mapper) { this.text = ageMapper.map(getAge()); # <1> } @IdMapping public abstract Long getId(); public abstract Long getAge(); public String getText() { return text; } } ---- <1> If the unsafe proxy is used, `getAge()` will return the actual value, otherwise it will return `null` Note that instead of using this unsafe approach which can't be used when generating entity view implementations through the annotation processor, one can make use of the `@Self` annotation to inject a view of the state to a constructor. The previous example defined in a safe way would look like this: [source,java] ---- @EntityView(Cat.class) public abstract class CatView { private final String text; public CatView(@Self CatView self, @MappingParameter(""ageMapper"") AgeToTextMapper mapper) { this.text = ageMapper.map(self.getAge()); } @IdMapping public abstract Long getId(); public abstract Long getAge(); public String getText() { return text; } } ---- Instead of calling the getter on the `this` instance which is not yet initialized, one uses the `@Self` annotated instance to access the state. The type of the instance is a serializable subclass of the entity view with the only purpose to serve as ""self"" instance. The construction of the ""self"" instance will not invoke any user code as it is constructed via deserialization to bypass constructor calls. === Inheritance mapping Entity views can have an inheritance relationship to subtypes via an inheritance mapping. This relationship allows instances of an entity view subtype to be materialized when a selection predicate defined by an inheritance mapping is satisfied. The inheritance feature for an entity view is activated by annotating link:{entity_view_jdoc}/persistence/view/EntityViewInheritance.html[`@EntityViewInheritance`] on an entity view. By default, all subtypes of the entity view are considered as inheritance subtypes and thus require a so called _inheritance mapping_. An _inheritance mapping_ is defined by annotating the subtype with link:{entity_view_jdoc}/persistence/view/EntityViewInheritanceMapping.html[`@EntityViewInheritanceMapping`] and defining a selection predicate that represents the condition on which decides the instantiation of that subtype. The predicate is a normal link:{core_doc}#expressions[JPQL predicate expression] and can refer to all attributes of the mapped entity type. Consider the following example [source,java] ---- @EntityView(Cat.class) @EntityViewInheritance public interface BaseCatView { String getName(); } @EntityView(Cat.class) @EntityViewInheritanceMapping(""age < 18"") public interface YoungCatView extends BaseCatView { @Mapping(""mother.name"") String getMotherName(); } @EntityView(Cat.class) @EntityViewInheritanceMapping(""age > 18"") public interface OldCatView extends BaseCatView { @Mapping(""kittens.name"") List getKittenNames(); } ---- When querying for entity views of the type `BaseCatView`, the selection predicates `age < 18` and `age > 18` are _merged_ into a _type discriminator_ expression that returns a type index. The type index refers to the entity view type into which a result should be materialized. The resulting JPQL query for such an entity view looks like the following [source,sql] ---- SELECT CASE WHEN age < 18 THEN 1 WHEN age > 18 THEN 2 ELSE 0 END, cat.name, mother_1.name, kittens_1.name FROM Cat cat LEFT JOIN cat.mother mother_1 LEFT JOIN cat.kittens kittens_1 ---- The type index 0 refers to the base type `BaseCatView`, hence instances of `BaseCatView` are materialized when the age of a result equals 18. Since it might not be desirable to use all entity view subtypes for the inheritance relationship, it is possible to explicitly declare the subtypes in the `@EntityViewInheritance` annotation on the super type. [source,java] ---- @EntityView(Cat.class) @EntityViewInheritance({ YoungCatView.class }) public interface BaseCatView { String getName(); } ---- This has the effect, that only `BaseCatView` or `YoungCatView` instances are materialized for a result. === Inheritance subview mapping Similarly to specifying the entity view inheritance subtypes at the declaration site, i.e. `BaseCatView`, it is also possible to define subtypes at the _use site_, i.e. at the subview attribute. By annotating the subview attribute with `@MappingInheritance`, it is possible to delimit and override the entity view subtype mappings that are considered for materialization from the result. When using the `@MappingInheritance` annotation, it is required to list all desired subtypes via `@MappingInheritanceSubtype` annotations that can optionally override the inheritance mapping. [source,java] ---- @EntityView(Person.class) interface PersonView { String getName(); @MappingInheritance({ @MappingInheritanceSubtype(mapping = ""age <= 18"", value = YoungCatView.class) }) Set getCats(); } @EntityView(Cat.class) @EntityViewInheritance public interface BaseCatView { String getName(); } @EntityView(Cat.class) @EntityViewInheritanceMapping(""age < 18"") public interface YoungCatView extends BaseCatView { @Mapping(""mother.name"") String getMotherName(); } @EntityView(Cat.class) @EntityViewInheritanceMapping(""age > 18"") public interface OldCatView extends BaseCatView { @Mapping(""kittens.name"") List getKittenNames(); } ---- When querying for `PersonView`, `YoungCatView` instances will be materialized if the cat's age is lower *or equal* to 18 and otherwise instances of `BaseCatView` will be created. By setting the annotation property `onlySubtypes` to true, instances of the base type `BaseCatView` aren't materialized but a null is propagated. Apart from skipping the base type, it is also possible to define the base type via `@MappingInheritanceSubtype` which allows to specify the inheritance mapping for the base type. TIP: When no `@MappingInheritanceSubtype` elements are given, only the base type is materialized which can be used to _disable_ the inheritance feature for an attribute. NOTE: It is illegal to set `onlySubtypes` to true and have an empty set of subtype mappings as that would always result in a `null` object. ==== Inheritance mapping with constructors Entity view inheritance is not limited to interface types but can also be used with custom constructors. If a view constructor is used, all entity view inheritance subtypes must have a view constructor with the same name. In case of just a single constructor the `@ViewConstructor` does not have to be applied, as the name `init` is chosen by default as name. [source,java] ---- @EntityView(Cat.class) @EntityViewInheritance public abstract class BaseCatView { private final String parentName; public BaseCatView(@Mapping(""father.name"") String parentName) { this.parentName = parentName; } public abstract String getName(); } @EntityView(Cat.class) @EntityViewInheritanceMapping(""age < 18"") public abstract class YoungCatView extends BaseCatView { public YoungCatView(@Mapping(""mother.name"") String parentName) { super(parentName); } @Mapping(""mother.name"") public abstract String getMotherName(); } @EntityView(Cat.class) @EntityViewInheritanceMapping(""age > 18"") public abstract class OldCatView extends BaseCatView { public OldCatView() { super(""None""); } @Mapping(""kittens.name"") public abstract List getKittenNames(); } ---- ==== Inheritance mapping and JPA inheritance The most obvious use case for entity view inheritance is mapping JPA entities that use an inheritance relationship. {projectname} supports this and also makes use of defaults for the inheritance mapping in case a entity view subtype uses an entity subtype in the `@EntityView` annotation. [source,java] ---- @EntityView(Animal.class) @EntityViewInheritance public interface AnimalView { String getName(); } @EntityView(Cat.class) public interface CatView extends AnimalView { String getKittyName(); } @EntityView(Dog.class) public interface DogView extends AnimalView { String getDoggyName(); } ---- The `DogView` uses the entity `Dog` and `CatView` the entity `Cat` which are both subtypes of `Animal`. In this case no inheritance mapping needs to be provided as {projectname} will generate a type constraint like `TYPE(this) = Dog` or `TYPE(this) = Cat` for the respective entity view subtypes `DogView` and `CatView`. The resulting JPQL query when using `AnimalView` might look like the following [source,sql] ---- SELECT CASE WHEN TYPE(animal) = Cat THEN 1 WHEN TYPE(animal) = Dog THEN 2 ELSE 0 END, animal.name, TREAT(animal AS Cat).kittyName, TREAT(animal AS Dog).doggyName FROM Animal animal ---- As can be seen, the expressions for the access of the subtype properties rightfully make use of the `TREAT` operator. An entity view could also be modelled flat i.e. not mirroring the entity inheritance relationship as entity views, but just put the desired properties on a single entity view type. This can be done by making use of the `TREAT` operator and the `this` expression in the entity view mappings just as expected. [source,java] ---- @EntityView(Animal.class) @EntityViewInheritance public interface MyAnimalView { String getName(); @Mapping(""TREAT(this AS Cat).kittyName"") String getKittyName(); @Mapping(""TREAT(this AS Dog).doggyName"") String getDoggyName(); } ---- The generated query looks approximately like this [source,sql] ---- SELECT animal.name, TREAT(animal AS Cat).kittyName, TREAT(animal AS Dog).doggyName FROM Animal animal ---- and in case an animal is not of the treated type, a `null` value will be produced. === Using CTEs in entity views A CTE can be used in an entity view by correlating the CTE entity type, but it is still necessary to define the CTE. This can be done on the underlying {projectname} core `CriteriaBuilder` before applying an entity view. Doing that is not always ideal e.g. when considering repositories for Spring Data or DeltaSpike Data, there is usually no access to the `CriteriaBuilder`. The `@With` annotation can be applied on an entity view class to register a `CTEProvider` to the entity view class. When applying an entity view, it's corresponding registered `CTEProvider` instances are invoked that can define CTEs [source,java] ---- @EntityView(Cat.class) @With(MyCteProvider.class) public interface BaseCatView { class MyCteProvider implements CTEProvider { @Override public void applyCtes(CTEBuilder builder, Map optionalParameters) { builder.with(MyCTE.class); // ... } } } ---- For more information about CTEs refer to the link:{core_doc}#ctes[CTE section] in the core documentation. === Secondary entity view roots Up until now, mappings were always relative to the entity type of the entity view within which the mappings are defined, except for <>. Although entity array expressions are very mighty, they always imply a left join and there is no way to define a limit on elements to be joined. This is where secondary entity view roots come in. A secondary entity view root has an name and is defined on the entity view class level through the `@EntityViewRoot` and `@EntityViewRoots` annotations. The name is very important as secondary entity view roots are registered on the underlying query builder with the name as alias. Roughly speaking, secondary entity view roots can be thought of as a way to define joins that are registered and make them available through the defined name to mappings of an entity view. [source,java] ---- @EntityView(Cat.class) @EntityViewRoot(name = ""v1"", entity = Cat.class, condition = ""id = VIEW(id)"", joinType = JoinType.INNER) @EntityViewRoot(name = ""v2"", expression = ""Cat[id = VIEW(id)]"", limit = ""1"", order = ""id DESC"") @EntityViewRoot(name = ""v3"", correlator = CatView.TestCorrelator.class) public interface CatView { @IdMapping Long getId(); String getName(); @Mapping(""v1.name"") String getV1Name(); @Mapping(""v2.name"") String getV2Name(); @Mapping(""v3.name"") String getV3Name(); class TestCorrelator implements CorrelationProvider { @Override public void applyCorrelation(CorrelationBuilder correlationBuilder, String correlationExpression) { correlationBuilder.correlate(Cat.class) .on(correlationBuilder.getCorrelationAlias()).eqExpression(correlationExpression) .end(); } } } ---- The generated query for such an entity view will roughly look like the following: [source,sql] ---- SELECT cat.id cat.name, v1.name, v2.name, v3.name FROM Cat cat JOIN Cat v1 ON v1.id = cat.id LEFT JOIN LATERAL Cat( SELECT v2_sub.age, v2_sub.father.id, v2_sub.id, v2_sub.mother.id, v2_sub.name FROM Cat v2_sub WHERE v2_sub.id = cat.id ORDER BY v2_sub.id DESC LIMIT 1 ) v2(age, father.id, id, mother.id, name) ON 1=1 LEFT JOIN Cat v3 ON v3.id = cat.id ---- The big differences to using entity array expressions directly are: * Possibility to specify the join type * Possibility to specify a limit/offset with an order to implement a TOP-N per category join * Possibility to use subqueries in the `ON` clause through a `CorrelationProvider` A view root can be either defined through an entity class with a condition: [source,java] ---- @EntityViewRoot( name = ""root1"", entity = Document.class, condition = ""id = VIEW(documentId)"" ) ---- an expression with an optional condition: [source,java] ---- @EntityViewRoot( name = ""root2"", expression = ""Document[id = VIEW(documentId)]"", condition = ""root2.age > 10"" ) ---- or through a correlator: [source,java] ---- @EntityViewRoot( name = ""root3"", correlator = MyCorrelationProvider.class ) ---- Paths that are not fully qualified i.e. relative paths that use no root alias, are prefixed with the entity view root alias. The entity view root name must be unique across all entity view types that are accessible through attributes. NOTE: During boot, every `CorrelationProvider` is probed to figure out the correlation type. If the `CorrelationProvider` is dynamic, you can optionally define the type through the `entity` attribute. NOTE: Using this feature requires a JPA provider that supports entity joins. Using `JoinType.INNER` can be a workaround as that is emulated through cross joins if needed. ",16240,True,3103.1831751862032,median "// Use these for links to issue and pulls. Note issues and pulls redirect one to // each other on Github, so don't worry too much on using the right prefix. :issue: https://github.com/elastic/beats/issues/ :pull: https://github.com/elastic/beats/pull/ === Beats version HEAD https://github.com/elastic/beats/compare/v7.0.0-alpha2...master[Check the HEAD diff] ==== Breaking changes *Affecting all Beats* - The document id fields has been renamed from @metadata.id to @metadata._id {pull}15859[15859] - Variable substitution from environment variables is not longer supported. {pull}15937{15937} - Change aws_elb autodiscover provider field name from elb_listener.* to aws.elb.*. {issue}16219[16219] {pull}16402{16402} - Remove `AddDockerMetadata` and `AddKubernetesMetadata` processors from the `script` processor. They can still be used as normal processors in the configuration. {issue}16349[16349] {pull}16514[16514] - Introduce APM libbeat instrumentation, active when running the beat with ELASTIC_APM_ACTIVE=true. {pull}17938[17938] - Remove the non-ECS `agent.hostname` field. Use the `agent.name` or `agent.id` fields for an identifier. {issue}16377[16377] {pull}18328[18328] - Make error message about locked data path actionable. {pull}18667[18667] - Ensure dynamic template names are unique for the same field. {pull}18849[18849] *Auditbeat* - File integrity dataset (macOS): Replace unnecessary `file.origin.raw` (type keyword) with `file.origin.text` (type `text`). {issue}12423[12423] {pull}15630[15630] *Filebeat* - Improve ECS field mappings in panw module. event.outcome now only contains success/failure per ECS specification. {issue}16025[16025] {pull}17910[17910] - Improve ECS categorization field mappings for nginx module. http.request.referrer only populated when nginx sets a value {issue}16174[16174] {pull}17844[17844] - Improve ECS field mappings in santa module. move hash.sha256 to process.hash.sha256 & move certificate fields to santa.certificate . {issue}16180[16180] {pull}17982[17982] - With the default configuration the cloud modules (aws, azure, googlecloud, o365, okta) will no longer send the `host` field that contains information about the host Filebeat is running on. This is because the `host` field specifies the host on which the event happened. {issue}13920[13920] {pull}18223[18223] - With the default configuration the following modules will no longer send the `host` field that contains information about the host on which Filebeat is running. You can revert this change by configuring tags for the module and omitting `forwarded` from the list. {issue}13920[13920] * CEF {pull}18223[18223] * PANW {pull}18223[18223] * Cisco {pull}18753[18753] * CrowdStrike {pull}19132[19132] * Fortinet {pull}19133[19133] * iptables {pull}18756[18756] * Checkpoint {pull}18754[18754] * Netflow {pull}19087[19087] * Zeek {pull}19113[19113] (`forwarded` tag is not included by default) * Suricata {pull}19107[19107] (`forwarded` tag is not included by default) * CoreDNS {pull}19134[19134] (`forwarded` tag is not included by default) * Envoy Proxy {pull}19134[19134] (`forwarded` tag is not included by default) - Preserve case of http.request.method. ECS prior to 1.6 specified normalizing to lowercase, which lost information. Affects filesets: apache/access, elasticsearch/audit, iis/access, iis/error, nginx/access, nginx/ingress_controller, aws/elb, suricata/eve, zeek/http. {issue}18154[18154] {pull}18359[18359] - Adds check on `` config option value for the azure input `resource_manager_endpoint`. {pull}18890[18890] - Okta module now requires objects instead of JSON strings for the `http_headers`, `http_request_body`, `pagination`, `rate_limit`, and `ssl` variables. {pull}18953[18953] - Adds oauth support for httpjson input. {issue}18415[18415] {pull}18892[18892] - Adds `split_events_by` option to httpjson input. {pull}19246[19246] - Adds `date_cursor` option to httpjson input. {pull}19483[19483] *Heartbeat* *Journalbeat* - Improve parsing of syslog.pid in journalbeat to strip the username when present {pull}16116[16116] *Metricbeat* - Make use of secure port when accessing Kubelet API {pull}16063[16063] - Add Tomcat overview dashboard {pull}14026[14026] - Move service config under metrics and simplify metric types. {pull}18691[18691] - Fix ECS compliance of user.id field in system/users metricset {pull}19019[19019] *Packetbeat* - Redis: fix incorrectly handle with two-words redis command. {issue}14872[14872] {pull}14873[14873] *Winlogbeat* - Add support to Sysmon file delete events (event ID 23). {issue}18094[18094] - Improve ECS field mappings in Sysmon module. `related.hash`, `related.ip`, and `related.user` are now populated. {issue}18364[18364] - Improve ECS field mappings in Sysmon module. Hashes are now also populated to the corresponding `process.hash`, `process.pe.imphash`, `file.hash`, or `file.pe.imphash`. {issue}18364[18364] - Improve ECS field mappings in Sysmon module. `file.name`, `file.directory`, and `file.extension` are now populated. {issue}18364[18364] - Improve ECS field mappings in Sysmon module. `rule.name` is populated for all events when present. {issue}18364[18364] - Add Powershell module. Support for event ID's: `400`, `403`, `600`, `800`, `4103`, `4014`, `4105`, `4106`. {issue}16262[16262] {pull}18526[18526] - Fix Powershell processing of downgraded engine events. {pull}18966[18966] - Fix unprefixed fields in `fields.yml` for Powershell module {issue}18984[18984] *Functionbeat* ==== Bugfixes *Affecting all Beats* - Fix Kubernetes autodiscovery provider to correctly handle pod states and avoid missing event data {pull}17223[17223] - Fix `add_cloud_metadata` to better support modifying sub-fields with other processors. {pull}13808[13808] - TLS or Beats that accept connections over TLS and validate client certificates. {pull}14146[14146] - Fix panics that could result from invalid TLS certificates. This can affect Beats that connect over TLS, or Beats that accept connections over TLS and validate client certificates. {pull}14146[14146] - Fix panic in the Logstash output when trying to send events to closed connection. {pull}15568[15568] - Fix missing output in dockerlogbeat {pull}15719[15719] - Fix logging target settings being ignored when Beats are started via systemd or docker. {issue}12024[12024] {pull}15422[15442] - Do not load dashboards where not available. {pull}15802[15802] - Fix issue where TLS settings would be ignored when a forward proxy was in use. {pull}15516{15516} - Update replicaset group to apps/v1 {pull}15854[15802] - Fix issue where default go logger is not discarded when either * or stdout is selected. {issue}10251[10251] {pull}15708[15708] - Upgrade go-ucfg to latest v0.8.1. {pull}15937{15937} - Fix index names for indexing not always guaranteed to be lower case. {pull}16081[16081] - Add `ssl.ca_sha256` option to the supported TLS option, this allow to check that a specific certificate is used as part of the verified chain. {issue}15717[15717] - Fix loading processors from annotation hints. {pull}16348[16348] - Fix an issue that could cause redundant configuration reloads. {pull}16440[16440] - Fix k8s pods labels broken schema. {pull}16480[16480] - Fix k8s pods annotations broken schema. {pull}16554[16554] - Upgrade go-ucfg to latest v0.8.3. {pull}16450{16450} - Fix `NewContainerMetadataEnricher` to use default config for kubernetes module. {pull}16857[16857] - Improve some logging messages for add_kubernetes_metadata processor {pull}16866[16866] - Fix k8s metadata issue regarding node labels not shown up on root level of metadata. {pull}16834[16834] - Fail to start if httpprof is used and it cannot be initialized. {pull}17028[17028] - Fix concurrency issues in convert processor when used in the global context. {pull}17032[17032] - Fix bug with `monitoring.cluster_uuid` setting not always being exposed via GET /state Beats API. {issue}16732[16732] {pull}17420[17420] - Fix building on FreeBSD by removing build flags from `add_cloudfoundry_metadata` processor. {pull}17486[17486] - Do not rotate log files on startup when interval is configured and rotateonstartup is disabled. {pull}17613[17613] - Fix goroutine leak and Elasticsearch output file descriptor leak when output reloading is in use. {issue}10491[10491] {pull}17381[17381] - Fix `setup.dashboards.index` setting not working. {pull}17749[17749] - Fix Elasticsearch license endpoint URL referenced in error message. {issue}17880[17880] {pull}18030[18030] - Fix panic when assigning a key to a `nil` value in an event. {pull}18143[18143] - Gives monitoring reporter hosts, if configured, total precedence over corresponding output hosts. {issue}17937[17937] {pull}17991[17991] - Change `decode_json_fields` processor, to merge parsed json objects with existing objects in the event instead of fully replacing them. {pull}17958[17958] - [Autodiscover] Check if runner is already running before starting again. {pull}18564[18564] - Fix `keystore add` hanging under Windows. {issue}18649[18649] {pull}18654[18654] - Fix an issue where error messages are not accurate in mapstriface. {issue}18662[18662] {pull}18663[18663] - Fix regression in `add_kubernetes_metadata`, so configured `indexers` and `matchers` are used if defaults are not disabled. {issue}18481[18481] {pull}18818[18818] - Fix potential race condition in fingerprint processor. {pull}18738[18738] - Add better handling for Kubernetes Update and Delete watcher events. {pull}18882[18882] - Fix the `translate_sid` processor's handling of unconfigured target fields. {issue}18990[18990] {pull}18991[18991] - Fixed a service restart failure under Windows. {issue}18914[18914] {pull}18916[18916] - The `monitoring.elasticsearch.api_key` value is correctly base64-encoded before being sent to the monitoring Elasticsearch cluster. {issue}18939[18939] {pull}18945[18945] - Fix kafka topic setting not allowing upper case characters. {pull}18854[18854] {issue}18640[18640] - Fix redis key setting not allowing upper case characters. {pull}18854[18854] {issue}18640[18640] - Fix config reload metrics (`libbeat.config.module.start/stops/running`). {pull}19168[19168] - Fix metrics hints builder to avoid wrong container metadata usage when port is not exposed {pull}18979[18979] - Server-side TLS config now validates certificate and key are both specified {pull}19584[19584] *Auditbeat* - system/socket: Fixed compatibility issue with kernel 5.x. {pull}15771[15771] - system/package: Fix parsing of Installed-Size field of DEB packages. {issue}16661[16661] {pull}17188[17188] - system module: Fix panic during initialisation when /proc/stat can't be read. {pull}17569[17569] - system/package: Fix an error that can occur while trying to persist package metadata. {issue}18536[18536] {pull}18887[18887] - system/socket: Fix dataset using 100% CPU and becoming unresponsive in some scenarios. {pull}19033[19033] - system/socket: Fixed tracking of long-running connections. {pull}19033[19033] - system/package: Fix librpm loading on Fedora 31/32. {pull}NNNN[NNNN] *Filebeat* - Ensure all zeek timestamps include millisecond precision. {issue}14599[14599] {pull}16766[16766] - Fix s3 input hanging with GetObjectRequest API call by adding context_timeout config. {issue}15502[15502] {pull}15590[15590] - Add shared_credential_file to cloudtrail config {issue}15652[15652] {pull}15656[15656] - Fix typos in zeek notice fileset config file. {issue}15764[15764] {pull}15765[15765] - Fix mapping error when zeek weird logs do not contain IP addresses. {pull}15906[15906] - Improve `elasticsearch/audit` fileset to handle timestamps correctly. {pull}15942[15942] - Prevent Elasticsearch from spewing log warnings about redundant wildcards when setting up ingest pipelines for the `elasticsearch` module. {issue}15840[15840] {pull}15900[15900] - Fix mapping error for cloudtrail additionalEventData field {pull}16088[16088] - Fix a connection error in httpjson input. {pull}16123[16123] - Fix s3 input with cloudtrail fileset reading json file. {issue}16374[16374] {pull}16441[16441] - Rewrite azure filebeat dashboards, due to changes in kibana. {pull}16466[16466] - Adding the var definitions in azure manifest files, fix for errors when executing command setup. {issue}16270[16270] {pull}16468[16468] - Fix merging of fileset inputs to replace paths and append processors. {pull}16450{16450} - Add queue_url definition in manifest file for aws module. {pull}16640{16640} - Fix issue where autodiscover hints default configuration was not being copied. {pull}16987[16987] - Fix Elasticsearch `_id` field set by S3 and Google Pub/Sub inputs. {pull}17026[17026] - Fixed various Cisco FTD parsing issues. {issue}16863[16863] {pull}16889[16889] - Fix default index pattern in IBM MQ filebeat dashboard. {pull}17146[17146] - Fix `elasticsearch.gc` fileset to not collect _all_ logs when Elasticsearch is running in Docker. {issue}13164[13164] {issue}16583[16583] {pull}17164[17164] - Fixed a mapping exception when ingesting CEF logs that used the spriv or dpriv extensions. {issue}17216[17216] {pull}17220[17220] - CEF: Fixed decoding errors caused by trailing spaces in messages. {pull}17253[17253] - Fixed a mapping exception when ingesting Logstash plain logs (7.4+) with pipeline ids containing non alphanumeric chars. {issue}17242[17242] {pull}17243[17243] - Fixed MySQL slowlog module causing ""regular expression has redundant nested repeat operator"" warning in Elasticsearch. {issue}17086[17086] {pull}17156[17156] - Fix `elasticsearch.audit` data ingest pipeline to be more forgiving with date formats found in Elasticsearch audit logs. {pull}17406[17406] - Fixed activemq module causing ""regular expression has redundant nested repeat operator"" warning in Elasticsearch. {pull}17428[17428] - Remove migrationVersion map 7.7.0 reference from Kibana dashboard file to fix backward compatibility issues. {pull}17425[17425] - Fix issue 17734 to retry on rate-limit error in the Filebeat httpjson input. {issue}17734[17734] {pull}17735[17735] - Fixed `cloudfoundry.access` to have the correct `cloudfoundry.app.id` contents. {pull}17847[17847] - Fixing `ingress_controller.` fields to be of type keyword instead of text. {issue}17834[17834] - Fixed typo in log message. {pull}17897[17897] - Fix Cisco ASA ASA 3020** and 106023 messages {pull}17964[17964] - Unescape file name from SQS message. {pull}18370[18370] - Improve cisco asa and ftd pipelines' failure handler to avoid mapping temporary fields. {issue}18391[18391] {pull}18392[18392] - Fix source.address not being set for nginx ingress_controller {pull}18511[18511] - Fix PANW module wrong mappings for bytes and packets counters. {issue}18522[18522] {pull}18525[18525] - Fixed ingestion of some Cisco ASA and FTD messages when a hostname was used instead of an IP for NAT fields. {issue}14034[14034] {pull}18376[18376] - Fix a rate limit related issue in httpjson input for Okta module. {issue}18530[18530] {pull}18534[18534] - Fix `googlecloud.audit` pipeline to only take in fields that are explicitly defined by the dataset. {issue}18465[18465] {pull}18472[18472] - Fix `o365.audit` failing to ingest events when ip address is surrounded by square brackets. {issue}18587[18587] {pull}18591[18591] - Fix Kubernetes Watcher goroutine leaks when input config is invalid and `input.reload` is enabled. {issue}18629[18629] {pull}18630[18630] - Okta module now sets the Elasticsearch `_id` field to the Okta UUID value contained in each system log to minimize the possibility of duplicating events. {pull}18953[18953] - Fix improper nesting of session_issuer object in aws cloudtrail fileset. {issue}18894[18894] {pull}18915[18915] - Fix `o365` module ignoring `var.api` settings. {pull}18948[18948] - Fix `netflow` module to support 7 bytepad for IPFIX template. {issue}18098[18098] - Fix Cisco ASA dissect pattern for 313008 & 313009 messages. {pull}19149[19149] - Fix date and timestamp formats for fortigate module {pull}19316[19316] - Fix memory leak in tcp and unix input sources. {pull}19459[19459] - Add missing `default_field: false` to aws filesets fields.yml. {pull}19568[19568] - Fix tls mapping in suricata module {issue}19492[19492] {pull}19494[19494] *Heartbeat* - Fixed excessive memory usage introduced in 7.5 due to over-allocating memory for HTTP checks. {pull}15639[15639] - Fixed TCP TLS checks to properly validate hostnames, this broke in 7.x and only worked for IP SANs. {pull}17549[17549] *Journalbeat* *Metricbeat* - Add dedot for tags in ec2 metricset and cloudwatch metricset. {issue}15843[15843] {pull}15844[15844] - Use RFC3339 format for timestamps collected using the SQL module. {pull}15847[15847] - Avoid parsing errors returned from prometheus endpoints. {pull}15712[15712] - Change lookup_fields from metricset.host to service.address {pull}15883[15883] - Add dedot for cloudwatch metric name. {issue}15916[15916] {pull}15917[15917] - Fixed issue `logstash-xpack` module suddenly ceasing to monitor Logstash. {issue}15974[15974] {pull}16044[16044] - Fix skipping protocol scheme by light modules. {pull}16205[pull] - Made `logstash-xpack` module once again have parity with internally-collected Logstash monitoring data. {pull}16198[16198] - Change sqs metricset to use average as statistic method. {pull}16438[16438] - Revert changes in `docker` module: add size flag to docker.container. {pull}16600[16600] - Fix diskio issue for windows 32 bit on disk_performance struct alignment. {issue}16680[16680] - Fix detection and logging of some error cases with light modules. {pull}14706[14706] - Fix imports after PR was merged before rebase. {pull}16756[16756] - Add dashboard for `redisenterprise` module. {pull}16752[16752] - Dynamically choose a method for the system/service metricset to support older linux distros. {pull}16902[16902] - Use max in k8s apiserver dashboard aggregations. {pull}17018[17018] - Reduce memory usage in `elasticsearch/index` metricset. {issue}16503[16503] {pull}16538[16538] - Check if CCR feature is available on Elasticsearch cluster before attempting to call CCR APIs from `elasticsearch/ccr` metricset. {issue}16511[16511] {pull}17073[17073] - Use max in k8s overview dashboard aggregations. {pull}17015[17015] - Fix Disk Used and Disk Usage visualizations in the Metricbeat System dashboards. {issue}12435[12435] {pull}17272[17272] - Fix missing Accept header for Prometheus and OpenMetrics module. {issue}16870[16870] {pull}17291[17291] - Further revise check for bad data in docker/memory. {pull}17400[17400] - Fix issue in Jolokia module when mbean contains multiple quoted properties. {issue}17375[17375] {pull}17374[17374] - Combine cloudwatch aggregated metrics into single event. {pull}17345[17345] - Fix how we filter services by name in system/service {pull}17400[17400] - Fix cloudwatch metricset missing tags collection. {issue}17419[17419] {pull}17424[17424] - check if cpuOptions field is nil in DescribeInstances output in ec2 metricset. {pull}17418[17418] - Fix aws.s3.bucket.name terms_field in s3 overview dashboard. {pull}17542[17542] - Fix Unix socket path in memcached. {pull}17512[17512] - Fix vsphere VM dashboard host aggregation visualizations. {pull}17555[17555] - Fix azure storage dashboards. {pull}17590[17590] - Metricbeat no longer needs to be started strictly after Logstash for `logstash-xpack` module to report correct data. {issue}17261[17261] {pull}17497[17497] - Fix pubsub metricset to collect all GA stage metrics from gcp stackdriver. {issue}17154[17154] {pull}17600[17600] - Add privileged option so as mb to access data dir in Openshift. {pull}17606[17606] - Fix ""ID"" event generator of Google Cloud module {issue}17160[17160] {pull}17608[17608] - Add privileged option for Auditbeat in Openshift {pull}17637[17637] - Fix storage metricset to allow config without region/zone. {issue}17623[17623] {pull}17624[17624] - Add a switch to the driver definition on SQL module to use pretty names. {pull}17378[17378] - Fix overflow on Prometheus rates when new buckets are added on the go. {pull}17753[17753] - Remove specific win32 api errors from events in perfmon. {issue}18292[18292] {pull}18361[18361] - Fix application_pool metricset after pdh changes. {pull}18477[18477] - Fix tags_filter for cloudwatch metricset in aws. {pull}18524[18524] - Fix panic on `metricbeat test modules` when modules are configured in `metricbeat.modules`. {issue}18789[18789] {pull}18797[18797] - Fix getting gcp compute instance metadata with partial zone/region in config. {pull}18757[18757] - Add missing network.sent_packets_count metric into compute metricset in googlecloud module. {pull}18802[18802] - Fix compute and pubsub dashboard for googlecloud module. {issue}18962[18962] {pull}18980[18980] - Fix crash on vsphere module when Host information is not available. {issue}18996[18996] {pull}19078[19078] - Fix incorrect usage of hints builder when exposed port is a substring of the hint {pull}19052[19052] - Remove dedot for tag values in aws module. {issue}19112[19112] {pull}19221[19221] - Stop counterCache only when already started {pull}19103[19103] - Set tags correctly if the dimension value is ARN {issue}19111[19111] {pull}19433[19433] - Fix bug incorrect parsing of float numbers as integers in Couchbase module {issue}18949[18949] {pull}19055[19055] - Fix config example in the perfmon configuration files. {pull}19539[19539] - Add missing info about the rest of the azure metricsets in the documentation. {pull}19601[19601] *Packetbeat* - Enable setting promiscuous mode automatically. {pull}11366[11366] *Winlogbeat* - Fix invalid IP addresses in DNS query results from Sysmon data. {issue}18432[18432] {pull}18436[18436] - Fields from Winlogbeat modules were not being included in index templates and patterns. {pull}18983[18983] *Functionbeat* - Fix timeout option of GCP functions. {issue}16282[16282] {pull}16287[16287] ==== Added *Affecting all Beats* - Add configuration for APM instrumentation and expose the tracer trough the Beat object. {pull}17938[17938] - Add document_id setting to decode_json_fields processor. {pull}15859[15859] - Include network information by default on add_host_metadata and add_observer_metadata. {issue}15347[15347] {pull}16077[16077] - Add `aws_ec2` provider for autodiscover. {issue}12518[12518] {pull}14823[14823] - Add monitoring variable `libbeat.config.scans` to distinguish scans of the configuration directory from actual reloads of its contents. {pull}16440[16440] - Add support for multiple password in redis output. {issue}16058[16058] {pull}16206[16206] - Add support for Histogram type in fields.yml {pull}16570[16570] - Windows .exe files now have embedded file version info. {issue}15232[15232]t - Remove experimental flag from `setup.template.append_fields` {pull}16576[16576] - Add `add_cloudfoundry_metadata` processor to annotate events with Cloud Foundry application data. {pull}16621[16621] - Add Kerberos support to Kafka input and output. {pull}16781[16781] - Add `add_cloudfoundry_metadata` processor to annotate events with Cloud Foundry application data. {pull}16621[16621 - Add support for kubernetes provider to recognize namespace level defaults {pull}16321[16321] - Add `translate_sid` processor on Windows for converting Windows security identifier (SID) values to names. {issue}7451[7451] {pull}16013[16013] - Add capability of enrich `container.id` with process id in `add_process_metadata` processor {pull}15947[15947] - Update RPM packages contained in Beat Docker images. {issue}17035[17035] - Update supported versions of `redis` output. {pull}17198[17198] - Update documentation for system.process.memory fields to include clarification on Windows os's. {pull}17268[17268] - Add `replace` processor for replacing string values of fields. {pull}17342[17342] - Add optional regex based cid extractor to `add_kubernetes_metadata` processor. {pull}17360[17360] - Add `urldecode` processor to for decoding URL-encoded fields. {pull}17505[17505] - Add support for AWS IAM `role_arn` in credentials config. {pull}17658[17658] {issue}12464[12464] - Add keystore support for autodiscover static configurations. {pull]16306[16306] - Add Kerberos support to Elasticsearch output. {pull}17927[17927] - Add k8s keystore backend. {pull}18096[18096] - Add support for fixed length extraction in `dissect` processor. {pull}17191[17191] - Set `agent.name` to the hostname by default. {issue}16377[16377] {pull}18000[18000] - Add support for basic ECS logging. {pull}17974[17974] - Add config example of how to skip the `add_host_metadata` processor when forwarding logs. {issue}13920[13920] {pull}18153[18153] - When using the `decode_json_fields` processor, decoded fields are now deep-merged into existing event. {pull}17958[17958] - Add backoff configuration options for the Kafka output. {issue}16777[16777] {pull}17808[17808] - Add TLS support to Kerberos authentication in Elasticsearch. {pull}18607[18607] - Change ownership of files in docker images so they can be used in secured environments. {pull}12905[12905] - Upgrade k8s.io/client-go and k8s keystore tests. {pull}18817[18817] - Add support for multiple sets of hints on autodiscover {pull}18883[18883] - Add a configurable delay between retries when an app metadata cannot be retrieved by `add_cloudfoundry_metadata`. {pull}19181[19181] - Add the `ignore_failure` configuration option to the dissect processor. {pull}19464[19464] - Add the `overwrite_keys` configuration option to the dissect processor. {pull}19464[19464] - Add support to trim captured values in the dissect processor. {pull}19464[19464] *Auditbeat* - Reference kubernetes manifests include configuration for auditd and enrichment with kubernetes metadata. {pull}17431[17431] - Reference kubernetes manifests mount data directory from the host, so data persist between executions in the same node. {pull}17429[17429] - Log to stderr when running using reference kubernetes manifests. {pull}17443[174443] - Fix syscall kprobe arguments for 32-bit systems in socket module. {pull}17500[17500] - Fix memory leak on when we miss socket close kprobe events. {pull}17500[17500] - Add system module process dataset ECS categorization fields. {pull}18032[18032] - Add system module socket dataset ECS categorization fields. {pull}18036[18036] - Add ECS categories for system module host dataset. {pull}18031[18031] - Add system module package dataset ECS categorization fields. {pull}18033[18033] - Add system module login dataset ECS categorization fields. {pull}18034[18034] - Add system module user dataset ECS categorization fields. {pull}18035[18035] - Add file integrity module ECS categorization fields. {pull}18012[18012] - Add `file.mime_type`, `file.extension`, and `file.drive_letter` for file integrity module. {pull}18012[18012] - Add ECS categorization info for auditd module {pull}18596[18596] *Filebeat* - Set event.outcome field based on googlecloud audit log output. {pull}15731[15731] - Add dashboard for AWS ELB fileset. {pull}15804[15804] - Add dashboard for AWS vpcflow fileset. {pull}16007[16007] - Add ECS tls fields to zeek:smtp,rdp,ssl and aws:s3access,elb {issue}15757[15757] {pull}15935[15936] - Add custom string mapping to CEF module to support Forcepoint NGFW {issue}14663[14663] {pull}15910[15910] - Add ingress nginx controller fileset {pull}16197[16197] - move create-[module,fileset,fields] to mage and enable in x-pack/filebeat {pull}15836[15836] - Add ECS tls and categorization fields to apache module. {issue}16032[16032] {pull}16121[16121] - Work on e2e ACK's for the azure-eventhub input {issue}15671[15671] {pull}16215[16215] - Add MQTT input. {issue}15602[15602] {pull}16204[16204] - Add ECS categorization fields to activemq module. {issue}16151[16151] {pull}16201[16201] - Add a TLS test and more debug output to httpjson input {pull}16315[16315] - Add an SSL config example in config.yml for filebeat MISP module. {pull}16320[16320] - Improve ECS categorization, container & process field mappings in auditd module. {issue}16153[16153] {pull}16280[16280] - Improve ECS field mappings in aws module. {issue}16154[16154] {pull}16307[16307] - Improve ECS categorization field mappings in googlecloud module. {issue}16030[16030] {pull}16500[16500] - Improve ECS field mappings in haproxy module. {issue}16162[16162] {pull}16529[16529] - Add cloudwatch fileset and ec2 fileset in aws module. {issue}13716[13716] {pull}16579[16579] - Improve ECS categorization field mappings in kibana module. {issue}16168[16168] {pull}16652[16652] - Improve the decode_cef processor by reducing the number of memory allocations. {pull}16587[16587] - Add `cloudfoundry` input to send events from Cloud Foundry. {pull}16586[16586] - Improve ECS categorization field mappings in iis module. {issue}16165[16165] {pull}16618[16618] - Improve ECS categorization field mapping in kafka module. {issue}16167[16167] {pull}16645[16645] - Allow users to override pipeline ID in fileset input config. {issue}9531[9531] {pull}16561[16561] - Add `o365audit` input type for consuming events from Office 365 Management Activity API. {issue}16196[16196] {pull}16244[16244] - Improve ECS categorization field mappings in logstash module. {issue}16169[16169] {pull}16668[16668] - Update filebeat httpjson input to support pagination via Header and Okta module. {pull}16354[16354] - Improve ECS categorization field mapping in icinga module. {issue}16164[16164] {pull}16533[16533] - Improve ECS categorization field mappings in ibmmq module. {issue}16163[16163] {pull}16532[16532] - Improve ECS categorization, host field mappings in elasticsearch module. {issue}16160[16160] {pull}16469[16469] - Add ECS related fields to CEF module {issue}16157[16157] {pull}16338[16338] - Improve ECS categorization field mappings in suricata module. {issue}16181[16181] {pull}16843[16843] - Release ActiveMQ module as GA. {issue}17047[17047] {pull}17049[17049] - Improve ECS categorization field mappings in iptables module. {issue}16166[16166] {pull}16637[16637] - Add Filebeat Okta module. {pull}16362[16362] - Add custom string mapping to CEF module to support Check Point devices. {issue}16041[16041] {pull}16907[16907] - Add pattern for Cisco ASA / FTD Message 734001 {issue}16212[16212] {pull}16612[16612] - Added new module `o365` for ingesting Office 365 management activity API events. {issue}16196[16196] {pull}16386[16386] - Add source field in k8s events {pull}17209[17209] - Improve AWS cloudtrail field mappings {issue}16086[16086] {issue}16110[16110] {pull}17155[17155] - Added new module `crowdstrike` for ingesting Crowdstrike Falcon streaming API endpoint event data. {pull}16988[16988] - Added documentation for running Filebeat in Cloud Foundry. {pull}17275[17275] - Move azure-eventhub input to GA. {issue}15671[15671] {pull}17313[17313] - Improve ECS categorization field mappings in mongodb module. {issue}16170[16170] {pull}17371[17371] - Improve ECS categorization field mappings for mssql module. {issue}16171[16171] {pull}17376[17376] - Added access_key_id, secret_access_key and session_token into aws module config. {pull}17456[17456] - Add dashboard for Google Cloud Audit and AWS CloudTrail. {pull}17379[17379] - Improve ECS categorization field mappings for mysql module. {issue}16172[16172] {pull}17491[17491] - Release Google Cloud module as GA. {pull}17511[17511] - Add config option to select a different azure cloud env in the azure-eventhub input and azure module. {issue}17649[17649] {pull}17659[17659] - Added new Checkpoint Syslog filebeat module. {pull}17682[17682] - Improve ECS categorization field mappings for nats module. {issue}16173[16173] {pull}17550[17550] - Add support for v10, v11 and v12 logs on Postgres {issue}13810[13810] {pull}17732[17732] - Enhance `elasticsearch/server` fileset to handle ECS-compatible logs emitted by Elasticsearch. {issue}17715[17715] {pull}17714[17714] - Add support for Google Application Default Credentials to the Google Pub/Sub input and Google Cloud modules. {pull}15668[15668] - Enhance `elasticsearch/deprecation` fileset to handle ECS-compatible logs emitted by Elasticsearch. {issue}17715[17715] {pull}17728[17728] - Enhance `elasticsearch/slowlog` fileset to handle ECS-compatible logs emitted by Elasticsearch. {issue}17715[17715] {pull}17729[17729] - Improve ECS categorization field mappings in misp module. {issue}16026[16026] {pull}17344[17344] - Added Unix stream socket support as an input source and a syslog input source. {pull}17492[17492] - Added new Fortigate Syslog filebeat module. {pull}17890[17890] - Improve ECS categorization field mappings in postgresql module. {issue}16177[16177] {pull}17914[17914] - Improve ECS categorization field mappings in rabbitmq module. {issue}16178[16178] {pull}17916[17916] - Make `decode_cef` processor GA. {pull}17944[17944] - Improve ECS categorization field mappings in redis module. {issue}16179[16179] {pull}17918[17918] - Improve ECS categorization field mappings for zeek module. {issue}16029[16029] {pull}17738[17738] - Improve ECS categorization field mappings for netflow module. {issue}16135[16135] {pull}18108[18108] - Added an input option `publisher_pipeline.disable_host` to disable `host.name` from being added to events by default. {pull}18159[18159] - Improve ECS categorization field mappings in system module. {issue}16031[16031] {pull}18065[18065] - Change the `json.*` input settings implementation to merge parsed json objects with existing objects in the event instead of fully replacing them. {pull}17958[17958] - Improve ECS categorization field mappings in osquery module. {issue}16176[16176] {pull}17881[17881] - Added http_endpoint input{pull}18298[18298] - Add support for array parsing in azure-eventhub input. {pull}18585[18585] - Added `observer.vendor`, `observer.product`, and `observer.type` to PANW module events. {pull}18223[18223] - The `logstash` module can now automatically detect the log file format (JSON or plaintext) and process it accordingly. {issue}9964[9964] {pull}18095[18095] - Improve ECS categorization field mappings in envoyproxy module. {issue}16161[16161] {pull}18395[18395] - Improve ECS categorization field mappings in coredns module. {issue}16159[16159] {pull}18424[18424] - Improve ECS categorization field mappings in cisco module. {issue}16028[16028] {pull}18537[18537] - The s3 input can now automatically detect gzipped objects. {issue}18283[18283] {pull}18764[18764] - Add geoip AS lookup & improve ECS categorization in aws cloudtrail fileset. {issue}18644[18644] {pull}18958[18958] - Improved performance of PANW sample dashboards. {issue}19031[19031] {pull}19032[19032] - Add support for v1 consumer API in Cloud Foundry input, use it by default. {pull}19125[19125] - Explicitly set ECS version in all Filebeat modules. {pull}19198[19198] - Add new mode to multiline reader to aggregate constant number of lines {pull}18352[18352] - Add automatic retries and exponential backoff to httpjson input. {pull}18956[18956] - Add awscloudwatch input. {pull}19025[19025] - Changed the panw module to pass through (rather than drop) message types other than threat and traffic. {issue}16815[16815] {pull}19375[19375] - Add support for timezone offsets and `Z` to decode_cef timestamp parser. {pull}19346[19346] - Improve ECS categorization field mappings in traefik module. {issue}16183[16183] {pull}19379[19379] *Heartbeat* - Allow a list of status codes for HTTP checks. {pull}15587[15587] - Add additional ECS compatible fields for TLS information. {pull}17687[17687] - Record HTTP response headers. {pull}18327[18327] *Journalbeat* - Added an `id` config option to inputs to allow running multiple inputs on the same journal. {pull}18467{18467} - Add basic ECS categorization and `log.syslog` fields. {pull}19176[19176] *Metricbeat* - Move the windows pdh implementation from perfmon to a shared location in order for future modules/metricsets to make use of. {pull}15503[15503] - Add lambda metricset in aws module. {pull}15260[15260] - Expand data for the `system/memory` metricset {pull}15492[15492] - Add azure `storage` metricset in order to retrieve metric values for storage accounts. {issue}14548[14548] {pull}15342[15342] - Add cost warnings for the azure module. {pull}15356[15356] - Add DynamoDB AWS Metricbeat light module {pull}15097[15097] - Release elb module as GA. {pull}15485[15485] - Add a `system/network_summary` metricset {pull}15196[15196] - Add mesh metricset for Istio Metricbeat module {pull}15535[15535] - Add mixer metricset for Istio Metricbeat module {pull}15696[15696] - Add pilot metricset for Istio Metricbeat module {pull}15761[15761] - Make the `system/cpu` metricset collect normalized CPU metrics by default. {issue}15618[15618] {pull}15729[15729] - Add galley metricset for Istio Metricbeat module {pull}15857[15857] - Add `key/value` mode for SQL module. {issue}15770[15770] {pull]15845[15845] - Add STAN dashboard {pull}15654[15654] - Add support for Unix socket in Memcached metricbeat module. {issue}13685[13685] {pull}15822[15822] - Add `up` metric to prometheus metrics collected from host {pull}15948[15948] - Add citadel metricset for Istio Metricbeat module {pull}15990[15990] - Add support for processors in light modules. {issue}14740[14740] {pull}15923[15923] - Add collecting AuroraDB metrics in rds metricset. {issue}14142[14142] {pull}16004[16004] - Reuse connections in SQL module. {pull}16001[16001] - Improve the `logstash` module (when `xpack.enabled` is set to `true`) to use the override `cluster_uuid` returned by Logstash APIs. {issue}15772[15772] {pull}15795[15795] - Add region parameter in googlecloud module. {issue}15780[15780] {pull}16203[16203] - Add kubernetes storage class support via kube-state-metrics. {pull}16145[16145] - Add database_account azure metricset. {issue}15758[15758] - Add support for NATS 2.1. {pull}16317[16317] - Add Load Balancing metricset to GCP {pull}15559[15559] - Add support for Dropwizard metrics 4.1. {pull}16332[16332] - Add azure container metricset in order to monitor containers. {issue}15751[15751] {pull}16421[16421] - Improve the `haproxy` module to support metrics exposed via HTTPS. {issue}14579[14579] {pull}16333[16333] - Add filtering option for prometheus collector. {pull}16420[16420] - Add metricsets based on Ceph Manager Daemon to the `ceph` module. {issue}7723[7723] {pull}16254[16254] - Release `statsd` module as GA. {pull}16447[16447] {issue}14280[14280] - Add collecting tags and tags_filter for rds metricset in aws module. {pull}16605[16605] {issue}16358[16358] - Add OpenMetrics Metricbeat module {pull}16596[16596] - Add `cloudfoundry` module to send events from Cloud Foundry. {pull}16671[16671] - Add `redisenterprise` module. {pull}16482[16482] {issue}15269[15269] - Add system/users metricset as beta {pull}16569[16569] - Align fields to ECS and add more tests for the azure module. {issue}16024[16024] {pull}16754[16754] - Add additional cgroup fields to docker/diskio{pull}16638[16638] - Add PubSub metricset to Google Cloud Platform module {pull}15536[15536] - Add overview dashboard for googlecloud compute metricset. {issue}16534[16534] {pull}16819[16819] - Add Prometheus remote write endpoint {pull}16609[16609] - Release STAN module as GA. {pull}16980[16980] - Add query metricset for prometheus module. {pull}17104[17104] - Release ActiveMQ module as GA. {issue}17047[17047] {pull}17049[17049] - Release Zookeeper/connection module as GA. {issue}14281[14281] {pull}17043[17043] - Add support for CouchDB v2 {issue}16352[16352] {pull}16455[16455] - Add dashboard for pubsub metricset in googlecloud module. {pull}17161[17161] - Add dashboards for the azure container metricsets. {pull}17194[17194] - Replace vpc metricset into vpn, transitgateway and natgateway metricsets. {pull}16892[16892] - Use Elasticsearch histogram type to store Prometheus histograms {pull}17061[17061] - Allow to rate Prometheus counters when scraping them {pull}17061[17061] - Release Oracle module as GA. {issue}14279[14279] {pull}16833[16833] - Release vsphere module as GA. {issue}15798[15798] {pull}17119[17119] - Add Storage metricsets to GCP module {pull}15598[15598] - Added documentation for running Metricbeat in Cloud Foundry. {pull}17275[17275] - Add test for documented fields check for metricsets without a http input. {issue}17315[17315] {pull}17334[17334] - Add final tests and move label to GA for the azure module in metricbeat. {pull}17319[17319] - Refactor windows/perfmon metricset configuration options and event output. {pull}17596[17596] - Reference kubernetes manifests mount data directory from the host when running metricbeat as daemonset, so data persist between executions in the same node. {pull}17429[17429] - Add more detailed error messages, system tests and small refactoring to the service metricset in windows. {pull}17725[17725] - Stack Monitoring modules now auto-configure required metricsets when `xpack.enabled: true` is set. {issue}16471[[16471] {pull}17609[17609] - Add Metricbeat IIS module dashboards. {pull}17966[17966] - Add dashboard for the azure database account metricset. {pull}17901[17901] - Allow partial region and zone name in googlecloud module config. {pull}17913[17913] - Add aggregation aligner as a config parameter for googlecloud stackdriver metricset. {issue}17141[[17141] {pull}17719[17719] - Move the perfmon metricset to GA. {issue}16608[16608] {pull}17879[17879] - Add static mapping for metricsets under aws module. {pull}17614[17614] {pull}17650[17650] - Add dashboard for googlecloud storage metricset. {pull}18172[18172] - Collect new `bulk` indexing metrics from Elasticsearch when `xpack.enabled:true` is set. {issue} {pull}17992[17992] - Remove requirement to connect as sysdba in Oracle module {issue}15846[15846] {pull}18182[18182] - Update MSSQL module to fix some SSPI authentication and add brackets to USE statements {pull}17862[17862]] - Add client address to events from http server module {pull}18336[18336] - Remove required for region/zone and make stackdriver a metricset in googlecloud. {issue}16785[16785] {pull}18398[18398] - Add memory metrics into compute googlecloud. {pull}18802[18802] - Add new fields to HAProxy module. {issue}18523[18523] - Add Tomcat overview dashboard {pull}14026[14026] - Accept prefix as metric_types config parameter in googlecloud stackdriver metricset. {pull}19345[19345] - Update Couchbase to version 6.5 {issue}18595[18595] {pull}19055[19055] - Add dashboards for googlecloud load balancing metricset. {pull}18369[18369] - Add support for v1 consumer API in Cloud Foundry module, use it by default. {pull}19268[19268] - Add param `aws_partition` to support aws-cn, aws-us-gov regions. {issue}18850[18850] {pull}19423[19423] - The `elasticsearch/index` metricset now collects metrics for hidden indices as well. {issue}18639[18639] {pull}18703[18703] *Packetbeat* - Add an example to packetbeat.yml of using the `forwarded` tag to disable `host` metadata fields when processing network data from network tap or mirror port. {pull}19209[19209] - Add ECS fields for x509 certs, event categorization, and related IP info. {pull}19167[19167] *Functionbeat* - Add basic ECS categorization and `cloud` fields. {pull}19174[19174] *Winlogbeat* - Add more DNS error codes to the Sysmon module. {issue}15685[15685] - Add experimental event log reader implementation that should be faster in most cases. {issue}6585[6585] {pull}16849[16849] - Set process.command_line and process.parent.command_line from Sysmon Event ID 1. {pull}17327[17327] - Add support for event IDs 4673,4674,4697,4698,4699,4700,4701,4702,4768,4769,4770,4771,4776,4778,4779,4964 to the Security module {pull}17517[17517] - Add registry and code signature information and ECS categorization fields for sysmon module {pull}18058[18058] - Add new winlogbeat security dashboard {pull}18775[18775] ==== Deprecated *Affecting all Beats* *Filebeat* *Heartbeat* *Journalbeat* *Metricbeat* - Deprecate tags config parameter in cloudwatch metricset. {pull}16733[16733] *Packetbeat* *Winlogbeat* *Functionbeat* ==== Known Issue *Journalbeat* ",16316,True,3702.075022139894,median ":toc: macro :toc-title: toc::[] == oc adm build-chain Output the inputs and dependencies of your builds ==== [options=""nowrap""] ---- # Build the dependency tree for the 'latest' tag in oc adm build-chain # Build the dependency tree for 'v2' tag in dot format and visualize it via the dot utility oc adm build-chain :v2 -o dot | dot -T svg -o deps.svg # Build the dependency tree across all namespaces for the specified image stream tag found in 'test' namespace oc adm build-chain -n test --all ---- ==== == oc adm ca decrypt Decrypt data encrypted with ""oc adm ca encrypt"" ==== [options=""nowrap""] ---- # Decrypt an encrypted file to a cleartext file: oc adm ca decrypt --key=secret.key --in=secret.encrypted --out=secret.decrypted # Decrypt from stdin to stdout: oc adm ca decrypt --key=secret.key < secret2.encrypted > secret2.decrypted ---- ==== == oc adm ca encrypt Encrypt data with AES-256-CBC encryption ==== [options=""nowrap""] ---- # Encrypt the content of secret.txt with a generated key: oc adm ca encrypt --genkey=secret.key --in=secret.txt --out=secret.encrypted # Encrypt the content of secret2.txt with an existing key: oc adm ca encrypt --key=secret.key < secret2.txt > secret2.encrypted ---- ==== == oc adm completion Output shell completion code for the given shell (bash or zsh) ==== [options=""nowrap""] ---- # Generate the oc adm completion code for bash oc adm completion bash > bash_completion.sh source bash_completion.sh # The above example depends on the bash-completion framework. It must be sourced before sourcing the openshift cli completion, i.e. on the Mac: brew install bash-completion source $(brew --prefix)/etc/bash_completion oc adm completion bash > bash_completion.sh source bash_completion.sh # In zsh, the following will load openshift cli zsh completion: source <(oc adm completion zsh) ---- ==== == oc adm config Change configuration files for the client ==== [options=""nowrap""] ---- # Change the config context to use oc adm config use-context my-context # Set the value of a config preference oc adm config set preferences.some true ---- ==== == oc adm config current-context Displays the current-context ==== [options=""nowrap""] ---- # Display the current-context oc adm config current-context ---- ==== == oc adm config set-cluster Sets a cluster entry in kubeconfig ==== [options=""nowrap""] ---- # Set only the server field on the e2e cluster entry without touching other values. oc adm config set-cluster e2e --server=https://1.2.3.4 # Embed certificate authority data for the e2e cluster entry oc adm config set-cluster e2e --certificate-authority=~/.kube/e2e/kubernetes.ca.crt # Disable cert checking for the dev cluster entry oc adm config set-cluster e2e --insecure-skip-tls-verify=true ---- ==== == oc adm config set-context Sets a context entry in kubeconfig ==== [options=""nowrap""] ---- # Set the user field on the gce context entry without touching other values oc adm config set-context gce --user=cluster-admin ---- ==== == oc adm config set-credentials Sets a user entry in kubeconfig ==== [options=""nowrap""] ---- # Set only the ""client-key"" field on the ""cluster-admin"" # entry, without touching other values: oc adm config set-credentials cluster-admin --client-key=~/.kube/admin.key # Set basic auth for the ""cluster-admin"" entry oc adm config set-credentials cluster-admin --username=admin --password=uXFGweU9l35qcif # Embed client certificate data in the ""cluster-admin"" entry oc adm config set-credentials cluster-admin --client-certificate=~/.kube/admin.crt --embed-certs=true ---- ==== == oc adm config view Displays merged kubeconfig settings or a specified kubeconfig file. ==== [options=""nowrap""] ---- # Show Merged kubeconfig settings. oc adm config view # Get the password for the e2e user oc adm config view -o jsonpath='{.users[?(@.name == ""e2e"")].user.password}' ---- ==== == oc adm cordon Mark node as unschedulable ==== [options=""nowrap""] ---- # Mark node ""foo"" as unschedulable. oc adm cordon foo ---- ==== == oc adm drain Drain node in preparation for maintenance ==== [options=""nowrap""] ---- # Drain node ""foo"", even if there are pods not managed by a ReplicationController, ReplicaSet, Job, or DaemonSet on it. $ oc adm drain foo --force # As above, but abort if there are pods not managed by a ReplicationController, ReplicaSet, Job, or DaemonSet, and use a grace period of 15 minutes. $ oc adm drain foo --grace-period=900 ---- ==== == oc adm groups add-users Add users to a group ==== [options=""nowrap""] ---- # Add user1 and user2 to my-group oc adm groups add-users my-group user1 user2 ---- ==== == oc adm groups new Create a new group ==== [options=""nowrap""] ---- # Add a group with no users oc adm groups new my-group # Add a group with two users oc adm groups new my-group user1 user2 ---- ==== == oc adm groups prune Prune OpenShift groups referencing missing records on an external provider. ==== [options=""nowrap""] ---- # Prune all orphaned groups oc adm groups prune --sync-config=/path/to/ldap-sync-config.yaml --confirm # Prune all orphaned groups except the ones from the blacklist file oc adm groups prune --blacklist=/path/to/blacklist.txt --sync-config=/path/to/ldap-sync-config.yaml --confirm # Prune all orphaned groups from a list of specific groups specified in a whitelist file oc adm groups prune --whitelist=/path/to/whitelist.txt --sync-config=/path/to/ldap-sync-config.yaml --confirm # Prune all orphaned groups from a list of specific groups specified in a whitelist oc adm groups prune groups/group_name groups/other_name --sync-config=/path/to/ldap-sync-config.yaml --confirm ---- ==== == oc adm groups remove-users Remove users from a group ==== [options=""nowrap""] ---- # Remove user1 and user2 from my-group oc adm groups remove-users my-group user1 user2 ---- ==== == oc adm groups sync Sync OpenShift groups with records from an external provider. ==== [options=""nowrap""] ---- # Sync all groups from an LDAP server oc adm groups sync --sync-config=/path/to/ldap-sync-config.yaml --confirm # Sync all groups except the ones from the blacklist file from an LDAP server oc adm groups sync --blacklist=/path/to/blacklist.txt --sync-config=/path/to/ldap-sync-config.yaml --confirm # Sync specific groups specified in a whitelist file with an LDAP server oc adm groups sync --whitelist=/path/to/whitelist.txt --sync-config=/path/to/sync-config.yaml --confirm # Sync all OpenShift Groups that have been synced previously with an LDAP server oc adm groups sync --type=openshift --sync-config=/path/to/ldap-sync-config.yaml --confirm # Sync specific OpenShift Groups if they have been synced previously with an LDAP server oc adm groups sync groups/group1 groups/group2 groups/group3 --sync-config=/path/to/sync-config.yaml --confirm ---- ==== == oc adm ipfailover Install an IP failover group to a set of nodes ==== [options=""nowrap""] ---- # Check the default IP failover configuration (""ipfailover""): oc adm ipfailover # See what the IP failover configuration would look like if it is created: oc adm ipfailover -o json # Create an IP failover configuration if it does not already exist: oc adm ipfailover ipf --virtual-ips=""10.1.1.1-4"" --create # Create an IP failover configuration on a selection of nodes labeled # ""router=us-west-ha"" (on 4 nodes with 7 virtual IPs monitoring a service # listening on port 80, such as the router process). oc adm ipfailover ipfailover --selector=""router=us-west-ha"" --virtual-ips=""1.2.3.4,10.1.1.100-104,5.6.7.8"" --watch-port=80 --replicas=4 --create # Use a different IP failover config image and see the configuration: oc adm ipfailover ipf-alt --selector=""hagroup=us-west-ha"" --virtual-ips=""1.2.3.4"" -o yaml --images=myrepo/myipfailover:mytag ---- ==== == oc adm manage-node Manage nodes - list pods, evacuate, or mark ready ==== [options=""nowrap""] ---- # Block accepting any pods on given nodes oc adm manage-node --schedulable=false # Mark selected nodes as schedulable oc adm manage-node --selector="""" --schedulable=true # Migrate selected pods oc adm manage-node --evacuate --pod-selector="""" # Show pods that will be migrated oc adm manage-node --evacuate --dry-run --pod-selector="""" # List all pods on given nodes oc adm manage-node --list-pods ---- ==== == oc adm migrate image-references Update embedded Docker image references ==== [options=""nowrap""] ---- # Perform a dry-run of migrating all ""docker.io"" references to ""myregistry.com"" oc adm migrate image-references docker.io/*=myregistry.com/* # To actually perform the migration, the confirm flag must be appended oc adm migrate image-references docker.io/*=myregistry.com/* --confirm # To see more details of what will be migrated, use the loglevel and output flags oc adm migrate image-references docker.io/*=myregistry.com/* --loglevel=2 -o yaml # Migrate from a service IP to an internal service DNS name oc adm migrate image-references 172.30.1.54/*=registry.openshift.svc.cluster.local/* # Migrate from a service IP to an internal service DNS name for all deployment configs and builds oc adm migrate image-references 172.30.1.54/*=registry.openshift.svc.cluster.local/* --include=buildconfigs,deploymentconfigs ---- ==== == oc adm migrate storage Update the stored version of API objects ==== [options=""nowrap""] ---- # Perform a dry-run of updating all objects oc adm migrate storage # To actually perform the update, the confirm flag must be appended oc adm migrate storage --confirm # Only migrate pods oc adm migrate storage --include=pods --confirm # Only pods that are in namespaces starting with ""bar"" oc adm migrate storage --include=pods --confirm --from-key=bar/ --to-key=bar/\\xFF ---- ==== == oc adm pod-network join-projects Join project network ==== [options=""nowrap""] ---- # Allow project p2 to use project p1 network oc adm pod-network join-projects --to= # Allow all projects with label name=top-secret to use project p1 network oc adm pod-network join-projects --to= --selector='name=top-secret' ---- ==== == oc adm pod-network make-projects-global Make project network global ==== [options=""nowrap""] ---- # Allow project p1 to access all pods in the cluster and vice versa oc adm pod-network make-projects-global # Allow all projects with label name=share to access all pods in the cluster and vice versa oc adm pod-network make-projects-global --selector='name=share' ---- ==== == oc adm policy add-role-to-user Add users or serviceaccounts to a role in the current project ==== [options=""nowrap""] ---- # Add the 'view' role to user1 in the current project oc adm policy add-role-to-user view user1 # Add the 'edit' role to serviceaccount1 in the current project oc adm policy add-role-to-user edit -z serviceaccount1 ---- ==== == oc adm policy add-scc-to-user Add users or serviceaccount to a security context constraint ==== [options=""nowrap""] ---- # Add the 'restricted' security context contraint to user1 and user2 oc adm policy add-scc-to-user restricted user1 user2 # Add the 'privileged' security context contraint to the service account serviceaccount1 in the current namespace oc adm policy add-scc-to-user privileged -z serviceaccount1 ---- ==== == oc adm policy reconcile-cluster-role-bindings Update cluster role bindings to match the recommended bootstrap policy ==== [options=""nowrap""] ---- # Display the names of cluster role bindings that would be modified oc adm policy reconcile-cluster-role-bindings -o name # Display the cluster role bindings that would be modified, removing any extra subjects oc adm policy reconcile-cluster-role-bindings --additive-only=false # Update cluster role bindings that don't match the current defaults oc adm policy reconcile-cluster-role-bindings --confirm # Update cluster role bindings that don't match the current defaults, avoid adding roles to the system:authenticated group oc adm policy reconcile-cluster-role-bindings --confirm --exclude-groups=system:authenticated # Update cluster role bindings that don't match the current defaults, removing any extra subjects from the binding oc adm policy reconcile-cluster-role-bindings --confirm --additive-only=false ---- ==== == oc adm policy reconcile-cluster-roles Update cluster roles to match the recommended bootstrap policy ==== [options=""nowrap""] ---- # Display the names of cluster roles that would be modified oc adm policy reconcile-cluster-roles -o name # Add missing permissions to cluster roles that don't match the current defaults oc adm policy reconcile-cluster-roles --confirm # Add missing permissions and remove extra permissions from # cluster roles that don't match the current defaults oc adm policy reconcile-cluster-roles --additive-only=false --confirm # Display the union of the default and modified cluster roles oc adm policy reconcile-cluster-roles --additive-only ---- ==== == oc adm policy reconcile-sccs Replace cluster SCCs to match the recommended bootstrap policy ==== [options=""nowrap""] ---- # Display the cluster SCCs that would be modified oc adm policy reconcile-sccs # Update cluster SCCs that don't match the current defaults preserving additional grants # for users and group and keeping any priorities that are already set oc adm policy reconcile-sccs --confirm # Replace existing users, groups, and priorities that do not match defaults oc adm policy reconcile-sccs --additive-only=false --confirm ---- ==== == oc adm prune builds Remove old completed and failed builds ==== [options=""nowrap""] ---- # Dry run deleting older completed and failed builds and also including # all builds whose associated BuildConfig no longer exists oc adm prune builds --orphans # To actually perform the prune operation, the confirm flag must be appended oc adm prune builds --orphans --confirm ---- ==== == oc adm prune deployments Remove old completed and failed deployments ==== [options=""nowrap""] ---- # Dry run deleting all but the last complete deployment for every deployment config oc adm prune deployments --keep-complete=1 # To actually perform the prune operation, the confirm flag must be appended oc adm prune deployments --keep-complete=1 --confirm ---- ==== == oc adm prune groups Prune OpenShift groups referencing missing records on an external provider. ==== [options=""nowrap""] ---- # Prune all orphaned groups oc adm prune groups --sync-config=/path/to/ldap-sync-config.yaml --confirm # Prune all orphaned groups except the ones from the blacklist file oc adm prune groups --blacklist=/path/to/blacklist.txt --sync-config=/path/to/ldap-sync-config.yaml --confirm # Prune all orphaned groups from a list of specific groups specified in a whitelist file oc adm prune groups --whitelist=/path/to/whitelist.txt --sync-config=/path/to/ldap-sync-config.yaml --confirm # Prune all orphaned groups from a list of specific groups specified in a whitelist oc adm prune groups groups/group_name groups/other_name --sync-config=/path/to/ldap-sync-config.yaml --confirm ---- ==== == oc adm prune images Remove unreferenced images ==== [options=""nowrap""] ---- # See, what the prune command would delete if only images more than an hour old and obsoleted # by 3 newer revisions under the same tag were considered. oc adm prune images --keep-tag-revisions=3 --keep-younger-than=60m # To actually perform the prune operation, the confirm flag must be appended oc adm prune images --keep-tag-revisions=3 --keep-younger-than=60m --confirm # See, what the prune command would delete if we're interested in removing images # exceeding currently set LimitRanges ('openshift.io/Image') oc adm prune images --prune-over-size-limit # To actually perform the prune operation, the confirm flag must be appended oc adm prune images --prune-over-size-limit --confirm ---- ==== == oc adm registry Install the integrated Docker registry ==== [options=""nowrap""] ---- # Check if default Docker registry (""docker-registry"") has been created oc adm registry --dry-run # See what the registry will look like if created oc adm registry -o yaml # Create a registry with two replicas if it does not exist oc adm registry --replicas=2 # Use a different registry image oc adm registry --images=myrepo/docker-registry:mytag # Enforce quota and limits on images oc adm registry --enforce-quota ---- ==== == oc adm router Install a router ==== [options=""nowrap""] ---- # Check the default router (""router"") oc adm router --dry-run # See what the router would look like if created oc adm router -o yaml # Create a router with two replicas if it does not exist oc adm router router-west --replicas=2 # Use a different router image oc adm router region-west --images=myrepo/somerouter:mytag # Run the router with a hint to the underlying implementation to _not_ expose statistics. oc adm router router-west --stats-port=0 ---- ==== == oc adm taint Update the taints on one or more nodes ==== [options=""nowrap""] ---- # Update node 'foo' with a taint with key 'dedicated' and value 'special-user' and effect 'NoSchedule'. # If a taint with that key already exists, its value and effect are replaced as specified. oc adm taint nodes foo dedicated=special-user:NoSchedule # Remove from node 'foo' the taint with key 'dedicated' if one exists. oc adm taint nodes foo dedicated- ---- ==== == oc adm top images Show usage statistics for Images ==== [options=""nowrap""] ---- # Show usage statistics for Images oc adm top images ---- ==== == oc adm top imagestreams Show usage statistics for ImageStreams ==== [options=""nowrap""] ---- # Show usage statistics for ImageStreams oc adm top imagestreams ---- ==== == oc adm uncordon Mark node as schedulable ==== [options=""nowrap""] ---- # Mark node ""foo"" as schedulable. $ oc adm uncordon foo ---- ==== == oc annotate Update the annotations on a resource ==== [options=""nowrap""] ---- # Update pod 'foo' with the annotation 'description' and the value 'my frontend'. # If the same annotation is set multiple times, only the last value will be applied oc annotate pods foo description='my frontend' # Update pod 'foo' with the annotation 'description' and the value # 'my frontend running nginx', overwriting any existing value. oc annotate --overwrite pods foo description='my frontend running nginx' # Update all pods in the namespace oc annotate pods --all description='my frontend running nginx' # Update pod 'foo' only if the resource is unchanged from version 1. oc annotate pods foo description='my frontend running nginx' --resource-version=1 # Update pod 'foo' by removing an annotation named 'description' if it exists. # Does not require the --overwrite flag. oc annotate pods foo description- ---- ==== == oc apply Apply a configuration to a resource by filename or stdin ==== [options=""nowrap""] ---- # Apply the configuration in pod.json to a pod. oc apply -f ./pod.json # Apply the JSON passed into stdin to a pod. cat pod.json | oc apply -f - ---- ==== == oc attach Attach to a running container. ==== [options=""nowrap""] ---- # Get output from running pod 123456-7890, using the first container by default oc attach 123456-7890 # Get output from ruby-container from pod 123456-7890 oc attach 123456-7890 -c ruby-container # Switch to raw terminal mode, sends stdin to 'bash' in ruby-container from pod 123456-780 # and sends stdout/stderr from 'bash' back to the client oc attach 123456-7890 -c ruby-container -i -t ---- ==== == oc autoscale Autoscale a deployment config or replication controller ==== [options=""nowrap""] ---- # Auto scale a deployment config ""foo"", with the number of pods between 2 to 10, target CPU utilization at a default value that server applies: oc autoscale dc/foo --min=2 --max=10 # Auto scale a replication controller ""foo"", with the number of pods between 1 to 5, target CPU utilization at 80% oc autoscale rc/foo --max=5 --cpu-percent=80 ---- ==== == oc cancel-build Cancel running, pending, or new builds ==== [options=""nowrap""] ---- # Cancel the build with the given name oc cancel-build ruby-build-2 # Cancel the named build and print the build logs oc cancel-build ruby-build-2 --dump-logs # Cancel the named build and create a new one with the same parameters oc cancel-build ruby-build-2 --restart # Cancel multiple builds oc cancel-build ruby-build-1 ruby-build-2 ruby-build-3 # Cancel all builds created from 'ruby-build' build configuration that are in 'new' state oc cancel-build bc/ruby-build --state=new ---- ==== == oc cluster down Stop OpenShift on Docker ==== [options=""nowrap""] ---- # Stop local Docker cluster oc cluster down # Stop cluster running on Docker machine 'mymachine' oc cluster down --docker-machine=mymachine ---- ==== == oc cluster up Start OpenShift on Docker with reasonable defaults ==== [options=""nowrap""] ---- # Start OpenShift on a new docker machine named 'openshift' oc cluster up --create-machine # Start OpenShift using a specific public host name oc cluster up --public-hostname=my.address.example.com # Start OpenShift and preserve data and config between restarts oc cluster up --host-data-dir=/mydata --use-existing-config # Use a different set of images oc cluster up --image=""registry.example.com/origin"" --version=""v1.1"" ---- ==== == oc completion Output shell completion code for the given shell (bash or zsh) ==== [options=""nowrap""] ---- # Generate the oc completion code for bash oc completion bash > bash_completion.sh source bash_completion.sh # The above example depends on the bash-completion framework. It must be sourced before sourcing the openshift cli completion, i.e. on the Mac: brew install bash-completion source $(brew --prefix)/etc/bash_completion oc completion bash > bash_completion.sh source bash_completion.sh # In zsh, the following will load openshift cli zsh completion: source <(oc completion zsh) ---- ==== == oc config Change configuration files for the client ==== [options=""nowrap""] ---- # Change the config context to use oc config use-context my-context # Set the value of a config preference oc config set preferences.some true ---- ==== == oc config current-context Displays the current-context ==== [options=""nowrap""] ---- # Display the current-context oc config current-context ---- ==== == oc config set-cluster Sets a cluster entry in kubeconfig ==== [options=""nowrap""] ---- # Set only the server field on the e2e cluster entry without touching other values. oc config set-cluster e2e --server=https://1.2.3.4 # Embed certificate authority data for the e2e cluster entry oc config set-cluster e2e --certificate-authority=~/.kube/e2e/kubernetes.ca.crt # Disable cert checking for the dev cluster entry oc config set-cluster e2e --insecure-skip-tls-verify=true ---- ==== == oc config set-context Sets a context entry in kubeconfig ==== [options=""nowrap""] ---- # Set the user field on the gce context entry without touching other values oc config set-context gce --user=cluster-admin ---- ==== == oc config set-credentials Sets a user entry in kubeconfig ==== [options=""nowrap""] ---- # Set only the ""client-key"" field on the ""cluster-admin"" # entry, without touching other values: oc config set-credentials cluster-admin --client-key=~/.kube/admin.key # Set basic auth for the ""cluster-admin"" entry oc config set-credentials cluster-admin --username=admin --password=uXFGweU9l35qcif # Embed client certificate data in the ""cluster-admin"" entry oc config set-credentials cluster-admin --client-certificate=~/.kube/admin.crt --embed-certs=true ---- ==== == oc config view Displays merged kubeconfig settings or a specified kubeconfig file. ==== [options=""nowrap""] ---- # Show Merged kubeconfig settings. oc config view # Get the password for the e2e user oc config view -o jsonpath='{.users[?(@.name == ""e2e"")].user.password}' ---- ==== == oc convert Convert config files between different API versions ==== [options=""nowrap""] ---- # Convert 'pod.yaml' to latest version and print to stdout. oc convert -f pod.yaml # Convert the live state of the resource specified by 'pod.yaml' to the latest version # and print to stdout in json format. oc convert -f pod.yaml --local -o json # Convert all files under current directory to latest version and create them all. oc convert -f . | oc create -f - ---- ==== == oc create Create a resource by filename or stdin ==== [options=""nowrap""] ---- # Create a pod using the data in pod.json. oc create -f pod.json # Create a pod based on the JSON passed into stdin. cat pod.json | oc create -f - ---- ==== == oc create clusterresourcequota Create cluster resource quota resource. ==== [options=""nowrap""] ---- # Create an cluster resource quota limited to 10 pods oc create clusterresourcequota limit-bob --project-label-selector=openshift.io/requester=user-bob --hard=pods=10 ---- ==== == oc create configmap Create a configMap from a local file, directory or literal value. ==== [options=""nowrap""] ---- # Create a new configmap named my-config with keys for each file in folder bar oc create configmap my-config --from-file=path/to/bar # Create a new configmap named my-config with specified keys instead of names on disk oc create configmap my-config --from-file=key1=/path/to/bar/file1.txt --from-file=key2=/path/to/bar/file2.txt # Create a new configMap named my-config with key1=config1 and key2=config2 oc create configmap my-config --from-literal=key1=config1 --from-literal=key2=config2 ---- ==== == oc create deploymentconfig Create deployment config with default options that uses a given image. ==== [options=""nowrap""] ---- # Create an nginx deployment config named my-nginx oc create deploymentconfig my-nginx --image=nginx ---- ==== == oc create identity Manually create an identity (only needed if automatic creation is disabled). ==== [options=""nowrap""] ---- # Create an identity with identity provider ""acme_ldap"" and the identity provider username ""adamjones"" oc create identity acme_ldap:adamjones ---- ==== == oc create imagestream Create a new empty image stream. ==== [options=""nowrap""] ---- # Create a new image stream oc create imagestream mysql ---- ==== == oc create namespace Create a namespace with the specified name. ==== [options=""nowrap""] ---- # Create a new namespace named my-namespace oc create namespace my-namespace ---- ==== == oc create policybinding Create a policy binding that references the policy in the targetted namespace. ==== [options=""nowrap""] ---- # Create a policy binding in namespace ""foo"" that references the policy in namespace ""bar"" oc create policybinding bar -n foo ---- ==== == oc create quota Create a quota with the specified name. ==== [options=""nowrap""] ---- // Create a new resourcequota named my-quota $ oc create quota my-quota --hard=cpu=1,memory=1G,pods=2,services=3,replicationcontrollers=2,resourcequotas=1,secrets=5,persistentvolumeclaims=10 // Create a new resourcequota named best-effort $ oc create quota best-effort --hard=pods=100 --scopes=BestEffort ---- ==== == oc create route edge Create a route that uses edge TLS termination ==== [options=""nowrap""] ---- # Create an edge route named ""my-route"" that exposes frontend service. oc create route edge my-route --service=frontend # Create an edge route that exposes the frontend service and specify a path. # If the route name is omitted, the service name will be re-used. oc create route edge --service=frontend --path /assets ---- ==== == oc create route passthrough Create a route that uses passthrough TLS termination ==== [options=""nowrap""] ---- # Create a passthrough route named ""my-route"" that exposes the frontend service. oc create route passthrough my-route --service=frontend # Create a passthrough route that exposes the frontend service and specify # a hostname. If the route name is omitted, the service name will be re-used. oc create route passthrough --service=frontend --hostname=www.example.com ---- ==== == oc create route reencrypt Create a route that uses reencrypt TLS termination ==== [options=""nowrap""] ---- # Create a route named ""my-route"" that exposes the frontend service. oc create route reencrypt my-route --service=frontend --dest-ca-cert cert.cert # Create a reencrypt route that exposes the frontend service and re-use # the service name as the route name. oc create route reencrypt --service=frontend --dest-ca-cert cert.cert ---- ==== == oc create secret docker-registry Create a secret for use with a Docker registry. ==== [options=""nowrap""] ---- # If you don't already have a .dockercfg file, you can create a dockercfg secret directly by using: oc create secret docker-registry my-secret --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL ---- ==== == oc create secret generic Create a secret from a local file, directory or literal value. ==== [options=""nowrap""] ---- # Create a new secret named my-secret with keys for each file in folder bar oc create secret generic my-secret --from-file=path/to/bar # Create a new secret named my-secret with specified keys instead of names on disk oc create secret generic my-secret --from-file=ssh-privatekey=~/.ssh/id_rsa --from-file=ssh-publickey=~/.ssh/id_rsa.pub # Create a new secret named my-secret with key1=supersecret and key2=topsecret oc create secret generic my-secret --from-literal=key1=supersecret --from-literal=key2=topsecret ---- ==== == oc create secret tls Create a TLS secret. ==== [options=""nowrap""] ---- # Create a new TLS secret named tls-secret with the given key pair: oc create secret tls tls-secret --cert=path/to/tls.cert --key=path/to/tls.key ---- ==== == oc create serviceaccount Create a service account with the specified name. ==== [options=""nowrap""] ---- # Create a new service account named my-service-account $ oc create serviceaccount my-service-account ---- ==== == oc create user Manually create a user (only needed if automatic creation is disabled). ==== [options=""nowrap""] ---- # Create a user with the username ""ajones"" and the display name ""Adam Jones"" oc create user ajones --full-name=""Adam Jones"" ---- ==== == oc create useridentitymapping Manually map an identity to a user. ==== [options=""nowrap""] ---- # Map the identity ""acme_ldap:adamjones"" to the user ""ajones"" oc create useridentitymapping acme_ldap:adamjones ajones ---- ==== == oc debug Launch a new instance of a pod for debugging ==== [options=""nowrap""] ---- # Debug a currently running deployment oc debug dc/test # Test running a deployment as a non-root user oc debug dc/test --as-user=1000000 # Debug a specific failing container by running the env command in the 'second' container oc debug dc/test -c second -- /bin/env # See the pod that would be created to debug oc debug dc/test -o yaml ---- ==== == oc delete Delete one or more resources ==== [options=""nowrap""] ---- # Delete a pod using the type and ID specified in pod.json. oc delete -f pod.json # Delete a pod based on the type and ID in the JSON passed into stdin. cat pod.json | oc delete -f - # Delete pods and services with label name=myLabel. oc delete pods,services -l name=myLabel # Delete a pod with name node-1-vsjnm. oc delete pod node-1-vsjnm # Delete all resources associated with a running app, includes # buildconfig,deploymentconfig,service,imagestream,route and pod, # where 'appName' is listed in 'Labels' of 'oc describe [resource] [resource name]' output. oc delete all -l app=appName # Delete all pods oc delete pods --all ---- ==== == oc deploy View, start, cancel, or retry a deployment ==== [options=""nowrap""] ---- # Display the latest deployment for the 'database' deployment config oc deploy database # Start a new deployment based on the 'database' oc deploy database --latest # Start a new deployment and follow its log oc deploy database --latest --follow # Retry the latest failed deployment based on 'frontend' # The deployer pod and any hook pods are deleted for the latest failed deployment oc deploy frontend --retry # Cancel the in-progress deployment based on 'frontend' oc deploy frontend --cancel ---- ==== == oc describe Show details of a specific resource or group of resources ==== [options=""nowrap""] ---- # Provide details about the ruby-22-centos7 image repository oc describe imageRepository ruby-22-centos7 # Provide details about the ruby-sample-build build configuration oc describe bc ruby-sample-build ---- ==== == oc edit Edit a resource on the server ==== [options=""nowrap""] ---- # Edit the service named 'docker-registry': oc edit svc/docker-registry # Edit the DeploymentConfig named 'my-deployment': oc edit dc/my-deployment # Use an alternative editor OC_EDITOR=""nano"" oc edit dc/my-deployment # Edit the service 'docker-registry' in JSON using the v1 API format: oc edit svc/docker-registry --output-version=v1 -o json ---- ==== == oc env DEPRECATED: set env ==== [options=""nowrap""] ---- # Update deployment 'registry' with a new environment variable oc env dc/registry STORAGE_DIR=/local # List the environment variables defined on a build config 'sample-build' oc env bc/sample-build --list # List the environment variables defined on all pods oc env pods --all --list # Output modified build config in YAML, and does not alter the object on the server oc env bc/sample-build STORAGE_DIR=/data -o yaml # Update all containers in all replication controllers in the project to have ENV=prod oc env rc --all ENV=prod # Import environment from a secret oc env --from=secret/mysecret dc/myapp # Import environment from a config map with a prefix oc env --from=configmap/myconfigmap --prefix=MYSQL_ dc/myapp # Remove the environment variable ENV from container 'c1' in all deployment configs oc env dc --all --containers=""c1"" ENV- # Remove the environment variable ENV from a deployment config definition on disk and # update the deployment config on the server oc env -f dc.json ENV- # Set some of the local shell environment into a deployment config on the server env | grep RAILS_ | oc env -e - dc/registry ---- ==== == oc ex dockerbuild Perform a direct Docker build ==== [options=""nowrap""] ---- # Build the current directory into a single layer and tag oc ex dockerbuild . myimage:latest # Mount a client secret into the build at a certain path oc ex dockerbuild . myimage:latest --mount ~/mysecret.pem:/etc/pki/secret/mysecret.pem ---- ==== == oc exec Execute a command in a container. ==== [options=""nowrap""] ---- # Get output from running 'date' in ruby-container from pod 'mypod' oc exec mypod -c ruby-container date # Switch to raw terminal mode, sends stdin to 'bash' in ruby-container from pod 'mypod' and sends stdout/stderr from 'bash' back to the client oc exec mypod -c ruby-container -i -t -- bash -il ---- ==== == oc explain Documentation of resources. ==== [options=""nowrap""] ---- # Get the documentation of the resource and its fields oc explain pods # Get the documentation of a specific field of a resource oc explain pods.spec.containers ---- ==== == oc export Export resources so they can be used elsewhere ==== [options=""nowrap""] ---- # export the services and deployment configurations labeled name=test oc export svc,dc -l name=test # export all services to a template oc export service --as-template=test # export to JSON oc export service -o json ---- ==== == oc expose Expose a replicated application as a service or route ==== [options=""nowrap""] ---- # Create a route based on service nginx. The new route will re-use nginx's labels oc expose service nginx # Create a route and specify your own label and route name oc expose service nginx -l name=myroute --name=fromdowntown # Create a route and specify a hostname oc expose service nginx --hostname=www.example.com # Expose a deployment configuration as a service and use the specified port oc expose dc ruby-hello-world --port=8080 # Expose a service as a route in the specified path oc expose service nginx --path=/nginx ---- ==== == oc extract Extract secrets or config maps to disk ==== [options=""nowrap""] ---- # extract the secret ""test"" to the current directory oc extract secret/test # extract the config map ""nginx"" to the /tmp directory oc extract configmap/nginx --to=/tmp # extract only the key ""nginx.conf"" from config map ""nginx"" to the /tmp directory oc extract configmap/nginx --to=/tmp --keys=nginx.conf ---- ==== == oc get Display one or many resources ==== [options=""nowrap""] ---- # List all pods in ps output format. oc get pods # List a single replication controller with specified ID in ps output format. oc get rc redis # List all pods and show more details about them. oc get -o wide pods # List a single pod in JSON output format. oc get -o json pod redis-pod # Return only the status value of the specified pod. oc get -o template pod redis-pod --template={{.currentState.status}} ---- ==== == oc idle Idle scalable resources ==== [options=""nowrap""] ---- # Idle the scalable controllers associated with the services listed in to-idle.txt $ oc idle -f to-idle.txt ---- ==== == oc import app.json Import an app.json definition into OpenShift (experimental) ==== [options=""nowrap""] ---- # Import a directory containing an app.json file $ oc import app.json -f . # Turn an app.json file into a template $ oc import app.json -f ./app.json -o yaml --as-template ---- ==== == oc import docker-compose Import a docker-compose.yml project into OpenShift (experimental) ==== [options=""nowrap""] ---- # Import a docker-compose.yml file into OpenShift oc import docker-compose -f ./docker-compose.yml # Turn a docker-compose.yml file into a template oc import docker-compose -f ./docker-compose.yml -o yaml --as-template ---- ==== == oc import-image Imports images from a Docker registry ==== [options=""nowrap""] ---- oc import-image mystream ---- ==== == oc label Update the labels on a resource ==== [options=""nowrap""] ---- # Update pod 'foo' with the label 'unhealthy' and the value 'true'. oc label pods foo unhealthy=true # Update pod 'foo' with the label 'status' and the value 'unhealthy', overwriting any existing value. oc label --overwrite pods foo status=unhealthy # Update all pods in the namespace oc label pods --all status=unhealthy # Update pod 'foo' only if the resource is unchanged from version 1. oc label pods foo status=unhealthy --resource-version=1 # Update pod 'foo' by removing a label named 'bar' if it exists. # Does not require the --overwrite flag. oc label pods foo bar- ---- ==== == oc login Log in to a server ==== [options=""nowrap""] ---- # Log in interactively oc login # Log in to the given server with the given certificate authority file oc login localhost:8443 --certificate-authority=/path/to/cert.crt # Log in to the given server with the given credentials (will not prompt interactively) oc login localhost:8443 --username=myuser --password=mypass ---- ==== == oc logout End the current server session ==== [options=""nowrap""] ---- # Logout oc logout ---- ==== == oc logs Print the logs for a resource. ==== [options=""nowrap""] ---- # Start streaming the logs of the most recent build of the openldap build config. oc logs -f bc/openldap # Start streaming the logs of the latest deployment of the mysql deployment config. oc logs -f dc/mysql # Get the logs of the first deployment for the mysql deployment config. Note that logs # from older deployments may not exist either because the deployment was successful # or due to deployment pruning or manual deletion of the deployment. oc logs --version=1 dc/mysql # Return a snapshot of ruby-container logs from pod backend. oc logs backend -c ruby-container # Start streaming of ruby-container logs from pod backend. oc logs -f pod/backend -c ruby-container ---- ==== == oc new-app Create a new application ==== [options=""nowrap""] ---- # List all local templates and image streams that can be used to create an app oc new-app --list # Search all templates, image streams, and Docker images for the ones that match ""ruby"" oc new-app --search ruby # Create an application based on the source code in the current git repository (with a public remote) # and a Docker image oc new-app . --docker-image=repo/langimage # Create a Ruby application based on the provided [image]~[source code] combination oc new-app centos/ruby-22-centos7~https://github.com/openshift/ruby-ex.git # Use the public Docker Hub MySQL image to create an app. Generated artifacts will be labeled with db=mysql oc new-app mysql MYSQL_USER=user MYSQL_PASSWORD=pass MYSQL_DATABASE=testdb -l db=mysql # Use a MySQL image in a private registry to create an app and override application artifacts' names oc new-app --docker-image=myregistry.com/mycompany/mysql --name=private # Create an application from a remote repository using its beta4 branch oc new-app https://github.com/openshift/ruby-hello-world#beta4 # Create an application based on a stored template, explicitly setting a parameter value oc new-app --template=ruby-helloworld-sample --param=MYSQL_USER=admin # Create an application from a remote repository and specify a context directory oc new-app https://github.com/youruser/yourgitrepo --context-dir=src/build # Create an application based on a template file, explicitly setting a parameter value oc new-app --file=./example/myapp/template.json --param=MYSQL_USER=admin # Search for ""mysql"" in all image repositories and stored templates oc new-app --search mysql # Search for ""ruby"", but only in stored templates (--template, --image and --docker-image # can be used to filter search results) oc new-app --search --template=ruby # Search for ""ruby"" in stored templates and print the output as an YAML oc new-app --search --template=ruby --output=yaml ---- ==== == oc new-build Create a new build configuration ==== [options=""nowrap""] ---- # Create a build config based on the source code in the current git repository (with a public # remote) and a Docker image oc new-build . --docker-image=repo/langimage # Create a NodeJS build config based on the provided [image]~[source code] combination oc new-build openshift/nodejs-010-centos7~https://github.com/openshift/nodejs-ex.git # Create a build config from a remote repository using its beta2 branch oc new-build https://github.com/openshift/ruby-hello-world#beta2 # Create a build config using a Dockerfile specified as an argument oc new-build -D $'FROM centos:7\\nRUN yum install -y httpd' # Create a build config from a remote repository and add custom environment variables oc new-build https://github.com/openshift/ruby-hello-world RACK_ENV=development # Create a build config from a remote repository and inject the npmrc into a build oc new-build https://github.com/openshift/ruby-hello-world --build-secret npmrc:.npmrc # Create a build config that gets its input from a remote repository and another Docker image oc new-build https://github.com/openshift/ruby-hello-world --source-image=openshift/jenkins-1-centos7 --source-image-path=/var/lib/jenkins:tmp ---- ==== == oc new-project Request a new project ==== [options=""nowrap""] ---- # Create a new project with minimal information oc new-project web-team-dev # Create a new project with a display name and description oc new-project web-team-dev --display-name=""Web Team Development"" --description=""Development project for the web team."" ---- ==== == oc patch Update field(s) of a resource using strategic merge patch. ==== [options=""nowrap""] ---- # Partially update a node using strategic merge patch oc patch node k8s-node-1 -p '{""spec"":{""unschedulable"":true}}' ---- ==== == oc policy add-role-to-user Add users or serviceaccounts to a role in the current project ==== [options=""nowrap""] ---- # Add the 'view' role to user1 in the current project oc policy add-role-to-user view user1 # Add the 'edit' role to serviceaccount1 in the current project oc policy add-role-to-user edit -z serviceaccount1 ---- ==== == oc port-forward Forward one or more local ports to a pod. ==== [options=""nowrap""] ---- # Listens on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in the pod oc port-forward mypod 5000 6000 # Listens on port 8888 locally, forwarding to 5000 in the pod oc port-forward mypod 8888:5000 # Listens on a random port locally, forwarding to 5000 in the pod oc port-forward mypod :5000 # Listens on a random port locally, forwarding to 5000 in the pod oc port-forward mypod 0:5000 ---- ==== == oc process Process a template into list of resources ==== [options=""nowrap""] ---- # Convert template.json file into resource list and pass to create oc process -f template.json | oc create -f - # Process template while passing a user-defined label oc process -f template.json -l name=mytemplate # Convert stored template into resource list oc process foo # Convert stored template into resource list by setting/overriding parameter values oc process foo PARM1=VALUE1 PARM2=VALUE2 # Convert template stored in different namespace into a resource list oc process openshift//foo # Convert template.json into resource list cat template.json | oc process -f - ---- ==== == oc project Switch to another project ==== [options=""nowrap""] ---- # Switch to 'myapp' project oc project myapp # Display the project currently in use oc project ---- ==== == oc projects Display existing projects ==== [options=""nowrap""] ---- # Display the projects that currently exist oc ---- ==== == oc proxy Run a proxy to the Kubernetes API server ==== [options=""nowrap""] ---- # Run a proxy to the api server on port 8011, serving static content from ./local/www/ oc proxy --port=8011 --www=./local/www/ # Run a proxy to the api server on an arbitrary local port. # The chosen port for the server will be output to stdout. oc proxy --port=0 # Run a proxy to the api server, changing the api prefix to my-api # This makes e.g. the pods api available at localhost:8011/my-api/api/v1/pods/ oc proxy --api-prefix=/my-api ---- ==== == oc replace Replace a resource by filename or stdin. ==== [options=""nowrap""] ---- # Replace a pod using the data in pod.json. oc replace -f pod.json # Replace a pod based on the JSON passed into stdin. cat pod.json | oc replace -f - # Force replace, delete and then re-create the resource oc replace --force -f pod.json ---- ==== == oc rollback Revert part of an application back to a previous deployment ==== [options=""nowrap""] ---- # Perform a rollback to the last successfully completed deployment for a deploymentconfig oc rollback frontend # See what a rollback to version 3 will look like, but don't perform the rollback oc rollback frontend --to-version=3 --dry-run # Perform a rollback to a specific deployment oc rollback frontend-2 # Perform the rollback manually by piping the JSON of the new config back to oc oc rollback frontend -o json | oc replace dc/frontend -f - ---- ==== == oc rollout history view rollout history ==== [options=""nowrap""] ---- # View the rollout history of a deployment oc rollout history dc/nginx # View the details of deployment revision 3 oc rollout history dc/nginx --revision=3 ---- ==== == oc rollout pause Mark the provided resource as paused ==== [options=""nowrap""] ---- # Mark the nginx deployment as paused. Any current state of # the deployment will continue its function, new updates to the deployment will not # have an effect as long as the deployment is paused. oc rollout pause dc/nginx ---- ==== == oc rollout resume Resume a paused resource ==== [options=""nowrap""] ---- # Resume an already paused deployment oc rollout resume dc/nginx ---- ==== == oc rollout undo undoes a previous rollout ==== [options=""nowrap""] ---- # Rollback to the previous deployment oc rollout undo dc/nginx # Rollback to deployment revision 3. The replication controller for that version must exist. oc rollout undo dc/nginx --to-revision=3 ---- ==== == oc rsh Start a shell session in a pod ==== [options=""nowrap""] ---- # Open a shell session on the first container in pod 'foo' oc rsh foo # Run the command 'cat /etc/resolv.conf' inside pod 'foo' oc rsh foo cat /etc/resolv.conf # See the configuration of your internal registry oc rsh dc/docker-registry cat config.yml # Open a shell session on the container named 'index' inside a pod of your job # oc rsh -c index job/sheduled ---- ==== == oc rsync Copy files between local filesystem and a pod ==== [options=""nowrap""] ---- # Synchronize a local directory with a pod directory oc rsync ./local/dir/ POD:/remote/dir # Synchronize a pod directory with a local directory oc rsync POD:/remote/dir/ ./local/dir ---- ==== == oc run Run a particular image on the cluster. ==== [options=""nowrap""] ---- # Starts a single instance of nginx. oc run nginx --image=nginx # Starts a replicated instance of nginx. oc run nginx --image=nginx --replicas=5 # Dry run. Print the corresponding API objects without creating them. oc run nginx --image=nginx --dry-run # Start a single instance of nginx, but overload the spec of the replication # controller with a partial set of values parsed from JSON. oc run nginx --image=nginx --overrides='{ ""apiVersion"": ""v1"", ""spec"": { ... } }' # Start a single instance of nginx and keep it in the foreground, don't restart it if it exits. oc run -i --tty nginx --image=nginx --restart=Never ---- ==== == oc scale Change the number of pods in a deployment ==== [options=""nowrap""] ---- # Scale replication controller named 'foo' to 3. oc scale --replicas=3 replicationcontrollers foo # If the replication controller named foo's current size is 2, scale foo to 3. oc scale --current-replicas=2 --replicas=3 replicationcontrollers foo # Scale the latest deployment of 'bar'. In case of no deployment, bar's template # will be scaled instead. oc scale --replicas=10 dc bar ---- ==== == oc secrets add DEPRECATED: secrets link ==== [options=""nowrap""] ---- # Add an image pull secret to a service account to automatically use it for pulling pod images: oc serviceaccount-name pull-secret --for=pull # Add an image pull secret to a service account to automatically use it for both pulling and pushing build images: oc builder builder-image-secret --for=pull,mount # If the cluster's serviceAccountConfig is operating with limitSecretReferences: True, secrets must be added to the pod's service account whitelist in order to be available to the pod: oc pod-sa pod-secret ---- ==== == oc secrets link Link secrets to a ServiceAccount ==== [options=""nowrap""] ---- # Add an image pull secret to a service account to automatically use it for pulling pod images: oc secrets link serviceaccount-name pull-secret --for=pull # Add an image pull secret to a service account to automatically use it for both pulling and pushing build images: oc secrets link builder builder-image-secret --for=pull,mount # If the cluster's serviceAccountConfig is operating with limitSecretReferences: True, secrets must be added to the pod's service account whitelist in order to be available to the pod: oc secrets link pod-sa pod-secret ---- ==== == oc secrets new Create a new secret based on a key file or on files within a directory ==== [options=""nowrap""] ---- # Create a new secret named my-secret with a key named ssh-privatekey oc secrets new my-secret ~/.ssh/ssh-privatekey # Create a new secret named my-secret with keys named ssh-privatekey and ssh-publickey instead of the names of the keys on disk oc secrets new my-secret ssh-privatekey=~/.ssh/id_rsa ssh-publickey=~/.ssh/id_rsa.pub # Create a new secret named my-secret with keys for each file in the folder ""bar"" oc secrets new my-secret path/to/bar # Create a new .dockercfg secret named my-secret oc secrets new my-secret path/to/.dockercfg # Create a new .docker/config.json secret named my-secret oc secrets new my-secret .dockerconfigjson=path/to/.docker/config.json ---- ==== == oc secrets new-basicauth Create a new secret for basic authentication ==== [options=""nowrap""] ---- // If your basic authentication method requires only username and password or token, add it by using: oc secrets new-basicauth SECRET --username=USERNAME --password=PASSWORD // If your basic authentication method requires also CA certificate, add it by using: oc secrets new-basicauth SECRET --username=USERNAME --password=PASSWORD --ca-cert=FILENAME // If you do already have a .gitconfig file needed for authentication, you can create a gitconfig secret by using: oc secrets new SECRET path/to/.gitconfig ---- ==== == oc secrets new-dockercfg Create a new dockercfg secret ==== [options=""nowrap""] ---- # Create a new .dockercfg secret: oc secrets new-dockercfg SECRET --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL # Create a new .dockercfg secret from an existing file: oc secrets new SECRET path/to/.dockercfg # Create a new .docker/config.json secret from an existing file: oc secrets new SECRET .dockerconfigjson=path/to/.docker/config.json # To add new secret to 'imagePullSecrets' for the node, or 'secrets' for builds, use: oc edit SERVICE_ACCOUNT ---- ==== == oc secrets new-sshauth Create a new secret for SSH authentication ==== [options=""nowrap""] ---- // If your SSH authentication method requires only private SSH key, add it by using: oc secrets new-sshauth SECRET --ssh-privatekey=FILENAME // If your SSH authentication method requires also CA certificate, add it by using: oc secrets new-sshauth SECRET --ssh-privatekey=FILENAME --ca-cert=FILENAME // If you do already have a .gitconfig file needed for authentication, you can create a gitconfig secret by using: oc secrets new SECRET path/to/.gitconfig ---- ==== == oc secrets unlink Detach secrets from a ServiceAccount ==== [options=""nowrap""] ---- # Unlink a secret currently associated with a service account: oc secrets unlink serviceaccount-name secret-name another-secret-name ... ---- ==== == oc serviceaccounts get-token Get a token assigned to a service account. ==== [options=""nowrap""] ---- # Get the service account token from service account 'default' oc serviceaccounts get-token 'default' ---- ==== == oc serviceaccounts new-token Generate a new token for a service account. ==== [options=""nowrap""] ---- # Generate a new token for service account 'default' oc serviceaccounts new-token 'default' # Generate a new token for service account 'default' and apply # labels 'foo' and 'bar' to the new token for identification # oc serviceaccounts new-token 'default' --labels foo=foo-value,bar=bar-value ---- ==== == oc set build-hook Update a build hook on a build config ==== [options=""nowrap""] ---- # Clear post-commit hook on a build config oc set build-hook bc/mybuild --post-commit --remove # Set the post-commit hook to execute a test suite using a new entrypoint oc set build-hook bc/mybuild --post-commit --command -- /bin/bash -c /var/lib/test-image.sh # Set the post-commit hook to execute a shell script oc set build-hook bc/mybuild --post-commit --script=""/var/lib/test-image.sh param1 param2 && /var/lib/done.sh"" # Set the post-commit hook as a set of arguments to the default image entrypoint oc set build-hook bc/mybuild --post-commit -- arg1 arg2 ---- ==== == oc set deployment-hook Update a deployment hook on a deployment config ==== [options=""nowrap""] ---- # Clear pre and post hooks on a deployment config oc set deployment-hook dc/myapp --remove --pre --post # Set the pre deployment hook to execute a db migration command for an application # using the data volume from the application oc set deployment-hook dc/myapp --pre -v data -- /var/lib/migrate-db.sh # Set a mid deployment hook along with additional environment variables oc set deployment-hook dc/myapp --mid -v data -e VAR1=value1 -e VAR2=value2 -- /var/lib/prepare-deploy.sh ---- ==== == oc set env Update environment variables on a pod template ==== [options=""nowrap""] ---- # Update deployment 'registry' with a new environment variable oc set env dc/registry STORAGE_DIR=/local # List the environment variables defined on a build config 'sample-build' oc set env bc/sample-build --list # List the environment variables defined on all pods oc set env pods --all --list # Output modified build config in YAML, and does not alter the object on the server oc set env bc/sample-build STORAGE_DIR=/data -o yaml # Update all containers in all replication controllers in the project to have ENV=prod oc set env rc --all ENV=prod # Import environment from a secret oc set env --from=secret/mysecret dc/myapp # Import environment from a config map with a prefix oc set env --from=configmap/myconfigmap --prefix=MYSQL_ dc/myapp # Remove the environment variable ENV from container 'c1' in all deployment configs oc set env dc --all --containers=""c1"" ENV- # Remove the environment variable ENV from a deployment config definition on disk and # update the deployment config on the server oc set env -f dc.json ENV- # Set some of the local shell environment into a deployment config on the server env | grep RAILS_ | oc set env -e - dc/registry ---- ==== == oc set probe Update a probe on a pod template ==== [options=""nowrap""] ---- # Clear both readiness and liveness probes off all containers oc set probe dc/registry --remove --readiness --liveness # Set an exec action as a liveness probe to run 'echo ok' oc set probe dc/registry --liveness -- echo ok # Set a readiness probe to try to open a TCP socket on 3306 oc set probe rc/mysql --readiness --open-tcp=3306 # Set an HTTP readiness probe for port 8080 and path /healthz over HTTP on the pod IP oc set probe dc/webapp --readiness --get-url=http://:8080/healthz # Set an HTTP readiness probe over HTTPS on 127.0.0.1 for a hostNetwork pod oc set probe dc/router --readiness --get-url=https://127.0.0.1:1936/stats # Set only the initial-delay-seconds field on all deployments oc set probe dc --all --readiness --initial-delay-seconds=30 ---- ==== == oc set triggers Update the triggers on a build or deployment config ==== [options=""nowrap""] ---- # Print the triggers on the registry oc set triggers dc/registry # Set all triggers to manual oc set triggers dc/registry --manual # Enable all automatic triggers oc set triggers dc/registry --auto # Reset the GitHub webhook on a build to a new, generated secret oc set triggers bc/webapp --from-github oc set triggers bc/webapp --from-webhook # Remove all triggers oc set triggers bc/webapp --remove-all # Stop triggering on config change oc set triggers dc/registry --from-config --remove # Add an image trigger to a build config oc set triggers bc/webapp --from-image=namespace1/image:latest ---- ==== == oc set volumes Update volumes on a pod template ==== [options=""nowrap""] ---- # List volumes defined on all deployment configs in the current project oc set volume dc --all # Add a new empty dir volume to deployment config (dc) 'registry' mounted under # /var/lib/registry oc set volume dc/registry --add --mount-path=/var/lib/registry # Use an existing persistent volume claim (pvc) to overwrite an existing volume 'v1' oc set volume dc/registry --add --name=v1 -t pvc --claim-name=pvc1 --overwrite # Remove volume 'v1' from deployment config 'registry' oc set volume dc/registry --remove --name=v1 # Create a new persistent volume claim that overwrites an existing volume 'v1' oc set volume dc/registry --add --name=v1 -t pvc --claim-size=1G --overwrite # Change the mount point for volume 'v1' to /data oc set volume dc/registry --add --name=v1 -m /data --overwrite # Modify the deployment config by removing volume mount ""v1"" from container ""c1"" # (and by removing the volume ""v1"" if no other containers have volume mounts that reference it) oc set volume dc/registry --remove --name=v1 --containers=c1 # Add new volume based on a more complex volume source (Git repo, AWS EBS, GCE PD, # Ceph, Gluster, NFS, ISCSI, ...) oc set volume dc/registry --add -m /repo --source= ---- ==== == oc start-build Start a new build ==== [options=""nowrap""] ---- # Starts build from build config ""hello-world"" oc start-build hello-world # Starts build from a previous build ""hello-world-1"" oc start-build --from-build=hello-world-1 # Use the contents of a directory as build input oc start-build hello-world --from-dir=src/ # Send the contents of a Git repository to the server from tag 'v2' oc start-build hello-world --from-repo=../hello-world --commit=v2 # Start a new build for build config ""hello-world"" and watch the logs until the build # completes or fails. oc start-build hello-world --follow # Start a new build for build config ""hello-world"" and wait until the build completes. It # exits with a non-zero return code if the build fails. oc start-build hello-world --wait ---- ==== == oc status Show an overview of the current project ==== [options=""nowrap""] ---- # See an overview of the current project. oc status # Export the overview of the current project in an svg file. oc status -o dot | dot -T svg -o project.svg # See an overview of the current project including details for any identified issues. oc status -v ---- ==== == oc tag Tag existing images into image streams ==== [options=""nowrap""] ---- # Tag the current image for the image stream 'openshift/ruby' and tag '2.0' into the image stream 'yourproject/ruby with tag 'tip'. oc tag openshift/ruby:2.0 yourproject/ruby:tip # Tag a specific image. oc tag openshift/ruby@sha256:6b646fa6bf5e5e4c7fa41056c27910e679c03ebe7f93e361e6515a9da7e258cc yourproject/ruby:tip # Tag an external Docker image. oc tag --source=docker openshift/origin:latest yourproject/ruby:tip # Remove the specified spec tag from an image stream. oc tag openshift/origin:latest -d ---- ==== == oc types An introduction to concepts and types ==== [options=""nowrap""] ---- # View all projects you have access to oc get projects # See a list of all services in the current project oc get svc # Describe a deployment configuration in detail oc describe dc mydeploymentconfig # Show the images tagged into an image stream oc describe is ruby-centos7 ---- ==== == oc volumes DEPRECATED: set volume ==== [options=""nowrap""] ---- # List volumes defined on all deployment configs in the current project oc volume dc --all # Add a new empty dir volume to deployment config (dc) 'registry' mounted under # /var/lib/registry oc volume dc/registry --add --mount-path=/var/lib/registry # Use an existing persistent volume claim (pvc) to overwrite an existing volume 'v1' oc volume dc/registry --add --name=v1 -t pvc --claim-name=pvc1 --overwrite # Remove volume 'v1' from deployment config 'registry' oc volume dc/registry --remove --name=v1 # Create a new persistent volume claim that overwrites an existing volume 'v1' oc volume dc/registry --add --name=v1 -t pvc --claim-size=1G --overwrite # Change the mount point for volume 'v1' to /data oc volume dc/registry --add --name=v1 -m /data --overwrite # Modify the deployment config by removing volume mount ""v1"" from container ""c1"" # (and by removing the volume ""v1"" if no other containers have volume mounts that reference it) oc volume dc/registry --remove --name=v1 --containers=c1 # Add new volume based on a more complex volume source (Git repo, AWS EBS, GCE PD, # Ceph, Gluster, NFS, ISCSI, ...) oc volume dc/registry --add -m /repo --source= ---- ==== ",16231,True,3104.256219215491,median "// // 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. // = Введение в JavaServer Faces 2.x :jbake-type: tutorial :jbake-tags: tutorials :jbake-status: published :icons: font :syntax: true :source-highlighter: pygments :toc: left :toc-title: :description: Введение в JavaServer Faces 2.x - Apache NetBeans :keywords: Apache NetBeans, Tutorials, Введение в JavaServer Faces 2.x JavaServer Faces (JSF) - это платформа разработки интерфейса пользователя для веб-приложений Java. Она призвана значительно упростить процесс создания и поддержки приложений, работающих на сервере приложений Java и визуализирующих свои пользовательские интерфейсы на целевом клиенте. JSF обеспечивает простоту использования благодаря целому ряду факторов: * упрощает формирование пользовательского интерфейса из набора повторно используемых компонентов пользовательского интерфейса; * упрощает перенос данных приложения в пользовательский интерфейс и из него; * помогает управлять состоянием пользовательского интерфейса при запросах к серверу; * предоставляет простую модель установления связи между созданными клиентом событиями и кодом приложения на стороне сервера; * упрощает сборку и повторное использование компонентов пользовательского интерфейса. Подробное описание платформы JSF приведено в link:http://docs.oracle.com/javaee/7/tutorial/doc/jsf-develop.htm[+учебном курсе по Java EE 7, Глава 12. Разработка по технологии JavaServer Faces+]. В этом учебном курсе описывается применение поддержки JSF 2.x к веб-приложениям с помощью IDE NetBeans. Сначала необходимо добавить поддержку платформы JSF 2.x к базовому веб-приложению, а затем приступить к выполнения следующих задач: * создать управляемый компонент JSF для обработки данных запроса, * подключить управляемый компонент к веб-страницам приложения и * преобразовать веб-страницы в файлы шаблонов Facelets. IDE NetBeans обеспечивает долгосрочную поддержку для JavaServer Faces. Начиная с редакции JSF 2.0 и Java EE 6, IDE NetBeans обеспечивает поддержку для JSF 2.0 и JSF 2.1. Подробнее см. в разделе link:jsf20-support.html[+Поддержка JSF 2.x в IDE NetBeans+]. image::images/netbeans-stamp-80-74-73.png[title=""Содержимое этой страницы применимо к IDE NetBeans 7.2, 7.3, 7.4 и 8.0""] Для работы с этим учебным курсом требуются программное обеспечение и материалы, перечисленные ниже. |=== |Программное обеспечение или материал |Требуемая версия |link:https://netbeans.org/downloads/index.html[+IDE NetBeans+] |7.2, 7.3, 7.4, 8.0, пакет Java EE |link:http://www.oracle.com/technetwork/java/javase/downloads/index.html[+Комплект для разработчика на языке Java (JDK)+] |7 или 8 |link:http://glassfish.dev.java.net/[+Сервер GlassFish+] |Open Source Edition 3.x или 4 |link:https://netbeans.org/projects/samples/downloads/download/Samples%252FJavaEE%252FjsfDemo.zip[+Проект веб-приложения `jsfDemo`+] |неприменимо |=== *Примечания* * В комплект Java в среде IDE NetBeans также входит сервер GlassFish - сервер, совместимый с Java EE, который требуется для этого учебного курса. * Для сравнения проекта с рабочим решением загрузите link:https://netbeans.org/projects/samples/downloads/download/Samples%252FJavaEE%252FjsfDemoCompleted.zip[+выполненный демонстрационный проект+]. [[support]] == Добавление поддержки JSF 2.x к веб-приложениям Начните работу с открытия <> в среде IDE. После открытия проекта в среде IDE в него можно добавить поддержку платформы с помощью окна ""Свойства"" в проекте. IDE также позволяет создавать новые проекты с поддержкой JSF 2.x. Подробнее см. раздел link:jsf20-support.html#creatingSupport[+Создание нового проекта с поддержкой JSF 2.x+]. 1. Нажмите кнопку 'Открыть проект' ( image:images/open-project-btn.png[] ) на главной панели инструментов IDE или нажмите Ctrl-Shift-O (⌘-Shift-O в Mac). 2. В диалоговом окне ""Открытие проекта"" перейдите к папке на компьютере, в которой хранится разархивированный файл учебного проекта. Выберите его, а затем для открытия проекта в среде IDE нажмите кнопку ""Открыть проект"". *Примечание.* При открытии проекта NetBeans может быть отображен запрос на разрешение ссылки на библиотеки JUnit, если при установке IDE не был установлен подключаемый модуль JUnit. . Выполните проект и посмотрите, как он выглядит в браузере. Либо щелкните правой кнопкой мыши узел проекта `jsfDemo` в окне 'Проекты' и выберите 'Запустить' или нажмите кнопку 'Запустить проект' ( image:images/run-project-btn.png[] ) на главной панели инструментов. Проект запакован и разворачивается на сервере GlassFish, а в браузере открывается страница приветствия(`index.xhtml`). image::images/run-project.png[title=""Запустите проект, чтобы просмотреть его в браузере.""] . Нажмите кнопку ""Отправить"". Страница ответа (`response.xhtml`) отображается следующим образом: image::images/response.png[title=""Страницы приветствия и отклика в настоящее время являются статическими страницами""] В настоящее время страницы приветствия и отклика являются статическими, и совместно с файлом `stylesheet.css` и изображением `duke.png` они являются единственными файлами приложений, доступными из браузера. . В окне 'Проекты' (Ctrl-1; ⌘ -1 в Mac) щелкните правой кнопкой мыши узел проекта и выберите 'Свойства', чтобы открыть окно 'Свойства проекта'. . Выберите категорию 'Платформы', а затем нажмите кнопку 'Добавить'. . Выберите 'JavaServer Faces' в диалоговом окне 'Добавление платформы'. Нажмите кнопку 'ОК'. image::images/add-framework.png[title=""Добавление поддержки JSF к существующему проекту""] После выбора ""JavaServer Faces"" станут доступными различные параметры настройки. На вкладке 'Библиотеки' вы можете указать, как проект обращается к библиотекам JSF 2.x. Доступная версия JSF будет зависеть от версии IDE и сервера GlassFish. По умолчанию используются библиотеки, поставляемые с сервером (сервером GlassFish). Тем не менее, в IDE также входят библиотеки JSF 2.x. (Можно выбрать параметр ""Зарегистрированные библиотеки"", если их необходимо использовать в проекте). image::images/libraries-tab.png[title=""Укажите доступ к библиотекам JSF 2.x""] . Выберите вкладку ""Настройка"". Можно указать способ регистрации сервлета Faces в дескрипторе развертывания проекта. Также можно указать, нужно ли в проекте использовать страницы Facelets или JSP. image::images/jsf-configuration.png[title=""Укажите параметры сервлета Faces и предпочитаемый язык""] Вы также можете легко настроить проект для использования различных наборов компонентов JSF на вкладке 'Компоненты'. Чтобы использовать набор компонентов, нужно загрузить необходимые библиотеки и использовать диспетчер Ant Library для создания новой библиотеки с библиотеками наборов компонентов. image::images/jsf-components.png[title=""Укажите параметры сервлета Faces и предпочитаемый язык""] . Нажмите кнопку ""ОК"" для подтверждения изменений и закройте окно ""Свойства проекта"". После добавления поддержки JSF к проекту дескриптор развертывания `web.xml` изменяется и выглядит следующим образом. (Изменения *выделены полужирным шрифтом*.) [source,xml] ---- * javax.faces.PROJECT_STAGE Development Faces Servlet javax.faces.webapp.FacesServlet 1 Faces Servlet /faces/* * *faces/*index.xhtml ---- *Важно!* Убедитесь, что файл `web.xml` содержит только одну запись `` с компонентом '`faces/`', как показано в примере. Это обеспечивает передачу страницы приветствия проекта (`index.xhtml`) через сервлет Faces перед ее отображением в браузере. Это необходимо для верного отображения компонентов библиотек тегов Facelets. Сервлет Faces регистрируется в проекте, и теперь страница приветствия `index.xhtml` при запросе передается через сервлет Faces. Кроме того, обратите внимание, что добавлена запись для параметра контекста `PROJECT_STAGE`. При установке значения этого параметра на ""`Development`"" предоставляется полезная информация во время отладки приложения. См. link:http://blogs.oracle.com/rlubke/entry/jsf_2_0_new_feature2[+http://blogs.oracle.com/rlubke/entry/jsf_2_0_new_feature2+] для получения дополнительной информации. Для просмотра библиотек JSF разверните узел ""Библиотеки"" проекта в окне ""Проекты"". Если используются библиотеки по умолчанию, включенные в GlassFish Server 3.1.2 или GlassFish Server 4, под узлом сервера GlassFish отображается `javax.faces.jar`. (Если вы используете старую версию GlassFish, вы увидите библиотеки `jsf-api.jar` и `jsf-impl.jar`, а не `javax.faces.jar`.) Поддержка JSF в среде IDE 2.x включает в себя в первую очередь большое количество мастеров для JSF, а также специальные функциональные возможности, предоставляемые редактором Facelets. Эти функциональные возможности описаны ниже. Подробнее см. в разделе link:jsf20-support.html[+Поддержка JSF 2.x в IDE NetBeans+]. [[managedBean]] == Создание управляемого компонента Управляемые компоненты JSF для обработки данных пользователя и сохранения их между запросами. Управляемый компонент – это link:http://en.wikipedia.org/wiki/Plain_Old_Java_Object[+POJO+] (простой объект Java), который используется для сохранения данных и управляется контейнером (например, сервером GlassFish) с помощью платформы JSF. Компонент POJO по существу является классом Java, который содержит публичный безаргументный конструктор и соответствует правилам присвоения имен link:http://download.oracle.com/javase/tutorial/javabeans/[+JavaBeans+] для свойств. При просмотре <>, полученной в результате выполнения проекта, пользователю необходим механизм, который проверяет введенное пользователем число на соответствие текущему выбранному числу и возвращает представление, соответствующее полученному результату. Чтобы создать управляемый компонент для этих целей, используйте link:jsf20-support.html#managedBean[+Мастер создания управляемого компонента+] среды IDE. Страницы Facelets, создаваемые в следующем разделе, должны иметь доступ к числу, вводимому пользователем, и к сгенерированному ответу. Для упрощения добавьте свойства `userNumber` и `response` к управляемому компоненту. * <> * <> * <> [[usingManagedBean]] === Использование мастера создания управляемого компонента 1. В окне 'Проекты' щелкните правой кнопкой мыши узел проекта `jsfDemo` и выберите 'Создать' > 'Управляемый компонент JSF'. (Если ""Управляемый компонент"" отсутствует, выберите ""Другие"". Затем выберите параметр ""Управляемый компонент JSF"" в категории ""JavaServer Faces"". Нажмите кнопку ""Далее"". 2. В мастере введите следующее: * *Имя класса:* UserNumberBean; * *Пакет:* guessNumber; * *Имя:* UserNumberBean * *Контекст:* сеанс image::images/managed-bean.png[title=""Используйте мастер управляемых компонентов JSF для создания нового управляемого компонента""] . Нажмите кнопку ""Завершить"". Класс `UserNumberBean` будет создан и открыт в редакторе. Обратите внимание на следующие аннотации (*выделено полужирным шрифтом*): [source,java] ---- package guessNumber; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; /** * * @author nbuser */ *@ManagedBean(name=""UserNumberBean"") @SessionScoped* public class UserNumberBean { /** Creates a new instance of UserNumberBean */ public UserNumberBean() { } } ---- Поскольку вы используете JSF 2.x, можно объявить все относящиеся к JSF компоненты с помощью аннотаций. В предыдущих версиях их необходимо было объявлять в файле настройки Faces (`faces-config.xml`). [tips]#Для просмотра документации Javadoc по всем аннотациям JSF 2.1 обратитесь к link:http://javaserverfaces.java.net/nonav/docs/2.1/managed-bean-javadocs/index.html[+Спецификации аннотации управляемого компонента Faces+].# [[creatingConstructor]] === Создание конструктора Конструктор `UserNumberBean` должен создавать случайное число от 0 до 10 и сохранять его в переменной экземпляра. Таким образом частично формируется бизнес-логика для приложения. 1. Определите конструктор для класса `UserNumberBean`. Введите следующий код (изменения выделены *полужирным шрифтом*). [source,java] ---- public class UserNumberBean { *Integer randomInt;* /** Creates a new instance of UserNumberBean */ public UserNumberBean() { *link:http://docs.oracle.com/javase/7/docs/api/java/util/Random.html[+Random+] randomGR = new Random(); randomInt = new Integer(randomGR.link:http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt%28int%29[+nextInt+](10)); System.out.println(""Duke's number: "" + randomInt);* } } ---- Вышеуказанный код создает случайное число от 0 до 10 и записывает это число в протокол сервера. . Исправьте операторы импорта. Для этого щелкните метку4 подсказки ( image:images/hint-icon.png[] ), которая отображается на левой границе редактора, затем выберите параметр для импорта `java.util.Random` в класс. . Повторно запустите проект (нажмите кнопку 'Запустить проект' ( image:images/run-project-btn.png[] ) или нажмите F6; fn-F6 в Mac). При выполнении проекта файл протокола сервера автоматически открывается в окне вывода. image::images/output1.png[title=""Файл журнала сервера автоматически открывается в окне вывода.""] Обратите внимание на то, что в окне вывода не отображается ""`Номер Дюка: `"" (как указывалось в конструкторе). Объект `UserNumberBean` не создан, так как по умолчанию в JSF используется _""ленивое"" создание экземпляра_. Таким образом, компоненты в определенных контекстах создаются и инициализируются, только если они необходимы в приложении. Состояния link:http://javaserverfaces.java.net/nonav/docs/2.1/managed-bean-javadocs/index.html[+Документации Javadoc по аннотации `@ManagedBean`+]: _Если атрибут `eager()` имеет значение `true`, а значением `managed-bean-scope` является ""application"", то в среде выполнения при запуске приложения должен быть создан экземпляр этого класса. Создание и сохранение экземпляра должно осуществляться до обслуживания запросов. Если атрибут _eager_ не указан либо имеет значение `false` или элементу `managed-bean-scope` не присвоено значение ""приложение"", по умолчанию происходит ""ленивое"" создание экземпляра и контекстное сохранение управляемого компонента._ . Поскольку класс `UserNumberBean` входит в контекст сеанса, реализуется интерфейс `Serializable`. [source,java] ---- @ManagedBean(name=""UserNumberBean"") @SessionScoped public class UserNumberBean *implements Serializable* { ---- Используйте метку подсказки ( image:images/hint-icon.png[] ) для импорта `java.io.Serializable` в класс. [[addingProperties]] === Добавление свойств Страницы Facelets, создаваемые в следующем разделе, должны иметь доступ к числу, вводимому пользователем, и к сгенерированному ответу. Для упрощения этого добавьте свойства `userNumber` и `response` к классу. 1. Начните с объявления `Integer` с именем `userNumber`. [source,java] ---- @ManagedBean(name=""UserNumberBean"") @SessionScoped public class UserNumberBean implements Serializable { Integer randomInt; *Integer userNumber;* ---- . Щелкните правой кнопкой мыши в редакторе и выберите команду ""Вставить код"" (ALT+INS; CTRL+I на компьютере Mac). Выберите методы получения и установки. image::images/getter-setter.png[title=""Используйте IDE для создания методов доступа для свойств""] . Выберите параметр `userNumber`: `Integer`. Нажмите кнопку ""Создать"". image::images/generate-getters-setters.png[title=""Используйте IDE для создания методов доступа для свойств""] Обратите внимание на то, что методы `getUserNumber()` и `setUserNumber(Integer userNumber)` добавлены в класс. . Создайте свойство `response`. Объявите `String` с именем `response`. [source,java] ---- @ManagedBean(name=""UserNumberBean"") @SessionScoped public class UserNumberBean implements Serializable { Integer randomInt; Integer userNumber; *String response;* ---- . Создайте метод получения для `response`. (Для этого приложения не требуется метод установки). Для создания кода шаблона в среде IDE можно использовать всплывающее окно ""Создание кода"", упомянутое выше в действии 2. Однако в целях изучения данного руководства просто вставьте нижеуказанный метод в класс. [source,html] ---- public String getResponse() { if ((userNumber != null) && (userNumber.link:http://download.oracle.com/javase/6/docs/api/java/lang/Integer.html#compareTo(java.lang.Integer)[+compareTo+](randomInt) == 0)) { //invalidate user session FacesContext context = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) context.getExternalContext().getSession(false); session.invalidate(); return ""Yay! You got it!""; } else { return ""

Sorry, "" + userNumber + "" isn't it.

"" + ""

Guess again...

""; } } ---- Вышеуказанный метод выполняет две функции. 1. Тестирует введенное пользователем число (`userNumber`) на равенство случайному числу, сгенерированному для сеанса (`randomInt`), и возвращает соответствующий ответ `String`. 2. Определяет пользовательский сеанс как недействительный, если пользователь ввел правильное число (т.е., если `userNumber` равно `randomInt`). Это необходимо для того, чтобы новое сгенерированное число побудило пользователя сыграть еще раз. . Щелкните правой кнопкой мыши в области редактора и выберите команду ""Исправить операторы импорта"" (ALT+SHIFT+I; &#8984+SHIFT+I на компьютере Mac). Параметры импорта автоматически создаются для: * `javax.servlet.http.HttpSession` * `javax.faces.context.FacesContext` Можно нажать сочетание клавиш CTRL+ПРОБЕЛ на элементах в редакторе для вызова предложений автозавершения кода и поддержки документации. Нажмите сочетание клавиш CTRL+ПРОБЕЛ, установив курсор на `FacesContext`, для просмотра описания класса из документации Javadoc. image::images/documentation-support.png[title=""Для вызова поддержки автозавершения кода и документации нажмите сочетание клавиш CTRL+ПРОБЕЛ.""] Щелкните значок веб-браузера ( image:images/web-browser-icon.png[] ) в окне документации, чтобы открыть Javadoc во внешнем веб-браузере. [[wire]] == Установление связи между управляемым компонентом и страницами Одной из первичных целей JSF является отмена необходимости записывать шаблонный код для управления объектами <> и их взаимодействием с видами приложений. Пример этого был приведен в предыдущем разделе, в котором JSF создал объект `UserNumberBean` при выполнении приложения. Это представление называется link:http://martinfowler.com/articles/injection.html[+Инверсия управления+] (IoC). Оно позволяет контейнеру принимать на себя ответственность за управление частями приложения, иначе разработчику потребовалось бы написать код с повторениями. В предыдущем разделе был создан управляемый компонент, генерирующий случайное число от 0 до 10. Также было создано два свойства `userNumber` и `response`, представляющие соответственно пользовательский ввод числа и ответ на вопрос пользователя. В этом разделе показаны способы использования `UserNumberBean` и его свойств на веб-страницах. JSF позволяет это сделать с помощью языка выражения. Язык выражения используется для привязки значений свойств к компонентам пользовательского интерфейса JSF, содержащихся на веб-страницах приложений. В этом разделе также показано, как можно воспользоваться внутренними функциями навигации JSF 2.x для перемещения между индексом и страницами ответов. Эта поддержка в среде IDE обеспечивается с помощью функции автозавершения кода и средств документации, которые вызываются нажатием сочетания клавиш CTRL+ПРОБЕЛ, когда курсор установлен на каком-либо элементе в редакторе. Начните с внесения изменений в `index.xhtml`, затем измените `response.xhtml`. На обеих страницах замените элементы формы HTML их эквивалентами JSF, поскольку они определены в link:http://javaserverfaces.java.net/nonav/docs/2.1/vdldocs/facelets/index.html[+библиотеке тегов HTML для JSF+]. Затем используйте язык выражений JSF для привязки значений свойств к выбранным компонентам пользовательского интерфейса. * <> * <> [[index]] === index.xhtml 1. Откройте страницу `index.xhtml` в редакторе. Дважды щелкните узел `index.xhtml` в окне ""Проекты"" или нажмите сочетание клавиш ALT+SHIFT+O для открытия диалогового окна ""Переход к файлу"". Как индекс, так и страницы ответов уже содержат компоненты пользовательского интерфейса JSF, необходимые для этого упражнения. Просто раскомментируйте их и закомментируйте элементы HTML, используемые в настоящий момент. . Закомментируйте элемент формы HTML. Для этого выделите элемент формы HTML, как показано на изображении ниже, затем нажмите CTRL+/ (&#8984+/ на компьютере Mac). *Примечание. *Для выделения воспользуйтесь функцией перетаскивания в редакторе с помощью мыши или с помощью клавиатуры удерживайте клавишу Shift и используйте клавиши со стрелками. image::images/comment-out.png[title=""Выделите код, затем нажмите Ctrl-/ для закомментирования кода""] Для переключения комментариев нажмите сочетание клавиш CTRL+/ (&#8984+/ на компьютере Mac). Эту комбинацию клавиш также можно использовать для других типов файлов, например, Java и CSS. . Раскомментируйте компонент формы HTML для JSF. Выделите этот компонент, как показано на рисунке ниже, затем нажмите CTRL+/ (&#8984+/ на компьютере Mac). *Примечание.* Возможно, вам придется нажать Ctrl-/ дважды, чтобы раскомментировать код. image::images/comment.png[title=""Выделите закомментированный код, затем нажмите Ctrl-/ для удаления комментария""] После того как компонент формы HTML для JSF раскомментирован, в редакторе будет указано, что теги ``, `` и `` не объявлены. image::images/undeclared-component.png[title=""Редактор обеспечивает сообщения об ошибках для необъявленных компонентов""] . Для объявления этих компонентов используйте автозавершение кода IDE, чтобы добавить пространство имен библиотеки тегов в тег `` страницы. Наведите курсор на любой из необъявленных тегов, нажмите Alt-Enter и нажмите Enter, чтобы добавить предложенные библиотеки тегов. (При наличии нескольких параметров перед нажатием клавиши ВВОД убедитесь, что выбран тег, отображаемый в редакторе.) Пространство имен библиотеки тегов HTML для JSF добавляется к тегу `` (*выделено ниже полужирным шрифтом*), и указания на ошибки исчезают. *Примечание.* Если в IDE нет возможности добавить библиотеку тегов, потребуется вручную изменить элемент ```` . [source,java] ---- ---- . Используйте язык выражения JSF для привязки свойства `userNumber` для `UserNumberBean` к компоненту `inputText`. Атрибут `value` используется для указания текущего значения визуализируемого компонента. Введите в код, отображаемый ниже *полужирным шрифтом*. [source,java] ---- ---- В языке выражения JSF используется синтаксис `#{}`. Внутри этих парных символов указывается имя требуемого управляемого компонента и его свойство, разделенные точкой (`.`). Теперь при отправке данных формы на сервер значение автоматически сохраняется в свойстве `userNumber` с помощью метода установки свойств (`setUserNumber()`). Кроме того, если страница запрошена и значение для `userNumber` уже установлено, значение автоматически отображается в визуализированном компоненте `inputText`. Дополнительные сведения приведены в link:http://docs.oracle.com/javaee/7/tutorial/doc/jsf-develop001.htm#BNAQP[+Руководстве по Java EE 7. Глава 12.1.2 Использование языка выражений для создания ссылок на управляемые сеансные объекты+]. . Укажите адресата для запроса, который вызывается при нажатии кнопки формы. В HTML-версии формы это возможно выполнить с помощью атрибута `action` тега `
`. С помощью JSF можно использовать атрибут `action` для `commandButton`. Кроме того, благодаря внутренней функции навигации JSF 2.x вам нужно только указать имя конечного файла без расширения. Введите код, отображаемый ниже *полужирным шрифтом*. [source,xml] ---- ---- В среде выполнения JSF осуществляется поиск файла с именем `response`. Предполагается, что расширение файла такое же, как у файла, из которого произошел запрос (`index*.xhtml*`), и поиск файла `response.xhtml` выполняется в папке исходного файла (т.е. в корневом веб-узле). *Примечание. *JSF 2.x позволяет упростить разработку. При использовании JSF 1.2 для этого проекта необходимо объявить правило перехода в файле настройки Faces. Объявление правила может выглядеть следующим образом: [source,xml] ---- /index.xhtml response /response.xhtml ---- Нижеприведенные действия с 7 по 12 являются дополнительными. Если необходимо выполнить быструю сборку проекта, сразу перейдите к <>. . Протестируйте, выполняется ли вызов метода `setUserNumber()` вышеуказанным выражением на языке выражения при обработке запроса. Для выполнения этого используйте отладчик Java среды IDE. Переключите на класс `UserNumberBean` (нажмите сочетание клавиш CTRL+TAB и выберите из списка файл). Установите точку останова в сигнатуре метода `setUserNumber()`. Это можно сделать, щелкнув мышкой в области левого поля. Появится красный значок, указывающий, что точка останова метода установлена. image::images/set-breakpoint.png[title=""Щелкните левую границу редактора для задания точек останова""] . Нажмите кнопку 'Отладка проекта' (image:images/breakpoint-btn.png[]) на главной панели инструментов IDE. Начинается сеанс отладки, и в браузере открывается страница приветствия проекта. *Примечания.* * Вам может быть предложено подтвердить порт сервера для отладки приложений. * Если появится диалоговое окно 'Отладить проект', выберите опцию по умолчанию 'Java на стороне сервера' и нажмите кнопку 'Отладка'. . В браузере введите номер в форму и нажмите кнопку ""Отправить"". . Вернитесь в среду IDE и проверьте класс `UserNumberBean`. Отладчик приостановлен в методе `setUserNumber()`. image::images/debugger-suspended.png[title=""Выполняется приостановка отладчика в соответствии с точками останова""] . Откройте окно ""Переменные отладчика"" (выберите ""Окно"" > ""Отладка > ""Переменные"" или нажмите сочетание клавиш CTRL+SHIFT+1). На экран будут выведены значения переменных для точки, в которой приостановлен отладчик. image::images/variables-window.png[title=""Отслеживание значений переменных с помощью окна 'Переменные отладчика'""] На приведенном выше изображении значение ""`4`"" предоставлено для переменной `userNumber` в сигнатуре `setUserNumber()`. (Число 4 введено в форму.) ""`this`"" относится к объекту `UserNumberBean`, созданному для пользовательского сеанса. Далее можно отметить, что значение свойства `userNumber` в настоящий момент равно `null`. . На панели отладчика нажмите кнопку 'Вход в' ( image:images/step-into-btn.png[] ). Отладчик выполняет обработку строки, на которой он в настоящий момент приостановлен. Происходит обновление окна ""Переменные"" с указанием выполненных изменений. image::images/variables-window2.png[title=""Окно переменных обновляется при переходе по коду""] Теперь свойству `userNumber` присвоено значение, введенное в форме. . Выберите Отладка> Завершить сеанс отладки (Shift-F5; Shift-Fn-F5 на Mac) из главного меню, чтобы остановить отладчик. [[response]] === response.xhtml 1. Откройте страницу `response.xhtml` в редакторе. В окне ""Проекты"" дважды щелкните узел `response.xhtml` или нажмите сочетание клавиш ALT+SHIFT+O для открытия диалогового окна ""Переход к файлу"". 2. Закомментируйте элемент формы HTML. Выделите открывающий и закрывающий теги HTML `` и код между ними, затем нажмите CTRL+/ (&#8984+/ на компьютере Mac). *Примечание: * Для выделения воспользуйтесь функцией перетаскивания в редакторе с помощью мыши или с помощью клавиатуры удерживайте клавишу Shift и используйте клавиши со стрелками. . Раскомментируйте компонент формы HTML для JSF. Выделите открывающий и закрывающий теги `` и код между ними, затем нажмите CTRL+/ (&#8984+/ на компьютере Mac). На данном этапе, код между тегами `` выглядит следующим образом: [source,html] ----

[ response here ]

---- После того как компонент формы HTML для JSF раскомментирован, в редакторе будет указано, что теги `` и `` не объявлены. . Для объявления этих компонентов используйте автозавершение кода IDE, чтобы добавить пространство имен библиотеки тегов в тег `` страницы. Используйте поддержку автозавершения кода в редакторе для добавления необходимых пространств имен JSF к файлу. При выборе тега JSF или Facelets через автозавершение кода происходит автоматическое добавление требуемого пространства имен к корневому элементу документа. Подробнее см. в разделе link:jsf20-support.html#facelets[+Поддержка JSF 2.x в IDE NetBeans+]. Установите курсор на один из необъявленных тегов и нажмите сочетание клавиш CTRL+ПРОБЕЛ. Предложения автозавершения кода и отображения поддержки документации. image::images/code-completion2.png[title=""Для вызова рекомендаций по автозавершению кода и всплывающего окна документации""] Нажмите ENTER. (При наличии нескольких параметров перед нажатием клавиши ВВОД убедитесь, что выбран тег, отображаемый в редакторе.) Пространство имен библиотеки тегов HTML для JSF добавляется к тегу `` (*выделено ниже полужирным шрифтом*), и указания на ошибки исчезают. [source,java] ---- ---- . Укажите адресата для запроса, который вызывается при нажатии пользователем кнопки формы. Кнопку необходимо установить так, чтобы при ее нажатии пользователь возвращался на страницу-указатель. Для этого следует использовать атрибут `action` для `commandButton`. Введите в код, отображаемый *полужирным шрифтом*. [source,xml] ---- ---- *Примечание. * При вводе `action=""index""` пользователи в работе зависят от функции явной навигации в JSF. При нажатии кнопки формы в среде выполнения JSF осуществляется поиск файла с именем `index`. Предполагается, что расширение файла такое же, как у файла, от которого был направлен запрос (`response*.xhtml*`), и поиск файла `index.xhtml` выполняется в папке исходного файла (т.е. в корневом веб-узле). . Замените статический текст ""[здесь ответ]"" значением свойства `response` для `UserNumberBean`. Для этого используйте язык выражения JSF. Введите следующее (*выделено полужирным шрифтом*). [source,html] ----

**

---- . Запустите проект (нажмите кнопку 'Запустить проект' ( image:images/run-project-btn.png[] ) или нажмите F6; fn-F6 в Mac). При появлении в браузере страницы приветствия введите номер и нажмите `submit`. Страница ответа будет отображаться следующим образом (выводится на экран, если введен неправильный номер). image::images/response2.png[title=""Просмотрит текущее состояния проекта в браузере""] Две ошибки в текущем состоянии страницы ответа: 1. Теги HTML `

` отображаются в ответном сообщении. 2. Кнопка ""Назад"" не отображается в правильном местоположении. (Сравните с <>.) При выполнении следующих двух шагов эти ошибки устраняются. . Установите атрибут `escape` тега `` на `false`. Установите курсор между `outputText` и `value`, вставьте пробел и нажмите сочетание клавиш CTRL+ПРОБЕЛ для вызова автозавершения кода. Прокрутите вниз для выбора атрибута `escape` и проверки документации. image::images/escape-false.png[title=""Нажмите Ctrl-Пробел для просмотра возможных значений атрибутов и документации""] Как указано в документации, значение `escape` установлено по умолчанию на `true`. Это означает, что символы, которые стандартно анализируются как html, включены в строку, как указано выше. Установка значения на `false` означает, что символы, анализируемые как HTML, можно визуализировать как HTML. Нажмите ENTER, затем в качестве значения введите `false`. [source,xml] ----

---- . Установите атрибут `prependId` тега `` на `false`. Установите курсор сразу после ""`m`"" в `` и вставьте пробел, затем нажмите сочетание клавиш CTRL+ПРОБЕЛ для вызова автозавершения кода. Прокрутите вниз для выбора атрибута `prependId` и проверки документации. Затем нажмите ENTER и в качестве значения введите `false`. [source,java] ---- ---- В JSF применяются внутренние идентификаторы для отслеживания компонентов пользовательского интерфейса. В текущем примере при проверке исходного кода визуализируемой страницы отображается следующее: [source,xml] ---- ---- Идентификатором элемента формы является `j_idt5`, и этот идентификатор _предшествует_ идентификатору кнопки ""Назад"", включенной в форму (*выделено полужирным шрифтом* в приведенном выше примере). Поскольку кнопка ""Назад"" зависит от правила стиля `#backButton` (определенного в `stylesheet.css`), это правило становится блокированным, если идентификатор JSF предшествует идентификатору кнопки. Этого можно избежать, если для `prependId` установить значение `false`. . Повторно запустите проект (нажмите кнопку 'Запустить проект' ( image:images/run-project-btn.png[] ) или нажмите F6; fn-F6 в Mac). Введите число на странице приветствия, затем нажмите кнопку ""Отправить"". Теперь на странице ответа отображается ответное сообщение без тегов `

`, и кнопка ""Назад"" размещена правильно. image::images/response3.png[title=""Просмотрит текущее состояния проекта в браузере""] . Нажмите кнопку ""Назад"". Поскольку текущее значение свойства `userNumber` для `UserNumberBean` привязано к компоненту `inputText` JSF, ранее введенное число теперь отображается в текстовом поле. . Проверьте протокол сервера в окне вывода среды IDE (CTRL+4; &#8984+4 на компьютере Mac) для определения правильного загаданного числа. Если по каким-то причинам просмотреть протокол сервера невозможно, откройте его посредством переключения на окно ""Службы"" (CTRL+5; &#8984+5 на компьютере Mac) и развертывания узла ""Серверы"". Затем щелкните правой кнопкой мыши сервер GlassFish, на котором развернут проект и выберите 'Просмотреть журнал сервера'. Если номер не отображается в журнале сервера, попробуйте повторно выполнить сборку приложения, щелкнув правой кнопкой мыши узел проекта и выбрав 'Очистка и сборка'. . Введите правильное число и нажмите кнопку ""Отправить"". В приложении происходит сравнение введенного числа с текущим сохраненным числом и выводится соответствующее сообщение. image::images/yay.png[title=""При вводе соответствующего числа отображается правильный отклик""] . Нажмите еще раз кнопку ""Назад"". Обратите внимание на то, что ранее введенное число более не отображается в текстовом поле. Следует помнить о том, что метод `getResponse()` для `UserNumberBean` <> при угадывании правильного числа. [[template]] == Применение шаблона Facelets Facelets сегодня является стандартной технологией отображения для JSF 2.x. Facelets - это облегченная платформа шаблонов, которая поддерживает все компоненты JSF пользовательского интерфейса и используется для построения и визуализации дерева компонентов JSF для просмотра приложений. Кроме того, эта технология обеспечивает поддержку разработки при возникновении ошибок языка выражений за счет возможности проверять трассировку стека, дерево компонентов и контекстные переменные. Хотя, возможно, вы об этом не задумывались, файлы `index.xhtml` и `response.xhtml`, с которыми вы работаете в этом руководстве, являются страницами Facelets. Страницы Facelets имеют расширение `.xhtml` и, поскольку вы работаете в проекте JSF 2.x (библиотеки JSF 2.x включают в себя файлы JAR Facelets), эти представления способны надлежащим образом визуализировать дерево компонентов JSF. Целью этого раздела является знакомство с созданием шаблона Facelets. Для проектов с несколькими представлениями зачастую полезно применять файл шаблона, определяющего структуру и внешний вид для нескольких представлений. При обслуживании запросов приложение вставляет динамически подготовленное содержимое во временный файл и отправляет результат обратно клиенту. Хотя данный проект имеет только два представления (страницу приветствия и страницу ответа), можно легко отметить, что большая часть содержимого в них дублируется. Это дублированное содержимое можно перенести в шаблон Facelets и создать файлы клиента шаблона для обработки содержимого, которое является специфичным для страницы приветствия и страницы ответа. В среде IDE существует link:jsf20-support.html#faceletsTemplate[+мастер создания шаблона Facelets+] для создания шаблонов Facelets и мастер создания клиента шаблона Facelets для создания файлов, зависящих от шаблона. В этом разделе описано использование этих мастеров. *Примечание.* IDE также предоставляет мастер страниц JSF, что позволяет создавать индивидуальные страницы Facelets для проекта. Подробнее см. в разделе link:jsf20-support.html#jsfPage[+Поддержка JSF 2.x в IDE NetBeans+]. * <> * <> [[templateFile]] === Создание файла шаблона Facelets 1. Создайте файл шаблона Facelets. Нажмите сочетание клавиш CTRL+N (&#8984+N на компьютере Mac) для открытия мастера создания файлов. Выберите категорию ""JavaServer Faces"", затем ""Шаблон Facelets"". Нажмите кнопку ""Далее"". 2. В поле ""Имя файла"" введите `template`. 3. Выберите один из восьми стилей размещения и нажмите кнопку ""Готово"". (Вы будете использовать существующую таблицу стилей, так что не имеет значения, какой стиль вы выберете.) image::images/layout-style.png[title=""Мастер шаблонов Facelets позволяет сделать выбор из распространенных стилей компоновки""] Мастером будут созданы файл `template.xhtml` и сопутствующие таблицы стилей на основе выбора, которые будут помещены в папку `resources` > `css` в корневом веб-узле проекта. После завершения выполнения мастера в редакторе открывается файл шаблона. Для просмотра шаблона в браузере, щелкните правой кнопкой мыши в редакторе и выберите 'Просмотр'. . Проверьте разметку файла шаблона. Обратите внимание на следующие моменты. * Библиотека тегов `facelets` объявлена в теге `` страницы. Библиотека тегов имеет префикс `ui`. [source,java] ---- ---- * На странице Facelets используются теги `` и `` вместо тегов HTML `` и ``. При использовании этих тегов у Facelets появляется возможность создания дерева компонентов, которое включает в себя всю страницу. * Страница ссылается на таблицы стилей, которые также создаются при завершении выполнения мастера. [source,xml] ---- ** ** Facelets Template ---- * Теги `` используются в теле страницы для каждого раздела, связанного с выбранным стилем размещения. Каждый тег `` имеет атрибут `name`, определяющий раздел. Например: [source,html] ----

*Top*
---- . Повторно проверьте страницу <> и страницу <>. Содержимым, которое изменяется на этих страницах, является только заголовок и текст в сером квадрате. Следовательно, шаблон может включать в себя все остальное содержимое. . Замените все содержимое файла шаблона содержимым, приведенным ниже. [source,html] ---- <ui:insert name=""title"">Facelets Template</ui:insert>
Box Content Here
---- Приведенный выше код реализует следующие изменения. * Файл `stylesheet.css` проекта заменяет ссылки на таблицу стилей шаблона, созданные в мастере. * Все теги `` (вместе с тегами `
`) удаляются за исключением одного с именем `box`. * В теги `` вставляется заголовок страницы с именем `title`. . Скопируйте в шаблон соответствующий код из файла `index.xhtml` или файла `response.xhtml`. Добавьте содержимое, отображаемое ниже *полужирным шрифтом*, в теги `` файла шаблона. [source,html] ---- *
*
Box Content Here
*
*
---- . Выполните проект. При открытии страницы приветствия в браузере измените URL-адрес на следующий: [source,java] ---- http://localhost:8080/jsfDemo/faces/template.xhtml ---- Файл шаблона отображается следующим образом: image::images/facelets-template.png[title=""Просмотрите шаблон Facelets в браузере""] Теперь проект включает в себя файл шаблона, предоставляющий внешний вид и структуру всех представлений. Теперь можно создавать файлы клиента для вызова шаблона. [[templateClient]] === Создание файлов клиента шаблона Создайте файлы клиента шаблона для страниц приветствия и ответа. Укажите имя файла клиента шаблона для страницы приветствия `greeting.xhtml`. Для страницы ответа – файл `response.xhtml`. ==== greeting.xhtml 1. Нажмите сочетание клавиш CTRL+N (⌘-N на компьютере Mac) для открытия мастера создания файлов. Выберите категорию ""JavaServer Faces"", затем ""Клиент шаблона Facelets"". Нажмите кнопку ""Далее"". 2. В поле ""Имя файла"" введите `greeting`. 3. Нажмите кнопку ""Обзор"" рядом с полем ""Шаблон"", затем в открывшемся диалоговом окне перейдите к файлу `template.xhtml`, созданному в предыдущем разделе. image::images/template-client.png[title=""Мастер создания клиентов шаблона Facelets""] . Нажмите кнопку ""Завершить"". Будет создан новый файл клиента шаблона `greeting.xhtml`, который откроется в редакторе. . Проверьте разметку. Обратите внимание на содержимое, выделенное *полужирным шрифтом*. [source,xml] ---- title box ---- Файл клиента шаблона ссылается на шаблон с помощью атрибута `template` тега ``. Поскольку шаблон содержит теги `` для `title` и `box`, клиент шаблона содержит теги `` для этих двух имен. Содержимое, указываемое в тегах ``, - это содержимое, вставляемое в шаблон в тегах `` соответствующего имени. . Укажите `greeting` в качестве заголовка файла. Внесите следующее изменение, выделенное *полужирным шрифтом*. [source,xml] ---- *Greeting* ---- . Перейдите к файлу `index.xhtml` (нажмите CTRL+TAB) и скопируйте содержимое, которое обычно появляется в сером квадрате, выведенном на визуализируемой странице. Затем обратно переключитесь на файл `greeting.xhtml` и вставьте его в файл клиента шаблона. (Изменения *выделены полужирным шрифтом*.) [source,xml] ---- *

Hi, my name is Duke!

I'm thinking of a number
between 0 and 10.
Can you guess it?
*
---- . Объявите библиотеку тегов HTML JSF для файла. Установите курсор на один из тегов, помеченных флагом ошибки (любой тег с префиксом ""`h`""), и нажмите сочетание клавиш CTRL+ПРОБЕЛ. Затем выберите тег из списка предложений автозавершения кодов. Пространство имен библиотеки тегов добавляется к тегу `` файла (выделено ниже *полужирным шрифтом*), и указания на ошибки исчезают. [source,java] ---- ---- При установке курсора после ""`m`"" в `` и нажатии сочетания клавиш CTRL+ПРОБЕЛ к файлу автоматически добавляется пространство имен. Если при нажатии сочетания клавиш CTRL+ПРОБЕЛ доступен только один логический параметр, он немедленно применяется к файлу. Библиотека тегов JSF автоматически объявляется при вызове автозавершения кода в тегах. ==== response.xhtml Поскольку проект уже содержит файл с именем `response.xhtml` и известно, как теперь должен выглядеть файл клиента шаблона, измените существующий файл `response.xhtml`, чтобы получить соответствующий файл клиента шаблона. (В целях данного руководства просто скопируйте и вставьте предоставленный код.) 1. Откройте файл `response.xhtml` в редакторе. (Если он уже открыт, нажмите CTRL+TAB и выберите его). Замените содержимое всего файла нижеприведенным кодом. [source,xml] ---- Response

---- Обратите внимание на то, что файл идентичен файлу `greeting.xhtml`, за исключением содержимого, указанного в тегах `` для `title` и `box`. . В дескрипторе развертывания `web.xml` проекта измените запись файла приветствия таким образом, чтобы при запуске приложения открывалась страница, представленная файлом `greeting.xhtml`. В окне 'Проекты' дважды щелкните 'Файлы конфигурации' > `web.xml`, чтобы открыть его в редакторе. На вкладке ""Страницы"" измените поле ""Файлы приветствия"" на `faces/greeting.xhtml`. image::images/welcome-files.png[title=""Измените запись 'Файлы приветствия' в дескрипторе развертывания""] . Выполните проект и посмотрите, как он выглядит в браузере. Нажмите F6 (fn-F6 в Mac) или нажмите кнопку 'Запустить проект'( image:images/run-project-btn.png[] ) на главной панели инструментов. Проект будет развернут на сервере GlassFish и открыт в браузере. При использовании шаблона Facelets и файлов клиента шаблона поведение приложения не меняется. Выделив повторяющийся код на страницах приветствия и ответа приложения, можно уменьшить размер приложения и устранить возможность написания повторяющегося кода, если впоследствии будут добавляться другие страницы. Это позволяет сделать разработку более эффективной и упростить управление при работе с большими проектами. link:/about/contact_form.html?to=3&subject=Feedback:%20Introduction%20to%20JSF%202.0[+Отправить отзыв по этому учебному курсу+] [[seealso]] == Дополнительные сведения Подробнее о JSF 2.x см. в следующих ресурсах. === Статьи и учебные курсы по NetBeans * link:jsf20-support.html[+Поддержка JSF 2.x в IDE NetBeans+] * link:jsf20-crud.html[+Создание приложения JavaServer Faces 2.x CRUD на основе базы данных+] * link:../../samples/scrum-toys.html[+Scrum Toys – полный пример приложения JSF 2.0+] * link:../javaee/javaee-gettingstarted.html[+Начало работы с приложениями Java EE+] * link:../../trails/java-ee.html[+Учебная карта по Java EE и Java Web+] === Внешние ресурсы * link:http://www.oracle.com/technetwork/java/javaee/javaserverfaces-139869.html[+Технология JavaServer Faces+] (официальная домашняя страница) * link:http://jcp.org/aboutJava/communityprocess/final/jsr314/index.html[+Спецификация JSR 314 для JavaServer Faces 2.0+] * link:http://docs.oracle.com/javaee/7/tutorial/doc/jsf-develop.htm[+Учебный курс по Java EE 7. Глава 12. Разработка по технологии JavaServer Faces+] * link:http://javaserverfaces.dev.java.net/[+GlassFish Project Mojarra+] (официальный пример реализации JSF 2.х) * link:http://forums.oracle.com/forums/forum.jspa?forumID=982[+Интернет-форум OTN: JavaServer Faces+] * link:http://www.jsfcentral.com/[+JSF Central+] === Блоги * link:http://www.java.net/blogs/edburns/[+Эд Бернс (Ed Burns)+] * link:http://www.java.net/blogs/driscoll/[+Джим Дрисколл (Jim Driscoll)+] ",16203,True,3230.8454105780484,median "script ""auto_post_adv.ash""; import boolean auto_post_adventure() { auto_log_debug(""Running auto_post_adv.ash""); if(limit_mode() == ""spelunky"") { return true; } /* This tracks noncombat-forcers like Clara's Bell and stench jelly, which * set our noncombat rate to maximum until we encounter a noncombat. * Superlikelies do not reset this effect. There's some complexity here - * since some noncombats precede a combat encounter (for example, the * Cosmetics Wraith in the Haunted Bathroom), and we SHOULD reset the * noncombat-forcer in those cases. * * Current solution: Have a list of monsters that can only be encountered * via noncombats. Have a list of semirare encounters. */ static boolean[monster] __MONSTERS_FOLLOWING_NONCOMBATS = $monsters[ // These monsters follow noncombats, so we should reset the noncombat-forcing tracker when we fight one. Protector Spectre, ancient protector spirit, ancient protector spirit (The Hidden Apartment Building), ancient protector spirit (The Hidden Hospital), ancient protector spirit (The Hidden Office Building), ancient protector spirit (The Hidden Bowling Alley), Cosmetics wraith, // If |lastEncounter| was a noncombat adventure, // it'll to_monster() to $monster[none]. none ]; if(get_property(""auto_forceNonCombatSource"") != """" && (__MONSTERS_FOLLOWING_NONCOMBATS contains get_property(""lastEncounter"").to_monster() && !is_superlikely(get_property(""lastEncounter"")))) { auto_log_info(""Encountered (assumed) forced noncombat: "" + get_property(""lastEncounter""), ""blue""); set_property(""auto_forceNonCombatSource"", """"); set_property(""auto_forceNonCombatTurn"", -1); } if(get_property(""auto_forceNonCombatSource"") != """" && get_property(""auto_forceNonCombatTurn"").to_int() > my_turncount() - 10) { auto_log_warning(""It's been 10 adventures since we forced a noncombat ("" + get_property(""auto_forceNonCombatSource"") + ""), am going to assume it happened but we missed it."", ""blue""); set_property(""auto_forceNonCombatSource"", """"); set_property(""auto_forceNonCombatTurn"", 0); } if(have_effect($effect[Eldritch Attunement]) > 0) { if(last_monster() != $monster[Eldritch Tentacle]) { auto_log_warning(""Expected Tentacle, uh oh!"", ""red""); return false; } auto_log_info(""No Tentacle expected this time!"", ""green""); } //We need to do this early, and even if postAdventure handling is done. if(my_path() == ""The Source"") { if(get_property(""auto_diag_round"").to_int() == 0) { monster last = last_monster(); string temp = visit_url(""main.php""); if(last != last_monster()) { auto_log_warning(""Interrupted battle detected at post combat time"", ""red""); if(have_effect($effect[Beaten Up]) > 0) { auto_log_warning(""Post combat time caused up to be Beaten Up!"", ""red""); return false; } autoAdv(my_location()); return true; } } } if((get_property(""lastEncounter"") == ""Daily Briefing"") && (auto_my_path() == ""License to Adventure"")) { set_property(""_auto_bondBriefing"", ""started""); } if((get_property(""_villainLairProgress"").to_int() < 999) && ((get_property(""_villainLairColor"") != """") || get_property(""_villainLairColorChoiceUsed"").to_boolean()) && (auto_my_path() == ""License to Adventure"") && (my_location() == $location[Super Villain\\'s Lair])) { if(item_amount($item[Can Of Minions-Be-Gone]) > 0) { use(1, $item[Can Of Minions-Be-Gone]); } } if(get_property(""auto_disableAdventureHandling"").to_boolean()) { auto_log_info(""Postadventure skipped by standard adventure handler."", ""green""); return true; } if(!get_property(""_ballInACupUsed"").to_boolean() && (item_amount($item[Ball-In-A-Cup]) > 0)) { use(1, $item[Ball-In-A-Cup]); } if(!get_property(""_setOfJacksUsed"").to_boolean() && (item_amount($item[Set of Jacks]) > 0)) { use(1, $item[Set of Jacks]); } if(!get_property(""_hobbyHorseUsed"").to_boolean() && (item_amount($item[Handmade Hobby Horse]) > 0)) { use(1, $item[Handmade Hobby Horse]); } if(!get_property(""_creepyVoodooDollUsed"").to_boolean() && (item_amount($item[Creepy Voodoo Doll]) > 0)) { use(1, $item[Creepy Voodoo Doll]); } if((my_location() == $location[The Lower Chambers]) && (item_amount($item[[2334]Holy MacGuffin]) == 0)) { auto_log_info(""Postadventure skipped by Ed the Undying!"", ""green""); return true; } if((my_location() == $location[The Invader])) { // Just so the ""are we beaten up?"" check in auto_koe works properly auto_log_info(""Postadventure skipped for The Invader!"", ""green""); return true; } ocrs_postHelper(); if(last_monster().random_modifiers[""clingy""]) { auto_log_info(""Postadventure skipped by clingy modifier."", ""green""); return true; } if(have_effect($effect[Cunctatitis]) > 0) { if((my_mp() >= 12) && auto_have_skill($skill[Disco Nap])) { use_skill(1, $skill[Disco Nap]); } else { uneffect($effect[Cunctatitis]); } } float regen = numeric_modifier(""MP Regen Min"").to_float() * 2.0; regen += numeric_modifier(""MP Regen Max"").to_float(); regen = regen / 3.0; if(my_class() == $class[Avatar of Sneaky Pete]) { buffMaintain($effect[All Revved Up], 25, 1, 10); buffMaintain($effect[Of Course It Looks Great], 55, 1, 10); if(auto_have_skill($skill[Throw Party]) && !get_property(""_petePartyThrown"").to_boolean()) { int threshold = 50; if(!possessEquipment($item[Sneaky Pete\\'s Leather Jacket]) && !possessEquipment($item[Sneaky Pete\\'s Leather Jacket (Collar Popped)])) { threshold = 30; } if(my_audience() >= threshold) { use_skill(1, $skill[Throw Party]); } } if(auto_have_skill($skill[Incite Riot]) && !get_property(""_peteRiotIncited"").to_boolean()) { int threshold = -50; if(!possessEquipment($item[Sneaky Pete\\'s Leather Jacket]) && !possessEquipment($item[Sneaky Pete\\'s Leather Jacket (Collar Popped)])) { threshold = -30; } if(my_audience() <= threshold) { use_skill(1, $skill[Incite Riot]); } } } if(my_path() == ""Nuclear Autumn"") { buffMaintain($effect[Juiced and Loose], 35, 1, 1); buffMaintain($effect[Hardened Sweatshirt], 35, 1, 1); buffMaintain($effect[Ear Winds], 35, 1, 1); buffMaintain($effect[Magnetized Ears], 40, 1, 1); buffMaintain($effect[Impeccable Coiffure], 75, 1, 1); buffMaintain($effect[Mind Vision], 200, 1, 1); buffMaintain($effect[Juiced and Loose], 75, 1, 50); buffMaintain($effect[Hardened Sweatshirt], 75, 1, 50); buffMaintain($effect[Bone Springs], 75, 1, 1); if((my_meat() > 5000) && ((my_turncount() >= 50) || get_property(""falloutShelterChronoUsed"").to_boolean())) { buffMaintain($effect[Rad-Pro Tected], 0, 1, 1); } } if (isActuallyEd()) { if ($location[The Shore\\, Inc. Travel Agency] != my_location()) { if (my_servant() != $servant[none] && my_servant().experience < 196) { buffMaintain($effect[Purr of the Feline], 10, 1, 10); } buffMaintain($effect[Wisdom of Thoth], 10, 1, 10); if (my_level() < 13) { buffMaintain($effect[Prayer of Seshat], 10, 1, 10); } buffMaintain($effect[Power of Heka], 10, 1, 10); buffMaintain($effect[Hide of Sobek], 10, 1, 10); if(!($locations[Hippy Camp, The Outskirts Of Cobb\\'s Knob, Pirates of the Garbage Barges, The Secret Government Laboratory] contains my_location())) { buffMaintain($effect[Bounty of Renenutet], 10, 1, 10); } if ((my_level() < 13 || get_property(""auto_disregardInstantKarma"").to_boolean()) && my_level() > 3 && !get_property(""auto_needLegs"").to_boolean() && !($locations[Hippy Camp, The Outskirts Of Cobb\\'s Knob, The Smut Orc Logging Camp] contains my_location())) { buffMaintain($effect[Blessing of Serqet], 10, 1, 10); } foreach ef in $effects[Prayer Of Seshat, Wisdom Of Thoth, Power of Heka, Hide Of Sobek, Bounty Of Renenutet] { if(my_mp() > 100) { buffMaintain(ef, 20, 1, 20); } } } else { buffMaintain($effect[Wisdom of Thoth], 10, 1, 10); } if((my_mp() + 100) < my_maxmp()) { acquireMP(100, my_meat()); } return true; } skill libram = preferredLibram(); if(my_adventures() > 20) { buffMaintain($effect[Merry Smithsness], 0, 1, 10); } #Deal with Poison, (should do all of them actually) boolean poisoned = false; foreach poison in $effects[A Little Bit Poisoned, Hardly Poisoned At All, Majorly Poisoned, Really Quite Poisoned, Somewhat Poisoned] { if(have_effect(poison) > 0) { poisoned = true; break; } } if(poisoned) { if((my_mp() > 12) && auto_have_skill($skill[Disco Nap]) && auto_have_skill($skill[Adventurer of Leisure])) { use_skill(1, $skill[Disco Nap]); } else if(isGeneralStoreAvailable()) { buyUpTo(1, $item[Anti-Anti-Antidote], 30); if(auto_my_path() != ""G-Lover"") { use(1, $item[Anti-Anti-Antidote]); } } } if(have_effect($effect[Temporary Amnesia]) > 0) { if(!uneffect($effect[Temporary Amnesia])) { abort(""Could not remove temporary amnesia and now I suckzor.""); } } if((my_class() == $class[Turtle Tamer]) && guild_store_available()) { buffMaintain($effect[Eau de Tortue], 0, 1, 1); } if((monster_level_adjustment() > 140) && !inAftercore()) { buffMaintain($effect[Butt-Rock Hair], 0, 1, 1); buffMaintain($effect[Go Get \\'Em\\, Tiger!], 0, 1, 1); } if(my_path() == ""Community Service"") { if(auto_have_skill($skill[Summon BRICKOs]) && (get_property(""_brickoEyeSummons"").to_int() < 3)) { libram = $skill[Summon BRICKOs]; } else if(auto_have_skill($skill[Summon Taffy])) { libram = $skill[Summon Taffy]; } int missing = (my_maxmp() - my_mp()) / 15; int casts = (my_soulsauce() - 25) / 5; if(casts < 0) { casts = 0; } int regen = casts; if(casts > missing) { regen = missing; } if(regen > 0) { use_skill(regen, $skill[Soul Food]); } buffMaintain($effect[Inscrutable Gaze], 30, 1, 1); buffMaintain($effect[Big], 50, 1, 1); boolean [skill] toCast = $skills[Acquire Rhinestones, Advanced Cocktailcrafting, Advanced Saucecrafting, Communism!, Grab a Cold One, Lunch Break, Pastamastery, Perfect Freeze, Prevent Scurvy and Sobriety, Request Sandwich, Spaghetti Breakfast, Summon Alice\\'s Army Cards, Summon Carrot, Summon Confiscated Things, Summon Crimbo Candy, Summon Geeky Gifts, Summon Hilarious Objects, Summon Holiday Fun!, Summon Kokomo Resort Pass, Summon Tasteful Items]; foreach sk in toCast { if(is_unrestricted(sk) && auto_have_skill(sk) && (my_mp() >= mp_cost(sk))) { use_skill(1, sk); } } if((libram != $skill[none]) && ((my_mp() - mp_cost(libram)) > 15) && (mp_cost(libram) < 75)) { use_skill(1, libram); } if((libram != $skill[none]) && ((my_mp() - mp_cost(libram)) > 175)) { use_skill(1, libram); } return true; } if(auto_my_path() == ""The Source"") { if((get_property(""sourceInterval"").to_int() > 0) && (get_property(""sourceInterval"").to_int() <= 600) && (get_property(""sourceAgentsDefeated"").to_int() >= 9)) { if((have_effect($effect[Song of Bravado]) == 0) && (have_effect($effect[Song of Sauce]) == 0) && (have_effect($effect[Song of Slowness]) == 0) && (have_effect($effect[Song of the North]) == 0)) { buffMaintain($effect[Song of Starch], 250, 1, 1); } } } if(my_class() == $class[Sauceror]) { if((my_level() >= 6) && (have_effect($effect[[1458]Blood Sugar Sauce Magic]) == 0) && auto_have_skill($skill[Blood Sugar Sauce Magic]) && !in_hardcore()) { use_skill(1, $skill[Blood Sugar Sauce Magic]); } if(((my_level() <= 8) && (my_soulsauce() >= 92)) || (my_soulsauce() >= 100)) { use_skill(1, $skill[Soul Rotation]); } int missing = (my_maxmp() - my_mp()) / 15; int casts = (my_soulsauce() - 25) / 5; if(casts < 0) { casts = 0; } int regen = casts; if(casts > missing) { regen = missing; } if(regen > 0) { use_skill(regen, $skill[Soul Food]); } } if((monster_level_adjustment() > 120) && ((my_hp() * 10) < (my_maxhp() * 8)) && (my_mp() >= 20)) { useCocoon(); } if((my_maxhp() > 200) && (my_hp() < 80) && (my_mp() > 25)) { useCocoon(); } if((my_maxhp() > 200) && (my_hp() < 140) && (my_mp() > 100)) { useCocoon(); } if(auto_have_skill($skill[Thunderheart]) && (my_thunder() >= 90) && ((my_turncount() - get_property(""auto_lastthunderturn"").to_int()) >= 9)) { use_skill(1, $skill[Thunderheart]); } effect awolDesired = awol_walkBuff(); if(awolDesired != $effect[none]) { if(!inAftercore()) { int awolMP = 85; if(my_class() == $class[Beanslinger]) { awolMP = 95; } buffMaintain(awolDesired, awolMP, 1, 20); } else { buffMaintain(awolDesired, 120, 1, 1); } } if(auto_have_skill($skill[Demand Sandwich]) && (my_mp() > 85) && (my_level() >= 9) && (get_property(""_demandSandwich"").to_int() < 3)) { use_skill(1, $skill[Demand Sandwich]); } if(auto_have_skill($skill[Summon Smithsness]) && (my_mp() > 20)) { use_skill(1, $skill[Summon Smithsness]); } # This is the list of castables that all MP sequences will use. boolean [skill] toCast = $skills[Acquire Rhinestones, Advanced Cocktailcrafting, Advanced Saucecrafting, Communism!, Grab a Cold One, Lunch Break, Pastamastery, Perfect Freeze, Request Sandwich, Spaghetti Breakfast, Summon Alice\\'s Army Cards, Summon Carrot, Summon Confiscated Things, Summon Crimbo Candy, Summon Geeky Gifts, Summon Hilarious Objects, Summon Holiday Fun!, Summon Kokomo Resort Pass, Summon Tasteful Items]; if(my_maxmp() < 50) { buffMaintain($effect[The Magical Mojomuscular Melody], 3, 1, 5); buffMaintain($effect[Power Ballad of the Arrowsmith], 7, 1, 5); buffMaintain(whatStatSmile(), 15, 1, 10); // Only maintain skills in path with familiars if(auto_have_familiar($familiar[Mosquito])) { buffMaintain($effect[Leash of Linguini], 20, 1, 10); if(regen > 10.0) { buffMaintain($effect[Empathy], 25, 1, 10); } } // TODO: 'Get Big' is a pretty good skill if((libram != $skill[none]) && ((my_mp() - mp_cost(libram)) > 25)) { use_skill(1, libram); } foreach sk in toCast { if(is_unrestricted(sk) && auto_have_skill(sk) && ((my_mp() - 40) >= mp_cost(sk))) { use_skill(1, sk); } } if(regen > 10.0) { buffMaintain($effect[Rage of the Reindeer], 30, 1, 10); } buffMaintain($effect[Astral Shell], 35, 1, 10); buffMaintain($effect[Elemental Saucesphere], 30, 1, 10); if(my_location() != $location[The Broodling Grounds]) { buffMaintain($effect[Spiky Shell], 20, 1, 10); buffMaintain($effect[Scarysauce], 25, 1, 10); } buffMaintain($effect[Ghostly Shell], 25, 1, 10); buffMaintain($effect[Walberg\\'s Dim Bulb], 35, 1, 10); # buffMaintain($effect[Springy Fusilli], 40, 1, 10); buffMaintain($effect[Blubbered Up], 30, 1, 10); # buffMaintain($effect[Tenacity of the Snapper], 30, 1, 10); buffMaintain($effect[Reptilian Fortitude], 30, 1, 10); if(regen > 10.0) { buffMaintain($effect[Disco Fever], 40, 1, 10); } buffMaintain($effect[Saucemastery], 25, 1, 4); buffMaintain($effect[Pasta Oneness], 25, 1, 4); if(regen > 7.5) { buffMaintain($effect[Seal Clubbing Frenzy], 10, 3, 4); buffMaintain($effect[Patience of the Tortoise], 10, 3, 4); buffMaintain($effect[Mariachi Mood], 25, 1, 4); buffMaintain($effect[Disco State of Mind], 25, 1, 4); } } else if(my_maxmp() < 80) { buffMaintain($effect[The Magical Mojomuscular Melody], 3, 1, 5); buffMaintain($effect[Power Ballad of the Arrowsmith], 7, 1, 5); buffMaintain(whatStatSmile(), 20, 1, 10); // Only Maintain skills in path with familiars if(auto_have_familiar($familiar[Mosquito])) { buffMaintain($effect[Leash of Linguini], 30, 1, 10); if(regen > 10.0) { buffMaintain($effect[Empathy], 35, 1, 10); } } if((libram != $skill[none]) && ((my_mp() - mp_cost(libram)) > 32)) { use_skill(1, libram); } foreach sk in toCast { if(is_unrestricted(sk) && auto_have_skill(sk) && ((my_mp() - 50) >= mp_cost(sk))) { use_skill(1, sk); } } # buffMaintain($effect[Prayer of Seshat], 5, 1, 10); if(regen > 10.0) { buffMaintain($effect[Rage of the Reindeer], 40, 1, 10); } buffMaintain($effect[Astral Shell], 50, 1, 10); buffMaintain($effect[Elemental Saucesphere], 40, 1, 10); if(my_location() != $location[The Broodling Grounds]) { buffMaintain($effect[Spiky Shell], 40, 1, 10); buffMaintain($effect[Scarysauce], 40, 1, 10); # buffMaintain($effect[Jalapeño Saucesphere], 50, 1, 10); } buffMaintain($effect[Ghostly Shell], 45, 1, 10); if(my_class() == $class[Turtle Tamer]) { buffMaintain($effect[Disdain of the Storm Tortoise], 60, 1, 10); } buffMaintain($effect[Walberg\\'s Dim Bulb], 50, 1, 10); # buffMaintain($effect[Springy Fusilli], 60, 1, 10); # buffMaintain($effect[Flimsy Shield of the Pastalord], 70, 1, 10); buffMaintain($effect[Blubbered Up], 60, 1, 10); # buffMaintain($effect[Tenacity of the Snapper], 50, 1, 10); buffMaintain($effect[Reptilian Fortitude], 50, 1, 10); if(regen > 10.0) { buffMaintain($effect[Disco Fever], 60, 1, 10); } buffMaintain($effect[Saucemastery], 50, 3, 4); buffMaintain($effect[Pasta Oneness], 50, 3, 4); if(regen > 8.2) { buffMaintain($effect[Seal Clubbing Frenzy], 25, 3, 4); buffMaintain($effect[Patience of the Tortoise], 25, 3, 4); buffMaintain($effect[Mariachi Mood], 50, 3, 4); buffMaintain($effect[Disco State of Mind], 50, 3, 4); } } else if(my_maxmp() < 170) { if(my_level() < 13) { buffMaintain(whatStatSmile(), 40, 1, 10); } // Only maintain in path with familiars if(auto_have_familiar($familiar[Mosquito])) { buffMaintain($effect[Leash of Linguini], 35, 1, 10); if(regen > 4.0) { buffMaintain($effect[Empathy], 50, 1, 10); } } foreach sk in toCast { if(is_unrestricted(sk) && auto_have_skill(sk) && ((my_mp() - 90) >= mp_cost(sk))) { use_skill(1, sk); } } if((libram != $skill[none]) && ((my_mp() - mp_cost(libram)) > 40)) { use_skill(1, libram); } # buffMaintain($effect[Prayer of Seshat], 5, 1, 10); buffMaintain($effect[Big], 100, 1, 10); buffMaintain($effect[Rage of the Reindeer], 80, 1, 10); buffMaintain($effect[Astral Shell], 80, 1, 10); buffMaintain($effect[Elemental Saucesphere], 120, 1, 10); if(my_location() != $location[The Broodling Grounds]) { buffMaintain($effect[Spiky Shell], 80, 1, 10); buffMaintain($effect[Scarysauce], 120, 1, 10); # buffMaintain($effect[Jalapeño Saucesphere], 60, 1, 10); } buffMaintain($effect[Ghostly Shell], 80, 1, 10); if(my_class() == $class[Turtle Tamer]) { buffMaintain($effect[Disdain of the Storm Tortoise], 80, 1, 10); } buffMaintain($effect[Walberg\\'s Dim Bulb], 80, 1, 10); buffMaintain($effect[Springy Fusilli], 80, 1, 10); # buffMaintain($effect[Flimsy Shield of the Pastalord], 80, 1, 10); buffMaintain($effect[Blubbered Up], 120, 1, 10); # buffMaintain($effect[Tenacity of the Snapper], 80, 1, 10); if(regen > 10.0) { buffMaintain($effect[Reptilian Fortitude], 150, 1, 10); buffMaintain($effect[Disco Fever], 80, 1, 10); buffMaintain($effect[Seal Clubbing Frenzy], 50, 5, 4); buffMaintain($effect[Patience of the Tortoise], 50, 5, 4); } # buffMaintain($effect[Rotten Memories], 100, 1, 10); if((libram != $skill[none]) && ((my_mp() - mp_cost(libram)) > 80)) { use_skill(1, libram); } if(my_mp() > 80) { buffMaintain($effect[Takin\\' It Greasy], 50, 1, 5); buffMaintain($effect[Intimidating Mien], 50, 1, 5); } } else { boolean didOutfit = false; if((my_basestat($stat[mysticality]) >= 200) && (my_buffedstat($stat[mysticality]) >= 200) && inAftercore() && (item_amount($item[Wand of Oscus]) > 0) && (item_amount($item[Oscus\\'s Dumpster Waders]) > 0) && (item_amount($item[Oscus\\'s Pelt]) > 0)) { cli_execute(""outfit save Backup""); #Using the cli command may not upgrade our stats if our max mp drops #Not sure if the ASH command actually handles it properly, we'll see. #cli_execute(""outfit Vile Vagrant Vestments""); #outfit does not... damn it. if(!autoOutfit(""Vile Vagrant Vestments"")) { auto_log_warning(""Could not wear Vile Vagrant Outfit for some raisin"", ""red""); } didOutfit = true; } if((my_mp() > 150) && (my_maxhp() > 300) && (my_hp() < 140)) { useCocoon(); } if((my_mp() > 100) && (my_maxhp() > 500) && (my_hp() < 250)) { useCocoon(); } if((my_mp() > 75) && (my_maxhp() > 500) && (my_hp() < 200)) { useCocoon(); } if((my_mp() > 75) && (my_maxhp() > 700) && (my_hp() < 300)) { useCocoon(); } if((my_mp() > 75) && ((my_hp() == 0) || ((my_maxhp()/my_hp()) > 3))) { useCocoon(); } buffMaintain($effect[Fat Leon\\'s Phat Loot Lyric], 250, 1, 10); if(my_level() < 13) { buffMaintain(whatStatSmile(), 40, 1, 10); } // Only maintain in path with familiars if(auto_have_familiar($familiar[Mosquito])) { buffMaintain($effect[Empathy], 50, 1, 10); buffMaintain($effect[Leash of Linguini], 35, 1, 10); } foreach sk in toCast { if(is_unrestricted(sk) && auto_have_skill(sk) && ((my_mp() - 85) >= mp_cost(sk))) { use_skill(1, sk); } } if((libram != $skill[none]) && ((my_mp() - mp_cost(libram)) > 32)) { auto_log_info(""Mymp: "" + my_mp() + "" of "" + my_maxmp() + "" and cost: "" + mp_cost(libram), ""blue""); boolean temp = false; try { #if(use_skill(1, libram)) {} temp = use_skill(1, libram); } finally { if(!temp) { auto_log_warning(""No longer have enough MP and failed."", ""red""); auto_log_info(""Mymp: "" + my_mp() + "" of "" + my_maxmp() + "" and cost: "" + mp_cost(libram), ""blue""); } } } # buffMaintain($effect[Prayer of Seshat], 5, 1, 10); buffMaintain($effect[Singer\\'s Faithful Ocelot], 280, 1, 10); buffMaintain($effect[Big], 100, 1, 10); buffMaintain($effect[Rage of the Reindeer], 80, 1, 10); buffMaintain($effect[Astral Shell], 80, 1, 10); buffMaintain($effect[Elemental Saucesphere], 120, 1, 10); if(my_location() != $location[The Broodling Grounds]) { buffMaintain($effect[Spiky Shell], 120, 1, 10); buffMaintain($effect[Scarysauce], 160, 1, 10); buffMaintain($effect[Jalapeño Saucesphere], 225, 1, 10); } buffMaintain($effect[Ghostly Shell], 80, 1, 10); if(regen > 15.0) { buffMaintain($effect[Disdain of the War Snapper], 200, 1, 10); } buffMaintain($effect[Walberg\\'s Dim Bulb], 80, 1, 10); buffMaintain($effect[Springy Fusilli], 80, 1, 10); if(regen > 15.0) { buffMaintain($effect[Flimsy Shield of the Pastalord], 180, 1, 10); } buffMaintain($effect[Blubbered Up], 200, 1, 10); buffMaintain($effect[Tenacity of the Snapper], 200, 1, 10); buffMaintain($effect[Reptilian Fortitude], 200, 1, 10); if(regen > 20.0) { buffMaintain($effect[Antibiotic Saucesphere], 350, 1, 10); } if(regen > 5.0) { buffMaintain($effect[Disco Fever], 120, 1, 10); } if(my_primestat() == $stat[Muscle]) { buffMaintain($effect[Seal Clubbing Frenzy], 200, 5, 4); buffMaintain($effect[Patience of the Tortoise], 200, 5, 4); } if(my_primestat() == $stat[Moxie]) { buffMaintain($effect[Mariachi Mood], 200, 5, 4); buffMaintain($effect[Disco State of Mind], 200, 5, 4); } if(my_primestat() == $stat[Mysticality]) { buffMaintain($effect[Saucemastery], 200, 5, 4); buffMaintain($effect[Pasta Oneness], 200, 5, 4); } if(familiar_weight(my_familiar()) < 20) { buffMaintain($effect[Curiosity of Br\\'er Tarrypin], 50, 1, 2); } // Only maintain in path with familiars if(auto_have_familiar($familiar[Mosquito])) { buffMaintain($effect[Jingle Jangle Jingle], 120, 1, 2); } buffMaintain($effect[A Few Extra Pounds], 200, 1, 2); buffMaintain($effect[Boon of the War Snapper], 200, 1, 5); buffMaintain($effect[Boon of She-Who-Was], 200, 1, 5); buffMaintain($effect[Boon of the Storm Tortoise], 200, 1, 5); buffMaintain($effect[Ruthlessly Efficient], 50, 1, 5); buffMaintain($effect[Mathematically Precise], 150, 1, 5); # buffMaintain($effect[Rotten Memories], 150, 1, 10); if(inAftercore()) { if((auto_have_skill($skill[Summon Rad Libs])) && (my_mp() > 6)) { use_skill(3, $skill[Summon Rad Libs]); } if((auto_have_skill($skill[Summon Geeky Gifts])) && (my_mp() > 5)) { use_skill(1, $skill[Summon Geeky Gifts]); } if((auto_have_skill($skill[Summon Stickers])) && (my_mp() > 6)) { use_skill(3, $skill[Summon Stickers]); } if((auto_have_skill($skill[Summon Sugar Sheets])) && (my_mp() > 6)) { use_skill(3, $skill[Summon Sugar Sheets]); } if(auto_have_skill($skill[Rainbow Gravitation])) { use_skill(3, $skill[Rainbow Gravitation]); } } if((libram != $skill[none]) && ((my_mp() - mp_cost(libram)) > 80)) { use_skill(1, libram); } if(my_mp() > 80) { buffMaintain($effect[Takin\\' It Greasy], 50, 1, 5); buffMaintain($effect[Intimidating Mien], 50, 1, 5); } if(didOutfit) { cli_execute(""outfit Backup""); } } // Experience and Powerlevelling Section if((my_level() < 13) || (get_property(""auto_disregardInstantKarma"").to_boolean())) { // +Stat expressions based on mainstat if(my_primestat() == $stat[Muscle]) { auto_faceCheck(""Patient Smile""); } if(my_primestat() == $stat[Moxie]) { auto_faceCheck(""Knowing Smile""); } if(my_primestat() == $stat[Mysticality]) { // If Gaze succeeds Smile will fail the check and vice versa auto_faceCheck(""Inscrutable Gaze""); auto_faceCheck(""Wry Smile""); } // Catch-all Expressions in decending order of importance (in case we could not get a stat specific one) auto_faceCheck(""Inscrutable Gaze""); auto_faceCheck(""Wry Smile""); auto_faceCheck(""Patient Smile""); auto_faceCheck(""Knowing Smile""); // Generic +Stat Buffs buffMaintain($effect[Carol of the Thrills], 30, 1, 1); // Aptitude is not worth it to maintain if we have Ur-Kel's if((40 < regen * auto_predictAccordionTurns()) && (have_effect($effect[Ur-Kel\\'s Aria of Annoyance]) == 0)) { buffMaintain($effect[Aloysius\\' Antiphon of Aptitude], 40, 1, 1); } } if(my_class() == $class[Pastamancer]) { thrall cur = my_thrall(); thrall consider = $thrall[none]; /* Cost L1 L5 L10 Vampieroghi 12 1-2 (Dmg, Heal) Dispel Neg +60 Max HP Vermincelli 30 2 MP Regen Dmg, Poison +30 Max MP Angel Hair Wisp 60 5% init Block Crits Block (Undead)Elbow Maraconi 100 Equalize Mus +2 Weapon Dmg +10% crit Penne Dreadful 150 Equalize Mox Jump Delevel DR + 10 Spaghetti Elemental 150 +Stats Ceil(/3) Block First Att +5 spell dmg Lasagmbie 200 20+2 Meat Spooky Dmg +10 spooky spell dmg Spice Ghost 250 10+1 Item Spices Stun Increase */ if((my_mp() >= (1.2 * mp_cost($skill[Bind Vermincelli]))) && (cur == $thrall[none]) && auto_have_skill($skill[Bind Vermincelli])) { consider = $thrall[Vermincelli]; } if((my_mp() >= (1.2 * mp_cost($skill[Bind Spice Ghost]))) && auto_have_skill($skill[Bind Spice Ghost]) && (my_daycount() > 1) && (numeric_modifier(""MP Regen Min"").to_int() > 9)) { consider = $thrall[Spice Ghost]; } if((consider != cur) && (consider != $thrall[none])) { skill toEquip = to_skill(""Bind "" + consider); if(toEquip != $skill[none]) { if(my_mp() >= mp_cost(toEquip)) { use_skill(1, toEquip); } } else { auto_log_warning(""Thrall handler error. Could not generate appropriate skill."", ""red""); } } } if(get_property(""auto_cubeItems"").to_boolean() && (item_amount($item[Ring Of Detect Boring Doors]) == 1) && (item_amount($item[Eleven-Foot Pole]) == 1) && (item_amount($item[Pick-O-Matic Lockpicks]) == 1)) { set_property(""auto_cubeItems"", false); } if(!inAftercore()) { if((my_daycount() == 1) && (my_bjorned_familiar() != $familiar[grim brother]) && (get_property(""_grimFairyTaleDropsCrown"").to_int() == 0) && (have_familiar($familiar[grim brother])) && (equipped_item($slot[back]) == $item[Buddy Bjorn]) && (my_familiar() != $familiar[Grim Brother])) { bjornify_familiar($familiar[grim brother]); } if((my_bjorned_familiar() == $familiar[grimstone golem]) && (get_property(""_grimstoneMaskDropsCrown"") == 1) && have_familiar($familiar[El Vibrato Megadrone])) { bjornify_familiar($familiar[el vibrato megadrone]); } if((my_bjorned_familiar() == $familiar[grim brother]) && (get_property(""_grimFairyTaleDropsCrown"").to_int() >= 1)) { bjornify_familiar($familiar[el vibrato megadrone]); } } if(my_path() == ""Heavy Rains"") { auto_log_info(""Post adventure done: Thunder: "" + my_thunder() + "" Rain: "" + my_rain() + "" Lightning: "" + my_lightning(), ""green""); } if((item_amount($item[The Big Book of Pirate Insults]) > 0) && ((my_location() == $location[Barrrney\\'s Barrr]) || (my_location() == $location[The Obligatory Pirate\\'s Cove]))) { auto_log_info(""Have "" + numPirateInsults() + "" insults."", ""green""); } if(my_location() == $location[The Broodling Grounds]) { auto_log_info(""Have "" + item_amount($item[Hellseal Brain]) + "" brain(s)."", ""green""); auto_log_info(""Have "" + item_amount($item[Hellseal Hide]) + "" hide(s)."", ""green""); auto_log_info(""Have "" + item_amount($item[Hellseal Sinew]) + "" sinew(s)."", ""green""); } if((my_location() == $location[The Hidden Bowling Alley]) && inAftercore()) { if(item_amount($item[Bowling Ball]) > 0) { put_closet(item_amount($item[Bowling Ball]), $item[Bowling Ball]); } } if((my_level() < 13) && !inAftercore() && (my_meat() > 7500)) { if(item_amount($item[pulled red taffy]) >= 6) { buffMaintain($effect[Cinnamon Challenger], 0, 6, 10); } if(item_amount($item[pulled orange taffy]) >= 6) { buffMaintain($effect[Orange Crusher], 0, 6, 10); } if(item_amount($item[pulled violet taffy]) >= 6) { buffMaintain($effect[Purple Reign], 0, 6, 10); } buffMaintain($effect[Gummi-Grin], 0, 1, 1); buffMaintain($effect[Strong Resolve], 0, 1, 1); buffMaintain($effect[Irresistible Resolve], 0, 1, 1); buffMaintain($effect[Brilliant Resolve], 0, 1, 1); buffMaintain($effect[From Nantucket], 0, 1, 1); buffMaintain($effect[Squatting and Thrusting], 0, 1, 1); buffMaintain($effect[You Read the Manual], 0, 1, 1); buyableMaintain($item[Hair Spray], 1, 200, my_class() != $class[Turtle Tamer]); buyableMaintain($item[Blood of the Wereseal], 1, 3500, (monster_level_adjustment() > 135)); buyableMaintain($item[Ben-gal™ Balm], 1, 200); } buyableMaintain($item[Turtle Pheromones], 1, 800, my_class() == $class[Turtle Tamer]); if((get_property(""auto_beatenUpCount"").to_int() <= 10) && (have_effect($effect[Beaten Up]) > 0) && (my_mp() >= mp_cost($skill[Tongue of the Walrus])) && auto_have_skill($skill[Tongue of the Walrus])) { auto_log_warning(""Owwie, was beaten up but trying to recover"", ""red""); if(my_location() == $location[The X-32-F Combat Training Snowman]) { auto_log_info(""At the snojo, let's not keep going there and dying...."", ""red""); set_property(""_snojoFreeFights"", 10); } set_property(""auto_beatenUpCount"", get_property(""auto_beatenUpCount"").to_int() + 1); use_skill(1, $skill[Tongue of the Walrus]); } # We only do this in aftercore because we don't want a spiralling death loop in-run. if(inAftercore() && (have_effect($effect[Beaten Up]) > 0) && (my_mp() >= mp_cost($skill[Tongue of the Walrus])) && auto_have_skill($skill[Tongue of the Walrus])) { auto_log_warning(""Owwie, was beaten up but trying to recover"", ""red""); use_skill(1, $skill[Tongue of the Walrus]); } #Should we create a separate function to track these? How many are we going to track? if((last_monster() == $monster[Writing Desk]) && (get_property(""lastEncounter"") == $monster[Writing Desk]) && (have_effect($effect[Beaten Up]) == 0)) { auto_log_info(""Fought "" + get_property(""writingDesksDefeated"") + "" writing desks."", ""blue""); } if((last_monster() == $monster[Modern Zmobie]) && (get_property(""lastEncounter"") == $monster[Modern Zmobie]) && (have_effect($effect[Beaten Up]) == 0)) { set_property(""auto_modernzmobiecount"", """" + (get_property(""auto_modernzmobiecount"").to_int() + 1)); auto_log_info(""Fought "" + get_property(""auto_modernzmobiecount"") + "" modern zmobies."", ""blue""); } if(have_effect($effect[Disavowed]) > 0) { if(get_property(""_auto_bondBriefing"") != ""finished"") { set_property(""_auto_bondBriefing"", ""started""); } if(auto_have_skill($skill[Disco Nap]) && (my_mp() > mp_cost($skill[Disco Nap]))) { auto_log_warning(""We have been disavowed..."", ""red""); use_skill(1, $skill[Disco Nap]); } else { abort(""We have been disavowed...""); } } set_property(""auto_combatDirective"", """"); set_property(""auto_digitizeDirective"", """"); if(have_effect($effect[Beaten Up]) > 0) { set_property(""auto_beatenUpCount"", get_property(""auto_beatenUpCount"").to_int() + 1); } set_property(""auto_januaryToteAcquireCalledThisTurn"", false); auto_log_info(""Post Adventure done, beep."", ""purple""); return true; } void main() { boolean ret = false; try { ret = auto_post_adventure(); } finally { if (!ret) { auto_log_error(""Error running auto_post_adv.ash, setting auto_interrupt=true""); set_property(""auto_interrupt"", true); } } }",12047,True,2621.962184820819,median "void generateRandomMessageLocation(string [int] random_messages) { if (__last_adventure_location == $location[none]) return; string message = """"; switch (__last_adventure_location) { case $location[the penultimate fantasy airship]: message = ""insert disc 2 to continue""; break; case $location[a-boo peak]: message = ""allons-y!""; break; case $location[twin peak]: message = ""fire walk with me""; break; case $location[The Arrrboretum]: message = ""save the planet""; break; case $location[the red queen's garden]: message = ""curiouser and curiouser""; break; case $location[A Massive Ziggurat]: message = ""1.21 ziggurats""; break; case $location[McMillicancuddy's Barn]: message = ""dooks""; break; case $location[The Roman Forum]: message = ""they go the house""; break; case $location[the battlefield (hippy uniform)]: message = ""love and war""; break; case $location[the middle chamber]: message = ""pyramid laundry machine""; break; case $location[the arid, extra-dry desert]: message = ""can't remember your name""; break; case $location[outside the club]: message = ""around the world around the world around the world around the world""; break; case $location[the hidden temple]: message = ""beware of temple guards""; break; case $location[sonar]: message = ""one ping only""; break; case $location[galley]: message = ""hungry?""; break; case $location[science lab]: message = ""poetry in motion""; break; case $location[fear man's level]: case $location[doubt man's level]: case $location[regret man's level]: case $location[anger man's level]: message = ""this isn't me""; break; case $location[domed city of ronaldus]: case $location[domed city of grimacia]: case $location[hamburglaris shield generator]: message = ""spaaaace!""; break; case $location[The Mansion of Dr. Weirdeaux]: case $location[The Deep Dark Jungle]: case $location[The Secret Government Laboratory]: message = ""they know where you live, "" + get_property(""System.user.name"").to_lower_case(); break; case $location[The castle in the clouds in the sky (ground floor)]: case $location[The castle in the clouds in the sky (basement)]: case $location[The castle in the clouds in the sky (top floor)]: if (my_class() == $class[disco bandit]) message = ""making castles of your disco""; break; case $location[The Prince's Restroom]: case $location[The Prince's Dance Floor]: case $location[The Prince's Kitchen]: case $location[The Prince's Balcony]: case $location[The Prince's Lounge]: case $location[The Prince's Canapes table]: message = ""social sabotage""; break; case $location[anemone mine (mining)]: case $location[itznotyerzitz mine (in disguise)]: case $location[the knob shaft (mining)]: case $location[The Crimbonium Mine]: case $location[The Velvet / Gold Mine (Mining)]: message = ""street sneaky pete don't you call me cause I can't go""; break; case lookupLocation(""Through the Spacegate""): message = ""oh look! rocks!""; case $location[hell]: message = ""that's a clean burning hell, I'll tell you what""; break; } if (message != """") random_messages.listAppend(message); } void generateRandomMessageFamiliar(string [int] random_messages) { string lowercase_player_name = my_name().to_lower_case().HTMLEscapeString(); if (my_familiar() == $familiar[none]) return; string message = """"; switch (my_familiar()) { case $familiar[none]: message = ""even introverts need friends""; break; case $familiar[crimbo shrub]: if (format_today_to_string(""MM"") == ""07"") message = ""crimbo in july""; break; case $familiar[black cat]: message = ""aww, cute kitty!""; break; case $familiar[temporal riftlet]: message = ""master of time and space""; break; case $familiar[Frumious Bandersnatch]: message = ""frabjous""; break; case $familiar[Pair of Stomping Boots]: if (__misc_state[""free runs usable""]) message = ""running away again?""; break; case $familiar[baby sandworm]: message = ""the waters of life""; break; case $familiar[baby bugged bugbear]: message = ""expected }, found }̋̑̀̆͊̑̔͏̱̩̠̰ ̣̻͊ͅf̝͎̰̥̙ͣͦͥ̎,̜̘̖ͭ͋ ̲͉̮̭̪̣͌͋ͤ̉͗ͪ̄̕;̹̼̋̈͛͊ ̧͔̥̤「͙̺̻͖̯͛̀̓̏͑̀l͍̍̍̍͑i̖̖͙͂ͪͮ̍ ̓͑̉̀̆҉̠̜͚̜̹1̶͔̩̬̦̦͍ͥ7͛҉̬̯͇̻͖͉1̆̑̂͒̓」̧̼̜̹̘͕͆̾́͆͐ͯͧ""; //causes severe rendering slowdown; working as intended break; case $familiar[mechanical songbird]: message = ""a little glowing friend""; break; case $familiar[nanorhino]: message = ""write every day""; break; case $familiar[rogue program]: message = ""ascends for the users""; break; case $familiar[O.A.F.]: message = ""helping""; break; case $familiar[Bank Piggy]: case $familiar[Egg Benedict]: case $familiar[Floating Eye]: case $familiar[Money-Making Goblin]: case $familiar[Oyster Bunny]: case $familiar[Plastic Grocery Bag]: case $familiar[Snowhitman]: case $familiar[Vampire Bat]: case $familiar[Worm Doctor]: message = ""hacker""; break; case $familiar[adorable space buddy]: message = ""far beyond the stars""; break; case $familiar[happy medium]: message = ""karma slave""; //what mistakes could I have made? break; case $familiar[wild hare]: message = ""or you wouldn't have come here""; //you must be mad break; case $familiar[artistic goth kid]: message = ""life is pain, "" + lowercase_player_name; break; case $familiar[angry jung man]: message = ""personal trauma""; break; case $familiar[unconscious collective]: message = ""zzz""; break; case $familiar[dataspider]: message = ""spiders are your friends""; break; case $familiar[stocking mimic]: message = ""delicious candy""; break; case $familiar[cocoabo]: message = ""flightless bird""; break; case $familiar[whirling maple leaf]: message = ""canadian pride""; break; case $familiar[Hippo Ballerina]: message = ""spin spin spin""; break; case $familiar[Mutant Cactus Bud]: message = ""always watching""; break; case $familiar[ghuol whelp]: message = ""¯\\\\_(ツ)_/¯""; //¯\\_(ツ)_/¯ break; case $familiar[bulky buddy box]: message = ""♥︎""; //♥︎ break; case $familiar[emo squid]: message = ""sob""; break; case $familiar[fancypants scarecrow]: message = ""the best in terms of pants""; break; case $familiar[jumpsuited hound dog]: message = ""a little less conversation""; break; case $familiar[Gluttonous Green Ghost]: message = ""I think he can hear you, "" + lowercase_player_name; break; case $familiar[hand turkey]: message = ""a rare bird""; break; case $familiar[reanimated reanimator]: message = ""weird science""; break; case $familiar[Twitching Space Critter]: message = ""right right right right down right agh""; break; case $familiar[slimeling]: message = ""lost mother""; break; case $familiar[Puck Man]: case $familiar[Ms. Puck Man]: message = ""ᗧ • • • • • • • • •""; break; case $familiar[Lil' Barrel Mimic]: message = "":D""; break; case $familiar[pet rock]: message = ""what if the rock's eyebrow froze that way. would anyone notice?""; break; case $familiar[space jellyfish]: message = ""deer force""; if (__quest_state[""Level 13""].state_boolean[""king waiting to be freed""]) { int obtained = 0; int obtainable = 0; foreach it in $items[] { if (it.quest) continue; //these disappear if (it.item_amount_almost_everywhere() > 0) obtained += 1; obtainable += 1; } float rate = to_float(obtained) / to_float(obtainable); random_messages.listClear(); message = ""SEE YOU NEXT MISSION
your rate for collecting items is "" + to_int(rate * 100) + ""%""; } else if (my_level() == 1 || my_turncount() <= 2) { random_messages.listClear(); message = ""the last jellyfish is in captivity
the kingdom is at peace""; } break; case $familiar[bad vibe]: message = ""it's all your fault""; break; } if (message != """") random_messages.listAppend(message); } string generateRandomMessage() { string [int] random_messages; int current_hour = now_to_string(""HH"").to_int_silent(); int current_minute = now_to_string(""mm"").to_int_silent(); int minute_of_day = current_hour * 60 + current_minute; if (!playerIsLoggedIn()) return ""the kingdom awaits""; if (__misc_state[""In valhalla""]) return ""rebirth""; if (__misc_state[""in run""]) { if (my_turncount() > 1000 && !in_bad_moon()) random_messages.listAppend(""so many turns""); if (false) random_messages.listAppend(""you are ascending perfectly, excellent work!""); else if (my_daycount() >= 365) random_messages.listAppend(""no king, forever""); else if (my_daycount() >= 11) random_messages.listAppend(""does the king even exist...?""); else if (my_turncount() > 500 && my_daycount() == 1) random_messages.listAppend(""you are ascending too... wait, what?""); else if (gameday_to_int() == 7) random_messages.listAppend(""you are ascending at a reasonable pace, could do better""); else random_messages.listAppend(""you are ascending too slowly, ascend faster!""); string what_does_the_spreadsheet_say = ""saves a turn""; if (myPathId() == PATH_ONE_CRAZY_RANDOM_SUMMER) what_does_the_spreadsheet_say = ""gives +fun""; if ($item[optimal spreadsheet].equipped_amount() > 0) random_messages.listAppend(""every spreadsheet you wear "" + what_does_the_spreadsheet_say); //sure, why not? else random_messages.listAppend(""every spreadsheet you make "" + what_does_the_spreadsheet_say); } string [string] holiday_messages; holiday_messages[""Groundhog Day""] = ""it's cold out there every day""; holiday_messages[""Crimbo""] = ""merry crimbo""; if ($item[tommy gun].equipped_amount() > 0) //I believe ya, but my tommy gun don't! holiday_messages[""Crimbo""] = ""merry crimbo, ya filthy animal""; holiday_messages[""April Fool's Day""] = ""you are ascending too quickly, ascend slower!""; holiday_messages[""Valentine's Day""] = HTMLGenerateSpanFont(""♥︎"", ""pink"", ""3.0em""); holiday_messages[""Towel Day""] = ""don't panic""; boolean [string] holidays_today = getHolidaysToday(); foreach holiday in holidays_today { if (holiday_messages contains holiday) { random_messages.listAppend(holiday_messages[holiday]); } } if ($item[The One Mood Ring].equipped_amount() > 0 || $item[mood ring].equipped_amount() > 0) { string [int] moods = split_string(""grateful,awake,accomplished,disappointed,enraged,tired,exhausted,amused,crushed,peaceful,energetic,listless,hyper,jubilant,hungry,sad,bewildered,alone,quixotic,recumbent,bored,excited,relaxed,lonely,curious,guilty,jealous,cheerful,depressed,stressed,infuriated,pleased,crappy,aggravated,okay,rejuvenated,apathetic,bittersweet,optimistic,exanimate,complacent,devious,rejected,blissful,discontent,sympathetic,mellow,refreshed,ecstatic,lazy,morose,dark,mischievous,bouncy,thankful,melancholy,content,drained,numb,uncomfortable,indifferent,groggy,calm,irate,determined,giggly,good,confused,anxious,relieved,mad,accepted,happy,angry,lethargic,shocked,indescribable,satisfied,gloomy,irritated,pessimistic,rushed,frustrated,surprised,annoyed,sleepy,touched,enthralled,cynical,envious,hopeful,ashamed,chipper,loved,giddy,restless"", "",""); string mood_today = moods[gameday_to_int()]; if (mood_today != """") random_messages.listAppend(mood_today); } if (__misc_state[""in run""]) { random_messages.listAppend(""optimal power, make up!""); random_messages.listAppend(""the faster your runs, the longer they take""); } generateRandomMessageLocation(random_messages); //random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""if you're feeling stressed, play alice's army"", generateMainLinkMap(""aagame.php""))); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""if you're feeling stressed, play witchess"", generateMainLinkMap(""playwitchess.php?action=another""))); random_messages.listAppend(""consider your mistakes creative spading""); if (hippy_stone_broken()) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""it's not easy having yourself a good time"", generateMainLinkMap(""peevpee.php""))); string [item] equipment_messages; equipment_messages[$item[whatsian ionic pliers]] = ""ionic pliers untinker to a screwdriver and a sonar-in-a-biscuit""; equipment_messages[$item[yearbook club camera]] = ""rule of thirds""; equipment_messages[$item[happiness]] = ""bang bang""; equipment_messages[$item[mysterious silver lapel pin]] = ""be seeing you""; equipment_messages[$item[Moonthril Circlet]] = ""moon tiara""; //action! equipment_messages[$item[numberwang]] = ""simply everyone""; equipment_messages[$item[Mark V Steam-Hat]] = ""girl genius""; equipment_messages[$item[mr. accessory]] = ""you can equip mr. accessories?""; equipment_messages[$item[white hat hacker T-shirt]] = ""hack the planet""; equipment_messages[$item[heart necklace]] = ""♥︎""; //♥︎ equipment_messages[$item[fleetwood chain]] = ""running in the shadows""; equipment_messages[$item[liar's pants]] = ""never tell the same lie twice""; equipment_messages[$item[detective skull]] = HTMLGenerateSpanFont(""too slow ascend faster"", ""#ACA200""); //speakeasy password equipment_messages[$item[gasmask]] = ""are you my mummy?""; equipment_messages[$item[spanish fly trap]] = ""around the world around the world around the world around the world""; equipment_messages[$item[wand of nagamar]] = ""levi OH sa""; if (in_bad_moon() && my_primestat() != $stat[moxie]) equipment_messages[$item[sneaky pete's breath spray]] = ""every class a moxie class""; foreach it in $items[twisted-up wet towel,sommelier's towel,time bandit time towel] equipment_messages[it] = ""don't panic""; equipment_messages[$item[pirate fledges]] = "" oh, better far to live and die, under the brave black flag I fly! ""; foreach it in equipment_messages { if (it.equipped_amount() > 0) { random_messages.listAppend(equipment_messages[it]); break; } } if (my_ascensions() == 0) random_messages.listAppend(""welcome to the kingdom!""); else if (my_ascensions() == 1) random_messages.listAppend(""run, while you still have the chance!""); if (__misc_state[""in run""]) random_messages.listAppend(""perfect runs are overrated""); random_messages.listAppend(""math is your helpful friend""); if (get_property_int(""_pantsgivingCount"") >= 5500) { random_messages.listAppend(""Could not connect to secondary database server:2003 - Can't connect to MySQL server on '10.0.0.51' (99)""); } if ((gameday_to_int() & 31) == 0) random_messages.listAppend(""seek the alchemist""); //a young lady's illustrated ascension guide string [effect] effect_messages; effect_messages[$effect[consumed by anger]] = ""don't ascend angry""; effect_messages[$effect[consumed by regret]] = ""wasted potential""; effect_messages[$effect[All Revved Up]] = ""vroom""; if (myPathId() != PATH_WAY_OF_THE_SURPRISING_FIST) effect_messages[$effect[Expert Timing]] = ""martial arts and crafts""; effect_messages[$effect[apathy]] = """"; // effect_messages[$effect[silent running]] = ""an awful lot of running""; effect_messages[$effect[Neuromancy]] = ""the silver paths""; effect_messages[$effect[Teleportitis]] = ""everywhere and nowhere""; effect_messages[$effect[Form of...Bird!]] = ""fiddle fiddle fiddle""; effect_messages[$effect[superstar]] = ""★""; effect_messages[$effect[hopped up on goofballs]] = ""a massive drug deficiency""; foreach s in $strings[Warlock\\, Warstock\\, and Warbarrel,Barrel of Laughs,Barrel Chested,Pork Barrel,Double-Barreled,Beer Barrel Polka] effect_messages[s.to_effect()] = ""just let me throw a barrel at it""; effect_messages[$effect[Meteor Showered]] = ""すきだ""; foreach e in effect_messages { if (e.have_effect() > 0 && e != $effect[none]) { random_messages.listAppend(effect_messages[e]); break; } } if (__misc_state[""single familiar run""]) random_messages.listAppend(""together forever""); random_messages.listAppend(""click click click""); switch (myPathId()) { case PATH_OXYGENARIAN: random_messages.listAppend(""the slow path""); break; case PATH_BEES_HATE_YOU: random_messages.listAppend(""bzzzzzz""); break; case PATH_WAY_OF_THE_SURPRISING_FIST: random_messages.listAppend(""martial arts and crafts""); break; case PATH_TRENDY: random_messages.listAppend(""played out""); break; case PATH_AVATAR_OF_BORIS: random_messages.listAppend(""testosterone poisoning""); break; case PATH_BUGBEAR_INVASION: random_messages.listAppend(""bugbears!""); break; case PATH_ZOMBIE_SLAYER: random_messages.listAppend(""consumerism metaphor""); break; case PATH_CLASS_ACT: random_messages.listAppend(""try the sequel""); break; case PATH_AVATAR_OF_JARLSBERG: random_messages.listAppend(""nerd""); break; case PATH_BIG: random_messages.listAppend(""everything's so tiny...""); break; case PATH_KOLHS: random_messages.listAppend(""did you study?""); break; case PATH_CLASS_ACT_2: random_messages.listAppend(""lonely guild trainer""); break; case PATH_AVATAR_OF_SNEAKY_PETE: random_messages.listAppend(""sunglasses at night""); break; case PATH_SLOW_AND_STEADY: if (!in_hardcore()) random_messages.listAppend(""infinite pulls""); else random_messages.listAppend(""skip a day if you like""); break; case PATH_HEAVY_RAINS: random_messages.listAppend(""survive""); break; case PATH_PICKY: if ($skill[cannelloni cannon].skill_is_usable() && !$skill[cannelloni cocoon].skill_is_usable()) //such an easy mistake... random_messages.listAppend(""cannelloni confusion""); else random_messages.listAppend(""combinatorial ascension""); break; case PATH_STANDARD: random_messages.listAppend(""no past no path""); break; case PATH_ACTUALLY_ED_THE_UNDYING: random_messages.listAppend(""UNDYING!""); break; case PATH_ONE_CRAZY_RANDOM_SUMMER: random_messages.listAppend(""dance the mersenne twist""); break; case PATH_COMMUNITY_SERVICE: random_messages.listAppend(""make the world a better place""); break; case PATH_AVATAR_OF_WEST_OF_LOATHING: random_messages.listAppend(""draw""); break; case PATH_THE_SOURCE: if (my_daycount() % 2 == 0) random_messages.listAppend(""don't think you aren't. know you aren't.""); else random_messages.listAppend(""it is not the spoon that ascends, it is only yourself""); break; case PATH_NUCLEAR_AUTUMN: random_messages.listAppend(""I do want to set the world on "" + HTMLGenerateSpanFont(""fire"", ""red"")); break; case PATH_GELATINOUS_NOOB: random_messages.listAppend(""you jelly?""); break; case PATH_LICENSE_TO_ADVENTURE: random_messages.listAppend(""FOR YOUR EYES ONLY""); break; case PATH_LIVE_ASCEND_REPEAT: random_messages.listAppend(""a single perfect day""); break; case PATH_POCKET_FAMILIARS: random_messages.listAppend(""adorable slaves""); break; case PATH_G_LOVER: random_messages.listAppend(""get going, guuuurl""); break; case PATH_DEMIGUISE: random_messages.listAppend(""who are you?""); break; case PATH_VAMPIRE: random_messages.listAppend(""die monster! you don't belong in this world!""); break; case PATH_2CRS: random_messages.listAppend(""what happened to my inventory?""); break; case PATH_EXPLOSIONS: random_messages.listAppend(""kaboooooom""); break; /*case PATH_CLASS_ACT_3: random_messages.listAppend(""buttons for the people""); break; case PATH_AVATAR_OF_THE_NAUGHTY_SORCERESS: random_messages.listAppend(""go forth to your lair! have some tea""); break;*/ } if (in_ronin() && my_adventures() <= 3) random_messages.listAppend(""always tomorrow""); random_messages.listAppend(""I don't know either, sorry""); string lowercase_player_name = my_name().to_lower_case().HTMLEscapeString(); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""check the wiki"", mapMake(""class"", ""r_a_undecorated"", ""href"", ""http://kol.coldfront.net/thekolwiki/index.php/Main_Page"", ""target"", ""_blank""))); random_messages.listAppend(""the RNG is only trying to "" + ((random(100) == 0) ? ""hurt"" : ""help"")); if (__misc_state[""in run""]) { int choice = gameday_to_int() & 3; if (choice == 0) random_messages.listAppend(""speed ascension is all I have left, "" + lowercase_player_name); else if (choice == 1) random_messages.listAppend(""let the turns go""); else if (choice == 2) random_messages.listAppend(""mostly made up""); else if (choice == 3) random_messages.listAppend(""kingdom of self loathing""); if (my_ascensions() >= 1000) random_messages.listAppend(""dedicated""); } if (item_drop_modifier() <= -100.0) random_messages.listAppend(""let go of your material posessions""); if ($item[puppet strings].item_amount() > 0 && my_id() != 1557284) { //full puppet string support: string chosen_message; switch (gameday_to_int() % 13) { case 0: chosen_message = ""%playername% is easily the most great person ever! three cheers for %playername%!""; break; case 1: chosen_message = ""%playername% is my hero! don't you all agree?""; break; case 2: chosen_message = ""%playername% is such a sexy beast!""; break; case 3: chosen_message = ""%playername% is super-attractive and studly! don't you all agree?""; break; case 4: chosen_message = ""%playername% is super-attractive and studly! just saying that name makes me feel all tingly inside!""; break; case 5: chosen_message = ""who do I think is the best KoLer? obviously\\, it's %playername%! how about a round of applause?""; break; case 6: chosen_message = ""I wish I was as good-looking as %playername%. hip hip hooray!""; break; case 7: chosen_message = ""I'm %playername%'s biggest fan! let's hear it for %playername%!""; break; case 8: chosen_message = ""I've never met anyone as attractive as %playername%! how about a round of applause?""; break; case 9: chosen_message = ""I've never met anyone as studly as %playername%! all the rest of us are totally lame in comparison!""; break; case 10: chosen_message = ""is anyone as fabulous as %playername%? I don't think so! just saying that name makes me feel all tingly inside!""; break; case 11: chosen_message = ""is anyone as intelligent as %playername%? I don't think so! hooray for %playername%!""; break; default: chosen_message = ""%playername% is totally awesome! hooray for %playername%!""; break; } chosen_message = chosen_message.replace_string(""%playername%"", lowercase_player_name); random_messages.listAppend(chosen_message); //random_messages.listAppend(lowercase_player_name + "" is totally awesome! hooray for "" + lowercase_player_name + ""!""); } if (__quest_state[""Level 12""].in_progress && __quest_state[""Level 12""].state_int[""hippies left on battlefield""] < 1000 && __quest_state[""Level 12""].state_int[""frat boys left on battlefield""] < 1000) random_messages.listAppend(""playing sides""); if (__iotms_usable[$item[Order of the Green Thumb Order Form]]) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""the forgotten friar cries himself to sleep"", generateMainLinkMap(""place.php?whichplace=forestvillage&action=fv_friar""))); if (!__misc_state[""skills temporarily missing""] && !$skill[Transcendent Olfaction].skill_is_usable()) { random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""visit the bounty hunter hunter sometime"", generateMainLinkMap(""bounty.php""))); } if (__misc_state[""in aftercore""]) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""ascension is waiting for you"", generateMainLinkMap(""place.php?whichplace=nstower""))); if (my_adventures() == 0) random_messages.listAppend(""nowhere left to go""); if (__quest_state[""Level 11""].in_progress) random_messages.listAppend(""try not to lose your sanity""); if (__quest_state[""Level 13""].in_progress) { if (my_daycount() == 1) random_messages.listAppend(""all the world's work in a day""); else random_messages.listAppend(""it'll be all over soon""); } if (!CounterLookup(""Semi-rare"").CounterIsRange() && CounterLookup(""Semi-rare"").CounterExists() && CounterLookup(""Semi-rare"").exact_turns.count() > 1) random_messages.listAppend(""superpositioned semi-rare""); if (hippy_stone_broken() && pvp_attacks_left() > 0) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""aggressive friendship"", generateMainLinkMap(""peevpee.php""))); if (get_property_boolean(""_warbearGyrocopterUsed"")) random_messages.listAppend(""[gyroseaten] => 109""); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""♫"", mapMake(""class"", ""r_a_undecorated"", ""href"", ""http://www.kingdomofloathing.com/radio.php"", ""target"", ""_blank""))); if (__misc_state_int[""free rests remaining""] > 0) random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""dream your life away"", generateMainLinkMap(__misc_state_string[""resting url""]))); if (get_property_int(""cinderellaScore"") >= 32) random_messages.listAppend(""mother knows best""); if ($location[the shore\\, inc. travel agency].turnsAttemptedInLocation() >= 11) { if (hippy_stone_broken()) random_messages.listAppend(""beware of shorebots""); else random_messages.listAppend(""under a distant shore you will find your answers""); } if (current_hour >= 2 && current_hour <= 3) random_messages.listAppend(""up late?""); else if (current_hour >= 4 && current_hour <= 5) random_messages.listAppend(""zzz...""); else if (current_hour == 6) random_messages.listAppend(""the dawn is your enemy""); random_messages.listAppend(""take chances, be courages, go exploring!""); switch (my_class()) { case $class[disco bandit]: random_messages.listAppend(""making discos of your castles""); break; case $class[seal clubber]: random_messages.listAppend(""I ♣︎ seals""); break; case $class[turtle tamer]: random_messages.listAppend(""friends everywhere you go""); break; case $class[sauceror]: random_messages.listAppend(""journey of the sauceror""); break; case $class[Snake Oiler]: random_messages.listAppend(""ten points to slytherin""); break; } if (numeric_modifier(""hot damage"") <= 0.0 && gameday_to_int() % 4 == 0) random_messages.listAppend(""have you tried "" + HTMLGenerateSpanFont(""fire"", ""red"")); if (__misc_state[""Chateau Mantegna available""] && get_property_monster(""chateauMonster"").phylum == $phylum[fish] && !get_property_boolean(""_chateauMonsterFought"")) { random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""personal aquarium"", generateMainLinkMap(""place.php?whichplace=chateau""))); //WhiteWizard42: feeeeesh. feesh in the waaaall } generateRandomMessageFamiliar(random_messages); if (last_monster().phylum == $phylum[penguin]) { random_messages.listClear(); //sufficiently rare random_messages.listAppend(""dood""); } string [monster] monster_messages; string [monster] beaten_up_monster_messages; //TODO add a message for the procrastination giant foreach m in $monsters[The Temporal Bandit,crazy bastard,Knott Slanding,hockey elemental,Hypnotist of Hey Deze,infinite meat bug,QuickBASIC Elemental,The Master of Thieves,Baiowulf,Count Bakula,The Nuge] //Pooltergeist (Ultra-Rare)? monster_messages[m] = ""an ultra rare! congratulations!""; monster_messages[$monster[The Master of Thieves]] = ""don't @ me""; monster_messages[$monster[Dad Sea Monkee]] = ""is always was always"" + HTMLGenerateSpanFont("" is always was always"", ""#444444"") + HTMLGenerateSpanFont("" is always was always"", ""#888888"") + HTMLGenerateSpanFont("" is always was always"", ""#BBBBBB""); foreach m in $monsters[Ed the Undying (1),Ed the Undying (2),Ed the Undying (3),Ed the Undying (4),Ed the Undying (5),Ed the Undying (6),Ed the Undying (7)] monster_messages[m] = ""UNDYING!""; foreach m in $monsters[Naughty Sorceress, Naughty Sorceress (2), Naughty Sorceress (3)] { if (holidays_today[""Valentine's Day""]) monster_messages[m] = ""please be mine, sorceress""; else monster_messages[m] = ""she isn't all that bad""; } foreach m in $monsters[Shub-Jigguwatt\\, Elder God of Violence,Yog-Urt\\, Elder Goddess of Hatred] monster_messages[m] = ""strange aeons""; monster_messages[$monster[daft punk]] = ""can you feel it?""; monster_messages[$monster[ghastly organist]] = ""phantom of the opera""; monster_messages[$monster[The Man]] = ""let the workers unite""; monster_messages[$monster[The Big Wisniewski]] = ""far out""; monster_messages[$monster[Quiet Healer]] = ""...""; monster_messages[$monster[menacing thug]] = ""watch your back""; monster_messages[$monster[sea cowboy]] = ""pardon me""; monster_messages[$monster[topiary golem]] = ""almost ther... wait, golems?""; monster_messages[$monster[The Server]] = ""console cowboy""; monster_messages[$monster[Fickle Finger of F8]] = ""f/8 and be there""; monster_messages[$monster[malevolent crop circle]] = ""I want to believe""; monster_messages[$monster[Enraged Cow]] = ""moo""; if ($item[bottle of blank-out].is_unrestricted()) monster_messages[$monster[Claybender Sorcerer Ghost]] = ""accio blank-out""; else monster_messages[$monster[Claybender Sorcerer Ghost]] = ""leaderboardus totalus""; monster_messages[$monster[Whatsian Commando Ghost]] = ""captain jack hotness""; if (myPathId() == PATH_ACTUALLY_ED_THE_UNDYING) monster_messages[$monster[Whatsian Commando Ghost]] = ""are you my mummy?""; monster_messages[$monster[Space Tourist Explorer Ghost]] = ""oh my""; monster_messages[$monster[Battlie Knight Ghost]] = ""boring conversation anyway""; monster_messages[$monster[oil slick]] = ""run more ML!""; monster_messages[$monster[Space Marine]] = ""as if it were from an old dream""; monster_messages[$monster[Regret Man]] = ""wasted potential""; monster_messages[$monster[Principal Mooney]] = ""life moves pretty fast""; if (my_turncount() < 11) monster_messages[$monster[family of kobolds]] = ""in a hurry?""; monster_messages[$monster[Black Crayon Spiraling Shape]] = ""be what you're like""; monster_messages[$monster[best-selling novelist]] = ""fiction to escape reality""; monster_messages[$monster[7-Foot Dwarf Replicant]] = ""it's too bad she won't live
but then again, who does?""; monster_messages[$monster[The Avatar of Jarlsberg]] = ""smoked cheese""; monster_messages[$monster[giant sandworm]] = ""walk without rhythm""; monster_messages[$monster[bookbat]] = ""tattered scrap of dignity""; monster_messages[$monster[Urge to Stare at Your Hands]] = "".⃝.⃝""; //.⃝.⃝ if (myPathId() == PATH_HEAVY_RAINS) monster_messages[$monster[pygmy bowler]] = ""right into the gutter""; //come back! monster_messages[$monster[Ron ""The Weasel"" Copperhead]] = ""RONALD WEASLEY! HOW DARE YOU STEAL THAT ZEPPELIN
"" + ChecklistGenerateModifierSpan(""your father's now facing an inquiry at work and it's entirely YOUR FAULT""); monster_messages[$monster[Mr. Loathing]] = HTMLGenerateTagWrap(""a"", ""ruuun! go! get to the towah!"", generateMainLinkMap(""place.php?whichplace=nstower"")); if (my_hp() < my_maxhp()) monster_messages[$monster[Smooth Criminal]] = ""you've been hit by
you've been struck by
a smooth criminal""; monster_messages[$monster[demonic icebox]] = ""zuul""; monster_messages[$monster[angry mushroom guy]] = ""touch fizzy, get dizzy""; beaten_up_monster_messages[$monster[storm cow]] = ""
^__^            
(oo)\\\\_______
(__)\\\\ )\\\\/\\\\
||----w |
|| ||
""; monster_messages[$monster[The Barrelmech of Diogenes]] = ""just let me throw a barrel at it""; //beaten_up_monster_messages[$monster[Lavalos]] = HTMLGenerateTagWrap(""span"", ""but... the future refused to change"", mapMake(""onclick"", ""var l = new Audio('"" + __lavalos_sound_data + ""'); l.play();"", ""class"", ""r_clickable"")); //copyright, etc beaten_up_monster_messages[$monster[Lavalos]] = ""but... the future refused to change""; if ($item[protonic accelerator pack].equipped_amount() > 0 && last_monster().monsterIsGhost()) beaten_up_monster_messages[last_monster()] = ""venkman makes it look easy""; if ($effect[beaten up].have_effect() > 0 && $items[rainbow pearl earring,rainbow pearl necklace,rainbow pearl ring,vampire pearl earring,vampire pearl ring,vampire pearl necklace,freshwater pearl necklace,pearl diver's ring,pearl diver's necklace,pearl necklace].equipped_amount() > 0) beaten_up_monster_messages[last_monster()] = ""WHY WON'T YOU LET ME DO THIS FOR YOU, ROSE?""; if (last_monster().phylum == $phylum[demon]) beaten_up_monster_messages[last_monster()] = ""he made the devil so much stronger than a man!""; if (current_hour >= 5 && current_hour <= 11) monster_messages[$monster[Lavalos]] = ""good morning, "" + lowercase_player_name + ""!""; else monster_messages[$monster[Lavalos]] = ""all life begins with nu and ends with nu""; monster_messages[$monster[sk8 gnome]] = ""he was a sk8 gnome she said see u l8 gnome""; monster_messages[$monster[The Inquisitor]] = ""nothing is up""; monster_messages[$monster[Doc Clock]] = ""your defeat will happen at "" + (current_hour > 12 ? current_hour - 12 : current_hour) + "":"" + current_minute + "" precisely""; // + (current_hour >= 12 ? "" PM"" : "" AM"") monster_messages[lookupMonster(""God Lobster"")] = ""what a grand and intoxicating innocence""; //how can you kill a god? equip the heart of the volcano? monster_messages[lookupMonster(""cockroach"")] = ""are bug exterminators professional assassins?""; string day_cycle; if (current_hour >= 5 && current_hour <= 11) day_cycle = ""morning""; else if (current_hour >= 12 && current_hour <= 16) day_cycle = ""afternoon""; else if (current_hour >= 17 && current_hour <= 20) day_cycle = ""evening""; else day_cycle = ""night""; monster_messages[$monster[Travoltron]] = now_to_string(""EEEE"").to_lower_case() + "" "" + day_cycle + "" fever""; if (my_daycount() == 2 && (my_adventures() == 0 || availableDrunkenness() < 0) && availableFullness() == 0 && availableDrunkenness() <= 0 && myPathId() != PATH_OXYGENARIAN && __quest_state[""Level 12""].started && !__quest_state[""Level 13""].state_boolean[""king waiting to be freed""] && myPathId() != PATH_NUCLEAR_AUTUMN && myPathId() != PATH_SLOW_AND_STEADY && !__quest_state[""Level 13""].finished) { //detect failed two-day runs, and provide psychological support: random_messages.listClear(); if (__quest_state[""Level 13""].started) random_messages.listAppend(""ever so close""); else random_messages.listAppend(""three days is fine""); } boolean already_output_relevant_beaten_up_effect = false; if ((my_hp() == 0 || $effect[beaten up].have_effect() > 0) && beaten_up_monster_messages contains last_monster() && last_monster() != $monster[none]) { random_messages.listClear(); random_messages.listAppend(beaten_up_monster_messages[last_monster()]); already_output_relevant_beaten_up_effect = true; } else if (monster_messages contains last_monster() && last_monster() != $monster[none]) { random_messages.listClear(); random_messages.listAppend(monster_messages[last_monster()]); } if (__quest_state[""Level 13""].state_boolean[""king waiting to be freed""]) { if (myPathId() == PATH_ONE_CRAZY_RANDOM_SUMMER) { random_messages.listClear(); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""roll the dice"", generateMainLinkMap(""place.php?whichplace=nstower""))); } } if (__misc_state_int[""Basement Floor""] == 500) { random_messages.listClear(); random_messages.listAppend(HTMLGenerateTagWrap(""a"", ""open it!"", generateMainLinkMap(""basement.php""))); } string [string] encounter_messages; boolean encounter_override = false; encounter_messages[""It's Always Swordfish""] = ""one two three four five""; encounter_messages[""Meet Frank""] = ""don't trust the skull""; encounter_messages[""The Mirror in the Tower has the View that is True""] = ""shatter the false reality""; encounter_messages[""A Tombstone""] = ""peperony and chease""; encounter_messages[""Witchess Puzzles""] = ""this etch a sketch is hard""; encounter_messages[""Rubbed it the Right Way""] = ""desire incarnate""; if (my_class() == $class[turtle tamer]) { //The Horror... needs disambiguation foreach s in $strings[Nantucket Snapper,Blue Monday,Capital!,Training Day,Boxed In,Duel Nature,Slow Food,A Rolling Turtle Gathers No Moss,Slow Road to Hell,C'mere\\, Little Fella,The Real Victims,Like That Time in Tortuga,Cleansing your Palette,Harem Scarum,Turtle in peril,No Man\\, No Hole,Slow and Steady Wins the Brawl,Stormy Weather,Turtles of the Universe,O Turtle Were Art Thou,Allow 6-8 Weeks For Delivery,Kick the Can,Turtles All The Way Around,More eXtreme Than Usual,Jewel in the Rough,The worst kind of drowning] encounter_messages[s] = ""friend!""; } if (encounter_messages contains get_property(""lastEncounter"")) { random_messages.listClear(); random_messages.listAppend(encounter_messages[get_property(""lastEncounter"")]); encounter_override = true; } if (__quest_state[""Level 12""].in_progress && __quest_state[""Level 12""].state_int[""hippies left on battlefield""] == 1 && __quest_state[""Level 12""].state_int[""frat boys left on battlefield""] == 1) { random_messages.listClear(); random_messages.listAppend(""wossname is waiting""); } if (my_familiar() == $familiar[Helix Fossil]) { buffer generated; string [int] commands; string property_value = get_property(""__voices""); if (property_value.length() > 1) //remove sentinel { if (property_value.char_at(property_value.length() - 1) == ""|"") property_value = property_value.substring(0, property_value.length() - 1); } commands = property_value.split_string_alternate("",""); for i from 0 to 0 { string word; int r = random(100); if (r < 15) word = ""⬆""; //⬆︎ else if (r < 30) word = ""⬇""; //⬇︎ else if (r < 45) word = ""➡""; //➡ else if (r < 60) word = ""⬅""; //⬅︎ else if (r < 75) word = ""A"";// Ⓐ = Ⓐ else if (r < 95) word = ""B""; //Ⓑ = Ⓑ else word = ""start""; commands.listAppend(word); } while (commands.count() > 6) remove commands[commands.listKeyForIndex(0)]; set_property(""__voices"", commands.listJoinComponents("","") + ""|""); //we add an ending sentinel because set_property() will remove "";"" if it's at the end of the string. set_property() is not guaranteed to keep data integrity random_messages.listClear(); string message = commands.listJoinComponents("" ""); message = HTMLGenerateTagWrap(""span"", message, mapMake(""onclick"", ""updatePageAndFireTimer()"", ""class"", ""r_clickable"")); random_messages.listAppend(message); } foreach s in $strings[rainDohMonster,spookyPuttyMonster,cameraMonster,photocopyMonster,envyfishMonster,iceSculptureMonster,crudeMonster,crappyCameraMonster,romanticTarget,chateauMonster] { if (get_property_monster(s) == $monster[Quiet Healer]) { random_messages.listClear(); random_messages.listAppend(""you can't bring her back""); break; } } if (false)//mmg_my_bets().count() > 0) { random_messages.listClear(); random_messages.listAppend(""win some, lose some""); } if ($effect[beaten up].have_effect() > 0 && limit_mode().length() == 0 && !already_output_relevant_beaten_up_effect) { random_messages.listClear(); switch (myPathId()) { case PATH_BEES_HATE_YOU: random_messages.listAppend(""BZZZZZZ""); break; case PATH_ONE_CRAZY_RANDOM_SUMMER: random_messages.listAppend(""tick, tock""); break; case PATH_ACTUALLY_ED_THE_UNDYING: random_messages.listAppend(""DYING!""); break; case PATH_COMMUNITY_SERVICE: random_messages.listAppend(""no good deed goes unpunished""); break; case PATH_AVATAR_OF_WEST_OF_LOATHING: random_messages.listAppend(""shucks""); break; case PATH_LIVE_ASCEND_REPEAT: random_messages.listAppend(""I got you babe""); break; case PATH_LICENSE_TO_ADVENTURE: random_messages.listAppend(""you only live twice""); break; case PATH_THE_SOURCE: random_messages.listAppend(""not like this""); break; case PATH_POCKET_FAMILIARS: random_messages.listAppend(lowercase_player_name + ""! now is not the time to use that!""); break; case PATH_G_LOVER: random_messages.listAppend(""the Gs will continue until morale improves""); break; default: random_messages.listAppend(""ow""); break; } } if (my_turncount() <= 0) { random_messages.listClear(); if (myPathId() == PATH_LIVE_ASCEND_REPEAT) random_messages.listAppend(""I got you babe""); else if (myPathId() == PATH_POCKET_FAMILIARS) random_messages.listAppend(""pika pika!""); else random_messages.listAppend(""find yourself
starting back""); } if (limit_mode() == ""Spelunky"" && !encounter_override) { random_messages.listClear(); if (get_property(""lastEncounter"") == ""Spelunkrifice"" && get_property(""spelunkyStatus"").contains_text(""Buddy: "")) { if (get_property(""spelunkingStatus"").contains_text(""Resourceful Kid"")) random_messages.listAppend(""he's only a child!""); else random_messages.listAppend(""et tu, "" + lowercase_player_name + ""?""); } else random_messages.listAppend(""ascend? yes! play? no!""); } if (limit_mode() == ""batman"" && !encounter_override) { random_messages.listClear(); random_messages.listAppend(""a superstitious, cowardly lot""); } if (format_today_to_string(""yyyyMMdd"") == ""20151021"") //october 21st, 2015 { //kept active for any time travelers random_messages.listClear(); if (get_property(""System.user.country.format"") == ""US"") random_messages.listAppend(""88 MPH
hey, you did it!""); else random_messages.listAppend(""142 km/h
hey, you did it!""); } //Choose: if (random_messages.count() == 0) return ""lack of cleverness""; string chosen_message = """"; //Base message off of the minute, so it doesn't cycle when the page reloads often: chosen_message = random_messages[minute_of_day % random_messages.count()]; return chosen_message; } ",12381,True,2570.401560336231,median "import ""relay/Guide/Support/Item Filter.ash"" void QLevel12Init() { //questL12War //fratboysDefeated, hippiesDefeated //sidequestArenaCompleted, sidequestFarmCompleted, sidequestJunkyardCompleted, sidequestLighthouseCompleted, sidequestNunsCompleted, sidequestOrchardCompleted //warProgress //Sidequests: //state_boolean[""Lighthouse Finished""] //state_boolean[""Orchard Finished""] QuestState state; QuestStateParseMafiaQuestProperty(state, ""questL12War""); if (myPathId() == PATH_COMMUNITY_SERVICE) QuestStateParseMafiaQuestPropertyValue(state, ""finished""); state.quest_name = ""Island War Quest""; state.image_name = ""island war""; state.council_quest = true; state.state_boolean[""Arena Finished""] = (get_property(""sidequestArenaCompleted"") != ""none""); state.state_boolean[""Farm Finished""] = (get_property(""sidequestFarmCompleted"") != ""none""); state.state_boolean[""Junkyard Finished""] = (get_property(""sidequestJunkyardCompleted"") != ""none""); state.state_boolean[""Lighthouse Finished""] = (get_property(""sidequestLighthouseCompleted"") != ""none""); state.state_boolean[""Nuns Finished""] = (get_property(""sidequestNunsCompleted"") != ""none""); state.state_boolean[""Orchard Finished""] = (get_property(""sidequestOrchardCompleted"") != ""none""); state.state_boolean[""War started""] = (state.mafia_internal_step >= 2); state.state_boolean[""War in progress""] = state.state_boolean[""War started""] && !state.finished; state.state_int[""hippies left on battlefield""] = 1000 - get_property_int(""hippiesDefeated""); state.state_int[""frat boys left on battlefield""] = 1000 - get_property_int(""fratboysDefeated""); if (state.finished) { state.state_boolean[""Arena Finished""] = true; state.state_boolean[""Farm Finished""] = true; state.state_boolean[""Junkyard Finished""] = true; state.state_boolean[""Lighthouse Finished""] = true; state.state_boolean[""Nuns Finished""] = true; state.state_boolean[""Orchard Finished""] = true; } if (myPathId() == PATH_EXPLOSIONS) state.state_boolean[""Lighthouse Finished""] = true; int quests_completed_hippy = 0; int quests_completed_frat = 0; foreach s in $strings[sidequestArenaCompleted,sidequestFarmCompleted,sidequestJunkyardCompleted,sidequestLighthouseCompleted,sidequestNunsCompleted,sidequestOrchardCompleted] { string property_value = get_property(s); if (property_value == ""hippy"") quests_completed_hippy += 1; else if (property_value == ""fratboy"") quests_completed_frat += 1; } state.state_int[""Quests completed for hippies""] = quests_completed_hippy; state.state_int[""Quests completed for frat boys""] = quests_completed_frat; if (!state.finished) { //define state.state_string[""Side seemingly fighting for""] //""hippy"", ""frat boys"", ""both"", """" if (state.state_int[""Quests completed for hippies""] > 0) state.state_string[""Side seemingly fighting for""] = ""hippy""; if (state.state_int[""Quests completed for frat boys""] > 0) state.state_string[""Side seemingly fighting for""] = ""frat boys""; if (state.state_int[""hippies left on battlefield""] == 1000 && state.state_int[""frat boys left on battlefield""] != 1000) state.state_string[""Side seemingly fighting for""] = ""hippy""; if (state.state_int[""hippies left on battlefield""] != 1000 && state.state_int[""frat boys left on battlefield""] == 1000) state.state_string[""Side seemingly fighting for""] = ""frat boys""; if (state.state_int[""hippies left on battlefield""] != 1000 && state.state_int[""frat boys left on battlefield""] != 1000) state.state_string[""Side seemingly fighting for""] = ""both""; if (state.state_int[""Quests completed for hippies""] > 0 && state.state_int[""Quests completed for frat boys""] > 0) state.state_string[""Side seemingly fighting for""] = ""both""; } if (false) { //Internal debugging: state.state_boolean[""Arena Finished""] = false; state.state_boolean[""Farm Finished""] = false; state.state_boolean[""Junkyard Finished""] = false; state.state_boolean[""Lighthouse Finished""] = false; state.state_boolean[""Nuns Finished""] = false; state.state_boolean[""Orchard Finished""] = false; } if (my_level() >= 12 && myPathId() != PATH_EXPLOSIONS) state.startable = true; __quest_state[""Level 12""] = state; __quest_state[""Island War""] = state; } void QLevel12GenerateTasksSidequests(ChecklistEntry [int] task_entries, ChecklistEntry [int] optional_task_entries, ChecklistEntry [int] future_task_entries) { QuestState base_quest_state = __quest_state[""Level 12""]; if (!base_quest_state.state_boolean[""Orchard Finished""]) { string [int] details; string [int] modifiers; string url = ""bigisland.php?place=orchard""; modifiers.listAppend(""+1000% item""); if (__misc_state[""yellow ray potentially available""]) modifiers.listAppend(""potential YR""); location next_location; monster pickpocket_monster = $monster[none]; boolean need_gland = false; if ($item[heart of the filthworm queen].available_amount() > 0) { modifiers.listClear(); details.listAppend(""Go talk to the hippies to complete quest.""); } else if ($effect[Filthworm Guard Stench].have_effect() > 0 || $item[Filthworm royal guard scent gland].available_amount() > 0) { if ($effect[Filthworm Guard Stench].have_effect() == 0) { url = ""inventory.php?ftext=filthworm+royal+guard+scent+gland""; details.listAppend(""Use filthworm royal guard scent gland.""); } modifiers.listClear(); modifiers.listAppend(""+meat""); details.listAppend(""Defeat the filthworm queen in the queen's chamber.""); next_location = $location[the filthworm queen's chamber]; } else if ($effect[Filthworm Drone Stench].have_effect() > 0 || $item[Filthworm drone scent gland].available_amount() > 0) { if ($effect[Filthworm Drone Stench].have_effect() == 0) { url = ""inventory.php?ftext=filthworm+drone+scent+gland""; details.listAppend(""Use filthworm drone scent gland""); } details.listAppend(""Adventure with +item in the guards' chamber.""); need_gland = true; pickpocket_monster = $monster[filthworm royal guard]; next_location = $location[the royal guard chamber]; } else if ($effect[Filthworm Larva Stench].have_effect() > 0 || $item[filthworm hatchling scent gland].available_amount() > 0) { if ($effect[Filthworm Larva Stench].have_effect() == 0) { url = ""inventory.php?ftext=filthworm+hatchling+scent+gland""; details.listAppend(""Use filthworm hatchling scent gland""); } details.listAppend(""Adventure with +item in the feeding chamber.""); need_gland = true; pickpocket_monster = $monster[filthworm drone]; next_location = $location[the feeding chamber]; } else { details.listAppend(""Adventure with +item in the hatching chamber.""); need_gland = true; pickpocket_monster = $monster[larval filthworm]; next_location = $location[the hatching chamber]; } if (__misc_state[""can pickpocket""] && pickpocket_monster != $monster[none]) { int total_initiative_needed = pickpocket_monster.base_initiative; int initiative_needed = total_initiative_needed - initiative_modifier(); if (initiative_needed > 0) details.listAppend(""Need "" + initiative_needed + ""% more initiative to pickpocket every turn.""); } if (need_gland) { float effective_item_drop = next_location.item_drop_modifier_for_location() / 100.0; //FIXME take into account pickpocketing, init, etc. float average_glands_found_per_combat = MIN(1.0, (effective_item_drop + 1.0) * 0.1); float turns_per_gland = -1.0; if (average_glands_found_per_combat != 0.0) turns_per_gland = 1.0 / average_glands_found_per_combat; details.listAppend(""~"" + roundForOutput(turns_per_gland, 1) + "" turns per gland.""); } optional_task_entries.listAppend(ChecklistEntryMake(""Island War Orchard"", url, ChecklistSubentryMake(""Island War Orchard Quest"", modifiers, details), $locations[the hatching chamber, the feeding chamber, the royal guard chamber, the filthworm queen's chamber])); } if (!base_quest_state.state_boolean[""Farm Finished""]) { string [int] details; details.listAppend(""Great flappin' beasts, with webbed feet and bills! dooks!""); string [int] modifiers; modifiers.listAppend(""+meat""); string [int] tasks; int ncs_seen = $location[McMillicancuddy's Barn].noncombatTurnsAttemptedInLocation(); if (ncs_seen < 3) { tasks.listAppend(""make a fence out of the barbed wire""); tasks.listAppend(""knock over the lantern""); tasks.listAppend(""dump out the drum""); details.listAppend(""Remember to use a chaos butterfly in combat before clearing the barn.|Then "" + tasks.listJoinComponents("", "", ""and"") + "".""); if (__misc_state[""free runs available""]) modifiers.listAppend(""free runs in barn""); } optional_task_entries.listAppend(ChecklistEntryMake(""Island War Farm"", ""bigisland.php?place=farm"", ChecklistSubentryMake(""Island War Farm Quest"", modifiers, details), $locations[mcmillicancuddy's farm,mcmillicancuddy's barn,mcmillicancuddy's pond,mcmillicancuddy's back 40,mcmillicancuddy's other back 40,mcmillicancuddy's granary,mcmillicancuddy's bog,mcmillicancuddy's family plot,mcmillicancuddy's shady thicket])); } if (!base_quest_state.state_boolean[""Nuns Finished""]) { string [int] details; int meat_gotten = get_property_int(""currentNunneryMeat""); int meat_remaining = 100000 - meat_gotten; details.listAppend(meat_remaining + "" meat remaining.""); float meat_drop_multiplier = meat_drop_modifier() / 100.0 + 1.0; vec2i brigand_meat_drop_range = vec2iMake(800 * meat_drop_multiplier, 1200 * meat_drop_multiplier); vec2i turn_range; if (brigand_meat_drop_range.x != 0 && brigand_meat_drop_range.y != 0) turn_range = vec2iMake(ceil(to_float(meat_remaining) / to_float(brigand_meat_drop_range.y)), ceil(to_float(meat_remaining) / to_float(brigand_meat_drop_range.x))); if (myPathId() == PATH_2CRS) turn_range = Vec2iMake(MAX(100, turn_range.x), MAX(100, turn_range.y)); string turns_extra = "".""; string [int] extra_details; if (get_property(""boomBoxSong"") == ""Total Eclipse of Your Meat"") { vec2i brigand_meat_drop_range_sing = vec2iMake(820 * meat_drop_multiplier, 1230 * meat_drop_multiplier); vec2i turn_range_sing; if (brigand_meat_drop_range_sing.x != 0 && brigand_meat_drop_range_sing.y != 0) turn_range_sing = vec2iMake(ceil(to_float(meat_remaining) / to_float(brigand_meat_drop_range_sing.y)), ceil(to_float(meat_remaining) / to_float(brigand_meat_drop_range_sing.x))); turns_extra = "", if you don't sing.""; if (turn_range_sing.x == turn_range.x && turn_range_sing.y == turn_range.y) { turns_extra = "".""; } else if (turn_range_sing.x == turn_range_sing.y) details.listAppend(pluralise(turn_range_sing.x, ""turn"", ""turns"") + "" remaining, if you sing.""); else details.listAppend(""["" + turn_range_sing.x + "" to "" + turn_range_sing.y + ""] turns remaining, if you sing.""); extra_details.listAppend(""Be sure to Sing Along with your boombox every turn.""); /*float without = meat_remaining / (1000.0 * meat_drop_multiplier); float with = meat_remaining / (1025.0 * meat_drop_multiplier); details.listAppend(""Singing saves "" + (without - with) + "" turns."");*/ } //FIXME consider looking into tracking how long until the semi-rare item runs out, for turn calculation if (turn_range.x == turn_range.y) details.listAppend(pluralise(turn_range.x, ""turn"", ""turns"") + "" remaining"" + turns_extra); else details.listAppend(""["" + turn_range.x + "" to "" + turn_range.y + ""] turns remaining"" + turns_extra); if (turn_range.x == 1 && turn_range.y == 2) { float chance = 1.0 - TriangularDistributionCalculateCDF(meat_remaining + 1, brigand_meat_drop_range.x, brigand_meat_drop_range.y); details.listAppend((chance * 100.0).floor() + ""% chance of completing in one turn.""); } if ($item[ice nine].available_amount() == 0 && __misc_state[""can equip just about any weapon""] && $item[ice harvest].available_amount() >= 9 && $item[ice nine].is_unrestricted() && $item[miracle whip].available_amount() == 0) //is this safe? unfinished ice sculpture is really nice, and ice bucket in sneaky pete... details.listAppend(""Possibly make and equip an ice nine. (+30% meat 1h weapon)""); if ($effect[Sinuses For Miles].have_effect() > 0 && !get_property_ascension(""lastTempleAdventures"") && $item[stone wool].available_amount() > 0 && get_property_ascension(""lastTempleUnlock"")) details.listAppend(""Potentially use stone wool and visit the hidden temple to extend Sinuses for Miles for 3 turns.""); if (myPathId() == PATH_HEAVY_RAINS && $skill[Make it Rain].skill_is_usable() && turn_range.y > 1) details.listAppend(""Cast Make it Rain each fight. (+300%? meat)""); if ($item[Sneaky Pete's leather jacket (collar popped)].equipped_amount() > 0 && turn_range.y > 1) details.listAppend(""Could unpop your collar. (+20% meat)""); if (__misc_state_int[""pulls available""] > 0 && meat_drop_modifier() < 1000.0) { int limit = 100; if (meat_drop_modifier() < 800.0) limit = 50; if (myPathId() == PATH_G_LOVER) limit = 25; limit = 0; //show them all - we'll go based off of turns saved boolean [item] blacklist = $items[uncle greenspan's bathroom finance guide,black snowcone]; item [int] relevant_potions = ItemFilterGetPotionsCouldPullToAddToNumericModifier(""Meat Drop"", limit, blacklist); string [int] relevant_potions_output; float average_turns_currently = meat_remaining / ((meat_drop_modifier() / 100.0 + 1.0) * 1000.0); foreach key, it in relevant_potions { effect e = it.to_effect(); if (!e.effect_is_usable()) continue; if (!it.item_is_usable()) continue; //average_turns_currently - float meat_dropped_per_turn_with_item = ((meat_drop_modifier() + e.numeric_modifier(""meat drop"")) / 100.0 + 1.0) * 1000.0; float turns_saved = average_turns_currently - meat_remaining / meat_dropped_per_turn_with_item; if (turns_saved < 1.0) continue; relevant_potions_output.listAppend(it + "" ("" + e.numeric_modifier(""meat drop"").roundForOutput(0) + ""%, "" + turns_saved.roundForOutput(1) + "" turns saved)""); } if (relevant_potions_output.count() > 0) details.listAppend(""Could try pulling "" + relevant_potions_output.listJoinComponents("", "", ""or"") + "".""); } details.listAppendList(extra_details); optional_task_entries.listAppend(ChecklistEntryMake(""Island War Nuns"", ""bigisland.php?place=nunnery"", ChecklistSubentryMake(""Island War Nuns Quest"", ""+meat"", details), $locations[the themthar hills])); } if (!base_quest_state.state_boolean[""Junkyard Finished""]) { string [int] details; if ($item[molybdenum magnet].available_amount() == 0) { details.listAppend(""Talk to Yossarian first.""); } else { location [item] items_and_locations; items_and_locations[$item[molybdenum hammer]] = $location[Next to that Barrel with Something Burning in it]; items_and_locations[$item[molybdenum pliers]] = $location[Near an Abandoned Refrigerator]; items_and_locations[$item[molybdenum crescent wrench]] = $location[Over Where the Old Tires Are]; items_and_locations[$item[molybdenum screwdriver]] = $location[Out By that Rusted-Out Car]; boolean have_all = true; string [location][int] location_monsters; location_monsters[$location[Next to that Barrel with Something Burning in it]] = listMake(""tool batwinged"", ""vegetable""); location_monsters[$location[Out By that Rusted-Out Car]] = listMake(""tool vegetable"", ""erudite""); location_monsters[$location[Near an Abandoned Refrigerator]] = listMake(""tool spider"", ""batwinged""); location_monsters[$location[Over Where the Old Tires Are]] = listMake(""tool erudite"", ""spider""); location [int][monster] banishment_locations; //it's time we had a talk... about your hair! it's gone too far! banishment_locations[1][$monster[batwinged gremlin]] = $location[Near an Abandoned Refrigerator]; banishment_locations[1][$monster[erudite gremlin]] = $location[Out By that Rusted-Out Car]; banishment_locations[1][$monster[spider gremlin]] = $location[Over Where the Old Tires Are]; banishment_locations[1][$monster[vegetable gremlin]] = $location[Next to that Barrel with Something Burning in it]; banishment_locations[0][$monster[batwinged gremlin]] = $location[Next to that Barrel with Something Burning in it]; banishment_locations[0][$monster[erudite gremlin]] = $location[Over Where the Old Tires Are]; banishment_locations[0][$monster[spider gremlin]] = $location[Near an Abandoned Refrigerator]; banishment_locations[0][$monster[vegetable gremlin]] = $location[Out By that Rusted-Out Car]; foreach key in banishment_locations { foreach m in banishment_locations[key] { if (!m.is_banished()) continue; location l = banishment_locations[key][m]; if (key == 0 && location_monsters[l][key].contains_text(""tool "")) location_monsters[l][key] = ""tool "" + HTMLGenerateSpanFont(location_monsters[l][key].replace_string(""tool "", """"), ""grey"", """"); else location_monsters[l][key] = HTMLGenerateSpanFont(location_monsters[l][key], ""grey""); } } item [int] item_display_order = listMake($item[molybdenum hammer],$item[molybdenum pliers],$item[molybdenum crescent wrench],$item[molybdenum screwdriver]); //make a path string [int] areas_left_strings; //foreach it in items_and_locations string [location] location_shorthand_name; location_shorthand_name[$location[Next to that Barrel with Something Burning in it]] = ""Barrel""; location_shorthand_name[$location[Out By that Rusted-Out Car]] = ""Car""; location_shorthand_name[$location[Near an Abandoned Refrigerator]] = ""Refrigerator""; location_shorthand_name[$location[Over Where the Old Tires Are]] = ""Tires""; foreach key in item_display_order { item it = item_display_order[key]; location loc = items_and_locations[it]; if (it.available_amount() > 0) { continue; } else have_all = false; string location_display_name; if (location_shorthand_name contains loc) location_display_name = location_shorthand_name[loc]; else location_display_name = loc.to_string().to_lower_case(); areas_left_strings.listAppend("""" + location_display_name + "" - "" + location_monsters[loc].listJoinComponents("", "")); } if (areas_left_strings.count() > 0) details.listAppend(""Areas left:|*"" + areas_left_strings.listJoinComponents(""
|*"")); if (have_all) details.listAppend(""Talk to Yossarian to complete quest.""); else { if ($item[dictionary].available_amount() > 0 && $item[dictionary].item_is_usable()) { details.listAppend(""Read from the dictionary to stasis gremlins.""); } else if ($item[facsimile dictionary].available_amount() > 0 && $item[facsimile dictionary].item_is_usable()) { details.listAppend(""Read from the facsimile dictionary to stasis gremlins.""); } else if ($item[seal tooth].available_amount() > 0 && $item[seal tooth].item_is_usable()) { details.listAppend(""Use your seal tooth to stasis gremlins.""); } else if ($skill[suckerpunch].skill_is_usable()) { details.listAppend(""Cast suckerpunch to stasis gremlins.""); } else if ($item[seal tooth].item_is_usable()) details.listAppend(HTMLGenerateSpanFont(""Acquire a seal tooth"", ""red"") + "" to stasis gremlins. (from hermit)""); else if ($item[beehive].available_amount() > 0) details.listAppend(""Use your beehive to stasis gremlins.""); if (!$monster[A.M.C. gremlin].is_banished()) details.listAppend(""Potentially banish A.M.C. Gremlin.""); } } optional_task_entries.listAppend(ChecklistEntryMake(""Island War Junkyard"", ""bigisland.php?place=junkyard"", ChecklistSubentryMake(""Island War Junkyard Quest"", listMake(""+DR"", ""+DA"", ""+HP"", ""+moxie""), details), $locations[next to that barrel with something burning in it,near an abandoned refrigerator,over where the old tires are,out by that rusted-out car])); } if (!base_quest_state.state_boolean[""Lighthouse Finished""]) { string [int] details; int gunpowder_needed = MAX(0, 5 - $item[barrel of gunpowder].available_amount()); string [int] modifiers; if (gunpowder_needed > 0) { modifiers = listMake(""+combat"", ""copies""); if (gunpowder_needed == 1) details.listAppend(""Need "" + gunpowder_needed + "" more barrel of gunpowder.""); else details.listAppend(""Need "" + gunpowder_needed + "" more barrels of gunpowder.""); //this is an approximation: //off by a little over half a turn on average float effective_combat_rate = (11.0 / 12.0) * clampNormalf(0.1 + combat_rate_modifier() / 100.0) + (1.0 / 12.0) * 1.0; float turns_per_lobster = -1.0; if (effective_combat_rate != 0.0) turns_per_lobster = 1.0 / effective_combat_rate; float turns_to_complete = gunpowder_needed.to_float() * turns_per_lobster; //I had the data lying around, so why not? //misses <-10 and >30, but the estimate above will catch that float [int][int] lfm_simulation_data; lfm_simulation_data[5][-10] = 60.00; lfm_simulation_data[5][-5] = 40.02; lfm_simulation_data[5][0] = 29.92; lfm_simulation_data[5][5] = 23.84; lfm_simulation_data[5][10] = 19.76; lfm_simulation_data[5][15] = 16.84; lfm_simulation_data[5][20] = 14.66; lfm_simulation_data[5][25] = 13.00; lfm_simulation_data[4][-10] = 48.00; lfm_simulation_data[4][-5] = 32.27; lfm_simulation_data[4][0] = 24.20; lfm_simulation_data[4][5] = 19.29; lfm_simulation_data[4][10] = 16.00; lfm_simulation_data[4][15] = 13.68; lfm_simulation_data[4][20] = 11.96; lfm_simulation_data[4][25] = 10.63; lfm_simulation_data[3][-10] = 36.00; lfm_simulation_data[3][-5] = 24.53; lfm_simulation_data[3][0] = 18.47; lfm_simulation_data[3][5] = 14.78; lfm_simulation_data[3][10] = 12.34; lfm_simulation_data[3][15] = 10.59; lfm_simulation_data[3][20] = 9.26; lfm_simulation_data[3][25] = 8.20; lfm_simulation_data[2][-10] = 24.00; lfm_simulation_data[2][-5] = 16.79; lfm_simulation_data[2][0] = 12.84; lfm_simulation_data[2][5] = 10.38; lfm_simulation_data[2][10] = 8.68; lfm_simulation_data[2][15] = 7.40; lfm_simulation_data[2][20] = 6.40; lfm_simulation_data[2][25] = 5.60; lfm_simulation_data[1][-10] = 12.00; lfm_simulation_data[1][-5] = 9.19; lfm_simulation_data[1][0] = 7.17; lfm_simulation_data[1][5] = 5.72; lfm_simulation_data[1][10] = 4.66; lfm_simulation_data[1][15] = 3.87; lfm_simulation_data[1][20] = 3.29; lfm_simulation_data[1][25] = 2.84; lfm_simulation_data[5][26] = 12.71; lfm_simulation_data[5][27] = 12.44; lfm_simulation_data[5][28] = 12.18; lfm_simulation_data[5][29] = 11.93; lfm_simulation_data[5][30] = 11.69; lfm_simulation_data[4][26] = 10.40; lfm_simulation_data[4][27] = 10.17; lfm_simulation_data[4][28] = 9.96; lfm_simulation_data[4][29] = 9.75; lfm_simulation_data[4][30] = 9.56; lfm_simulation_data[3][26] = 8.01; lfm_simulation_data[3][27] = 7.83; lfm_simulation_data[3][28] = 7.65; lfm_simulation_data[3][29] = 7.48; lfm_simulation_data[3][30] = 7.32; lfm_simulation_data[2][26] = 5.46; lfm_simulation_data[2][27] = 5.33; lfm_simulation_data[2][28] = 5.20; lfm_simulation_data[2][29] = 5.07; lfm_simulation_data[2][30] = 4.96; lfm_simulation_data[1][26] = 2.76; lfm_simulation_data[1][27] = 2.69; lfm_simulation_data[1][28] = 2.62; lfm_simulation_data[1][29] = 2.56; lfm_simulation_data[1][30] = 2.50; if (lfm_simulation_data[gunpowder_needed] contains combat_rate_modifier().to_int()) { turns_to_complete = lfm_simulation_data[gunpowder_needed][combat_rate_modifier().to_int()]; if (gunpowder_needed != 0.0) turns_per_lobster = turns_to_complete / gunpowder_needed.to_float(); } details.listAppend(""~"" + roundForOutput(turns_to_complete, 1) + "" turns to complete quest at "" + combat_rate_modifier().floor() + ""% combat.|~"" + roundForOutput(turns_per_lobster, 1) + "" turns per lobster.""); if ($skill[meteor lore].have_skill() && get_property_int(""_macrometeoriteUses"") < 10) { details.listAppend(""Could use macrometeorite on a wandering monster (portscan, voting) to guarantee an LFM.""); if (lookupItem("""I Voted!" sticker"").available_amount() > 0 && get_property_int(""_voteFreeFights"") >= 3) { if (total_turns_played() % 11 == 1 && get_property_int(""lastVoteMonsterTurn"") < total_turns_played()) { details.listAppend(""Voting monster now!""); } else { int turns_to_next_voting_monster = 11 - (((total_turns_played() % 11) - 1 + 11) % 11); details.listAppend(""Voting monster will appear in "" + pluralise(turns_to_next_voting_monster, ""more turn"", ""more turns"") + "".""); } } } } else details.listAppend(""Talk to the lighthouse keeper to finish quest.""); optional_task_entries.listAppend(ChecklistEntryMake(""Island War Lighthouse"", ""bigisland.php?place=lighthouse"", ChecklistSubentryMake(""Island War Lighthouse Quest"", modifiers, details), $locations[sonofa beach])); } if (!base_quest_state.state_boolean[""Arena Finished""] && myPathId() != PATH_G_LOVER && myPathId() != PATH_POCKET_FAMILIARS) { string [int] modifiers; modifiers.listAppend(""+ML""); float percent_done = clampf(get_property_int(""flyeredML"") / 10000.0 * 100.0, 0.0, 100.0); int ml_remaining = 10000 - get_property_int(""flyeredML""); string [int] details; if (percent_done >= 100.0) { modifiers.listClear(); details.listAppend(""Turn in quest.""); } else { if ($item[jam band flyers].available_amount() == 0 && $item[rock band flyers].available_amount() == 0) details.listAppend(""Acquire fliers.""); details.listAppend(round(percent_done, 1) + ""% ML completed, "" + ml_remaining + "" ML remains.""); } //Normally, this would be bigisland.php?place=concert //But that could theoretically complete the quest for the wrong side, if they're wearing the wrong uniform and misclick. optional_task_entries.listAppend(ChecklistEntryMake(""Island War Arena"", ""bigisland.php"", ChecklistSubentryMake(""Island War Arena Quest"", modifiers, details))); if (ml_remaining > 0 && ($item[jam band flyers].available_amount() > 0 || $item[rock band flyers].available_amount() > 0)) { item it = $item[jam band flyers]; if ($item[rock band flyers].available_amount() > 0 && $item[jam band flyers].available_amount() == 0) it = $item[rock band flyers]; task_entries.listAppend(ChecklistEntryMake(it, """", ChecklistSubentryMake(""Flyer with "" + it + "" every combat"", ""+ML"", details), -11)); } } } void QLevel12GenerateBattlefieldDescription(ChecklistSubentry subentry, string side, int enemies_remaining, int enemies_defeated_per_combat, string enemy_name, string enemy_name_plural, string boss_name, string [int] sidequest_list, string [int] base_sidequest_list) { if (enemies_defeated_per_combat == 0) return; int enemies_defeated = 1000 - enemies_remaining; string line; if (enemies_remaining > 0) { line = pluralise(enemies_remaining, enemy_name, enemy_name_plural) + "" left.""; } else { line += ""Fight "" + boss_name + ""!""; if (myPathId() == PATH_DEMIGUISE && $effect[Flared Nostrils].have_effect() > 0) line += ""|"" + HTMLGenerateSpanFont(""Remove Flared Nostrils"", ""red"") + "" or you will die.""; if (myPathId() == PATH_DEMIGUISE) { int damage_taken = 0; damage_taken += ceil(my_maxhp() * 2.0 * (1.0 - elemental_resistance($element[stench]) / 100.0)); if ($effect[flared nostrils].have_effect() > 0) damage_taken += ceil(my_maxhp() * 2.0 * 2.0); else damage_taken += ceil(my_maxhp() * 2.0 * (1.0 - elemental_resistance($element[sleaze]) / 100.0)); subentry.modifiers.listAppend(HTMLGenerateSpanOfClass(""+stench res"", ""r_element_stench_desaturated"")); subentry.modifiers.listAppend(HTMLGenerateSpanOfClass(""+sleaze res"", ""r_element_sleaze_desaturated"")); line += ""|Will take "" + damage_taken + "" damage at the start of combat""; if (damage_taken >= my_maxhp()) line += "", "" + HTMLGenerateSpanFont(""which you cannot survive"", ""red""); line += "".""; line += ""|Run "" + HTMLGenerateSpanOfClass(""stench"", ""r_element_stench"") + "" and "" + HTMLGenerateSpanOfClass(""sleaze"", ""r_element_sleaze"") + "" resistance.""; if (my_hp() != my_maxhp()) line += ""|"" + HTMLGenerateSpanFont(""Also restore your HP."", ""red""); } } string outfit_name; if (side == ""hippy"") outfit_name = ""War Hippy Fatigues""; if (side == ""frat boy"") outfit_name = ""Frat Warrior Fatigues""; if (outfit_name != """") { item [int] missing_outfit_components = missing_outfit_components(outfit_name); if (missing_outfit_components.count() > 0) line += ""|*Missing outfit piece"" + (missing_outfit_components.count() > 1 ? ""s"" : """") + "" "" + missing_outfit_components.listJoinComponents("", "", ""and"") + "".""; } int turns_remaining = ceiling(enemies_remaining.to_float() / enemies_defeated_per_combat.to_float()); if (turns_remaining > 0) { line += ""|*"" + pluralise(turns_remaining, ""turn"", ""turns"") + "" remaining.""; line += "" "" + pluralise(enemies_defeated_per_combat, enemy_name, enemy_name_plural) + "" defeated per combat.""; } int enemies_to_defeat_for_unlock = -1; string area_to_unlock = """"; string [int] areas_unlocked_but_not_completed; boolean [string] areas_blocked; if (myPathId() == PATH_G_LOVER || myPathId() == PATH_POCKET_FAMILIARS) areas_blocked[""Arena""] = true; foreach key, sidequest in base_sidequest_list { if (areas_blocked[sidequest]) continue; if (!__quest_state[""Level 12""].state_boolean[sidequest + "" Finished""]) { areas_unlocked_but_not_completed.listAppend(sidequest); } } if (myPathId() != PATH_BUGBEAR_INVASION) //FIXME test against trendy bugbear chef being needed { if (side == ""frat boy"" && __misc_state[""free runs usable""]) subentry.modifiers.listAppend(""possibly olfact Green Ops Soldier""); else if (side == ""hippy"") subentry.modifiers.listAppend(""possibly olfact Sorority Operator""); } int [int] unlock_threshold; unlock_threshold[0] = 64; unlock_threshold[1] = 192; unlock_threshold[2] = 458; for i from 2 to 0 by -1 { int threshold = unlock_threshold[i]; if (areas_blocked[sidequest_list[i]]) continue; if (!__quest_state[""Level 12""].state_boolean[sidequest_list[i] + "" Finished""]) { if (enemies_defeated < threshold) { area_to_unlock = sidequest_list[i]; enemies_to_defeat_for_unlock = threshold - enemies_defeated; } else { areas_unlocked_but_not_completed.listAppend(sidequest_list[i]); } } } if (enemies_to_defeat_for_unlock != -1) { int turns_to_reach = ceiling(enemies_to_defeat_for_unlock.to_float() / enemies_defeated_per_combat.to_float()); line += ""|*"" + pluralise(turns_to_reach, ""turn"", ""turns"") + "" ("" + pluralise(enemies_to_defeat_for_unlock, enemy_name, enemy_name_plural) + "") to unlock "" + area_to_unlock + "".""; } if (areas_unlocked_but_not_completed.count() > 0 && enemies_remaining > 0) line += ""|*Quests accessible: "" + areas_unlocked_but_not_completed.listJoinComponents("", "", ""and"") + "".""; subentry.entries.listAppend(line); if (enemies_remaining == 0) { string [int] items_to_turn_in_for; if (__quest_state[""Level 13""].state_boolean[""shadow will need to be defeated""]) { if (side == ""hippy"") items_to_turn_in_for.listAppend(""filthy poultices for shadow""); else items_to_turn_in_for.listAppend(""gauze garters for shadow""); } string line2 = ""Also, turn in gear to your home camp.""; if (items_to_turn_in_for.count() > 0) line2 += "" Acquire "" + items_to_turn_in_for.listJoinComponents("", "", ""and"") + "", etc.""; subentry.entries.listAppend(line2); } } void QLevel12ExplosionsGenerateTasks(ChecklistEntry [int] task_entries, ChecklistEntry [int] optional_task_entries, ChecklistEntry [int] future_task_entries) { if (myPathId() != PATH_EXPLOSIONS) return; if (QuestState(""questL12HippyFrat"").finished) return; string [int] description; string url = ""place.php?whichplace=exploathing""; int fratboys_defeated = get_property_int(""fratboysDefeated""); int hippies_defeated = get_property_int(""hippiesDefeated""); int fratboys_left = clampi(333 - fratboys_defeated, 0, 333); int hippies_left = clampi(333 - hippies_defeated, 0, 333); if (!have_outfit_components(""War Hippy Fatigues"") && !have_outfit_components(""Frat Warrior Fatigues"")) description.listAppend(""Find a uniform. Either calculate the universe 151st + YR, wish + YR?, pull, or yellow-ray a battlefield enemy with the outfit?""); else if (!is_wearing_outfit(""War Hippy Fatigues"") && !is_wearing_outfit(""Frat Warrior Fatigues"")) { description.listAppend(""Equip a war outfit first.""); url = ""inventory.php?which=2""; } if ($items[jacob's rung,haunted paddle-ball].available_amount() == 0) { description.listAppend((!in_hardcore() ? ""Pull/"" : """") + ""YR a jacob's rung or haunted paddle-ball, from the top floor of spookyraven manor.|Jacob's adder in the Haunted Laboratory or possessed toy chest in the The Haunted Nursery have them.""); } else if ($items[jacob's rung,haunted paddle-ball].equipped_amount() == 0) { if ($item[haunted paddle-ball].have()) { description.listAppend(""Equip haunted paddle-ball first.""); url = ""inventory.php?ftext=haunted+paddle-ball""; } else if ($item[jacob's rung].have()) { description.listAppend(""Equip jacob's rung first.""); url = ""inventory.php?ftext=jacob's+rung""; } } boolean likely_fighting_frats = false; if (fratboys_defeated > 0 && fratboys_defeated > hippies_defeated) { likely_fighting_frats = true; if (fratboys_left <= 0) description.listAppend(""Fight the Man!""); else description.listAppend(""Defeat "" + pluralise(fratboys_left, ""more fratboy"", ""more fratboys"") + "".""); } else { if (hippies_left <= 0) description.listAppend(""Fight the Big Wisniewski!""); else description.listAppend(""Defeat "" + pluralise(hippies_left, ""more hippy"", ""more hippies"") + "".""); } int battlefield_turns = lookupLocation(""The Exploaded Battlefield"").turns_spent; int turns_until_next_war_nc = -1; if (battlefield_turns < 7) turns_until_next_war_nc = 7 - battlefield_turns; else { turns_until_next_war_nc = (battlefield_turns + 7) % 7; if (turns_until_next_war_nc != 0) turns_until_next_war_nc = 7 - turns_until_next_war_nc; } if (turns_until_next_war_nc == 0) { description.listAppend(""Non-combat now. Throw high-adventure consumable to speed up war.""); } else description.listAppend(pluraliseWordy(turns_until_next_war_nc, ""More Turn"", ""more turns"").capitaliseFirstLetter() + "" until war NC.""); if (likely_fighting_frats) { if (lookupItems(""space wine"").available_amount() == 0) description.listAppend(""Buy some space wine for the non-combat.""); } else { if (lookupItems(""pie man was not meant to eat,space chowder"").available_amount() == 0) description.listAppend(""Buy some space chowder for the non-combat.""); } task_entries.listAppend(ChecklistEntryMake(""island war"", url, ChecklistSubentryMake(""War!"", """", description), 0)); } void QLevel12GenerateTasks(ChecklistEntry [int] task_entries, ChecklistEntry [int] optional_task_entries, ChecklistEntry [int] future_task_entries) { if (myPathId() == PATH_EXPLOSIONS) QLevel12ExplosionsGenerateTasks(task_entries, optional_task_entries, future_task_entries); if (!__quest_state[""Level 12""].in_progress) return; QuestState base_quest_state = __quest_state[""Level 12""]; ChecklistSubentry subentry; subentry.header = base_quest_state.quest_name; task_entries.listAppend(ChecklistEntryMake(base_quest_state.image_name, ""island.php"", subentry, $locations[the battlefield (frat uniform), the battlefield (hippy uniform), frat house, hippy camp, wartime frat house, wartime frat house (hippy disguise), wartime hippy camp, wartime hippy camp (frat disguise)])); if (base_quest_state.mafia_internal_step < 2) { subentry.modifiers.listAppend(""-combat""); subentry.entries.listAppend(""Start the war!""); float noncombat_rate = 1.0 - (.85 + combat_rate_modifier() / 100.0); float turns_remaining = -1.0; if (noncombat_rate != 0.0) turns_remaining = 3.0 / noncombat_rate; if (!have_outfit_components(""War Hippy Fatigues"") && !have_outfit_components(""Frat Warrior Fatigues"")) { //FIXME suggest routes to doing both. subentry.entries.listAppend(""Need either the war hippy fatigues or frat warrior fatigues outfit.""); if ($familiar[slimeling].familiar_is_usable()) subentry.modifiers.listAppend(""slimeling?""); } else { string [int] stats_needed; if (my_basestat($stat[moxie]) < 70) stats_needed.listAppend((70 - my_basestat($stat[moxie])) + "" more moxie""); if (my_basestat($stat[mysticality]) < 70) stats_needed.listAppend((70 - my_basestat($stat[mysticality])) + "" more mysticality""); if (stats_needed.count() == 0) subentry.entries.listAppend(""Wear war outfit, run -combat, adventure in other side's camp.""); else { string line = ""Acquire "" + stats_needed.listJoinComponents("", "", ""and"") + "" to wear war outfit.""; if (my_class() == $class[pastamancer] && (is_wearing_outfit(""War Hippy Fatigues"") || is_wearing_outfit(""Frat Warrior Fatigues""))) line += ""|Or... wear it anyways, because you're a pastamancer.""; subentry.entries.listAppend(line); } //need 70 moxie, 70 myst } if (false && $item[talisman o' namsilat].available_amount() == 0 && !__quest_state[""Level 11 Palindome""].finished && myPathId() != PATH_G_LOVER) { subentry.entries.listAppend(""May want to "" + HTMLGenerateSpanFont(""acquire the Talisman o' Nam"", ""red"") + "" first.""); } subentry.entries.listAppend(generateTurnsToSeeNoncombat(85, 3, ""start war"")); } else { int sides_completed_hippy = base_quest_state.state_int[""Quests completed for hippies""]; int sides_completed_frat = base_quest_state.state_int[""Quests completed for frat boys""]; int frat_boys_left = base_quest_state.state_int[""frat boys left on battlefield""]; int hippies_left = base_quest_state.state_int[""hippies left on battlefield""]; int frat_boys_defeated_per_combat = powi(2, sides_completed_hippy); int hippies_defeated_per_combat = powi(2, sides_completed_frat); if (myPathId() == PATH_AVATAR_OF_SNEAKY_PETE && get_property(""peteMotorbikeCowling"") == ""Rocket Launcher"") { frat_boys_defeated_per_combat += 3; hippies_defeated_per_combat += 3; } if (myPathId() == PATH_LICENSE_TO_ADVENTURE && get_property_boolean(""bondWar"")) { frat_boys_defeated_per_combat += 3; hippies_defeated_per_combat += 3; } subentry.modifiers.listAppend(""+item""); if (hippies_left < 1000 || (frat_boys_left == 1000 && hippies_left == 1000) || sides_completed_frat > 0) QLevel12GenerateBattlefieldDescription(subentry, ""frat boy"", hippies_left, hippies_defeated_per_combat, ""hippy"", ""hippies"", ""The Big Wisniewski"", listMake(""Orchard"", ""Nuns"", ""Farm""), listMake(""Lighthouse"", ""Junkyard"", ""Arena"")); //specific exception to deal with 151st cheating: if ((frat_boys_left < 1000 && !(frat_boys_left >= 998 && hippies_left < 1000)) || (frat_boys_left == 1000 && hippies_left == 1000) || sides_completed_hippy > 0) QLevel12GenerateBattlefieldDescription(subentry, ""hippy"", frat_boys_left, frat_boys_defeated_per_combat, ""frat boy"", ""frat boys"", ""The Man"", listMake(""Lighthouse"", ""Junkyard"", ""Arena""), listMake(""Orchard"", ""Nuns"", ""Farm"")); if (frat_boys_left == 1 && hippies_left == 1) { if ($item[flaregun].available_amount() > 0) subentry.entries.listAppend(""Wossname time! Adventure on battlefield, use a flaregun.""); else if (!in_hardcore()) subentry.entries.listAppend(""Pull a flaregun for wossname.""); else if (__misc_state[""fax equivalent accessible""]) subentry.entries.listAppend(""Fax smarmy pirate, run +234% item (or YR) for flaregun for wossname.""); else subentry.entries.listAppend(""That almost was a wossname, but you needed more flare.""); } item [int] items_to_closet_for_desert_hippy; foreach it in $items[reinforced beaded headband,round purple sunglasses,bullet-proof corduroys,beer helmet,distressed denim pants,bejeweled pledge pin] { if (it.available_amount() == 0) continue; items_to_closet_for_desert_hippy.listAppend(it); } if (!have_outfit_components(""War Hippy Fatigues"") && !have_outfit_components(""Frat Warrior Fatigues"")) { string line = ""Visit the Arid, Extra-Dry Desert to find a hippy uniform.""; if (items_to_closet_for_desert_hippy.count() > 0) line += ""|But first closet "" + items_to_closet_for_desert_hippy.listJoinComponents("", "", ""and""); subentry.entries.listAppend(line); } //FIXME Add when spaded: /*else if (!have_outfit_components(""War Hippy Fatigues"")) { string line = ""If you want a hippy uniform without visiting the battlefield, adventure in the Arid, Extra-Dry Desert.""; if (items_to_closet_for_desert_hippy.count() > 0) line += ""|But first closet "" + items_to_closet_for_desert_hippy.listJoinComponents("", "", ""and""); subentry.entries.listAppend(line); }*/ QLevel12GenerateTasksSidequests(task_entries, optional_task_entries, future_task_entries); } } ",12136,False,2103.5471228609813,median "= Verkaufspreise und Preiskalkulation :lang: de :keywords: Preis, Preis, Preis, Preise, Preise, Preise, Verkaufspreis, Verkaufspreis, Verkaufspreis, Verkaufspreise, Verkaufspreise, Verkaufspreise, Preiskalkulation, Preiskalkulation, Preiskalkulation, Preiskalkulationen, Preiskalkulationen, Preiskalkulationen, Kalkulation, Kalkulationen, Preis-Kalkulation, Preis-Kalkulationen, Verkaufspreis-Assistent, UVP, EK, Aktionspreis, Setpreis, Mengenabhängigkeit, Währung, Währungen, Ab Menge, Live umrechnen, Standardwährung, Umrechnungsfaktor, Preistyp, Preis-Typ, Geldbetrag, Geldbeträge, Gewinnspanne, Einkaufspreis, Preisquelle, Transportkosten, Lagerkosten, Betriebskosten, Staffelpreis, Staffelpreise, Preisstaffel, Preisstaffelung, Staffelung, Preisstaffel nach Menge, Formel :description: Lerne alles über Verkaufspreise, Preiskalkulationen, deren Einstellungen und deine Möglichkeiten. :url: artikel/einstellungen/preise :position: 40 :id: GBG1FJX :author: team-item //// zuletzt bearbeitet 03.12.2021 //// Preise sind ein wichtiges Thema für jedes Geschäft. Dank plentymarkets bist du bei der Gestaltung deiner Preise sehr flexibel. * Erstens kannst du die <>, unter denen deine Produkte zu einem bestimmten Preis verkauft werden. Zum Beispiel kannst du deine Produkte im plentyShop günstiger anbieten als auf Amazon. Oder du kannst deine Produkte günstiger an B2B-Kunden verkaufen als an B2C-Kunden. In plentymarkets bezeichnen wir solche Bedingungen als _Verkaufspreise_. * Zweitens kannst du <> speichern. Wenn du also ein T-Shirt in S, M, L und XL verkaufst, kannst du entscheiden, ob die XL-Variante etwas teurer als die anderen sein soll. * Drittens kannst du plentymarkets deine <>. Beispielsweise startest du mit dem Einkaufspreis des Artikels und fügst dann die Transportkosten, Lagerkosten und Steuern hinzu. Schließlich legst du eine Gewinnspanne von 7% oben drauf. [#100] == Verkaufspreise Verkaufspreise definieren die _Bedingungen_, unter denen eine Variante zu einem bestimmten Preis verkauft wird. Zum Beispiel kannst du deine Produkte im plentyShop günstiger anbieten als auf Amazon. Oder du kannst deine Produkte günstiger an B2B-Kunden verkaufen als an B2C-Kunden. Neue plentymarkets Systeme sind mit _zwei Standard-Verkaufspreisen_ ausgestattet. Wirf bei Bedarf einen Blick auf diese Standard-Verkaufspreise und nutze sie, um dich mit dem Thema vertraut zu machen. Es steht dir frei, die Standard-Verkaufspreise zu ändern und/oder völlig neue Verkaufspreise zu erstellen. video::265406117[vimeo] [#200] === Neue Verkaufspreise erstellen In plentymarkets werden Verkaufspreise zentral angelegt und verwaltet. Entweder kannst du neue Verkaufspreise mit Hilfe eines _Assistenten_ erstellen oder du kannst neue Verkaufspreise manuell im _Einrichtungsmenü_ erstellen. So oder so, wirst du die Verkaufspreise an deine Bedürfnisse anpassen. Du vergibst den Verkaufspreisen eindeutige Namen und entscheidest, für welche Währungen, Kundenklassen, Marktplätze, oder andere Bedingungen sie gelten sollen. [.tabs] ==== Im Einrichtungsmenü:: + -- Erstelle beliebig viele Verkaufspreise, um die gesamte Breite deiner benötigten Preise in plentymarkets abzubilden. Während des Prozesses vergibst du den Verkaufspreisen eindeutige Namen und entscheidest, für welche Währungen, Kundenklassen, Marktplätze, oder andere Bedingungen sie gelten sollen. . Öffne das Menü *Einrichtung » Artikel » Verkaufspreise*. . Klicke auf icon:plus[role=""green""] *Neu*. + → Das Tab *Neu* wird geöffnet. . Nimm die Einstellungen vor. Beachte <>. . *Speichere* (icon:save[set=plenty, role=""green""]) die Einstellungen. . Anschließend werden die fertige <>. IMPORTANT: Um Fehler zu vermeiden, sollst du nicht mehrere Verkaufspreise mit genau denselben Bedingungen, d.h. mit genau demselben Einstellungs-Mix, konfigurieren. Beispiel: Legst du zwei verschiedene Verkaufspreise an, die beide für B2B-Kunden, Amazon DE und das Lieferland Deutschland gelten, dann weiß plentymarkets nicht, welcher Verkaufspreis verwendet werden soll. plentymarkets wird zufällig einen der beiden Verkaufspreise verwenden, da beide gleichermaßen gelten. [[table-create-sales-price]] .Verkaufspreis erstellen [cols=""1,3""] |====== |Einstellung |Erläuterung | *Abo-Interv.* |Diese Option ist relevant, wenn du Plugins auf dem plentyMarketplace auf Abonnementbasis anbietest. *_Hinweis_*: Diese Option hat aktuell weder eine Funktion für den plentyShop noch für das Scheduler oder Abonnement Modul. | *Position* |Positionsnummer eingeben. Wenn du mehrere <>, dann werden die Verkaufspreise anhand ihrer Positionsnummer im Artikeldatensatz sortiert angezeigt. | *Interner Name DE* |Gib einen Namen für den Verkaufspreis ein. Dieser Name wird an verschiedenen Stellen innerhalb deines plentymarkets Backends angezeigt. Du wählst z.B. den Verkaufspreis anhand seines Namens, wenn du <>. | *Externer Name DE* |Gib einen externen Namen für den Verkaufspreis ein. Dieser Name wird derzeit nicht im plentyShop angezeigt. | *Ab Menge* |Sollte der Verkaufspreis nur gelten, wenn ein Kunde _mehrere Exemplare des Artikels_ kauft? Nehmen wir zum Beispiel an, du verkaufst Socken für 6 EUR pro Paar. Möchtest du, dass der Preis auf 5 EUR pro Paar reduziert wird, wenn ein Kunde 3 oder mehr Paar Socken kauft? Falls ja, dann gib die Menge an, für die dieser Verkaufspreis gilt. *_Tipp_*: Füge _noch weitere_ mengenabhängige Verkaufspreise hinzu, um eine Preisstaffel nach Mengen zu erstellen. | *Währung* |Für welche Währungen soll der Verkaufspreis gelten? Wähle sie aus der Liste aus (icon:check-square[role=""blue""]). *_Hintergrund-Info_*: Während du dein plentyShop konfigurierst, kannst du entscheiden, in welchen <> und <> dein Shop zugänglich sein soll. Nehmen wir zum Beispiel an, dass Kunden die Währungen EUR, PLN, CHF und GBP aus der Kopfzeile wählen können. Dann wäre es sinnvoll, Preise auch für diese Währungen zu speichern. *_Automatisch umrechnen lassen_*: Aktiviere die Option *Live umrechnen* (icon:check-square[role=""blue""]), um deine Preise automatisch von der <>, z.B. EUR, in die anderen Währungen, z.B. PLN, CHF und GBP, umrechnen zu lassen. + Wenn du diese Option _nicht_ aktivierst, werden deine Preise alle die gleiche Zahl, aber unterschiedliche Währungen haben, z.B. 19 EUR und 19 PLN. Daher ist es meistens sinnvoll, die Preise automatisch umrechnen zu lassen. Vergewissere dich, dass du mit den im Menü *Einrichtung » Aufträge » Zahlung » Währungen* gespeicherten <> einverstanden bist. | *Preistyp* |Welche Art von Verkaufspreis möchtest du konfigurieren? In den meisten Fällen wirst du einen _Standard-Verkaufspreis_ anlegen. Aber in manchen Situationen willst du vielleicht stattdessen ein ""UVP"", ""Setpreis"" oder ""Aktionspreis"" erstellen. Falls ja, dann wähle den entsprechenden Preistyp (icon:check-square[role=""blue""]). *UVP* = Eine unverbindliche Preisempfehlung, die nur dazu dient, den Preisvergleich zwischen dem UVP und einem Standard-Verkaufspreis darzustellen. Der UVP wird im plentyShop durchgestrichen neben dem Verkaufspreis dargestellt. Produkte können nicht zu dem UVP-Preis verkauft werden. *Aktionspreis* = Ein Angebotspreis, der z.B. bei Amazon nur für eine begrenzte Zeit gilt. *Setpreis* = <> sind eine Möglichkeit, Produkte zu kombinieren und als eine Verkaufseinheit anzubieten. Wenn du dich entscheidest, Produkte zu einem Set zu kombinieren, dann musst du den einzelnen Set-Bestandteilen einen Setpreis geben. | *Darstellung* |Soll dieser Verkaufspreis _automatisch_ mit neuen Artikeldatensätzen verknüpft werden? Falls ja, dann aktiviere die Option *Bei neuem Artikel immer anzeigen* (icon:check-square[role=""blue""]). Wenn diese Einstellung deaktiviert ist, kannst du den <>. | *Mandant* |Soll der Verkaufspreis nur für bestimmte Mandanten (Shops) gelten? Falls ja, dann wähle alle Shops (icon:check-square[role=""blue""]), für die dieser Verkaufspreis gelten soll. *_Hintergrund-Info_*: Mit plentymarkets kannst du mehrere Webshops, d.h. <>, mit nur einer Software verwalten. Somit ist es möglich, über ein plentymarkets System mehrere unterschiedliche Geschäftsbereiche zu realisieren. Das ist ein großer Vorteil. Aber es bedeutet auch, dass du plentymarkets immer mitteilen musst, für welchen Webshop der Verkaufspreis gilt. | *Klasse* |Soll der Verkaufspreis nur für bestimmte Kundenklassen gelten? Willst du z.B. deine Produkte günstiger an B2B-Kunden verkaufen als an B2C-Kunden? Falls ja, dann wähle alle Kundenklassen (icon:check-square[role=""blue""]), für die dieser Verkaufspreis gilt. *_Häufige Fehlerquelle_*: Um Fehler zu vermeiden, sollst du nicht mehrere Verkaufspreise mit genau denselben Bedingungen, d.h. mit genau demselben Einstellungs-Mix, konfigurieren. Beispiel: Legst du zwei verschiedene Verkaufspreise an, die beide für B2B-Kunden, Amazon DE und das Lieferland Deutschland gelten, dann weiß plentymarkets nicht, welcher Verkaufspreis verwendet werden soll. plentymarkets wird zufällig einen der beiden Verkaufspreise verwenden, da beide gleichermaßen gelten. *_Hinweis_*: <> im Voraus, falls sie nicht bereits in deinem plentymarkets System vorhanden sind. | *Land* |Soll der Verkaufspreis nur für bestimmte Lieferländer gelten? Beispielsweise zahlst du wahrscheinlich unterschiedliche Steuersätze in unterschiedlichen Ländern. Aus diesem Grund willst du vielleicht einen Artikel in einigen Ländern zu einem etwas höheren Preis verkaufen, damit du die Differenz nicht selbst bezahlen musst. Wähle alle Länder (icon:check-square[role=""blue""]), für die dieser Verkaufspreis gelten soll. | *Herkunft* |Soll der Verkaufspreis nur für bestimmte Verkaufskanäle gelten? Möchtest du zum Beispiel den Artikel zu einem niedrigeren Preis in deinem plentyShop verkaufen als auf Amazon? Wähle alle Plattformen (icon:check-square[role=""blue""]), für die dieser Verkaufspreis gelten soll. *_Häufige Fehlerquelle_*: Um Fehler zu vermeiden, sollst du nicht mehrere Verkaufspreise mit genau denselben Bedingungen, d.h. mit genau demselben Einstellungs-Mix, konfigurieren. Beispiel: Legst du zwei verschiedene Verkaufspreise an, die beide für B2B-Kunden, Amazon DE und das Lieferland Deutschland gelten, dann weiß plentymarkets nicht, welcher Verkaufspreis verwendet werden soll. plentymarkets wird zufällig einen der beiden Verkaufspreise verwenden, da beide gleichermaßen gelten. *_Hinweis_*: Wenn du eBay oder Amazon wählst, wird die entsprechende Kontoeinstellung weiter unten eingeblendet. Hier teilst du plentymarkets mit, für welches eBay- oder Amazon-Konto der Verkaufspreis gelten soll. <>. | *Amazon-Konten* |Teile plentymarkets mit, für welches Amazon-Konto der Verkaufspreis gelten soll. <>. Diese Einstellung ist ausgegraut, bis du eine Amazon-Plattform aus der Liste weiter oben auswählst. | *eBay-Konten* |Teile plentymarkets mit, für welches eBay-Konto der Verkaufspreis gelten soll. <>. Diese Einstellung ist ausgegraut, bis du eine eBay-Plattform aus der Liste weiter oben auswählst. |====== -- Mit dem Assistenten:: + -- Mit Hilfe des Assistenten kannst du auf einfache Weise neue Verkaufspreise erstellen. Der Assistent führt dich durch die gängigsten Einstellungen. Während des Prozesses vergibst du den Verkaufspreisen eindeutige Namen und entscheidest, für welche Währungen, Kundenklassen, Marktplätze, oder andere Bedingungen sie gelten sollen. Es gibt auch einige erweiterte Einstellungen, die optional auch im Anschluß konfiguriert werden können. . Öffne das Menü *Einrichtung » Assistenten » Grundeinrichtung*. . Klicke auf den Verkaufspreise-Assistenten. . Klicke auf *Neue Konfiguration* (icon:plus[role=""green""]). . Folge den Anweisungen auf dem Bildschirm. Beachte <>, wenn du zusätzliche Informationen zu einer der Optionen benötigst. . Überprüfe die Zusammenfassung auf mögliche Fehler und klicke auf icon:check[role=""green""] *Abschließen*. + → Der Assistent ist fertig. Wiederhole diese Schritte, bis du alle von deinem Unternehmen benötigten Verkaufspreise erstellt hast. . Anschließend werden die fertige <>. IMPORTANT: Um Fehler zu vermeiden, sollst du nicht mehrere Verkaufspreise mit genau denselben Bedingungen, d.h. mit genau demselben Einstellungs-Mix, konfigurieren. Beispiel: Legst du zwei verschiedene Verkaufspreise an, die beide für B2B-Kunden, Amazon DE und das Lieferland Deutschland gelten, dann weiß plentymarkets nicht, welcher Verkaufspreis verwendet werden soll. plentymarkets wird zufällig einen der beiden Verkaufspreise verwenden, da beide gleichermaßen gelten. [[table-sales-price-assistant]] .Verkaufspreis erstellen [cols=""1,3""] |====== |Einstellung |Erläuterung 2+| *Schritt: Einstellungen* | *Typ* |Welche Art von Verkaufspreis möchtest du konfigurieren? In den meisten Fällen wirst du einen _Standard-Verkaufspreis_ anlegen. Aber in manchen Situationen willst du vielleicht stattdessen ein ""UVP"", ""Setpreis"" oder ""Aktionspreis"" erstellen. Falls ja, dann aktiviere diese Option (icon:toggle-on[role=""green""]). Ein zusätzlicher Konfigurationsschritt wird eingeblendet. In diesem Schritt legst du die Art des zu erstellenden Verkaufspreises fest. *UVP* = Eine unverbindliche Preisempfehlung, die nur dazu dient, den Preisvergleich zwischen dem UVP und einem Standard-Verkaufspreis darzustellen. Der UVP wird im plentyShop in rot und durchgestrichen neben dem Verkaufspreis dargestellt. Produkte können nicht zu dem UVP-Preis verkauft werden. *Aktionspreis* = Ein Angebotspreis, der z.B. bei Amazon nur für eine begrenzte Zeit gilt. *Setpreis* = <> sind eine Möglichkeit, Produkte zu kombinieren und als eine Verkaufseinheit anzubieten. Wenn du dich entscheidest, Produkte zu einem Set zu kombinieren, dann musst du den einzelnen Set-Bestandteilen einen Setpreis geben. | *Kundenklassen* |Soll der Verkaufspreis nur für bestimmte Kundenklassen gelten? Willst du z.B. deine Produkte günstiger an B2B-Kunden verkaufen als an B2C-Kunden? Falls ja, dann aktiviere diese Option (icon:toggle-on[role=""green""]). Ein zusätzlicher Konfigurationsschritt wird eingeblendet. In diesem Schritt gibst du die Kundenklasse an, für die dieser Verkaufspreis gilt. *_Häufige Fehlerquelle_*: Um Fehler zu vermeiden, sollst du nicht mehrere Verkaufspreise mit genau denselben Bedingungen, d.h. mit genau demselben Einstellungs-Mix, konfigurieren. Beispiel: Legst du zwei verschiedene Verkaufspreise an, die beide für B2B-Kunden, Amazon DE und das Lieferland Deutschland gelten, dann weiß plentymarkets nicht, welcher Verkaufspreis verwendet werden soll. plentymarkets wird zufällig einen der beiden Verkaufspreise verwenden, da beide gleichermaßen gelten. *_Hinweis_*: <> im Voraus, falls sie nicht bereits in deinem plentymarkets System vorhanden sind. | *Mengenabhängigkeit* |Sollte der Verkaufspreis nur gelten, wenn ein Kunde _mehrere Exemplare des Artikels_ kauft? Nehmen wir zum Beispiel an, du verkaufst Socken für 6 EUR pro Paar. Möchtest du, dass der Preis auf 5 EUR pro Paar reduziert wird, wenn ein Kunde 3 oder mehr Paar Socken kauft? Falls ja, dann aktiviere diese Option (icon:toggle-on[role=""green""]). Ein zusätzlicher Konfigurationsschritt wird eingeblendet. In diesem Schritt gibst du die Menge an, für die dieser Verkaufspreis gilt. *_Tipp_*: Füge _noch weitere_ mengenabhängige Verkaufspreise hinzu, um eine Preisstaffel nach Mengen zu erstellen. 2+| *Schritt: Name* | *Interner Name* |Gib einen Namen für den Verkaufspreis ein. Dieser Name wird an verschiedenen Stellen innerhalb deines plentymarkets Backends angezeigt. Du wählst z.B. den Verkaufspreis anhand seines Namens, wenn du <>. | *Externer Name* |Gib einen externen Namen für den Verkaufspreis ein. Dieser Name wird derzeit nicht im plentyShop angezeigt. 2+| *Schritt: Verfügbarkeiten* | *Währungen* |In welche Währungen soll der Preis automatisch umgerechnet werden? Wähle sie aus der Liste aus (icon:check-square[role=""blue""]). *_Hintergrund-Info_*: Während du dein plentyShop konfigurierst, kannst du entscheiden, in welchen <> und <> dein Shop zugänglich sein soll. Nehmen wir zum Beispiel an, dass Kunden die Währungen EUR, PLN, CHF und GBP aus der Kopfzeile wählen können. Dann wäre es sinnvoll, deine Preise automatisch von der <>, z.B. EUR, in die anderen Währungen, z.B. PLN, CHF und GBP, umrechnen zu lassen. Vergewissere dich, dass du mit den im Menü *Einrichtung » Aufträge » Zahlung » Währungen* gespeicherten <> einverstanden bist. | *Verkaufskanäle* |Soll der Verkaufspreis nur für bestimmte Verkaufskanäle gelten? Möchtest du zum Beispiel den Artikel zu einem niedrigeren Preis in deinem plentyShop verkaufen als auf Amazon? Wähle alle Plattformen (icon:check-square[role=""blue""]), für die dieser Verkaufspreis gelten soll. *_Häufige Fehlerquelle_*: Um Fehler zu vermeiden, sollst du nicht mehrere Verkaufspreise mit genau denselben Bedingungen, d.h. mit genau demselben Einstellungs-Mix, konfigurieren. Beispiel: Legst du zwei verschiedene Verkaufspreise an, die beide für B2B-Kunden, Amazon DE und das Lieferland Deutschland gelten, dann weiß plentymarkets nicht, welcher Verkaufspreis verwendet werden soll. plentymarkets wird zufällig einen der beiden Verkaufspreise verwenden, da beide gleichermaßen gelten. *_Hinweis_*: Wenn du eBay oder Amazon wählst, wird ein zusätzlicher Konfigurationsschritt eingeblendet. In diesem Schritt teilst du plentymarkets mit, für welches eBay- oder Amazon-Konto der Verkaufspreis gelten soll. <>. | *Lieferländer* |Soll der Verkaufspreis nur für bestimmte Lieferländer gelten? Beispielsweise zahlst du wahrscheinlich unterschiedliche Steuersätze in unterschiedlichen Ländern. Aus diesem Grund willst du vielleicht einen Artikel in einigen Ländern zu einem etwas höheren Preis verkaufen, damit du die Differenz nicht selbst bezahlen musst. Wähle alle Länder (icon:check-square[role=""blue""]), für die dieser Verkaufspreis gelten soll. | *Mandant* |Soll der Verkaufspreis nur für bestimmte Mandanten (Shops) gelten? Falls ja, dann wähle alle Shops (icon:check-square[role=""blue""]), für die dieser Verkaufspreis gelten soll. *_Hintergrund-Info_*: Diese Einstellung wird nur eingeblendet, wenn du mehrere Webshops, d.h. <>, mit plentymarkets verwaltest. Da es möglich ist, über ein plentymarkets System mehrere unterschiedliche Geschäftsbereiche zu realisieren, musst du plentymarkets immer mitteilen, für welchen Webshop der Verkaufspreis gilt. |====== [discrete] ===== Erweiterte Einstellungen (nicht im Assistenten enthalten) Der Assistent führt dich durch die gängigsten Einstellungen für Verkaufspreise. Es gibt jedoch einige erweiterte Einstellungen, die optional auch konfiguriert werden können. . Öffne das Menü *Einrichtung » Artikel » Verkaufspreise*. . <> und öffne den Verkaufspreis. . Konfiguriere die erweiterten Einstellungen falls benötigt. Beachte <>. . *Speichere* (icon:save[set=plenty, role=""green""]) die Einstellungen. [[table-sales-price-advanced-settings]] .Folgende Einstellungen sind im Assistenten nicht enthalten [cols=""1,3""] |====== |Einstellung |Erläuterung | *Abo-Interv.* |Diese Option ist relevant, wenn du Plugins auf dem plentyMarketplace auf Abonnementbasis anbietest. *_Hinweis_*: Diese Option hat aktuell weder eine Funktion für den plentyShop noch für das Scheduler oder Abonnement Modul. | *Position* |Positionsnummer eingeben. Wenn du mehrere <>, dann werden die Verkaufspreise anhand ihrer Positionsnummer im Artikeldatensatz sortiert angezeigt. | *Darstellung* |Soll dieser Verkaufspreis _automatisch_ mit neuen Artikeldatensätzen verknüpft werden? Falls ja, dann aktiviere die Option *Bei neuem Artikel immer anzeigen* (icon:check-square[role=""blue""]). Wenn diese Einstellung deaktiviert ist, kannst du den <>. |====== -- ==== [#500] === Mit bestehenden Verkaufspreisen arbeiten Sobald du einen <> hast, wird er automatisch zur Übersicht im Menü *Einrichtung » Artikel » Verkaufspreise* hinzugefügt. [#600] ==== Verkaufspreise suchen Verwende die Filter links, um die in der Übersicht rechts angezeigten Verkaufspreise einzugrenzen. [.instruction] Verkaufspreise filtern: . Öffne das Menü *Einrichtung » Artikel » Verkaufspreise*. . Wähle die Filter links. Beachte <>. . Klicke auf *Suchen* (icon:search[role=""blue""]). + → Die gefilterten Verkaufspreise werden in der Übersicht rechts angezeigt. [[table-filter-sales-prices]] .Verkaufspreise filtern [cols=""1,3""] |==== |Einstellung |Erläuterung | *ID* |ID eingeben, um nach dem Verkaufspreis mit dieser ID zu suchen. | *Name* |Name eingeben, um nach dem Verkaufspreis mit diesem Namen zu suchen. | *Ab Menge* |Mengenwert eingeben, um nach dem Verkaufspreis mit dieser Mengenstaffelung zu suchen. | *Mandant* |Mandant oder *ALLE* wählen, um nach Verkaufspreisen für diesen Mandanten (Shop) zu suchen. | *Klasse* |Klasse oder *ALLE* wählen, um nach Verkaufspreisen für diese Kundenklasse zu suchen. | *Herkunft* |Herkunft oder *ALLE* wählen, um nach Verkaufspreisen für diese Auftragsherkunft zu suchen. | *Amazon-Konten* |Amazon-Konto oder *ALLE* wählen, um nach Verkaufspreisen für dieses Amazon-Konto zu suchen. | *eBay-Konten* |eBay-Konto oder *ALLE* wählen, um nach Verkaufspreisen für dieses eBay-Konto zu suchen. | *Währung* |Währung oder *ALLE* wählen, um nach Verkaufspreisen für diese Währung zu suchen. | *Sprache* |Sprache oder *ALLE* wählen, um nach Verkaufspreisen in dieser Sprache zu suchen. Standardmäßig ist *Deutsch* voreingestellt. | *Land* |Land oder *ALLE* wählen, um nach Verkaufspreisen für dieses Lieferland zu suchen. |==== [#700] ==== Die Namen in mehreren Sprachen speichern Nachdem du einen <> hast, übersetze nach Bedarf den Namen des Verkaufspreises in die von dir verwendeten Sprachen. [.instruction] Verkaufspreis übersetzen: . Öffne das Menü *Einrichtung » Artikel » Verkaufspreise*. . <> und öffne den Verkaufspreis. . Wechsele in das Tab *Sprache*. . Gib den *internen Namen* in den benötigten Sprachen ein. . Gib den *externen Namen* in den benötigten Sprachen ein. . *Speichere* (icon:save[set=plenty, role=""green""]) die Einstellungen. [#900] === Verkaufspreis auf Produkte anwenden Verkaufspreise werden mit <> verknüpft, nicht mit dem Artikel als Ganzes. Wenn du also ein T-Shirt in S, M, L und XL verkaufst, kannst du entscheiden, ob die XL-Variante etwas teurer als die anderen sein soll. Es gibt verschiedene Möglichkeiten, Verkaufspreise mit Varianten zu verknüpfen und die eigentlichen Geldpreise einzugeben: * Wenn du Preise für _nur wenige Artikel_ speichern möchtest, dann empfiehlt es sich, die <>. * Wenn du Preise für _viele Artikel_ speichern möchtest, dann empfiehlt es sich, die <>. Alternativ könntest du diese Daten mit Hilfe eines <> importieren. * Anstatt die Geldbeträge manuell einzugeben, willst du vielleicht, dass plentymarkets sie <>. [#1000] == Neue Preiskalkulation Lass plentymarkets deine Preise für dich berechnen. Starte zum Beispiel mit dem Einkaufspreis und füge dann die Transportkosten, Lagerkosten und Steuern hinzu. Lege schließlich noch einen Aufschlag von 7% oben drauf. Mit plentymarkets entscheidest du, wie deine Preise berechnet werden sollen. [discrete] === Ablauf Die Konfiguration in plentymarkets besteht aus mehreren Schritten: * <> * <> * <> video::527266670[vimeo] [#1100] === Neue Preiskalkulation erstellen . Öffne das Menü *Artikel » Preiskalkulation*. . Klicke auf icon:plus[role=""darkGrey""] *Preiskalkulation*. . Passe die Einstellungen an deine Bedürfnisse an: .. Gib einen eindeutigen Namen für die Kalkulation ein. .. Erstelle deine eigenen Formeln. .. Wähle Nachkommastellen und Rundungsverhalten pro Zielpreis. . *Speichere* (icon:save[set=plenty, role=""darkGrey""]) die Einstellungen. [#1200] ==== Einstellungen [[table-pricecalculation-settings]] [cols=""1,4""] |==== |Einstellung |Erläuterung | *Name* |Gib einen eindeutigen Namen für die Kalkulation ein. Der Name dient nur internen Zwecken und ist _nicht_ für Kunden sichtbar. Du wirst die Preiskalkulation z.B. anhand ihres Namens wählen, wenn du sie auf bestimmte Varianten anwendest. | icon:toggle-on[role=""blue""] *Aktiv* a|Die Preiskalkulation wird erst dann auf Produkte angewendet, wenn sie aktiviert wurde. Das heißt, du kannst neue Formeln und Rundungsverhalten ausprobieren, ohne eine Neuberechnung der Artikelpreise anzustoßen. Aktiviere die Preiskalkulation, sobald sie in Kraft treten soll. * icon:toggle-off[role=""darkGrey""] = Das Speichern löst keine Neuberechnung aus. * icon:toggle-on[role=""blue""] = Beim Speichern öffnet sich ein Pop-up-Fenster. Du wirst aufgefordert, deine Entscheidung zu bestätigen, denn das Speichern löst eine Neuberechnung aus. Du siehst, wie viele Varianten betroffen werden. *_Hinweis_*: Preise werden nicht sofort neu berechnet. Stattdessen beginnt die Neuberechnung nach einer kurzen Verzögerung (ca. 3 Minuten). |==== [#1300] ==== Formel Wie soll der Preis berechnet werden? Beispielsweise startest du mit dem Einkaufspreis und fügst dann die Transportkosten, Lagerkosten und Steuern hinzu. Schließlich legst du noch einen Aufschlag von 7% oben drauf. In diesem Fall könnte die Formel etwa so aussehen: + `(EK + Transport + Lager + Steuer) * 1.07` image::artikel/einstellungen/assets/formel.gif[] [.instruction] Formel schreiben: . Gib bei Bedarf einen Namen für die Formel ein, z.B. Grundformel. . Klicke in das Eingabefeld. + → Ein Taschenrechner wird geöffnet. . Gib die Formel ein: .. Gib Zahlen und mathematische Symbole mit dem Taschenrechner oder über die Tastatur ein. .. Suche nach verfügbaren Variablen und füge sie zu deiner Berechnung hinzu (icon:plus[role=""darkGrey""]). . Klicke auf *Übernehmen*. [#1350] [discrete] ===== Verfügbare Variablen [.collapseBox] .*Variante* -- [cols=""1,4""] |==== |Einstellung |Erläuterung | *Einkaufspreis* |Entspricht dem Netto-Einkaufspreis unter: + <> Abhängig von den Einstellungen im Menü *Einrichtung » Waren » Warenbestand » Wareneingang* wird der Einkaufspreis <>. | *Gld. Einkaufspreis* |Entspricht dem gleitenden Durchschnitts-Einkaufspreis unter: + <> Der GLD EK netto wird bei jedem Wareneingang neu aus den Einkaufspreisen aller im Lager verfügbaren Bestände einer Variante berechnet. *_Hinweis_*: Bei der Berechung wird nur Wareneingang in die *Lager für gleitenden Durchschnittspreis* berücksichtigt, die im Menü *Einrichtung » Waren » Warenbestand » Wareneingang* aktiviert wurden. Wenn keine Lager aktiviert sind, erfolgt keine Berechnung. | *Transportkosten* |Entspricht den Netto-Transportkosten unter: + <> | *Mehrwertsteuer + (Standardmandant)* |Entspricht dem prozentualen Umsatzsteuersatz unter: + <> *_Hinweis_*: In der Variante wird der Steuersatz als Prozentzahl gespeichert. In der Formel musst du die Prozentzahl in eine Dezimalzahl umwandeln. Beispiel: `7%` wird zu `1,07` durch `(1 + Steuersatz / 100)`. | *Zoll* |Entspricht dem Zoll-Prozentsatz unter: + <> *_Hinweis_*: In der Variante wird der Zollaufschlag als Prozentzahl gespeichert. In der Formel musst du die Prozentzahl in eine Dezimalzahl umwandeln. Beispiel: `11,2%` wird zu `1,112` durch `(1 + Zollaufschlag / 100)`. | *Betriebskosten* |Entspricht dem Prozentsatz der Betriebskosten unter: + <> *_Hinweis_*: In der Variante werden die Betriebskosten als Prozentzahl gespeichert. In der Formel musst du die Prozentzahl in eine Dezimalzahl umwandeln. Beispiel: `7%` wird zu `1,07` durch `(1 + Betriebskosten / 100)`. | *Lagerkosten* |Entspricht den Netto-Lagerkosten unter: + <> | *Portoaufschlag 1*; + *Portoaufschlag 2* a|Entspricht dem Portoaufschlag unter: + <> Dies ist eine Gebühr, die _zusätzlich_ zu den normalen Versandkosten erhoben werden soll. Solche Portoaufschläge bieten sich für größere oder sperrige Artikel an, deren Versand teurer ist. * Portoaufschlag 1 gilt für den ersten Artikel. * Portoaufschlag 2 gilt für jeden weiteren Artikel. *_Zusätzliche Einstellungen_*: Gib in jedem deiner <> an, ob die Aufschläge zum Grundporto hinzugefügt werden sollen. Das Handbuch enthält auch einige <>. |==== -- [.collapseBox] .*Verkaufspreise* -- Füge Verkaufspreise zu deiner Formel hinzu. Diese Liste enthält nur Verkaufspreise, die du <> hast. *_Anwendungsbeispiel_* + Stell dir vor, du verkaufst Artikel im plentyShop und auf Amazon. Du willst, dass der Amazon-Preis immer 10% über dem plentyShop-Preis liegt. In diesem Fall könntest du den Amazon-Preis wie folgt berechnen: + `Amazon = plentyShop * 1.10` *_Warum stehen manche Verkaufspreise nicht zur Auswahl?_* + Um Fehler zu vermeiden, stehen manche Verkaufspreise nicht zur Auswahl. Es ist nicht möglich, einen Verkaufspreis als Variable zu verwenden, wenn dieser bereits als Zielpreis festgelegt wurde. -- [.collapseBox] .*Eigenschaften* -- Füge Eigenschaften vom Typ ""Ganze Zahl"" oder ""Kommazahl"" zu deiner Formel hinzu. Diese Liste enthält nur Eigenschaften, die du <> hast. //Diese Liste enthält nur Eigenschaften, die du <> hast und die ein Häkchen neben der Option <> haben. *_Hast du auch einen Wert für die Eigenschaft gespeichert?_* + Stelle sicher, dass du die Eigenschaft mit den entsprechenden Varianten <> hast und dass du eine ganze Zahl oder eine Dezimalzahl als Wert gespeichert hast. -- [.collapseBox] .*Formeln* -- Es ist möglich, Formeln aufeinander aufzubauen. Beispielsweise könntest du zuerst eine Grundformel erstellen. Danach könntest du <>, um die Formel weiter anzupassen. Bereits erstellte Formeln werden dabei zu Variablen, die hier ausgewählt werden können. *_Warum sehe ich diesen Bereich nicht?_* + Dieser Bereich wird nur angezeigt, wenn deine Preiskalkulation mehr als nur einen Kalkulations-Baustein enthält. -- [#1400] ==== Zielpreis Welche Verkaufspreise soll die Formel berechnen? Vielleicht willst du z.B. die Preise im plentyShop mit dieser Formel berechnen und die Preise auf Amazon mit einer anderen. Wie viele Nachkommastellen soll der Verkaufspreis haben? Soll er auf- oder abgerundet werden? Wähle deine Präferenzen aus den Dropdown-Listen aus. image::artikel/einstellungen/assets/zielpreis.gif[] [.instruction] Zielpreise wählen: . Klicke auf icon:plus[role=""darkGrey""] *Zielpreis*. + → Eine neue Zeile wird hinzugefügt. . Wähle den passenden Verkaufspreis, das Rundungsverhalten und die Anzahl an Nachkommastellen. Beachte <>. . Wiederhole den Vorgang, um weitere Zielpreise bei Bedarf hinzuzufügen. [[table-pricecalculation-targetprices]] .Zielpreise, Rundungsverhalten und Nachkommastellen [cols=""1,4""] |==== |Einstellung |Erläuterung | *Zielpreis* a|Wähle den passenden Verkaufspreis aus der Dropdown-Liste. *_Warum stehen manche Verkaufspreise nicht zur Auswahl?_* + * Um doppelte Zielpreise zu vermeiden. Hast du z.B. den plentyShop als Zielpreis in die erste Zeile gewählt, kannst du den plentyShop nicht erneut als Zielpreis in die zweite Zeile wählen. * Um Fehler zu vermeiden. Es ist nicht möglich, einen Verkaufspreis als Zielpreis festzulegen, wenn dieser gerade als Variable verwendet wird. 2+a| [.collapseBox] .*Rundungsverhalten* -- [cols=""1,4a,1""] !=== !Verhalten !Erläuterung !Beispiele ! *Nicht runden, sondern Nachkommastellen begrenzen* !Preise werden nicht gerundet. Gib stattdessen eine Anzahl an Nachkommastellen ein. Ab dieser Stelle werden weitere Nachkommastellen abgeschnitten. !4,3275 + 4,327 + 4,32 ! *Auf vollen Euro* !Preise werden immer auf den nächsten vollen Euro, Pfund, Franken usw. gerundet. !10,00 + 11,00 + 12,00 ! *Auf vollen Cent* !Preise werden immer auf den nächsten Cent, Penny, Centime usw. gerundet. Das heißt, Preise werden auf maximal zwei Nachkommastellen gerundet. !4,32 + 4,33 + 4,34 ! *Auf x,99* !Preise werden immer auf einen Cent vor dem vollen Euro gerundet (bzw. ein Penny vor dem vollen Pfund, usw.). !10,99 + 11,99 + 12,99 ! *Auf x,95* !Preise werden immer auf fünf Cents vor dem vollen Euro gerundet (bzw. fünf Pence vor dem vollen Pfund, usw.). !10,95 + 11,95 + 12,95 ! *Auf x,45 oder x,95* !Preise werden immer auf fünf Cents vor dem vollen oder halben Euro gerundet (bzw. fünf Pence vor dem vollen oder halben Pfund, usw.). !10,45 + 10,95 + 11,45 ! *In 50 Cent Schritten* !Preise werden immer in Schritten von 50 Cents, Pence, Centimes usw. gerundet. !10,50 + 11,00 + 11,50 ! *In 25 Cent Schritten* !Preise werden immer in Schritten von 25 Cents, Pence, Centimes usw. gerundet. !10,25 + 10,50 + 10,75 ! *In 10 Cent Schritten* !Preise werden immer in Schritten von 10 Cents, Pence, Centimes usw. gerundet. !10,10 + 10,20 + 10,30 ! *Auf x,x9* !Preise haben immer eine 9 als zweite Dezimalstelle. !10,19 + 10,29 + 10,39 ! *In 5 Cent Schritten* !Preise werden immer in Schritten von 5 Cents, Pence, Centimes usw. gerundet. !10,05 + 10,10 + 10,15 !=== -- | *Rundungsrichtung* a|In welche Richtung sollen die Preise gerundet werden? * *Kaufmännisch* = Die berechneten Preise werden entweder auf- oder abgerundet. Die Richtung hängt davon ab, ob der Preis über oder unter einem bestimmten Schwellenwert liegt. Für das Rundungsverhalten *Auf x,99* liegt der Grenzwert beispielsweise bei 49 Cent. Endet also ein berechneter Preis mit x,48, dann wird abgerundet. Endet ein berechneter Preis mit x,49, dann wird aufgerundet. * *Aufrunden* = Die berechneten Preise werden immer aufgerundet. * *Abrunden* = Die berechneten Preise werden immer abgerundet. | *Nachkommastellen* a|Gib die passende Anzahl an Nachkommastellen ein. Der berechnete Preis wird an dieser Stelle abgeschnitten. *_Beispiele_*: * Berechneter Preis: 199,123456 * 4 Nachkommastellen: 199,1234 * 2 Nachkommastellen: 199,12 *_Warum kann ich keine Nachkommastellen eingeben?_* + Die meisten Rundungsverhalten sind definitionsgemäß auf 2 Nachkommastellen begrenzt. Wählst du eines dieser Rundungsverhalten, dann wirst du keine Nachkommastellen eingeben können. |==== [#1500] ==== Weitere Kalkulation hinzufügen Eine Preiskalkulation besteht aus einem oder mehreren _Kalkulations-Bausteinen_. Innerhalb jedes Bausteins: * <> * <> image::artikel/einstellungen/assets/weitere-kalkulation.gif[] Der erste Baustein erscheint automatisch, wenn du die Preiskalkulation erstellst. Klicke auf icon:plus[role=""darkGrey""] *Kalkulation*, um noch weitere Bausteine hinzuzufügen und deine Formeln somit aufeinander aufzubauen. Beispielsweise könntest du die erste Kalkulation verwenden, um eine Grundformel zu erstellen. Und du könntest zusätzliche Kalkulationen verwenden, um diese Formel weiter anzupassen. [TIP] .Bisherige Formeln werden zu Variablen ==== Das Schöne an diesem Bausteinformat ist, dass du bereits erstellte Formeln wiederverwenden kannst. Sie werden nämlich zu <>, die du im Taschenrechner auswählen kannst. ==== [#1600] === Mit bestehenden Kalkulationen arbeiten Sobald du eine neue Preiskalkulation erstellt hast, wird sie automatisch zur Übersicht im Menü *Artikel » Preiskalkulation* hinzugefügt. Klicke auf eine Preiskalkulation, um sie zu öffnen und weiter zu bearbeiten. [#1700] ==== Symbolleiste in der Übersicht [[table-pricecalculation-overview-symbols]] [cols=""1,4""] |==== |Symbol |Erläuterung |icon:undo[role=""darkGrey""] |Lädt das Menü neu. |icon:plus[role=""darkGrey""] |Öffnet die Eingabemaske zum Erstellen einer <>. |icon:pencil[role=""darkGrey""] |Es ist möglich, mehrere Preiskalkulationen gleichzeitig zu öffnen. Wähle dazu die gewünschten Kalkulationen (icon:check-square[role=""blue""]) und klicke auf icon:pencil[role=""darkGrey""]. Die Preiskalkulationen werden untereinander auf der linken Seite des Bildschirms angezeigt. |icon:copy[set=plenty] |Es ist möglich, bestehende Preiskalkulationen zu kopieren. Wähle dazu die gewünschten Kalkulationen (icon:check-square[role=""blue""]) und klicke auf icon:copy[set=plenty]. Die neuen Kalkulationen werden zur Übersicht hinzugefügt. Sie werden automatisch inaktiv geschaltet und als *Copy of ""ursprünglicher Name""* bezeichnet. *_Hinweis_*: Verknüpfungen zu Varianten werden _nicht mitkopiert_. |icon:trash[role=""darkGrey""] |Es ist möglich, mehrere Preiskalkulationen gleichzeitig zu löschen. Wähle dazu die gewünschten Kalkulationen (icon:check-square[role=""blue""]) und klicke auf icon:trash[role=""darkGrey""]. *_Hinweis_*: Eine Preiskalkulation kann nur gelöscht werden, wenn sie _nicht_ mit einer Variante verknüpft ist. |==== [#1800] ==== Spalten in der Tabelle [[table-pricecalculation-overview-columns]] [cols=""1,4""] |==== |Spaltenkopf |Erläuterung |icon:square-o[role=""darkGrey""] |Es ist möglich, mehrere Preiskalkulationen gleichzeitig zu öffnen oder zu löschen. Wähle die gewünschten Kalkulationen (icon:check-square[role=""blue""]) und klicke auf eines der Symbole in der Leiste. | *Aktiv* |<> werden mit einem blauen Punkt gekennzeichnet (icon:circle[role=""blue""]). So erkennst du die aktiven und inaktiven Kalkulationen auf einen Blick. | *ID* |UUID der Preiskalkulation. Beim Erstellen der Kalkulation wird die ID automatisch vergeben. Die ID kann nicht geändert werden. *_Tipp_*: Willst du die UUID kopieren? Öffne dazu die Preiskalkulation und klicke auf die UUID unten links. Die UUID wird in die Zwischenablage kopiert. | *Name* |Der <>, der beim Erstellen der Preiskalkulation eingegeben wurde. Die Preiskalkulationen sind in der Übersicht alphabetisch nach Namen sortiert. | *Berechnete Verkaufspreise* |Die <>, die beim Erstellen der Preiskalkulation gewählt wurden. | *Verknüpfte Varianten* |Die Anzahl an Varianten, die mit der Preiskalkulation verknüpft sind. Diese Zahl gibt an, wie viele Varianten von einer Neuberechnung betroffen sein werden. | *Anzahl Varianten mit Fehlern* |Die Anzahl an Varianten, die zwar mit der Preiskalkulation verknüpft sind, aber deren Preise noch nicht korrekt berechnet werden können. <>, um die Ursache des Problems zu ermitteln. |==== [#1900] ==== Metadaten Nachdem du eine Preiskalkulation geöffnet hast, siehst du unten links ein kleines Kärtchen mit Metainformationen. Hier werden folgende Daten angezeigt: * Name * UUID * Erstellungsdatum * Datum der letzten Änderung [TIP] .UUID kann kopiert werden ==== Bewege deinen Mauszeiger über die UUID. Der Mauszeiger ändert seine Form (icon:plus-circle[role=""green""]). Klicke auf die UUID, um sie in die Zwischenablage zu kopieren. ==== [#2000] ==== Fehlerberichte Jede Preiskalkulation enthält einen Fehlerbericht. Der Bericht zeigt an, bei welchen Varianten die Preise nicht automatisch berechnet werden können und warum. [.instruction] Fehler einsehen und beheben: . Öffne das Menü *Artikel » Preiskalkulation*. . Öffne die Preiskalkulation und klicke links auf icon:exclamation-circle[role=""darkGrey""] *Fehlerbericht*. . Klappe eine Zeile auf (icon:chevron-right[role=""darkGrey""]), um weitere Informationen zu den Fehlern zu sehen. . Klicke auf eine Varianten-ID, um die Variante zu öffnen und die Fehler zu beheben. //// GIF neu machen //// image::artikel/einstellungen/assets/fehlerbericht.gif[] [[table-pricecalculation-errors]] .Fehlerberichte [cols=""1,4""] |==== |Spaltenkopf |Erläuterung | *Varianten ID* |Eine Liste aller Varianten, die zwar mit der Preiskalkulation verknüpft sind, aber deren Preise noch nicht korrekt berechnet werden können. Klicke auf eine Varianten-ID, um die Variante zu öffnen und den Fehler zu beheben. | *Fehler* |Die Anzahl an Fehlern, die für die Variante aufgetreten sind. |==== [#2100] === Kalkulation auf Produkte anwenden [.tabs] ==== Manuell:: + -- Wenn du die Preiskalkulation für _nur wenige Artikel_ speichern möchtest, dann empfiehlt es sich, die Preiskalkulation manuell zu verknüpfen. include::../import-export-anlage/anlage/verzeichnis.adoc[tag=preiskalkulation-anwenden] -- Import:: + -- Wenn du die Preiskalkulation für _viele Artikel_ speichern möchtest, dann empfiehlt es sich, die Preiskalkulation <> zu verknüpfen. Verwende dazu den <> und das Zuordnungsfeld *Varianten / Preiskalkulation UUID*. Gib die UUID der Preiskalkulation in die CSV-Datei ein. Dadurch wird die Preiskalkulation auf die für die Variante gespeicherten Preise angewendet. *_Tipp_*: Die Preiskalkulation-UUID kannst du kopieren. Öffne dazu das Menü *Artikel » Preiskalkulation » [Preiskalkulation öffnen]*. Klicke auf die UUID unten links. Die UUID wird in die Zwischenablage kopiert. *_Importiere die Preiskalkulation-UUID zum Schluss_*: Stell dir vor, deine Preise werden nach der folgenden Formel berechnet: `(EK + Transport) * 1.07`. In diesem Fall musst du zuerst den Einkaufspreis und die Transportkosten importieren und danach die Preiskalkulation. Sonst verfügt plentymarkets nicht über alle nötigen Informationen, um den Preis korrekt zu berechnen. . <>, die die Preisbestandteile Einkaufspreis und Transportkosten importiert. . <> im selben Import, die die Preiskalkulation-UUID importiert. + → Die Zuordnungen werden nacheinander abgearbeitet. -- Gruppenfunktion oder Stapelverarbeitung:: + -- Wenn du die Preiskalkulation für _viele Artikel_ speichern möchtest, dann empfiehlt es sich, die Preiskalkulation per Varianten-Gruppenfunktion oder Stapelverarbeitung zu verknüpfen. [discrete] ===== Varianten-Gruppenfunktion include::../import-export-anlage/anlage/massenbearbeitung.adoc[tag=varianten-gruppenfunktion] . Aktiviere die Option *Preiskalkulation* (icon:check-square[role=""blue""]) und wähle eine bereits erstellte Kalkulation aus der Dropdown-Liste. . Klicke auf icon:execute[set=plenty] *Ausführen*, um die Einstellungen an den Varianten vorzunehmen. [discrete] ===== Stapelverarbeitung include::../import-export-anlage/anlage/massenbearbeitung.adoc[tag=varianten-stapelverarbeitung] . Aktiviere _rechts_ die Option *Preiskalkulation* (icon:check-square[role=""blue""]) und wähle eine bereits erstellte Kalkulation aus der Dropdown-Liste. . Klicke auf icon:execute[set=plenty] *Anwenden*, um die Einstellungen an den Varianten vorzunehmen. -- ==== [IMPORTANT] .Nur eine Preiskalkulation pro Variante ==== Pro Variante kann nur eine Preiskalkulation verknüpft sein. Stell dir vor, du hast bereits eine Preiskalkulation mit einer Variante verknüpft. Dann verknüpfst du eine zweite Preiskalkulation mit der selben Variante. In diesem Fall wird die zweite Preiskalkulation die erste überschreiben. Beide Preiskalkulationen können nicht gleichzeitig mit der Variante verknüpft sein. Dennoch ist es möglich, Preise z.B. im plentyShop und auf Amazon unterschiedlich zu berechnen. Füge dazu <> zu deiner Preiskalkulation hinzu. ==== [#2200] === Fragen und Antworten [.collapseBox] .*Welche Aktionen lösen eine Neuberechnung der Preise aus?* -- * *_Preiskalkulation ändern_*: Das Speichern von Änderungen an einer aktiven Preiskalkulation (icon:toggle-on[role=""blue""]) führt zu einer Neuberechnung der Preise. Genauer gesagt, wird die Neuberechnung angestoßen, wenn ein Wert im Kalkulations-Baustein geändert wurde (Formel, Zielpreis, Rundungsverhalten). Das Speichern ohne Änderungen oder das Ändern eines Namens löst keine Neuberechnung aus. Beim Speichern öffnet sich ein Pop-up-Fenster. Du wirst aufgefordert, deine Entscheidung zu bestätigen. Du siehst, wie viele Varianten betroffen werden. * *_Wert einer Variable ändern_*: Stell dir vor, deine Preise werden nach der folgenden Formel berechnet: `(EK + Transport + Lager + Steuer) * 1.07`. Änderst du den Einkaufspreis, Transportkosten, Lagerkosten oder Steuern eines Produkts, fließen die neuen Daten in die Formel ein und der Preis wird neu berechnet. <>, die du zu einer Formel hinzufügen kannst, werden ständig auf Änderungen überwacht. *_Hinweis_*: Preise werden nicht sofort neu berechnet. Stattdessen beginnt die Neuberechnung nach einer kurzen Verzögerung (ca. 3 Minuten). -- [.collapseBox] .*Wann werden meine Preise neu berechnet?* -- Preise werden nicht sofort neu berechnet. Stattdessen beginnt die Neuberechnung nach einer kurzen Verzögerung (ca. 3 Minuten nach Auslösung). Änderst du zum Beispiel den Einkaufspreis eines Produkts, dann beginnt die Neuberechnung etwa 3 Minuten später. Warum nicht sofort? Oftmals wird mehr als nur eine Änderung am Produkt vorgenommen. Vielleicht musst du zum Beispiel den Einkaufspreis und die Transportkosten eines Produkts ändern. Würden die Preise sofort neu berechnet, wäre die erste Neuberechnung vielleicht noch nicht abgeschlossen, bevor die zweite beginnt. -- [.collapseBox] .*Was passiert, wenn ein Wert aus der Formel fehlt?* -- Der Preis wird nicht berechnet. Stell dir vor, deine Preise werden nach der folgenden Formel berechnet: `(EK + Transport + Lager + Steuer) * 1.07`. Hast du in diesem Fall keinen Einkaufspreis gespeichert, dann wird der Preis nicht berechnet. <>, um zu prüfen, ob Werte für deine Produkte fehlen. Der Fehlerbericht zeigt an, welche Varianten nicht berechnet werden können und warum. -- [.collapseBox] .*Was passiert, wenn der berechnete Preis 0 ist?* -- plentymarkets verhindert, dass Preise versehentlich mit dem Wert 0,00 gespeichert werden. Sowohl vor als auch nach der Rundung wird geprüft, ob der berechnete Preis 0 ist. Ist dies der Fall, dann wird der Preis nicht gespeichert und der <> enthält Informationen über das Problem. -- [.collapseBox] .*Was passiert, wenn ich einen Zielpreis wähle, der noch nicht mit der Variante verknüpft wurde?* -- Kein Problem. Beim Auslösen der Preiskalkulation wird der Verkaufspreis mit der Variante verknüpft und der Geldpreis berechnet. -- [.collapseBox] .*Kann ich mehrere Preiskalkulationen auf dieselbe Variante anwenden?* -- Nein. Pro Variante kann nur eine Preiskalkulation verknüpft sein. Stell dir vor, du hast bereits eine Preiskalkulation mit einer Variante verknüpft. Dann verknüpfst du eine zweite Preiskalkulation mit der selben Variante. In diesem Fall wird die zweite Preiskalkulation die erste überschreiben. Beide Preiskalkulationen können nicht gleichzeitig mit der Variante verknüpft sein. Dennoch ist es möglich, Preise z.B. im plentyShop und auf Amazon unterschiedlich zu berechnen. Füge dazu <> zu deiner Preiskalkulation hinzu. -- [#2300] == Alte Preiskalkulation (wird zukünftig eingestellt) . Öffne das Menü *Einrichtung » Artikel » Preiskalkulation*. . Klicke auf icon:plus[role=""green""] *Neue Preiskalkulation*. + → Das Fenster *Neue Preiskalkulation* wird geöffnet. . Gib einen Namen ein. . Klicke auf icon:plus[role=""green""] *Hinzufügen*. + → Die neue Preiskalkulation wird geöffnet. . Nimm die Einstellungen vor. Beachte <>. . *Speichere* (icon:save[set=plenty, role=""green""]) die Einstellungen. [[table-create-price-calculation]] .Preiskalkulation erstellen [cols=""1,3""] |==== |Einstellung |Erläuterung 2+|Einstellungen | *Name* |Name für die Preiskalkulation eingeben. Der Name wird im Bereich *Verkaufspreise* im Tab *Einstellungen* einer Artikelvariante angezeigt. | *Preisquelle* |Preis wählen, der als Grundlage für die Preiskalkulation dient. | *Transportkosten* |Aktivieren, um Transportkosten zur Preisquelle zu addieren. Die Transportkosten werden im Bereich *Kosten* im Tab *Einstellungen* einer Artikelvariante eingegeben. | *Lagerkosten* |Aktivieren, um Lagerkosten zur Preisquelle zu addieren. Die Lagerkosten werden im Bereich *Kosten* im Tab *Einstellungen* einer Artikelvariante eingegeben. | *Zoll* |Aktivieren, um Zollkosten zur Preisquelle zu addieren. Die Zollkosten werden im Bereich *Kosten* im Tab *Einstellungen* einer Artikelvariante eingegeben. Die Zollkosten werden in Prozent angegeben. | *Betriebskosten* |Aktivieren, um Betriebskosten zur Preisquelle zu addieren. Die Betriebskosten werden im Bereich *Kosten* im Tab *Einstellungen* einer Artikelvariante eingegeben. Die Betriebskosten werden in Prozent angegeben. | *MwSt.* |Aktivieren, um die Umsatzsteuer zur Preisquelle zu addieren. Der Umsatzsteuersatz wird im Bereich *Kosten* im Tab *Einstellungen* einer Artikelvariante gewählt. Die Umsatzsteuer wird in Prozent angegeben. 2+|Verknüpfungen | *Hinzufügen* |Auf *Hinzufügen* klicken, um eine neue Verknüpfung zu erstellen. | *Ziel* |Preis wählen, der als Zielpreis für die Preiskalkulation dient. | *Operator* |Operator wählen. *Plus*, *Minus*, *Plus Prozentwert*, *Minus Prozentwert*, *Mal* und *Geteilt* stehen zur Auswahl. | *Operand* |Numerischen Wert eingeben. | *Mandant (Shop)* |Diese Option bezieht sich _nur_ auf die <>. Mandant (Shop) wählen, der mit der Preiskalkulation verknüpft wird. | *Herkunft* |Diese Option bezieht sich _nur_ auf die <>. Herkunft wählen, die mit der Preiskalkulation verknüpft wird. |==== ",16302,True,3264.716525805253,median " == Lab {counter:labs}: Getting Started The primary data source for this workshop is a MySQL database running in your data center. Connected to this database is a orders application which we will discuss shortly. image::./1_mysql.png[] === Database Schema The MySQL database contains a simple schema that includes _Customer_, _Supplier_, _Product_, _Sales Order_ and _Purchase Order_ information. The idea behind this schema is simple, customers order products from a company and sales orders get created, the company then sends purchase orders to their suppliers so that product demand can be met by maintaining sensible stock levels. image::./mysql_schema.png[MySQL schema] We can inspect this schema further by logging into the MySQL CLI... [source] ---- docker exec -it mysql bash -c 'mysql -u root -p$MYSQL_ROOT_PASSWORD --database orders' ---- ...and viewing your tables [source] ---- show tables; ---- There's an extra table here called `{dc}_out_of_stock_events` that not in the schema diagram above, we'll cover this table separately later on. [source,subs=""attributes""] ---- +--------------------------+ | Tables_in_orders | +--------------------------+ | customers | | {dc}_out_of_stock_events | | products | | purchase_order_details | | purchase_orders | | sales_order_details | | sales_orders | | suppliers | +--------------------------+ 8 rows in set (0.00 sec) ---- Let's view the row count for each table [source] ---- SELECT * from ( SELECT 'customers' as table_name, COUNT(*) FROM customers UNION SELECT 'products' as table_name, COUNT(*) FROM products UNION SELECT 'suppliers' as table_name, COUNT(*) FROM suppliers UNION SELECT 'sales_orders' as table_name, COUNT(*) FROM sales_orders UNION SELECT 'sales_order_details' as table_name, COUNT(*) FROM sales_order_details UNION SELECT 'purchase_orders' as table_name, COUNT(*) FROM purchase_orders UNION SELECT 'purchase_order_details' as table_name, COUNT(*) FROM purchase_order_details ) row_counts; ---- As you can see, we have 30 customers, suppliers and products, 0 sales orders and 1 purchase order. [source] ---- +------------------------+----------+ | table_name | COUNT(*) | +------------------------+----------+ | customers | 30 | | products | 30 | | suppliers | 30 | | sales_orders | 0 | | sales_order_details | 0 | | purchase_orders | 1 | | purchase_order_details | 30 | +------------------------+----------+ 7 rows in set (0.00 sec) ---- The single purchase order was created so we have something in stock to sell, let's have a look at what was ordered. [source] ---- SELECT * FROM purchase_order_details; ---- [source] ---- +----+-------------------+------------+----------+------+ | id | purchase_order_id | product_id | quantity | cost | +----+-------------------+------------+----------+------+ | 1 | 1 | 1 | 100 | 6.82 | | 2 | 1 | 2 | 100 | 7.52 | | 3 | 1 | 3 | 100 | 6.16 | | 4 | 1 | 4 | 100 | 8.07 | | 5 | 1 | 5 | 100 | 2.10 | | 6 | 1 | 6 | 100 | 7.45 | | 7 | 1 | 7 | 100 | 4.02 | | 8 | 1 | 8 | 100 | 0.64 | | 9 | 1 | 9 | 100 | 8.51 | | 10 | 1 | 10 | 100 | 3.61 | | 11 | 1 | 11 | 100 | 2.62 | | 12 | 1 | 12 | 100 | 2.60 | | 13 | 1 | 13 | 100 | 1.26 | | 14 | 1 | 14 | 100 | 4.08 | | 15 | 1 | 15 | 100 | 3.56 | | 16 | 1 | 16 | 100 | 7.13 | | 17 | 1 | 17 | 100 | 7.64 | | 18 | 1 | 18 | 100 | 5.94 | | 19 | 1 | 19 | 100 | 2.94 | | 20 | 1 | 20 | 100 | 1.91 | | 21 | 1 | 21 | 100 | 8.89 | | 22 | 1 | 22 | 100 | 7.62 | | 23 | 1 | 23 | 100 | 6.19 | | 24 | 1 | 24 | 100 | 2.83 | | 25 | 1 | 25 | 100 | 5.51 | | 26 | 1 | 26 | 100 | 4.23 | | 27 | 1 | 27 | 100 | 8.33 | | 28 | 1 | 28 | 100 | 7.09 | | 29 | 1 | 29 | 100 | 1.75 | | 30 | 1 | 30 | 100 | 1.72 | +----+-------------------+------------+----------+------+ 30 rows in set (0.00 sec) ---- Here we have a single purchase order that is procuring 100 of each product, this reflects our initial and current stock levels. Type `exit` to leave the MySQL CLI === Starting the Orders Application To start generating some sales orders we need to start the orders application. This application will continuously create new sales orders to simulate product demand. The application will also raise purchase orders when told to do so, we'll cover this aspect later on in the workshop. Start the orders application by running the following command. [IMPORTANT] ==== [source] ---- docker exec -dit db-trans-simulator sh -c ""python -u /simulate_dbtrans.py > /proc/1/fd/1 2>&1"" ---- ==== Confirm that the simulator is working as expected [source] ---- docker logs -f db-trans-simulator ---- You should see an output like this: [source] ---- Sales Order 1 Created Sales Order 2 Created Sales Order 3 Created Sales Order 4 Created Sales Order 5 Created Sales Order 6 Created ... ---- Press `ctrl-c` to quit We now have `sales_order` and `sales_order_details` rows being created for us by the orders application. == Lab {counter:labs}: Stream Events to Confluent Platform Now that we have data being automatically created in our MySQL database it's time to stream those changes into your on-premise Kafka cluster. We can do this using the link:https://debezium.io/documentation/reference/1.0/connectors/mysql.html[Debezium MySQL Source connector , window=_blank] image::./2_mysql_source_connector.png[] === Create the MySQL source connector We have a Kafka Connect worker already up and running in a docker container called `kafka-connect-onprem`. This Kafka Connect worker is configured to connect to your on-premise Kafka cluster and has a internal REST server listening on port `18083`. We can create a connector from the command line using the cURL command. The cURL command allows us to send an HTTP POST request to the REST server, the '-H' option specifies the header of the request and includes the target host and port information, the `-d` option specifies the data we will send, in this case its the configuration options for the connector. You can of course create and manage connectors using any tool or language capable of issuing HTTP requests. To create the Debezium MySQL Source connector instance run the following command:- [IMPORTANT] ==== [source,subs=""attributes""] ---- curl -i -X POST -H ""Accept:application/json"" \\ -H ""Content-Type:application/json"" http://localhost:18083/connectors/ \\ -d '{ ""name"": ""mysql-source-connector"", ""config"": { ""connector.class"": ""io.debezium.connector.mysql.MySqlConnector"", ""database.hostname"": ""mysql"", ""database.port"": ""3306"", ""database.user"": ""mysqluser"", ""database.password"": ""mysqlpw"", ""database.server.id"": ""12345"", ""database.server.name"": ""{dc}"", ""database.whitelist"": ""orders"", ""table.blacklist"": ""orders.{dc}_out_of_stock_events"", ""database.history.kafka.bootstrap.servers"": ""broker:29092"", ""database.history.kafka.topic"": ""debezium_dbhistory"" , ""include.schema.changes"": ""false"", ""snapshot.mode"": ""when_needed"", ""transforms"": ""unwrap,sourcedc,TopicRename,extractKey"", ""transforms.unwrap.type"": ""io.debezium.transforms.UnwrapFromEnvelope"", ""transforms.sourcedc.type"":""org.apache.kafka.connect.transforms.InsertField$Value"", ""transforms.sourcedc.static.field"":""sourcedc"", ""transforms.sourcedc.static.value"":""{dc}"", ""transforms.TopicRename.type"": ""org.apache.kafka.connect.transforms.RegexRouter"", ""transforms.TopicRename.regex"": ""(.*)\\\\.(.*)\\\\.(.*)"", ""transforms.TopicRename.replacement"": ""$1_$3"", ""transforms.extractKey.type"": ""org.apache.kafka.connect.transforms.ExtractField$Key"", ""transforms.extractKey.field"": ""id"", ""key.converter"": ""org.apache.kafka.connect.converters.IntegerConverter"" } }' ---- ==== We can confirm the connector is running by querying the REST interface [source] ---- curl -s localhost:18083/connectors/mysql-source-connector/status | jq ---- You should see that the connector's state is `RUNNING` [source] ---- { ""name"": ""mysql-source-connector"", ""connector"": { ""state"": ""RUNNING"", ""worker_id"": ""kafka-connect-onprem:18083"" }, ""tasks"": [ { ""id"": 0, ""state"": ""RUNNING"", ""worker_id"": ""kafka-connect-onprem:18083"" } ], ""type"": ""source"" } ---- === View Messages in Confluent Control Center Now that the MySQL source connector is up and running, we will be able to see messages appear in our local Kafka cluster. We can use link:http://{externalip}:9021[Confluent Control Center, window=_blank] to confirm this. Use the following and username and password to authenticate to Confluent Control Center [source,subs=""attributes""] ---- Username: {dc} Password: your workshop password ---- image::./c3_05.png[] On the landing page we can see that Confluent Control Center is monitoring two Kafka Clusters, our on-premise cluster and a Confluent Cloud Cluster image::./c3_10.png[] Click on the ""controlcenter.cluster"" tile, this is your on-premise cluster. image::./c3_20.png[] Select the Topics Menu on the left image::./c3_30.png[] Select the `{dc}_sales_order_details` topic image::./c3_40.png[] Finally select the Messages tab and observe that messages are being streamed into Kafka from MySQL in real time. image::./c3_50.png[] .Further Reading [TIP] ==== * link:https://debezium.io/documentation/reference/1.1/connectors/mysql.html#mysql-connector-configuration-properties_debezium[Debezium MySQL Configuration Options , window=_blank] * link:https://docs.confluent.io/current/connect/references/restapi.html[Kafka Connect REST API] * link:https://curl.haxx.se/docs/manpage.html[cURL manpage] * link:https://docs.confluent.io/current/control-center/index.html[Confluent Control Center Documentation] ==== == Lab {counter:labs}: Stream Events to Confluent Cloud Now that your on-premise Kafka cluster is receiving events from your MySQL Database let's use Confluent Replicator to stream those messages to Confluent Cloud image::./3_replicate_to_ccloud.png[] === Create the Replicator Connector Instance Confluent Replicator uses Kafka Connect under the covers and can be considered a special type of connector, however, unlike other connectors, the source _and_ target technology for the connector is a Kafka Cluster. To support this connector, we have another Kafka Connect worker running in a different docker container called `kafka-connect-ccloud`. This Kafka Connect worker is configured to connect to the Confluent Cloud instance provisioned for this workshop. This Kafka Connect worker has an internal REST server listening on port `18084`. Run the following from the command line to create the Replicator Connector instance, this connector will replicate events from you on-premise Kafka cluster to your Confluent Cloud Cluster. [IMPORTANT] ==== [source,subs=""attributes""] ---- curl -i -X POST -H ""Accept:application/json"" \\ -H ""Content-Type:application/json"" http://localhost:18084/connectors/ \\ -d '{ ""name"": ""replicator-{dc}-to-ccloud"", ""config"": { ""connector.class"": ""io.confluent.connect.replicator.ReplicatorSourceConnector"", ""key.converter"": ""io.confluent.connect.replicator.util.ByteArrayConverter"", ""value.converter"": ""io.confluent.connect.replicator.util.ByteArrayConverter"", ""topic.config.sync"": false, ""topic.regex"": ""dc[0-9][0-9][_].*"", ""topic.blacklist"": ""{dc}_out_of_stock_events"", ""dest.kafka.bootstrap.servers"": ""${file:/secrets.properties:CCLOUD_CLUSTER_ENDPOINT}"", ""dest.kafka.security.protocol"": ""SASL_SSL"", ""dest.kafka.sasl.mechanism"": ""PLAIN"", ""dest.kafka.sasl.jaas.config"": ""org.apache.kafka.common.security.plain.PlainLoginModule required username=\\""${file:/secrets.properties:CCLOUD_API_KEY}\\"" password=\\""${file:/secrets.properties:CCLOUD_API_SECRET}\\"";"", ""dest.kafka.replication.factor"": 3, ""src.kafka.bootstrap.servers"": ""broker:29092"", ""src.consumer.group.id"": ""replicator-{dc}-to-ccloud"", ""src.consumer.interceptor.classes"": ""io.confluent.monitoring.clients.interceptor.MonitoringConsumerInterceptor"", ""src.consumer.confluent.monitoring.interceptor.bootstrap.servers"": ""broker:29092"", ""src.kafka.timestamps.producer.interceptor.classes"": ""io.confluent.monitoring.clients.interceptor.MonitoringProducerInterceptor"", ""src.kafka.timestamps.producer.confluent.monitoring.interceptor.bootstrap.servers"": ""broker:29092"", ""tasks.max"": ""1"" } }' ---- ==== Confirm that Replicator is in a `RUNNING` state [source,subs=""attributes""] ---- curl -s localhost:18084/connectors/replicator-{dc}-to-ccloud/status | jq ---- [source,subs=""attributes""]] ---- { ""name"": ""replicator-{dc}-to-ccloud"", ""connector"": { ""state"": ""RUNNING"", ""worker_id"": ""kafka-connect-ccloud:18084"" }, ""tasks"": [ { ""id"": 0, ""state"": ""RUNNING"", ""worker_id"": ""kafka-connect-ccloud:18084"" } ], ""type"": ""source"" } ---- === Confirm that Messages are Arriving in Confluent Cloud Jump back to link:http://{externalip}:9021[Confluent Control Center, window=_blank] You can always reach back the home by clicking on the confluent logo on the top left, or by clicking ont the HOME in the top navigation bar. Select the ""ccloud"" cluster and then select ""Topics"". This Confluent Cloud Instance is being shared by other users of the workshop and as a result you will see topics being replicated from other data centers. To see just your topics, type your data center name, {dc}, into the search box at the top to filter. image::./c3_60.png[] Select the `{dc}_sales_order_details` topic and finally the ""Messages"" tab under the topic heading. You should see messages streaming in from your on-premise Kafka cluster. image::./c3_70.png[] We can also view the status of Replicator in Confluent Control Center by selecting ""Replicators"" on the left-hand navigation pane. Here we can see throughput and latency statistics. image::./c3_72.png[] .Further Reading [TIP] ==== * link:https://docs.confluent.io/current/connect/kafka-connect-replicator/index.html[Confluent Replicator] * link:https://docs.confluent.io/current/connect/kafka-connect-replicator/configuration_options.html[Confluent Replicator Configuration Properties] ==== == Lab {counter:labs}: Creating a ksqlDB Application We now have all the data we need being streamed, in realtime, to Confluent Cloud. You have a ksqlDB Server running inside a docker container that is configured to point to our Confluent Cloud cluster. In a real world deployment, it is likely that this ksqlDB Server would be running closer to Confluent Cloud but for the purposes of this workshop it is not important. image::./4_ksql_application.png[] Below is an illustration of the completed Supply & Demand ksqlDB Application, over the next few labs you will be building this step-by-step. image::./ksqlDB_topology.png[] === Start the ksqlDB CLI To start the ksqlDB CLI run the following command:- [IMPORTANT] ==== [source,subs=""attributes""] ---- docker exec -it ksqldb-cli ksql http://ksqldb-server-ccloud:8088 ---- ==== You should see something like this:- ``` =========================================== = _ _ ____ ____ = = | | _____ __ _| | _ \\| __ ) = = | |/ / __|/ _` | | | | | _ \\ = = | <\\__ \\ (_| | | |_| | |_) | = = |_|\\_\\___/\\__, |_|____/|____/ = = |_| = = Event Streaming Database purpose-built = = for stream processing apps = =========================================== Copyright 2017-2020 Confluent Inc. CLI v6.1.1, Server v6.1.1 located at http://ksqldb-server-ccloud:8088 Having trouble? Type 'help' (case-insensitive) for a rundown of how things work! ksql> ``` The ksqlDB CLI is pointing at a ksqlDB Server connected to your Confluent Cloud instance. To view a list of all topics in Confluent Cloud run the following command:- `show topics;` You should see your own topics, `{dc}_*`, along with topics from other workshop users. ``` ksql> show topics; Kafka Topic | Partitions | Partition Replicas --------------------------------------------------------------- dc01_customers | 1 | 3 dc01_products | 1 | 3 dc01_purchase_order_details | 1 | 3 dc01_purchase_orders | 1 | 3 dc01_sales_order_details | 1 | 3 dc01_sales_orders | 1 | 3 dc01_suppliers | 1 | 3 dc02_customers | 1 | 3 dc02_products | 1 | 3 dc02_purchase_order_details | 1 | 3 dc02_purchase_orders | 1 | 3 dc02_sales_order_details | 1 | 3 ... ``` === Inspect a topic\\'s contents To inspect the contents of a topic run the following:- `PRINT {dc}_sales_orders;` You should see something similar:- [source,subs=""attributes""] ---- ksql> PRINT {dc}_sales_orders; Key format: AVRO Value format: AVRO rowtime: 2020/05/20 10:10:29.264 Z, key: {""id"": 1}, value: {""id"": 1, ""order_date"": 1589969387000, ""customer_id"": 14, ""sourcedc"": ""{dc}""} rowtime: 2020/05/20 10:10:29.265 Z, key: {""id"": 2}, value: {""id"": 2, ""order_date"": 1589969392000, ""customer_id"": 14, ""sourcedc"": ""{dc}""} rowtime: 2020/05/20 10:10:29.265 Z, key: {""id"": 3}, value: {""id"": 3, ""order_date"": 1589969397000, ""customer_id"": 14, ""sourcedc"": ""{dc}""} rowtime: 2020/05/20 10:10:29.265 Z, key: {""id"": 4}, value: {""id"": 4, ""order_date"": 1589969402000, ""customer_id"": 7, ""sourcedc"": ""{dc}""} ... ---- Press `ctrl-c` to stop === ksqlDB Streams In order to work with a stream of data in ksqlDB we first need to register a stream over an existing topic. We can do this using a `CREATE STREAM` statement. Run the following command to create your first ksqlDB stream:- [IMPORTANT] ==== [source,subs=""quotes,attributes""] ---- *CREATE STREAM* sales_orders *WITH* (KAFKA_TOPIC='{dc}_sales_orders', PARTITIONS=1, VALUE_FORMAT='AVRO'); ---- ==== image::./ksql_001.png[align=""center""] You should see the following output [source,subs=""attributes""] ---- ksql> CREATE STREAM sales_orders WITH (KAFKA_TOPIC='{dc}_sales_orders', PARTITIONS=1, VALUE_FORMAT='AVRO'); Message ---------------- Stream created ---------------- ---- Create streams for each of your remaining topics [IMPORTANT] ==== [source,subs=""quotes,attributes""] ---- *CREATE STREAM* sales_order_details *WITH* (KAFKA_TOPIC='{dc}_sales_order_details', PARTITIONS=1, VALUE_FORMAT='AVRO'); *CREATE STREAM* purchase_orders *WITH* (KAFKA_TOPIC='{dc}_purchase_orders', PARTITIONS=1, VALUE_FORMAT='AVRO'); *CREATE STREAM* purchase_order_details *WITH* (KAFKA_TOPIC='{dc}_purchase_order_details', PARTITIONS=1, VALUE_FORMAT='AVRO'); *CREATE STREAM* products *WITH* (KAFKA_TOPIC='{dc}_products', PARTITIONS=1, VALUE_FORMAT='AVRO'); *CREATE STREAM* customers *WITH* (KAFKA_TOPIC='{dc}_customers', PARTITIONS=1, VALUE_FORMAT='AVRO'); *CREATE STREAM* suppliers *WITH* (KAFKA_TOPIC='{dc}_suppliers', PARTITIONS=1, VALUE_FORMAT='AVRO'); ---- ==== image::./ksql_002.png[align=""center""] To view your current streams run the following command:- [source,subs=""quotes,attributes""] ---- SHOW STREAMS; ---- Notice that each stream is mapped to an underlying Kafka topic and that the format is AVRO. [source,subs=""attributes""] ---- Stream Name | Kafka Topic | Format --------------------------------------------------------------- CUSTOMERS | {dc}_customers | AVRO PRODUCTS | {dc}_products | AVRO PURCHASE_ORDERS | {dc}_purchase_orders | AVRO PURCHASE_ORDER_DETAILS | {dc}_purchase_order_details | AVRO SALES_ORDERS | {dc}_sales_orders | AVRO SALES_ORDER_DETAILS | {dc}_sales_order_details | AVRO SUPPLIERS | {dc}_suppliers | AVRO --------------------------------------------------------------- ---- To view the details of an individual topic you can you can use the `describe` command:- [source,subs=""quotes,attributes""] ---- *DESCRIBE* sales_order_details; ---- Notice that all the columns have been created for us and we didn't need to explicitly set their names and data types when we created the stream, this is one of the advantages of using AVRO and the Schema Registry. [source,subs=""attributes""] ---- Name : SALES_ORDER_DETAILS Field | Type ---------------------------------- ID | INTEGER SALES_ORDER_ID | INTEGER PRODUCT_ID | INTEGER QUANTITY | INTEGER PRICE | DECIMAL SOURCEDC | VARCHAR(STRING) ---------------------------------- For runtime statistics and query details run: DESCRIBE EXTENDED ; ---- .Further Reading [TIP] ==== * link:https://docs.ksqldb.io/en/latest/[ksqlDB Overview] * link:https://docs.ksqldb.io/en/latest/developer-guide/create-a-stream/[ksqlDB Streams] ==== == Lab {counter:labs}: Querying Streams with ksqlDB There are two types of query in ksqlDB, *Push* queries and *Pull* queries. * https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/select-push-query/[Push Queries] enable you to subscribe to a result as it changes in real-time. You can subscribe to the output of any query, including those that return a stream or a materialized aggregate table. The `EMIT CHANGES` clause is used to indicate a query is a push query. * https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/select-pull-query/[Pull Queries] enable you to look up information at a point in time. Another important point to understand is where within a stream a query starts to read from. You can control this behaviour using the `ksql.streams.auto.offset.reset` property. This property can either be set to `earliest` where data is consumed from the very beginning of the topic or `latest` where only new data is consumed. To see the current values for _all_ properties run the following command [source,subs=""quotes,attributes""] ---- SHOW PROPERTIES; ---- Look out for a property called `ksql.streams.auto.offset.reset`, it should currently be set to `earliest`. [source,subs=""attributes""] ---- Property | Default override | Effective Value -------------------------------------------------------------------------------------------- ... ksql.streams.auto.offset.reset | | earliest ... -------------------------------------------------------------------------------------------- ksql> ---- You can override this setting to suit you needs:- [source,subs=""quotes,attributes""] ---- *SET* 'ksql.streams.auto.offset.reset'='earliest'; *SET* 'ksql.streams.auto.offset.reset'='latest'; ---- Or preferably, using the abbreviated property names:- [source,subs=""quotes,attributes""] ---- *SET* 'auto.offset.reset' = 'latest'; *SET* 'auto.offset.reset' = 'earliest'; ---- Let's start by running a Push query and consume all messages from the beginning of a stream. [source,subs=""quotes,attributes""] ---- *SET* 'auto.offset.reset'='earliest'; *SELECT* id, sales_order_id, product_id, quantity, price *FROM* sales_order_details *EMIT CHANGES*; ---- You should see something similar to this:- ``` ksql> SELECT id, sales_order_id, product_id, quantity, price FROM sales_order_details EMIT CHANGES; +-----------------+-----------------+-----------------+-----------------+-----------------+ |ID |SALES_ORDER_ID |PRODUCT_ID |QUANTITY |PRICE | +-----------------+-----------------+-----------------+-----------------+-----------------+ |1 |1 |1 |10 |2.68 | |2 |1 |23 |1 |9.01 | |3 |1 |14 |6 |5.84 | |4 |2 |12 |7 |4.00 | |5 |2 |9 |4 |9.83 | |6 |2 |5 |1 |8.81 | |7 |2 |3 |8 |9.99 | |8 |2 |1 |9 |2.68 | |9 |3 |21 |5 |9.90 | |10 |3 |2 |1 |8.23 | |11 |3 |4 |2 |9.78 | |12 |4 |15 |2 |6.16 | ... ... |480 |157 |26 |5 |9.03 | |481 |158 |2 |2 |8.23 | |482 |159 |10 |4 |5.32 | |483 |160 |25 |8 |9.00 | ``` Press `ctrl-c` to stop Notice that events continue to stream to the console until you explicitly cancel the query, this is because when we are working with streams in ksqlDB the data set is unbounded and could theoretically continue forever. To inspect a bounded set of data, you can use the `LIMIT` clause. [source,subs=""quotes,attributes""] ---- *SELECT* id, sales_order_id, product_id, quantity, price *FROM* sales_order_details *EMIT CHANGES* *LIMIT* 10; ---- Here we are seeing the first 10 messages that were written to the topic. Notice that the query automatically terminates when the limit of 10 events is reached. [source,subs=""attributes""] ---- +-----------------+-----------------+-----------------+-----------------+-----------------+ |ID |SALES_ORDER_ID |PRODUCT_ID |QUANTITY |PRICE | +-----------------+-----------------+-----------------+-----------------+-----------------+ |1 |1 |1 |10 |2.68 | |2 |1 |23 |1 |9.01 | |3 |1 |14 |6 |5.84 | |4 |2 |12 |7 |4.00 | |5 |2 |9 |4 |9.83 | |6 |2 |5 |1 |8.81 | |7 |2 |3 |8 |9.99 | |8 |2 |1 |9 |2.68 | |9 |3 |21 |5 |9.90 | |10 |3 |2 |1 |8.23 | Limit Reached Query terminated ksql> ---- === Filtering Streams Since ksqlDB is based on SQL, you can do many of the standard SQL things you'd expect to be able to do, including predicates and projections. The following query will return a stream of you the latest sales orders where the `quantity` column is greater than 3. [source,subs=""quotes,attributes""] ---- *SET* 'auto.offset.reset'='latest'; *SELECT* id, product_id, quantity *FROM* sales_order_details *WHERE* quantity > 3 *EMIT CHANGES*; ---- You should only see events where the `quantity` column value is greater than `3`. [source] ---- +------------------------------+------------------------------+------------------------------+ |ID |PRODUCT_ID |QUANTITY | +------------------------------+------------------------------+------------------------------+ |3153 |22 |8 | |3154 |4 |6 | |3155 |9 |4 | |3156 |25 |10 | |3158 |24 |8 | |3159 |7 |4 | |3161 |28 |8 | |3162 |22 |7 | |3163 |24 |6 | |3165 |5 |8 | |3167 |21 |9 | ---- Press `ctrl-c` to stop .Further Reading [TIP] ==== * link:https://docs.confluent.io/current/ksql/docs/developer-guide/syntax-reference.html#push-query[Push Query Syntax] * link:https://docs.confluent.io/current/ksql/docs/developer-guide/syntax-reference.html#pull-query[Pull Query Syntax] * link:https://docs.confluent.io/current/ksql/docs/installation/server-config/config-reference.html#ksql-streams-auto-offset-reset[ksqlDB Offset Management] ==== == Lab {counter:labs}: Creating ksqlDB tables ksqlDB tables allow you to work the data in topics as key/value pairs, with a single value for each key. Tables can be created from an existing topic or from the query results from other tables or streams. You can read more about this https://docs.confluent.io/current/streams/concepts.html#duality-of-streams-and-tables[here]. === Creating Tables We want to create tables over our `customers`, `suppliers` and `products` streams so we can look up the current state for each customer, supplier and product. Later on we'll be joining these tables to other streams. To successfully join to a table in ksqlDB you need to ensure that the table is keyed on the column you are going to use in the join. Our underlying topics already have the correct key set thanks to the Debezium MySQL connector configuration so we just need to use the `PRIMARY KEY` clause when we create each table. Create your 3 ksqlDB tables. [IMPORTANT] ==== [source,subs=""quotes,attributes""] ---- *CREATE TABLE* customers_tbl ( ROWKEY INT PRIMARY KEY, FIRST_NAME VARCHAR, LAST_NAME VARCHAR, EMAIL VARCHAR, CITY VARCHAR, COUNTRY VARCHAR, SOURCEDC VARCHAR ) *WITH* ( KAFKA_TOPIC='{dc}_customers', VALUE_FORMAT='AVRO' ); ---- ==== [IMPORTANT] ==== [source,subs=""quotes,attributes""] ---- *CREATE TABLE* suppliers_tbl ( ROWKEY INT PRIMARY KEY, NAME VARCHAR, EMAIL VARCHAR, CITY VARCHAR, COUNTRY VARCHAR, SOURCEDC VARCHAR ) *WITH* ( KAFKA_TOPIC='{dc}_suppliers', VALUE_FORMAT='AVRO' ); ---- ==== [IMPORTANT] ==== [source,subs=""quotes,attributes""] ---- *CREATE TABLE* products_tbl ( ROWKEY INT PRIMARY KEY, NAME VARCHAR, DESCRIPTION VARCHAR, PRICE DECIMAL(10,2), COST DECIMAL(10,2), SOURCEDC VARCHAR ) *WITH* ( KAFKA_TOPIC='{dc}_products', VALUE_FORMAT='AVRO' ); ---- ==== image::./ksql_005.png[align=""center""] We can view our current tables using the following command:- [source,subs=""attributes""] ---- SHOW TABLES; ---- [source,subs=""attributes""] ---- Table Name | Kafka Topic | Format | Windowed ---------------------------------------------------- CUSTOMERS_TBL | {dc}_customers | AVRO | false PRODUCTS_TBL | {dc}_products | AVRO | false SUPPLIERS_TBL | {dc}_suppliers | AVRO | false ---------------------------------------------------- ---- We'll use these tables soon and join them to our streams. .Further Reading [TIP] ==== * link:https://docs.confluent.io/current/ksql/docs/developer-guide/syntax-reference.html#create-table[CREATE TABLE Syntax] * link:https://docs.confluent.io/current/ksql/docs/developer-guide/syntax-reference.html#describe[DESCRIBE Syntax] * link:https://docs.confluent.io/current/ksql/docs/developer-guide/syntax-reference.html#create-stream-as-select[CREATE STREAM AS SELECT Syntax] ==== == Lab {counter:labs}: Joining Streams & Tables with ksqlDB We can join two streams together in ksqlDB using a windowed join. When using a windowed join, you must specify a windowing scheme by using the `WITHIN` clause. A new input record on one side produces a join output for each matching record on the other side, and there can be multiple such matching records within a join window. In the example below you can see that we are joining the `sales_orders` stream to the `sales_order_details` stream using a window of 1 seconds (`INNER JOIN sales_order_details od WITHIN 1 SECONDS ON (o.id = od.sales_order_id)`). The orders application creates sales orders and their associated sales order detail rows at the same time, so 1 second will be plenty of time to ensure that a join takes place. We are also joining to the `customers_tbl` and `products_tbl` tables [IMPORTANT] ==== [source,subs=""quotes,attributes""] ---- SET 'auto.offset.reset'='earliest'; *CREATE STREAM* sales_enriched *WITH* (PARTITIONS = 1, KAFKA_TOPIC = '{dc}_sales_enriched') AS SELECT o.id order_id, od.id order_details_id, o.order_date, od.product_id product_id, pt.name product_name, pt.description product_desc, od.price product_price, od.quantity product_qty, o.customer_id customer_id, ct.first_name customer_fname, ct.last_name customer_lname, ct.email customer_email, ct.city customer_city, ct.country customer_country *FROM* sales_orders o *INNER JOIN* sales_order_details od WITHIN 1 SECONDS ON (o.id = od.sales_order_id) *INNER JOIN* customers_tbl ct ON (o.customer_id = ct.rowkey) *INNER JOIN* products_tbl pt ON (od.product_id = pt.rowkey); ---- ==== image::./ksql_006.png[align=""center""] If we run a describe on this stream... [source,subs=""quotes,attributes""] ---- *DESCRIBE* sales_enriched; ---- ...you'll see that we have effectively denormalized the `sales_orders`, `sales_order_details`, `customers` and `products` streams/tables into a single event stream. [source,subs=""quotes,attributes""] ---- Name : SALES_ENRICHED Field | Type ------------------------------------------- ROWKEY | INTEGER (key) ORDER_ID | INTEGER ORDER_DETAILS_ID | INTEGER ORDER_DATE | BIGINT PRODUCT_ID | INTEGER PRODUCT_NAME | VARCHAR(STRING) PRODUCT_DESC | VARCHAR(STRING) PRODUCT_PRICE | DECIMAL PRODUCT_QTY | INTEGER CUSTOMER_ID | INTEGER CUSTOMER_FNAME | VARCHAR(STRING) CUSTOMER_LNAME | VARCHAR(STRING) CUSTOMER_EMAIL | VARCHAR(STRING) CUSTOMER_CITY | VARCHAR(STRING) CUSTOMER_COUNTRY | VARCHAR(STRING) ------------------------------------------- ---- We now need to create an equivalent `purchases_enriched` stream that combines the `purchase_orders`, `purchase_order_details`, `suppliers` and `products` streams/tables. Since the purchases data model is very similar to that of the sales data model the query looks very similar. [IMPORTANT] ==== [source,subs=""quotes,attributes""] ---- SET 'auto.offset.reset'='earliest'; *CREATE STREAM* purchases_enriched *WITH* (PARTITIONS = 1, KAFKA_TOPIC = '{dc}_purchases_enriched') AS SELECT o.id order_id, od.id order_details_id, o.order_date, od.product_id product_id, pt.name product_name, pt.description product_desc, od.cost product_cost, od.quantity product_qty, o.supplier_id supplier_id, st.name supplier_name, st.email supplier_email, st.city supplier_city, st.country supplier_country *FROM* purchase_orders o *INNER JOIN* purchase_order_details od WITHIN 1 SECONDS ON (o.id = od.purchase_order_id) *INNER JOIN* suppliers_tbl st ON (o.supplier_id = st.rowkey) *INNER JOIN* products_tbl pt ON (od.product_id = pt.rowkey); ---- ==== image::./ksql_007.png[align=""center""] If we run a describe on this stream... [source,subs=""quotes,attributes""] ---- *DESCRIBE* purchases_enriched; ---- [source,subs=""quotes,attributes""] ---- Name : PURCHASES_ENRICHED Field | Type ------------------------------------------- ROWKEY | INTEGER (key) ORDER_ID | INTEGER ORDER_DETAILS_ID | INTEGER ORDER_DATE | BIGINT PRODUCT_ID | INTEGER PRODUCT_NAME | VARCHAR(STRING) PRODUCT_DESC | VARCHAR(STRING) PRODUCT_COST | DECIMAL PRODUCT_QTY | INTEGER SUPPLIER_ID | INTEGER SUPPLIER_NAME | VARCHAR(STRING) SUPPLIER_EMAIL | VARCHAR(STRING) SUPPLIER_CITY | VARCHAR(STRING) SUPPLIER_COUNTRY | VARCHAR(STRING) ------------------------------------------- ---- ...you'll see that we have also denormalized the `purchase_orders`, `purchase_order_details`, `suppliers` and `products` streams/tables into a single event stream. Let's query the `purchases_enriched` stream from the very beginning [source,subs=""quotes,attributes""] ---- *SET* 'auto.offset.reset'='earliest'; *SELECT* product_id, product_name, product_qty *FROM* purchases_enriched *EMIT CHANGES*; ---- Notice that the query returns the first 30 purchase order lines and then stops; this is because no purchase orders are being created by our orders application. The orders application will raise purchase orders for us when we send it some out of stock events. [source,subs=""quotes,attributes""] ---- +-------------------------+----------------------------------+------------------------+ |PRODUCT_ID |PRODUCT_NAME |PRODUCT_QTY | +-------------------------+----------------------------------+------------------------+ |1 |Yogurt - Assorted Pack |100 | |2 |Ostrich - Fan Fillet |100 | |3 |Fish - Halibut, Cold Smoked |100 | |4 |Tomatoes Tear Drop Yellow |100 | |5 |Pasta - Fettuccine, Egg, Fresh |100 | |6 |Plastic Wrap |100 | |7 |Pineapple - Regular |100 | |8 |Quail - Eggs, Fresh |100 | |9 |Pork - Ground |100 | |10 |Lamb Shoulder Boneless Nz |100 | |11 |Sausage - Meat |100 | |12 |Herb Du Provence - Primerba |100 | |13 |Bread - Kimel Stick Poly |100 | |14 |Food Colouring - Red |100 | |15 |Cheese - Grie Des Champ |100 | |16 |Longos - Lasagna Veg |100 | |17 |Beets - Golden |100 | |18 |Bread - Dark Rye |100 | |19 |Pepperoni Slices |100 | |20 |Glass - Wine, Plastic, Clear 5 Oz |100 | |21 |Soup - Campbells, Beef Barley |100 | |22 |Bread - Kimel Stick Poly |100 | |23 |Plate - Foam, Bread And Butter |100 | |24 |Parsley - Fresh |100 | |25 |Cookie - Oreo 100x2 |100 | |26 |Bread - Crusty Italian Poly |100 | |27 |Wine - Chateauneuf Du Pape |100 | |28 |Country Roll |100 | |29 |Wine - Redchard Merritt |100 | |30 |Doilies - 5, Paper |100 | ---- .Further Reading [TIP] ==== * link:https://docs.ksqldb.io/en/latest/developer-guide/joins/join-streams-and-tables/[Stream-Table Joins] ==== == Lab {counter:labs}: Streaming Current Stock Levels Before we can create an out of stock event stream, we need to work out the current stock levels for each product. We can do this by combining the `sales_enriched` stream with the `purchases_enriched` stream and summing the `sales_enriched.quantity` column (stock decrements) and the `purchases_enriched.quantity` column (stock increments). Let's have a go at this now by creating a new stream called `product_supply_and_demand`. This stream is consuming messages from the `sales_enriched` stream and included the `product_id` and `quantity` column converted to a negative value, we do this because sales events are our _demand_ and hence decrement stock. [IMPORTANT] ==== [source,subs=""quotes,attributes""] ---- *SET* 'auto.offset.reset'='earliest'; *CREATE STREAM* product_supply_and_demand *WITH* (PARTITIONS=1, KAFKA_TOPIC='{dc}_product_supply_and_demand') *AS SELECT* product_id, product_qty * -1 ""QUANTITY"" *FROM* sales_enriched; ---- ==== image::./ksql_012.png[align=""center""] Let's have a quick look at the first few rows of this stream [source,subs=""quotes,attributes""] ---- *SET* 'auto.offset.reset'='earliest'; *SELECT* product_id, quantity *FROM* product_supply_and_demand *EMIT CHANGES* *LIMIT* 10; ---- This query shows a history of all sales and their affect on stock levels. [source,subs=""quotes,attributes""] ---- +------------------------------------------+------------------------------------------+ |PRODUCT_ID |QUANTITY | +------------------------------------------+------------------------------------------+ |1 |-6 | |15 |-3 | |14 |-7 | |23 |-3 | |13 |-10 | |4 |-9 | |10 |-9 | |15 |-8 | |10 |-2 | |27 |-7 | Limit Reached Query terminated ---- What we need to do now is also include all product purchases in the same stream. We can do this using an `INSERT INTO` statement. The `INSERT INTO` statement streams the result of a SELECT query into an existing stream and its underlying topic. [IMPORTANT] ==== [source,subs=""quotes,attributes""] ---- *INSERT INTO* product_supply_and_demand *SELECT* product_id, product_qty ""QUANTITY"" *FROM* purchases_enriched; ---- ==== image::./ksql_013.png[align=""center""] Our `product_supply_and_demand` now includes all product sales as stock decrements and all product purchases as stock increments. We can see the demand for a single product by filtering on the `product_id` and including only events where the `quantity` is less than zero, i.e. stock decrements. [source,subs=""quotes,attributes""] ---- *SET* 'auto.offset.reset'='earliest'; *SELECT* product_id, quantity *FROM* product_supply_and_demand *WHERE* product_id = 15 *AND* quantity < 0 *EMIT CHANGES*; ---- [source,subs=""quotes,attributes""] ---- +------------------------------------------+------------------------------------------+ |PRODUCT_ID |QUANTITY | +------------------------------------------+------------------------------------------+ |15 |-6 | |15 |-9 | |15 |-7 | |15 |-5 | |15 |-1 | |15 |-7 | |15 |-7 | |15 |-10 | |15 |-8 | |15 |-4 | |15 |-2 | ... ... ... ---- We can also see the supply for a single product by filtering on the `product_id` and including only events where the `quantity` is greater than zero, i.e. stock increments. [source,subs=""quotes,attributes""] ---- *SET* 'auto.offset.reset'='earliest'; *SELECT* product_id, quantity *FROM* product_supply_and_demand *WHERE* product_id = 15 *AND* quantity > 0 *EMIT CHANGES*; ---- This query will only return a single event and reflects the initial purchase order line that was raised for this product. [source,subs=""quotes,attributes""] ---- +------------------------------------------+------------------------------------------+ |PRODUCT_ID |QUANTITY | +------------------------------------------+------------------------------------------+ |15 |100 | ---- We're now is a position where we can calculate the current stock level for each product. We can do this by creating a table that groups by the `product_id` and sums up the `quantity` column which contains both stock decrements and stock increments. [IMPORTANT] ==== [source,subs=""quotes,attributes""] ---- *SET* 'auto.offset.reset'='earliest'; *CREATE TABLE* current_stock *WITH* (PARTITIONS = 1, KAFKA_TOPIC = '{dc}_current_stock') *AS SELECT* product_id , SUM(quantity) ""STOCK_LEVEL"" *FROM* product_supply_and_demand *GROUP BY* product_id; ---- ==== image::./ksql_014.png[align=""center""] When we query this table with a Push query... [source,subs=""quotes,attributes""] ---- *SET* 'auto.offset.reset'='latest'; *SELECT* product_id, stock_level *FROM* current_stock *EMIT CHANGES*; ---- ...each new event that is displayed on the console reflects the current stock level for the associated product, a new event will be emitted each time a product's stock level changes. Depending on how long it took you to get to this point in the workshop, you may see that all your stock levels are negative. This is because, apart from the initial purchase order for 100 of each product, we have not created any more purchase orders and our customers will have their orders on hold until we acquire more stock, not good, but we'll fix that soon. .Further Reading [TIP] ==== * link:https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/insert-into/[INSERT INTO Syntax] * link:https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/create-table-as-select/[CREATE TABLE AS SELECT Syntax] * link:https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/create-table-as-select/[ksqlDB Aggregate Functions] ==== == Lab {counter:labs}: Pull Queries We can now run our first Pull query. Pull queries are used against tables with aggregates and can only query a single key. To run a Pull query we just query the table as normal but drop the `EMIT CHANGES` clause. In this query we are asking ""*what is the _current_ stock level for product id 1?*"" [source,subs=""quotes,attributes""] ---- select product_id, stock_level from current_stock where product_id=15; ---- image::./ksql_015.png[align=""center""] The query will return the current stock level and immediatly terminate. [source,subs=""quotes,attributes""] ---- +----------------------------------------------------+----------------------------------------------------+ |PRODUCT_ID |STOCK_LEVEL | +----------------------------------------------------+----------------------------------------------------+ |1 |-67 | Query terminated ---- We can also use the ksqlDB Server's REST endpoint to make Pull queries. Exit from the ksqlDB CLI and run the following from the command line. [source,subs=""quotes,attributes""] ---- curl -s -X ""POST"" ""http://localhost:8088/query"" -H ""Content-Type: application/vnd.ksql.v1+json; charset=utf-8"" -d $'{ ""ksql"": ""select product_id, stock_level from current_stock where product_id=15;"" }'| jq . ---- As you can see, the ksqlDB Server's REST endpoint will return a JSON message with the `product_id` and its current `stock_level`. This is useful for applications that want access to the current state of the world using a request/response type pattern. [source,subs=""quotes,attributes""] ---- [ { ""header"": { ""queryId"": ""query_1582892390468"", ""schema"": ""`PRODUCT_ID` INTEGER, `STOCK_LEVEL` INTEGER"" } }, { ""row"": { ""columns"": [ 1, -76 ] } } ] ---- .Further Reading [TIP] ==== * link:https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/select-pull-query/[Pull Queries] * link:https://docs.ksqldb.io/en/latest/developer-guide/api/[ksqlDB REST API] ==== == Lab {counter:labs}: Streaming Recent Product Demand Now that we know the current stock level is for each product, we can use this information to send an event to the orders application and ask it to create purchase orders to replenish the stock, but how much should we stock should we order? we could just order enough to satisfy the current backlog but we'd quickly run out of stock again. What we really want to do is order enough to satisfy the backlog _and_ enough to meet future demand, we can make an attempt at predicting what the future demand will be by looking at the past. In the following query we are creating a table that will calculate the demand for each product over the last 3 minutes using a `WINDOW HOPPING` clause. Hopping windows are based on time intervals. They model fixed-sized, possibly overlapping windows. A hopping window is defined by two properties: the window’s duration and its advance, or “hop”, interval. The advance interval specifies how far a window moves forward in time relative to the previous window. In our query we we have a window with a duration of three minutes and an advance interval of one minute. Because hopping windows can overlap, a record can belong to more than one such window. Start the ksqlDB CLI if you haven't already [source,subs=attributes+] ---- docker exec -it ksqldb-cli ksql http://ksqldb-server-ccloud:8088 ---- Create the windowed query [IMPORTANT] ==== [source,subs=""quotes,attributes""] ---- *SET* 'auto.offset.reset'='earliest'; *CREATE TABLE* product_demand_last_3mins_tbl *WITH* (PARTITIONS = 1, KAFKA_TOPIC = '{dc}_product_demand_last_3mins') *AS SELECT* timestamptostring(windowStart,'HH:mm:ss') ""WINDOW_START_TIME"" , timestamptostring(windowEnd,'HH:mm:ss') ""WINDOW_END_TIME"" , product_id *AS* product_id_key , AS_VALUE(product_id) *AS* product_id , *SUM*(product_qty) ""DEMAND_LAST_3MINS"" *FROM* sales_enriched *WINDOW HOPPING* (SIZE 3 MINUTES, ADVANCE BY 1 MINUTE) *GROUP BY* product_id *EMIT CHANGES*; ---- ==== image::./ksql_016.png[align=""center""] If we query this table for a single product... [source,subs=""quotes,attributes""] ---- *SET* 'auto.offset.reset'='latest'; *SELECT* window_start_time, window_end_time, product_id, demand_last_3mins *FROM* product_demand_last_3mins_tbl *WHERE* product_id = 15 *EMIT CHANGES*; ---- ...you'll see the start and end times for each three minute window, along with the product demand for those 3 minutes. Notice how the window start times are staggered by one minute, this is the advance interval in action. As new sales events occur a new message will be displayed with an update to the window(s) total. [source,subs=""quotes,attributes""] ---- +-----------------+-----------------+-----------------+-----------------+ |WINDOW_START_TIME|WINDOW_END_TIME |PRODUCT_ID |DEMAND_LAST_3MINS| +-----------------+-----------------+-----------------+-----------------+ |13:33:00 |13:36:00 |1 |10 | |13:34:00 |13:37:00 |1 |10 | |13:35:00 |13:38:00 |1 |1 | |13:33:00 |13:36:00 |1 |11 | |13:34:00 |13:37:00 |1 |11 | |13:35:00 |13:38:00 |1 |2 | |13:34:00 |13:37:00 |1 |21 | |13:35:00 |13:38:00 |1 |12 | |13:36:00 |13:39:00 |1 |10 | |13:34:00 |13:37:00 |1 |26 | |13:35:00 |13:38:00 |1 |17 | |13:36:00 |13:39:00 |1 |15 | |13:35:00 |13:38:00 |1 |22 | |13:36:00 |13:39:00 |1 |20 | |13:37:00 |13:40:00 |1 |5 | |13:36:00 |13:39:00 |1 |28 | |13:37:00 |13:40:00 |1 |13 | |13:38:00 |13:41:00 |1 |8 | ---- We will now create a stream from this table and then join it to the `current_stock` table Create a stream from the table's underlying topic... [IMPORTANT] ==== [source,subs=""quotes,attributes""] ---- *CREATE STREAM* product_demand_last_3mins *WITH* (KAFKA_TOPIC='{dc}_product_demand_last_3mins', VALUE_FORMAT='AVRO'); ---- ==== image::./ksql_017.png[align=""center""] .Further Reading [TIP] ==== * link:https://docs.ksqldb.io/en/latest/concepts/time-and-windows-in-ksqldb-queries/#windows-in-sql-queries[Windows in ksqlDB Queries] ==== == Lab {counter:labs}: Streaming _""Out of Stock""_ Events Now that we have the `current_stock` table and `product_demand_last_3mins` stream, we can create a `out_of_stock_events` stream by joining the two together and calculating the required purchase order quantity. We calculate the `purchase_qty` from adding the inverse of the current stock level to the last 3 minutes of demand. The stream is filtered to only include products that have negative stock and therefore need purchase orders raising for them. [IMPORTANT] ==== [source,subs=""quotes,attributes""] ---- *SET* 'auto.offset.reset' = 'latest'; *CREATE STREAM* out_of_stock_events *WITH* (PARTITIONS = 1, KAFKA_TOPIC = '{dc}_out_of_stock_events') *AS SELECT* cs.product_id ""PRODUCT_ID_KEY"", AS_VALUE(cs.product_id) AS product_id, pd.window_start_time, pd.window_end_time, cs.stock_level, pd.demand_last_3mins, (cs.stock_level * -1) + pd.DEMAND_LAST_3MINS ""QUANTITY_TO_PURCHASE"" *FROM* product_demand_last_3mins pd *INNER JOIN* current_stock cs *ON* pd.product_id = cs.product_id *WHERE* stock_level <= 0; ---- ==== image::./ksql_018.png[align=""center""] When we query the `out_of_stock_events` stream... [source,subs=""quotes,attributes""] ---- *SET* 'auto.offset.reset' = 'latest'; *SELECT* product_id, window_start_time, window_end_time, stock_level, demand_last_3mins, quantity_to_purchase *FROM* out_of_stock_events *EMIT CHANGES*; ---- ...you'll see a constant stream of _out of stock products_ and the predicted purchase quantity that should be ordered to satisfy any current backlog and also meet the next 3 minutes demand. [source,subs=""quotes,attributes""] ---- +----------------+------------------+----------------+-------------+-----------------+-------------------+ |PRODUCT_ID |WINDOW_START_TIME |WINDOW_END_TIME |STOCK_LEVEL |DEMAND_LAST_3MINS|QUANTITY_TO_PURCASE| +----------------+------------------+----------------+-------------+-----------------+-------------------+ |28 |13:53:00 |13:56:00 |-85 |12 |97 | |28 |13:54:00 |13:57:00 |-85 |1 |86 | |28 |13:55:00 |13:58:00 |-85 |1 |86 | |4 |13:53:00 |13:56:00 |-128 |26 |154 | |4 |13:54:00 |13:57:00 |-128 |11 |139 | |4 |13:55:00 |13:58:00 |-128 |11 |139 | |5 |13:53:00 |13:56:00 |-73 |15 |88 | |5 |13:54:00 |13:57:00 |-73 |15 |88 | |5 |13:55:00 |13:58:00 |-73 |15 |88 | |28 |13:53:00 |13:56:00 |-85 |18 |103 | |28 |13:54:00 |13:57:00 |-91 |7 |98 | |28 |13:55:00 |13:58:00 |-91 |7 |98 | |14 |13:53:00 |13:56:00 |-156 |31 |187 | |14 |13:54:00 |13:57:00 |-156 |15 |171 | |14 |13:55:00 |13:58:00 |-156 |6 |162 | |5 |13:53:00 |13:56:00 |-73 |25 |98 | |5 |13:54:00 |13:57:00 |-83 |25 |108 | |5 |13:55:00 |13:58:00 |-83 |25 |108 | |12 |13:53:00 |13:56:00 |-197 |25 |222 | |12 |13:54:00 |13:57:00 |-197 |21 |218 | |12 |13:55:00 |13:58:00 |-200 |3 |203 | ... ... ---- == Lab {counter:labs}: Replicate Events to On-Premise Kafka The next step is to replicate the `out_of_stock_events` topic to our on-premise cluster. image::./5_replicate_to_onprem.png[] Before we do that, let's create the target topic in our on-premise Kafka cluster using link:http://{externalip}:9021[Confluent Control Center, window=_blank] Select your on-premise cluster from the home, select _""topics""_ and then click on _""Add a Topic""_. [IMPORTANT] ==== image::./c3_80.png[] Name the topic `{dc}_out_of_stock_events` with one partition and click _""Customize settings""_ , image::./c3_90.png[] choose Custom availability settings and use replication_factor=1 and min_insync_replicas=1 image::./c3_91.png[] Click on _""Save & create""_ We are now ready to replicate this topic from Confluent Cloud to your on-premise cluster. ==== === Submit the Replicator Connector Config Execute the following to create the Replicator Connector. Exit the ksqlDB cli [IMPORTANT] ==== exit ==== Create the connector using the cURL command. [IMPORTANT] ==== [source,subs=""attributes""] ---- curl -i -X POST -H ""Accept:application/json"" \\ -H ""Content-Type:application/json"" http://localhost:18083/connectors/ \\ -d '{ ""name"": ""replicator-ccloud-to-{dc}"", ""config"": { ""connector.class"": ""io.confluent.connect.replicator.ReplicatorSourceConnector"", ""key.converter"": ""io.confluent.connect.replicator.util.ByteArrayConverter"", ""value.converter"": ""io.confluent.connect.replicator.util.ByteArrayConverter"", ""topic.config.sync"": ""false"", ""topic.whitelist"": ""{dc}_out_of_stock_events"", ""dest.kafka.bootstrap.servers"": ""broker:29092"", ""dest.kafka.replication.factor"": 1, ""src.kafka.bootstrap.servers"": ""${file:/secrets.properties:CCLOUD_CLUSTER_ENDPOINT}"", ""src.kafka.security.protocol"": ""SASL_SSL"", ""src.kafka.sasl.mechanism"": ""PLAIN"", ""src.kafka.sasl.jaas.config"": ""org.apache.kafka.common.security.plain.PlainLoginModule required username=\\""${file:/secrets.properties:CCLOUD_API_KEY}\\"" password=\\""${file:/secrets.properties:CCLOUD_API_SECRET}\\"";"", ""src.consumer.group.id"": ""replicator-ccloud-to-{dc}"", ""src.consumer.interceptor.classes"": ""io.confluent.monitoring.clients.interceptor.MonitoringConsumerInterceptor"", ""src.consumer.confluent.monitoring.interceptor.bootstrap.servers"": ""${file:/secrets.properties:CCLOUD_CLUSTER_ENDPOINT}"", ""src.kafka.timestamps.producer.interceptor.classes"": ""io.confluent.monitoring.clients.interceptor.MonitoringProducerInterceptor"", ""src.kafka.timestamps.producer.confluent.monitoring.interceptor.bootstrap.servers"": ""${file:/secrets.properties:CCLOUD_CLUSTER_ENDPOINT}"", ""tasks.max"": ""1"" } }' ---- ==== Notice that we've specified only to replicate the `{dc}_out_of_stock_events` topic by configuring `""topic.whitelist"": ""{dc}_out_of_stock_events""` We can confirm that the `{dc}_out_of_stock_events` is being replicated from Confluent Cloud to our on-premise cluster by checking for messages in link:http://{externalip}:9021[Confluent Control Center, window=_blank] image::./c3_100.png[] .Further Reading [TIP] ==== * link:https://docs.confluent.io/current/connect/kafka-connect-replicator/index.html[Confluent Replicator] * link:https://docs.confluent.io/current/connect/kafka-connect-replicator/configuration_options.html[Confluent Replicator Configuration Properties] ==== == Lab {counter:labs}: Sink Events into MySQL Finally we need to sink the `{dc}_out_of_stock_events` topic into a MySQL database table, the on-premise application will then process these events and create purchase order for us. image::./6_jdbc_sink.png[] But before we do that, let's open a couple more terminal sessions and start the ksqlDB CLI in each. [source,subs=attributes+] ---- ssh {dc}@{externalip} ---- [source,subs=attributes+] ---- docker exec -it ksqldb-cli ksql http://ksqldb-server-ccloud:8088 ---- Execute the following query in the 1st session... [source,subs=""quotes,attributes""] ---- SET 'auto.offset.reset'='latest'; SELECT product_id, stock_level FROM current_stock EMIT CHANGES; ---- ...and this query in the 2nd session [source,subs=""quotes,attributes""] ---- SET 'auto.offset.reset'='latest'; SELECT product_id, product_qty FROM purchases_enriched EMIT CHANGES; ---- You now have a real time view of the current product stock levels in the first ksqlDB session and the purchases being made to replenish the stock in second. Not that the second query isn't returning anything yet. Let's now sink the _out of stock events_ to the MySQL database using the JDBC Connector. Once the events start arriving in the database, the orders application will process them and start generating the required purchase orders. In a third terminal session, create the JDBC Sink Connector by running the following from the command line. [IMPORTANT] ==== [source,subs=""quotes,attributes""] ---- curl -i -X POST -H ""Accept:application/json"" \\ -H ""Content-Type:application/json"" http://localhost:18083/connectors/ \\ -d '{ ""name"": ""jdbc-mysql-sink"", ""config"": { ""connector.class"": ""io.confluent.connect.jdbc.JdbcSinkConnector"", ""topics"": ""{dc}_out_of_stock_events"", ""connection.url"": ""jdbc:mysql://mysql:3306/orders"", ""connection.user"": ""mysqluser"", ""connection.password"": ""mysqlpw"", ""insert.mode"": ""INSERT"", ""batch.size"": ""3000"", ""auto.create"": ""true"", ""key.converter"": ""org.apache.kafka.connect.storage.StringConverter"" } }' ---- ==== Observe the current stock query in the first ksqlDB session, when a product has zero or less stock you should see a purchase event appear in the second ksqlDB session and then the new stock level reflected in the first session. In theory, given a constant demand, each product should run out of stock and get replenished roughly every 3 minutes. .Further Reading [TIP] ==== * link:https://docs.confluent.io/current/connect/kafka-connect-jdbc/sink-connector/index.html#jdbc-sink-connector-for-cp[JDBC Sink Connector] * link:https://docs.confluent.io/current/connect/kafka-connect-jdbc/sink-connector/sink_config_options.html[JDBC Sink Connector Configuration Properties] ==== ",16361,True,2913.947197433855,median "[[es6-essentials]] == ES6 Essentials The sixth edition of the language comes with a plethora of non-breaking syntax improvements, most of which we'll tackle throughout this chapter. Many of these changes are syntactic sugar; that is, they could be represented in ES5, albeit using more complicated pieces of code. There are also changes that aren't merely (((""syntactic sugar"")))syntactic sugar but a completely different way of declaring variables using `let` and `const`, as we'll see toward the end of the chapter. Object literals get a few syntax changes in ES6, and they're a good place to start. === Object Literals An (((""object literals"", id=""ol2"")))_object literal_ is any object declaration using the `{}` shorthand syntax, such as the following example: [source,javascript] ---- var book = { title: 'Modular ES6', author: 'Nicolas', publisher: 'O´Reilly' } ---- ES6 brings a few improvements to object literal syntax: property value shorthands, computed property names, and method definitions. Let's go through them and describe their use cases as well. ==== Property Value Shorthands Sometimes (((""object literals"", ""property value shorthands"", id=""ol2pvs"")))(((""property value shorthands"", id=""pvs2"")))we declare objects with one or more properties whose values are references to variables by the same name. For example, we might have a `listeners` collection, and in order to assign it to a property called `listeners` of an object literal, we have to repeat its name. The following snippet has a typical example where we have an object literal declaration with a couple of these repetitive properties: [source,javascript] ---- var listeners = [] function listen() {} var events = { listeners: listeners, listen: listen } ---- Whenever you find yourself in this situation, you can omit the property value and the colon by taking advantage of the new property value shorthand syntax in ES6. As shown in the following example, the new ES6 syntax makes the assignment implicit: [source,javascript] ---- var listeners = [] function listen() {} var events = { listeners, listen } ---- As we'll further explore in the second part of the book, property value shorthands help de-duplicate the code we write without diluting its meaning. In the following snippet, I reimplemented part of `localStorage`, a browser API for persistent storage, as an in-memory ponyfill.pass:[Like polyfills, ponyfills are user-land implementations of features that aren't available in every JavaScript runtime. While polyfills try to patch the runtime environment so that it behaves as if the feature was indeed available on the runtime, ponyfills implement the missing functionality as standalone modules that don't pollute the runtime environment. This has the benefit of not breaking expectations third-party libraries (that don't know about your polyfill) may have about the environment.] If it weren't for the shorthand syntax, the `storage` object would be more verbose to type out: [source,javascript] ---- var store = {} var storage = { getItem, setItem, clear } function getItem(key) { return key in store ? store[key] : null } function setItem(key, value) { store[key] = value } function clear() { store = {} } ---- That's the first of many ES6 features that are aimed toward reducing complexity in the code you have to maintain. Once you get used to the syntax, you'll notice that code readability and developer productivity get boosts as (((""object literals"", ""property value shorthands"", startref=""ol2pvs"")))(((""property value shorthands"", startref=""pvs2"")))well. ==== Computed Property Names Sometimes (((""object literals"", ""computed property names"", id=""ol2cpn"")))(((""computed property names"", id=""cpn2"")))you have to declare objects that contain properties with names based on variables or other JavaScript expressions, as shown in the following piece of code written in ES5. For this example, assume that `expertise` is provided to you as a function parameter, and is not a value you know beforehand: [source,javascript] ---- var expertise = 'journalism' var person = { name: 'Sharon', age: 27 } person[expertise] = { years: 5, interests: ['international', 'politics', 'internet'] } ---- Object literals in ES6 aren't constrained to declarations with static names. With computed property names, you can wrap any expression in square brackets, and use that as the property name. When the declaration is reached, your expression is evaluated and used as the property name. The following example shows how the piece of code we just saw could declare the +person+ object in a single step, without having to resort to a second statement adding the person's `expertise`. [source,javascript] ---- var expertise = 'journalism' var person = { name: 'Sharon', age: 27, [expertise]: { years: 5, interests: ['international', 'politics', 'internet'] } } ---- You can't combine the property value shorthands with computed property names. Value shorthands are simple compile-time syntactic sugar that helps avoid repetition, while computed property names are evaluated at runtime. Given that we're trying to mix these two incompatible features, the following example would throw a syntax error. In most cases this combination would lead to code that's hard to interpret for other humans, so it's probably a good thing that you can't combine the two. [source,javascript] ---- var expertise = 'journalism' var journalism = { years: 5, interests: ['international', 'politics', 'internet'] } var person = { name: 'Sharon', age: 27, [expertise] // this is a syntax error! } ---- A common scenario for computed property names is when we want to add an entity to an object map that uses the `entity.id` ((("" entity.id field"")))field as its keys, as shown next. Instead of having to have a third statement where we add the `grocery` to the `groceries` map, we can inline that declaration in the `groceries` object literal itself. [source,javascript] ---- var grocery = { id: 'bananas', name: 'Bananas', units: 6, price: 10, currency: 'USD' } var groceries = { [grocery.id]: grocery } ---- Another case may be whenever a function receives a parameter that it should then use to build out an object. In ES5 code, you'd need to allocate a variable declaring an object literal, then add the dynamic property, and then return the object. The following example shows exactly that, when creating an envelope that could later be used for Ajax messages that follow a convention: they have an `error` property with a description when something goes wrong, and a `success` property (((""error property"")))(((""success property"")))when things turn out okay: [source,javascript] ---- function getEnvelope(type, description) { var envelope = { data: {} } envelope[type] = description return envelope } ---- Computed property names help us write the same function more concisely, using a single statement: [source,javascript] ---- function getEnvelope(type, description) { return { data: {}, [type]: description } } ---- The last enhancement coming to object literals is (((""object literals"", ""computed property names"", startref=""ol2cpn"")))(((""computed property names"", startref=""cpn2"")))about functions. ==== Method Definitions Typically, (((""object literals"", ""method definitions"", id=""ol2md"")))(((""method definitions"", id=""mdef2"")))you can declare methods on an object by adding properties to it. In the next snippet, we're creating a small event emitter that supports multiple kinds of events. It comes with an `emitter#on` method (((""emitter object"", id=""eo2"")))that can be used to register event listeners, and an `emitter#emit` method that can be used to raise events: [source,javascript] ---- var emitter = { events: {}, on: function (type, fn) { if (this.events[type] === undefined) { this.events[type] = [] } this.events[type].push(fn) }, emit: function (type, event) { if (this.events[type] === undefined) { return } this.events[type].forEach(function (fn) { fn(event) }) } } ---- Starting in ES6, you can declare methods on an object literal using the new method definition syntax. In this case, we can omit the colon and the `function` keyword. This is meant as a terse alternative to traditional method declarations where you need to use the pass:[function] (((""function keyword"")))keyword. The following example shows how our `emitter` object looks when using method definitions. [source,javascript] ---- var emitter = { events: {}, on(type, fn) { if (this.events[type] === undefined) { this.events[type] = [] } this.events[type].push(fn) }, emit(type, event) { if (this.events[type] === undefined) { return } this.events[type].forEach(function (fn) { fn(event) }) } } ---- Arrow (((""emitter object"", startref=""eo2"")))(((""arrow functions"", id=""af2"")))functions are another way of declaring functions in ES6, and they come in several flavors. Let's investigate what arrow functions are, how they can be declared, and how they behave (((""object literals"", startref=""ol2"")))(((""object literals"", ""method definitions"", startref=""ol2md"")))(((""method definitions"", startref=""mdef2"")))semantically. [[arrow_functions]] === Arrow Functions In JavaScript you typically declare functions using code like the following, where you have a name, a list of parameters, and a function body. [source,javascript] ---- function name(parameters) { // function body } ---- You could also create (((""arrow functions"", ""anonymous"", id=""af2a"")))(((""anonymous functions"", id=""anonf2"")))anonymous functions, by omitting the name when assigning the function to a variable, a property, or a function call. [source,javascript] ---- var example = function (parameters) { // function body } ---- Starting with ES6, you can use arrow functions as another way of writing anonymous functions. Keep in mind, there are several slightly different ways of writing them. The following piece of code shows an arrow function that's very similar to the anonymous function we just saw. The only difference seems to be the missing `function` keyword and the `=>` arrow to the right of the parameter list. [source,javascript] ---- var example = (parameters) => { // function body } ---- While arrow functions look very similar to your typical anonymous function, they are fundamentally different: arrow functions can't be named explicitly, although modern runtimes can infer a name based on the variable they're assigned to; they can't be used as constructors nor do they have a `prototype` property, meaning you can't use `new` on an arrow function; and they are bound to their lexical scope, which is the reason why they don't alter the meaning of `this`. Let's dig into their semantic differences with traditional functions, the many ways to declare an arrow function, and practical use cases. ==== Lexical Scoping In (((""arrow functions"", ""lexical scoping"", id=""af2ls"")))(((""lexical scoping"", id=""ls2"")))the body of an arrow function, `this`, `arguments`, and `super` point to the containing scope, since arrow functions don't create a new scope. Consider the following example. We have a `timer` object with a `seconds` counter and a `start` method defined using the syntax we learned about earlier. We then start the timer, wait for a few seconds, and log the current amount of elapsed `seconds`: [source,javascript] ---- var timer = { seconds: 0, start() { setInterval(() => { this.seconds++ }, 1000) } } timer.start() setTimeout(function () { console.log(timer.seconds) }, 3500) // <- 3 ---- If we had defined the function passed to `setInterval` as a regular anonymous function instead of using an arrow function, `this` would've been bound to the context of the (((""arrow functions"", ""anonymous"", startref=""af2a"")))(((""anonymous functions"", startref=""anonf2"")))anonymous function, instead of the context of the `start` method. We could have implemented `timer` with a declaration like `var self = this` at the beginning of the `start` method, and then referencing `self` instead of `this`. With arrow functions, the added complexity of keeping context references around fades away and we can focus on the functionality of our code. In a similar fashion, lexical binding in ES6 arrow functions also means that function calls won't be able to change the `this` context when using `.call`, `.apply`, `.bind`, etc. That limitation is usually more useful than not, as it ensures that the context will always be preserved and constant. Let's now shift our attention to the following example. What do you think the `console.log` statement will print? [source,javascript] ---- function puzzle() { return function () { console.log(arguments) } } puzzle('a', 'b', 'c')(1, 2, 3) ---- The answer is that `arguments` refers (((""arguments object"")))to the context of the anonymous function, and thus the arguments passed to that function will be printed. In this case, those arguments are `1, 2, 3`. What about in the following case, where we use an arrow function instead of the anonymous function in the previous example? [source,javascript] ---- function puzzle() { return () => console.log(arguments) } puzzle('a', 'b', 'c')(1, 2, 3) ---- In this case, the `arguments` object refers to the context of the `puzzle` function, because arrow functions don't create a closure. For this reason, the printed arguments will be `'a', 'b', 'c'`. I've mentioned there are several flavors of arrow functions, but so far we've only looked at their fully fleshed version. What are the other ways to represent an (((""arrow functions"", ""lexical scoping"", startref=""af2ls"")))(((""lexical scoping"", startref=""ls2"")))arrow function? ==== Arrow Function Flavors Let's (((""arrow functions"", ""flavors"", id=""af2f"")))look one more time at the arrow function syntax we've learned so far: [source,javascript] ---- var example = (parameters) => { // function body } ---- An arrow function with exactly one parameter can omit the parentheses. This is optional. It's useful when passing the arrow function to another method, as it reduces the amount of parentheses involved, making it easier for some humans to parse the code: [source,javascript] ---- var double = value => { return value * 2 } ---- Arrow functions are heavily used for simple functions, such as the `double` function (((""double functions"")))(((""arrow functions"", ""double"")))we just saw. The following flavor of arrow functions does away with the function body. Instead, you provide an expression such as `value * 2`. When the function is called, the expression is evaluated and its result is returned. The `return` statement is (((""return statement"")))implicit, and there's no need for curly braces denoting the function body anymore, as you can only use a single expression: [source,javascript] ---- var double = (value) => value * 2 ---- Note that you can combine implicit parentheses and implicit return, making for concise arrow functions: [source,javascript] ---- var double = value => value * 2 ---- .Implicitly Returning Object Literals **** When you need to implicitly return an object literal, you'll need to wrap that object literal expression in parentheses. Otherwise, the compiler would interpret your curly braces as the start and the end of the function block. [source,javascript] ---- var objectFactory = () => ({ modular: 'es6' }) ---- In the following example, JavaScript interprets the curly braces as the body of our arrow function. Furthermore, `number` is interpreted as a labelpass:[Labels are used as a way of identifying instructions. Labels can be used by goto statements, to indicate what instruction we should jump to; break statements, to indicate the sequence we want to break out of; and continue statements, to indicate the sequence we want to advance.] and then figures out we have a `value` expression that doesn't do anything. Since we're in a block and not returning anything, the mapped values will be `undefined`: [source,javascript] ---- [1, 2, 3].map(value => { number: value }) // <- [undefined, undefined, undefined] ---- If our attempt at implicitly returning an object literal had more than a single property, then the compiler wouldn't be able to make sense of the second property, and it'd throw a `SyntaxError`: [source,javascript] ---- [1, 2, 3].map(value => { number: value, verified: true }) // <- SyntaxError ---- Wrapping the expression in parentheses fixes these issues, because the compiler would no longer interpret it as a function block. Instead, the object declaration becomes an expression that evaluates to the object literal we want to return implicitly: [source,javascript] ---- [1, 2, 3].map(value => ({ number: value, verified: true })) /* <- [ { number: 1, verified: true }, { number: 2, verified: true }, { number: 3, verified: true }] */ ---- **** Now that you understand arrow functions, let's ponder about their merits and where they might be a (((""arrow functions"", ""flavors"", startref=""af2f"")))good fit. ==== Merits and Use Cases As (((""arrow functions"", ""merits and use cases"", id=""af2mauc"")))a rule of thumb, you shouldn't blindly adopt ES6 features wherever you can. Instead, it's best to reason about each case individually and see whether adopting the new feature actually improves code readability and maintainability. ES6 features are not strictly better than what we had all along, and it's a bad idea to treat them as such. There are a few situations where arrow functions may not be the best tool. For example, if you have a large function comprised of several lines of code, replacing `function` with `=>` is hardly going to improve your code. Arrow functions are often most effective for short routines, where the `function` keyword and syntax boilerplate make up a significant portion of the function expression. Properly (((""arrow functions"", ""naming"")))naming a function adds context to make it easier for humans to interpret them. Arrow functions can't be explicitly named, but they can be named implicitly by assigning them to a variable. In the following example, we assign an arrow function to the `throwError` variable. When calling this function results in an error, the stack trace properly identifies the arrow function as `throwError`: [source,javascript] ---- var throwError = message => { throw new Error(message) } throwError('this is a warning') <- Uncaught Error: this is a warning at throwError ---- Arrow functions are neat when it comes to defining anonymous functions that should probably be lexically bound anyway, and they can definitely make your code more terse in some situations. They are particularly useful in most functional programming situations, such as when using `.map`, `.filter`, or `.reduce` on collections, as shown in the following example: [source,javascript] ---- [1, 2, 3, 4] .map(value => value * 2) .filter(value => value > 2) .forEach(value => console.log(value)) // <- 4 // <- 6 // <- 8 ---- === Assignment Destructuring This (((""arrow functions"", startref=""af2"")))(((""arrow functions"", ""merits and use cases"", startref=""af2mauc"")))(((""assignment destructuring"", id=""ad2"")))(((""destructuring"", id=""d2"")))is one of the most flexible and expressive features in ES6. It's also one of the simplest. It binds properties to as many variables as you need. It works with objects, arrays, and even in `function` parameter lists. Let's go step by step, starting with objects. ==== Destructuring Objects Imagine (((""assignment destructuring"", ""objects"", id=""ad2o"")))(((""destructuring"", ""objects"", id=""d2o"")))(((""objects"", ""destructuring"", id=""o2d"")))you had a program describing a color palette and you want to refer to properties in the object that describes it. Here's an example object we'll be using for our palette: [source,javascript] ---- var palette = { profile: 'intense-red', name: 'Red', color: { code: `#f00` }, luminosity: 0.8 } ---- If you wanted a `profile` variable referencing `palette.profile`, you could write the following bit of ES5 code. This is commonplace when, for instance, you'll be referencing `profile` in several places in your codebase and you'd prefer to avoid typing out `palette.profile` each time: [source,javascript] ---- var profile = palette.profile ---- With destructuring in assignment, the syntax becomes a bit more clear. As you can see in the next example, you don't have to write `profile` twice, while still clearly conveying intent. The following statement is equivalent to the previous one written in ES5 code: [source,javascript] ---- var { profile } = palette ---- Just like you could declare multiple comma-separated variables with a single `var` statement, you can also declare multiple variables within the curly braces of a destructuring expression: [source,javascript] ---- var { profile, name } = palette ---- In a similar fashion, you could mix and match destructuring with regular variable declarations in the same `var` statement. While this might look a bit confusing at first, it'll be up to any JavaScript coding style guides you follow to determine whether it's appropriate to declare several variables in a single statement. In any case, it goes to show the flexibility offered by destructuring syntax: [source,javascript] ---- var { profile } = palette, two = 2 ---- If you want to extract a property named `profile` but would like to declare it as a variable named `id`, you can use the following destructuring syntax, known as _aliasing_. Note that you can use `id` or any other valid variable name: [source,javascript] ---- var { profile: id } = palette console.log(id) // <- 'intense-red' ---- While aliases don't look any simpler than the ES5 flavor, `id = palette.profile`, (((""aliases"", id=""al2"")))they start making sense when you consider the fact that destructuring supports deep structures, as in the following example: [source,javascript] ---- var { color: { code } } = palette ---- In cases like the previous one, where you have deeply nested properties being destructured, you might be able to convey a property name more clearly if you choose an alias. Consider the next snippet, where a property named `code` wouldn't have been as indicative of its contents as `colorCode` could be: [source,javascript] ---- var { color: { code: colorCode } } = palette ---- The scenario we just saw repeats itself frequently, because properties are often named in the context of their host object. While `palette.color.code` is perfectly descriptive, `code` on its own could mean a wide variety of things, and aliases such as `colorCode` can help you bring context back into the variable name while still using destructuring. Whenever you access a nonexistent property in ES5 notation, you get a value of `undefined`: [source,javascript] ---- console.log(palette.luminosity) // <- undefined console.log(palette['luminosity']) // <- undefined ---- With destructuring, the same behavior prevails. When declaring a destructured variable for a property that's missing, you'll get back `undefined` as well. [source,javascript] ---- var { luminosity } = palette console.log(luminosity) // <- undefined ---- A destructured declaration accessing a nested property of a parent object that's `null` or `undefined` will throw an `Exception`, just like regular attempts to access properties of `null` or `undefined` would, in other cases. [source,javascript] ---- var { stroke: { width } } = palette // <- Exception var { missing } = null // <- Exception ---- When you think of that piece of code as the equivalent ES5 code shown next, it becomes evident why the expression must throw, given that destructuring is mostly syntactic sugar. [source,javascript] ---- var nothing = null var missing = nothing.missing // <- Exception ---- As part of destructuring, you can provide default values for those cases where the value is `undefined`. The default value can be anything you can think of: numbers, strings, functions, objects, a reference to another variable, etc. [source,javascript] ---- var { description = 'This is a color palette' } = palette console.log(description) // <- 'This is a color palette' ---- Default values can also be provided in nested property destructuring. [source,javascript] ---- var { color: { density = 320 } } = palette console.log(density) // <- 320 ---- For use in combination with aliases, you should place the alias first, and then the default value, as shown next. [source,javascript] ---- var { color: paletteColor = { density: 320 } } = palette ---- It's possible to use the (((""computed property names"")))computed property names syntax in destructuring patterns. In this case, however, you're required to provide an alias to be used as the variable name. That's because computed property names allow arbitrary expressions and thus the compiler wouldn't be able to infer a variable name. In the following example we use the `paletteProfile` alias, and a computed property name to extract the `profile` property from the `palette` object. [source,javascript] ---- var { ['pro' + 'file']: paletteProfile } = palette console.log(paletteProfile) // <- true ---- This flavor of destructuring is probably the least useful, as `sourceProperty = source[property]` is usually simpler than `{ [property]: sourceProperty } = source`, as it's a more sequential statement. That being said, the feature is useful when you have properties you want to declare in the object literal, as opposed to using subsequent assignment statements. That's it, as far as objects go, in terms of destructuring. (((""assignment destructuring"", ""objects"", startref=""ad2o"")))(((""destructuring"", ""objects"", startref=""d2o"")))(((""objects"", ""destructuring"", startref=""o2d"")))(((""aliases"", startref=""al2"")))What about arrays? ==== Destructuring Arrays The (((""assignment destructuring"", ""arrays"", id=""ad2a"")))(((""destructuring"", ""arrays"", id=""d2a"")))(((""arrays"", id=""a2d"")))syntax for destructuring arrays is similar to that of objects. The (((""coordinates object"")))following example shows a `coordinates` object that's destructured into two variables: `x` and `y`. Note how the notation uses square brackets instead of curly braces; this denotes we're using array destructuring instead of object destructuring. Instead of having to sprinkle your code with implementation details like `x = coordinates[0]`, with destructuring you can convey your meaning clearly and without explicitly referencing the indices, naming the values instead. [source,javascript] ---- var coordinates = [12, -7] var [x, y] = coordinates console.log(x) // <- 12 ---- When destructuring arrays, you can skip uninteresting properties or those that you otherwise don't need to reference. [source,javascript] ---- var names = ['James', 'L.', 'Howlett'] var [ firstName, , lastName ] = names console.log(lastName) // <- 'Howlett' ---- Array destructuring allows for default values just like object destructuring. [source,javascript] ---- var names = ['James', 'L.'] var [ firstName = 'John', , lastName = 'Doe' ] = names console.log(lastName) // <- 'Doe' ---- In ES5, when you have to swap the values of two variables, you typically resort to a third, temporary variable, as in the following snippet. [source,javascript] ---- var left = 5 var right = 7 var aux = left left = right right = aux ---- Destructuring helps you avoid the `aux` declaration and focus on your intent. Once again, destructuring helps us convey intent more tersely and effectively for the use case. [source,javascript] ---- var left = 5 var right = 7 [left, right] = [right, left] ---- The last area of destructuring we'll be covering is (((""assignment destructuring"", ""arrays"", startref=""ad2a"")))(((""destructuring"", ""arrays"", startref=""d2a"")))(((""arrays"", startref=""a2d"")))function parameters. ==== Function Parameter Defaults Function parameters (((""assignment destructuring"", ""function parameters"", id=""ad2fpd"")))(((""destructuring"", ""function parameters"", id=""d2fpd"")))(((""function parameters"", id=""fpd2"")))in ES6 enjoy the ability of specifying default values as well. The following example defines a default `exponent` with the most commonly used value. [source,javascript] ---- function powerOf(base, exponent = 2) { return Math.pow(base, exponent) } ---- Defaults can be applied to arrow function parameters as well. When we have default values in an arrow function we must wrap the parameter list in parentheses, even when there's a single parameter. [source,javascript] ---- var double = (input = 0) => input * 2 ---- Default values aren't limited to the rightmost parameters of a function, as in a few other programming languages. You could provide default values for any parameter, in any position. [source,javascript] ---- function sumOf(a = 1, b = 2, c = 3) { return a + b + c } console.log(sumOf(undefined, undefined, 4)) // <- 1 + 2 + 4 = 7 ---- In JavaScript it's not uncommon to provide a function with an `options` object, containing several properties. You could determine a default `options` object (((""options object"", id=""oo2"")))if one isn't provided, as shown in the next snippet. [source,javascript] ---- var defaultOptions = { brand: 'Volkswagen', make: 1999 } function carFactory(options = defaultOptions) { console.log(options.brand) console.log(options.make) } carFactory() // <- 'Volkswagen' // <- 1999 ---- The problem with this approach is that as soon as the consumer of `carFactory` provides an `options` object, you lose all of your defaults. [source,javascript] ---- carFactory({ make: 2000 }) // <- undefined // <- 2000 ---- We can mix function parameter default values with destructuring, and get the best of both worlds. ==== Function Parameter Destructuring A better approach than merely providing a default value might be to destructure `options` entirely, providing default values for each property, individually, within the destructuring pattern. This approach also lets you reference each option without going through an `options` object, but you lose the ability to reference `options` directly, which might represent an issue in some situations. [source,javascript] ---- function carFactory({ brand = 'Volkswagen', make = 1999 }) { console.log(brand) console.log(make) } carFactory({ make: 2000 }) // <- 'Volkswagen' // <- 2000 ---- In this case, however, we've once again lost the default value for the case where the consumer doesn't provide any `options`. Meaning `carFactory()` will now throw when an `options` object isn't provided. This can be remedied by using the syntax shown in the following snippet of code, which adds a default `options` value of an empty object. The empty object is then filled, property by property, with the default values on the destructuring pattern. [source,javascript] ---- function carFactory({ brand = 'Volkswagen', make = 1999 } = {}) { console.log(brand) console.log(make) } carFactory() // <- 'Volkswagen' // <- 1999 ---- Besides default values, you can use destructuring in function parameters to describe the shape of objects your function can handle. Consider the following code snippet, where we have a `car` object with several properties. The `car` object describes its owner, what kind of car it is, who manufactured it, when, and the owner's preferences when he (((""options object"", startref=""oo2"")))purchased the car. [source,javascript] ---- var car = { owner: { id: 'e2c3503a4181968c', name: 'Donald Draper' }, brand: 'Peugeot', make: 2017, model: '208', preferences: { airbags: true, airconditioning: false, color: 'red' } } ---- If we wanted to implement a function that only takes into account certain properties of a parameter, it might be a good idea to reference those properties explicitly by destructuring up front. The upside is that we become aware of every required property upon reading the function's signature. When we destructure everything up front, it's easy to spot when input doesn't adhere to the contract of a function. The following example shows how every property we need could be specified in the parameter list, laying bare the shape of the objects we can handle in the `getCarProductModel` API. [source,javascript] ---- var getCarProductModel = ({ brand, make, model }) => ({ sku: brand + ':' + make + ':' + model, brand, make, model }) getCarProductModel(car) ---- Besides default values and filling an `options` object, let's explore what else destructuring is good at. ==== Use Cases for Destructuring Whenever (((""assignment destructuring"", ""use cases for"", id=""ad2ucf"")))(((""destructuring"", ""use cases for"", id=""d2ucf"")))there's a function that returns an object or an array, destructuring makes it much terser to interact with. The following example shows a function that returns an object with some coordinates, where we grab only the ones we're interested in: `x` and `y`. We're avoiding an intermediate `point` variable declaration that often gets in the way without adding a lot of value to the readability of your code. [source,javascript] ---- function getCoordinates() { return { x: 10, y: 22, z: -1, type: '3d' } } var { x, y } = getCoordinates() ---- The case for default option values bears repeating. Imagine you have a `random` function that produces random integers between a `min` and a `max` value, and that it should default to values between 1 and 10. This is particularly interesting as an alternative to named parameters in languages with strong typing features, such as Python and C#. This pattern, where you're able to define default values for options and then let consumers override them individually, offers great flexibility. [source,javascript] ---- function random({ min = 1, max = 10 } = {}) { return Math.floor(Math.random() * (max - min)) + min } console.log(random()) // <- 7 console.log(random({ max: 24 })) // <- 18 ---- Regular (((""assignment destructuring"", ""function parameters"", startref=""ad2fpd"")))(((""destructuring"", ""function parameters"", startref=""d2fpd"")))(((""function parameters"", startref=""fpd2"")))expressions are another great fit for destructuring. Destructuring empowers you to name groups from a match without having to resort to index numbers. Here's an example `RegExp` that could be used for parsing simple dates, and an example of destructuring those dates into each of their components. The first entry in the resulting array is reserved for the full matched text, and we can discard it. [source,javascript] ---- function splitDate(date) { var rdate = /(\\d+).(\\d+).(\\d+)/ return rdate.exec(date) } var [ , year, month, day] = splitDate('2017-11-06') ---- You'll want to be careful when the regular expression doesn't match, as that returns `null`. Perhaps a better approach would be to test for the failure case before destructuring, as shown in the following bit of code. [source,javascript] ---- var matches = splitDate('2017-11-06') if (matches === null) { return } var [, year, month, day] = matches ---- Let's turn our attention to spread and rest operators (((""assignment destructuring"", ""use cases for"", startref=""ad2ucf"")))(((""destructuring"", ""use cases for"", startref=""d2ucf"")))(((""assignment destructuring"", startref=""ad2"")))(((""destructuring"", startref=""d2"")))next. === Rest Parameter and Spread Operator Before ES6, interacting with an arbitrary amount of function parameters was complicated. You had to use `arguments`, which isn't an array but has a `length` property. Usually you'd end up casting the `arguments` object into an actual array using `Array#slice.call`, and going from there, as shown in the following snippet. [source,javascript] ---- function join() { var list = Array.prototype.slice.call(arguments) return list.join(', ') } join('first', 'second', 'third') // <- 'first, second, third' ---- ES6 has a better solution to the problem, and that's rest parameters. ==== Rest Parameters You (((""rest parameters"", id=""rp2"")))can now precede the last parameter in any JavaScript function with three dots, converting it into a special ""rest parameter."" When the rest parameter is the only parameter in a function, it gets all arguments passed to the function: it works just like the `.slice` solution we saw earlier, but you avoid the need for a complicated construct like `arguments`, and it's specified in the parameter list. [source,javascript] ---- function join(...list) { return list.join(', ') } join('first', 'second', 'third') // <- 'first, second, third' ---- Named parameters before the rest parameter won't be included in the `list`. [source,javascript] ---- function join(separator, ...list) { return list.join(separator) } join('; ', 'first', 'second', 'third') // <- 'first; second; third' ---- Note that arrow functions with a rest parameter must include parentheses, even when it's the only parameter. Otherwise, a `SyntaxError` would be thrown. The following piece of code is a beautiful example of how combining arrow functions and rest parameters can yield concise functional expressions. [source,javascript] ---- var sumAll = (...numbers) => numbers.reduce( (total, next) => total + next ) console.log(sumAll(1, 2, 5)) // <- 8 ---- Compare that with the ES5 version of the same function. Granted, it's all in the complexity. While terse, the `sumAll` function can be confusing to readers unused to the `.reduce` method, or because it uses two arrow functions. This is a complexity trade-off that we'll cover in the second part of the book. [source,javascript] ---- function sumAll() { var numbers = Array.prototype.slice.call(arguments) return numbers.reduce(function (total, next) { return total + next }) } console.log(sumAll(1, 2, 5)) // <- 8 ---- Next up we have the spread operator. It's also denoted with three dots, but it serves a slightly different (((""rest parameters"", startref=""rp2"")))purpose. ==== Spread Operator The (((""spread operator"", id=""so2"")))spread operator can be used to cast any iterable object into an array. Spreading effectively expands an expression onto a target such as an array literal or a function call. The following example uses `...arguments` to cast function parameters into an array literal. [source,javascript] ---- function cast() { return [...arguments] } cast('a', 'b', 'c') // <- ['a', 'b', 'c'] ---- We could use the spread operator to split a string into an array with each code point that makes up the string. [source,javascript] ---- [...'show me'] // <- ['s', 'h', 'o', 'w', ' ', 'm', 'e'] ---- You can place additional elements to the left and to the right of a spread operation and still get the result you would expect. [source,javascript] ---- function cast() { return ['left', ...arguments, 'right'] } cast('a', 'b', 'c') // <- ['left', 'a', 'b', 'c', 'right'] ---- Spread is an useful way of combining multiple arrays. The following example shows how you can spread arrays anywhere into an array literal, expanding their elements into place. [source,javascript] ---- var all = [1, ...[2, 3], 4, ...[5], 6, 7] console.log(all) // <- [1, 2, 3, 4, 5, 6, 7] ---- Note that the spread operator isn't limited to arrays and `arguments`. The spread operator can be used with any iterable object. Iterable is a protocol in ES6 that allows you to turn any object into something that can be iterated over. We'll research the (((""iterable protocol"")))iterable protocol in <>. .Shifting and Spreading **** When you want to extract an element or two from the beginning of an array, the common approach is to ((("".shift()"", primary-sortas=""shift"")))((("".shift()"")))use `.shift`. While functional, the following snippet of code can be hard to understand at a glance, because it uses `.shift` twice to grab a different item from the beginning of the `list` each time. The focus is, like in many other pre-ES6 situations, placed on getting the language to do what we want. [source,javascript] ---- var list = ['a', 'b', 'c', 'd', 'e'] var first = list.shift() var second = list.shift() console.log(first) // <- 'a' ---- In ES6, you can combine spread with array destructuring. The following piece of code is similar to the preceding one, except we're using a single line of code, and that single line is more descriptive of what we're doing than repeatedly calling `list.shift()` in the previous example. [source,javascript] ---- var [first, second, ...other] = ['a', 'b', 'c', 'd', 'e'] console.log(other) // <- ['c', 'd', 'e'] ---- Using the spread operator you can focus on implementing the functionality you need while the language stays out of the way. Improving expressiveness and decreasing time spent working around language limitations is a common pattern we can observe in ES6 features. **** Before ES6, whenever you had a dynamic list of arguments that needed to be applied to a function call, you'd use `.apply`. This ((("".apply()"", primary-sortas=""apply"", id=""apply2"")))is inelegant because `.apply` also takes a context for `this`, which, in this scenario, you don't want to concern yourself with. [source,javascript] ---- fn.apply(null, ['a', 'b', 'c']) ---- Besides spreading onto arrays, you can also spread items onto function calls. The following example shows how you could use the spread operator to pass an arbitrary number of arguments to the `multiply` (((""multiply()"")))function. [source,javascript] ---- function multiply(left, right) { return left * right } var result = multiply(...[2, 3]) console.log(result) // <- 6 ---- Spreading arguments onto a function call can be combined with regular arguments as much as necessary, just like with array literals. The next example calls `print` with a couple of regular arguments and a couple of arrays being spread over the parameter list. Note how conveniently the rest `list` parameter matches all the provided arguments. Spread and rest can help make code intent more clear without diluting your codebase. [source,javascript] ---- function print(...list) { console.log(list) } print(1, ...[2, 3], 4, ...[5]) // <- [1, 2, 3, 4, 5] ---- Another limitation of `.apply` is that combining it with the `new` keyword, when instantiating an object, becomes very verbose. Here's an example of combining `new` and `.apply` to create a `Date` object. Ignore for a moment that months in JavaScript dates are zero-based, turning `11` into December, and consider how much of the following line of code is spent bending the language in our favor, ((("".apply()"", primary-sortas=""apply"", startref=""apply2"")))just to instantiate a `Date` object. [source,javascript] ---- new (Date.bind.apply(Date, [null, 2017, 11, 31])) // <- Thu Dec 31 2017 ---- As shown in the next snippet, the spread operator strips away all the complexity and we're only left with the important bits. It's a `new` instance, it uses `...` to spread a dynamic list of arguments over the function call, and it's a `Date`. (((""Date()"")))That's it. [source,javascript] ---- new Date(...[2017, 11, 31]) // <- Thu Dec 31 2017 ---- The following table summarizes the use cases we've discussed for the spread operator. [options=""header""] |======= |Use case|ES5|ES6 |Concatenation|`[1, 2].concat(more)`|`[1, 2, ...more]` |Push an array onto list|`list.push.apply(list, items)`|`list.push(...items)` |Destructuring|`a = list[0], other = list.slice(1)` | `[a, ...other] = list` |`new` and `apply`|`new (Date.bind.apply(Date, [null,2017,11,31]))`| `new Date(...[2017,11,31])` |======= [[template_literals]] === Template Literals Template (((""spread operator"", startref=""so2"")))(((""template literals"", id=""templ2"")))literals are a vast improvement upon regular JavaScript strings. Instead of using single or double quotes, template literals are declared using backticks, as shown next. [source,javascript] ---- var text = `This is my first template literal` ---- Given that template literals are delimited by backticks, you're now able to declare strings with both `'` and `""` quotation marks in them without having to escape either, as shown here. [source,javascript] ---- var text = `I'm ""amazed"" at these opportunities!` ---- One of the most appealing features of template literals is their ability to interpolate JavaScript expressions. ==== String Interpolation With (((""template literals"", ""string interpolation"", id=""temp2si"")))(((""string interpolation"", id=""si2"")))template literals, you're able to interpolate any JavaScript expressions inside your templates. When the template literal expression is reached, it's evaluated and you get back the compiled result. The following example interpolates a `name` variable into a template literal. [source,javascript] ---- var name = 'Shannon' var text = `Hello, ${ name }!` console.log(text) // <- 'Hello, Shannon!' ---- We've already established that you can use any JavaScript expressions, and not just variables. You can think of each expression in a template literal as defining a variable before the template runs, and then concatenating each variable with the rest of the string. However, the code becomes easier to maintain because it doesn't involve manually concatenating strings and JavaScript expressions. The variables you use in those expressions, the functions you call, and so on, should all be available to the current scope. It will be up to your coding style guides to decide how much logic you want to cram into the interpolation expressions. The following code snippet, for example, instantiates a `Date` object and formats it into a human-readable date inside a template literal. [source,javascript] ---- `The time and date is ${ new Date().toLocaleString() }.` // <- 'the time and date is 8/26/2017, 3:15:20 PM' ---- You could interpolate mathematical operations. [source,javascript] ---- `The result of 2+3 equals ${ 2 + 3 }` // <- 'The result of 2+3 equals 5' ---- You could even nest template literals, as they are also valid JavaScript expressions. [source,javascript] ---- `This template literal ${ `is ${ 'nested' }` }!` // <- 'This template literal is nested!' ---- Another perk of template literals is their multiline string representation (((""template literals"", ""string interpolation"", startref=""temp2si"")))(((""string interpolation"", startref=""si2"")))support. ==== Multiline Template Literals Before (((""template literals"", ""multiline string representation"", id=""templ2msr"")))(((""multiline strings"", id=""ms2"")))(((""strings, multiline"", id=""sm2"")))template literals, if you wanted to represent strings in multiple lines of JavaScript, you had to resort to escaping, concatenation, arrays, or even elaborate hacks using comments. The following snippet summarizes some of the most common multiline string representations prior to ES6. [source,javascript] ---- var escaped = 'The first line\\n\\ A second line\\n\\ Then a third line' var concatenated = 'The first line\\n' + 'A second line\\n' + 'Then a third line' var joined = [ 'The first line', 'A second line', 'Then a third line' ].join('\\n') ---- Under ES6, you could use backticks instead. Template literals support multiline strings by default. Note how there are no `\\n` escapes, no concatenation, and no arrays involved. [source,javascript] ---- var multiline = `The first line A second line Then a third line` ---- Multiline strings really shine when you have, for instance, a chunk of HTML you want to interpolate some variables into. If you need to display a list within the template, you could iterate the list, mapping its items into the corresponding markup, and then return the joined result from an interpolated expression. This makes it a breeze to declare subcomponents within your templates, as shown in the following piece of code. [source,javascript] ---- var book = { title: 'Modular ES6', excerpt: 'Here goes some properly sanitized HTML', tags: ['es6', 'template-literals', 'es6-in-depth'] } var html = `

${ book.title }

${ book.excerpt }
    ${ book.tags .map(tag => `
  • ${ tag }
  • `) .join('\\n ') }
` ---- The template we've just prepared would produce output like what's shown in the following snippet of code. Note how spacing was preserved,footnoteref:[multi-line-indentation,When using multiline template literals, spacing isn't preserved automatically. However, in many cases we can provide just enough indentation to make it work. Be wary of indented code blocks that may result in undesired indentation due to our code block being nested.] and how `
  • ` tags are properly indented thanks to how we joined them together using a few spaces. [source,html] ----

    Modular ES6

    Here goes some properly sanitized HTML
    • es6
    • template-literals
    • es6-in-depth
    ---- A downside when it comes to multiline template literals is indentation. The following example shows a typically indented piece of code with a template literal contained in a function. While we may have expected no indentation, the string has four spaces of indentation. [source,javascript] ---- function getParagraph() { return ` Dear Rod, This is a template literal string that's indented four spaces. However, you may have expected for it to be not indented at all. Nico ` } ---- While not ideal, we could get away with a utility function to remove indentation from each line in the resulting string. [source,javascript] ---- function unindent(text) { return text .split('\\n') .map(line => line.slice(4)) .join('\\n') .trim() } ---- Sometimes, it might be a good idea to pre-process the results of interpolated expressions before inserting them into your templates. For these advanced kinds of use cases, it's possible to use another feature of template literals called _tagged templates_.(((""template literals"", ""multiline string representation"", startref=""templ2msr"")))(((""multiline strings"", startref=""ms2"")))(((""strings, multiline"", startref=""sm2""))) ==== Tagged Templates By (((""template literals"", ""tagged templates"", id=""tl2tt"")))(((""tagged templates"", id=""tt2"")))default, JavaScript interprets `\\` as an escape character with special meaning. For example, `\\n` is interpreted as a newline, `\\u00f1` is interpreted as `ñ`, etc. You could avoid these rules using the `String.raw` tagged template. The next snippet shows a template literal using `String.raw`, which prevents `\\n` from being interpreted as a newline. [source,javascript] ---- var text = String.raw`""\\n"" is taken literally. It'll be escaped instead of interpreted.` console.log(text) // ""\\n"" is taken literally. // It'll be escaped instead of interpreted. ---- The `String.raw` prefix we've added to our template literal is a tagged template. It's used to parse the template. Tagged templates receive a parameter with an array containing the static parts of the template, as well as the result of evaluating each expression, each in its own parameter. As an example, consider the tagged template literal in the next code snippet. [source,javascript] ---- tag`Hello, ${ name }. I am ${ emotion } to meet you!` ---- That tagged template expression would, in practice, be translated into the following function call. [source,javascript] ---- tag( ['Hello, ', '. I am ', ' to meet you!'], 'Maurice', 'thrilled' ) ---- The resulting string is built by taking each part of the template and placing one of the expressions next to it, until there are no more parts of the template left. It might be hard to interpret the argument list without looking at a potential implementation of the default template literal `tag`, so let's do that. The following snippet of code shows a possible implementation of the default `tag`. It provides the same functionality as a template literal does when a tagged template isn't explicitly provided. It reduces the `parts` array into a single value, the result of evaluating the template literal. The result is initialized with the first `part`, and then each other `part` of the template is preceded by one of the `values`. We've used the rest parameter syntax for `...values` in order to make it easier to grab the result of evaluating each expression in the template. We're using an arrow function with an implicit `return` statement, given that its expression is relatively simple. [source,javascript] ---- function tag(parts, ...values) { return parts.reduce( (all, part, index) => all + values[index - 1] + part ) } ---- You can try the `tag` template using code like in the following snippet. You'll notice you get the same output as if you omitted `tag`, since we're copying the default behavior. [source,javascript] ---- var name = 'Maurice' var emotion = 'thrilled' var text = tag`Hello, ${ name }. I am ${ emotion } to meet you!` console.log(text) // <- 'Hello, Maurice. I am thrilled to meet you!' ---- Multiple use cases apply to tagged templates. One possible use case might be to make user input uppercase, making the string sound satirical. That's what the following piece of code does. We've modified `tag` slightly so that any interpolated strings are uppercased. [source,javascript] ---- function upper(parts, ...values) { return parts.reduce((all, part, index) => all + values[index - 1].toUpperCase() + part ) } var name = 'Maurice' var emotion = 'thrilled' upper`Hello, ${ name }. I am ${ emotion } to meet you!` // <- 'Hello, MAURICE. I am THRILLED to meet you!' ---- A decidedly more useful use case would be to sanitize expressions interpolated into your templates, automatically, using a tagged template. Given a template where all expressions are considered user input, we could use a hypothetical `sanitize` library to remove HTML tags and similar hazards, preventing cross-site scripting (XSS) attacks where users might inject malicious HTML into our websites. [source,javascript] ---- function sanitized(parts, ...values) { return parts.reduce((all, part, index) => all + sanitize(values[index - 1]) + part ) } var comment = 'Evil comment' var html = sanitized`
    ${ comment }
    ` console.log(html) // <- '
    Evil comment
    ' ---- Phew, (((""template literals"", ""tagged templates"", startref=""tl2tt"")))(((""tagged templates"", startref=""tt2"")))(((""template literals"", startref=""templ2"")))that malicious `